xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision da6c28aaf62fa55f0fdb8004aa40f88f23bf53f0)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <inet/rawip_impl.h>
122 #include <inet/rts_impl.h>
123 #include <sys/sunddi.h>
124 
125 #include <sys/tsol/label.h>
126 #include <sys/tsol/tnet.h>
127 
128 #include <rpc/pmap_prot.h>
129 
130 /*
131  * Values for squeue switch:
132  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
133  * IP_SQUEUE_ENTER: squeue_enter
134  * IP_SQUEUE_FILL: squeue_fill
135  */
136 int ip_squeue_enter = 2;	/* Setable in /etc/system */
137 
138 squeue_func_t ip_input_proc;
139 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
140 
141 /*
142  * Setable in /etc/system
143  */
144 int ip_poll_normal_ms = 100;
145 int ip_poll_normal_ticks = 0;
146 int ip_modclose_ackwait_ms = 3000;
147 
148 /*
149  * It would be nice to have these present only in DEBUG systems, but the
150  * current design of the global symbol checking logic requires them to be
151  * unconditionally present.
152  */
153 uint_t ip_thread_data;			/* TSD key for debug support */
154 krwlock_t ip_thread_rwlock;
155 list_t	ip_thread_list;
156 
157 /*
158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
159  */
160 
161 struct listptr_s {
162 	mblk_t	*lp_head;	/* pointer to the head of the list */
163 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
164 };
165 
166 typedef struct listptr_s listptr_t;
167 
168 /*
169  * This is used by ip_snmp_get_mib2_ip_route_media and
170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
171  */
172 typedef struct iproutedata_s {
173 	uint_t		ird_idx;
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 /*
180  * Cluster specific hooks. These should be NULL when booted as a non-cluster
181  */
182 
183 /*
184  * Hook functions to enable cluster networking
185  * On non-clustered systems these vectors must always be NULL.
186  *
187  * Hook function to Check ip specified ip address is a shared ip address
188  * in the cluster
189  *
190  */
191 int (*cl_inet_isclusterwide)(uint8_t protocol,
192     sa_family_t addr_family, uint8_t *laddrp) = NULL;
193 
194 /*
195  * Hook function to generate cluster wide ip fragment identifier
196  */
197 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
198     uint8_t *laddrp, uint8_t *faddrp) = NULL;
199 
200 /*
201  * Synchronization notes:
202  *
203  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
204  * MT level protection given by STREAMS. IP uses a combination of its own
205  * internal serialization mechanism and standard Solaris locking techniques.
206  * The internal serialization is per phyint (no IPMP) or per IPMP group.
207  * This is used to serialize plumbing operations, IPMP operations, certain
208  * multicast operations, most set ioctls, igmp/mld timers etc.
209  *
210  * Plumbing is a long sequence of operations involving message
211  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
212  * involved in plumbing operations. A natural model is to serialize these
213  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
214  * parallel without any interference. But various set ioctls on hme0 are best
215  * serialized. However if the system uses IPMP, the operations are easier if
216  * they are serialized on a per IPMP group basis since IPMP operations
217  * happen across ill's of a group. Thus the lowest common denominator is to
218  * serialize most set ioctls, multicast join/leave operations, IPMP operations
219  * igmp/mld timer operations, and processing of DLPI control messages received
220  * from drivers on a per IPMP group basis. If the system does not employ
221  * IPMP the serialization is on a per phyint basis. This serialization is
222  * provided by the ipsq_t and primitives operating on this. Details can
223  * be found in ip_if.c above the core primitives operating on ipsq_t.
224  *
225  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
226  * Simiarly lookup of an ire by a thread also returns a refheld ire.
227  * In addition ipif's and ill's referenced by the ire are also indirectly
228  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
229  * the ipif's address or netmask change as long as an ipif is refheld
230  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
231  * address of an ipif has to go through the ipsq_t. This ensures that only
232  * 1 such exclusive operation proceeds at any time on the ipif. It then
233  * deletes all ires associated with this ipif, and waits for all refcnts
234  * associated with this ipif to come down to zero. The address is changed
235  * only after the ipif has been quiesced. Then the ipif is brought up again.
236  * More details are described above the comment in ip_sioctl_flags.
237  *
238  * Packet processing is based mostly on IREs and are fully multi-threaded
239  * using standard Solaris MT techniques.
240  *
241  * There are explicit locks in IP to handle:
242  * - The ip_g_head list maintained by mi_open_link() and friends.
243  *
244  * - The reassembly data structures (one lock per hash bucket)
245  *
246  * - conn_lock is meant to protect conn_t fields. The fields actually
247  *   protected by conn_lock are documented in the conn_t definition.
248  *
249  * - ire_lock to protect some of the fields of the ire, IRE tables
250  *   (one lock per hash bucket). Refer to ip_ire.c for details.
251  *
252  * - ndp_g_lock and nce_lock for protecting NCEs.
253  *
254  * - ill_lock protects fields of the ill and ipif. Details in ip.h
255  *
256  * - ill_g_lock: This is a global reader/writer lock. Protects the following
257  *	* The AVL tree based global multi list of all ills.
258  *	* The linked list of all ipifs of an ill
259  *	* The <ill-ipsq> mapping
260  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
261  *	* The illgroup list threaded by ill_group_next.
262  *	* <ill-phyint> association
263  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
264  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
265  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
266  *   will all have to hold the ill_g_lock as writer for the actual duration
267  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
268  *   may be found in the IPMP section.
269  *
270  * - ill_lock:  This is a per ill mutex.
271  *   It protects some members of the ill and is documented below.
272  *   It also protects the <ill-ipsq> mapping
273  *   It also protects the illgroup list threaded by ill_group_next.
274  *   It also protects the <ill-phyint> assoc.
275  *   It also protects the list of ipifs hanging off the ill.
276  *
277  * - ipsq_lock: This is a per ipsq_t mutex lock.
278  *   This protects all the other members of the ipsq struct except
279  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
280  *
281  * - illgrp_lock: This is a per ill_group mutex lock.
282  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
283  *   which dictates which is the next ill in an ill_group that is to be chosen
284  *   for sending outgoing packets, through creation of an IRE_CACHE that
285  *   references this ill.
286  *
287  * - phyint_lock: This is a per phyint mutex lock. Protects just the
288  *   phyint_flags
289  *
290  * - ip_g_nd_lock: This is a global reader/writer lock.
291  *   Any call to nd_load to load a new parameter to the ND table must hold the
292  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
293  *   as reader.
294  *
295  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
296  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
297  *   uniqueness check also done atomically.
298  *
299  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
300  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
301  *   as a writer when adding or deleting elements from these lists, and
302  *   as a reader when walking these lists to send a SADB update to the
303  *   IPsec capable ills.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
314  *   ip_sioctl_flags since the these operations are executed exclusively and
315  *   that ensures that the "usesrc group state" cannot change. The "usesrc
316  *   group state" change can happen only in the latter part of
317  *   ip_sioctl_slifusesrc and in ill_delete.
318  *
319  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
320  *
321  * To change the <ill-phyint> association, the ill_g_lock must be held
322  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
323  * must be held.
324  *
325  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
326  * and the ill_lock of the ill in question must be held.
327  *
328  * To change the <ill-illgroup> association the ill_g_lock must be held as
329  * writer and the ill_lock of the ill in question must be held.
330  *
331  * To add or delete an ipif from the list of ipifs hanging off the ill,
332  * ill_g_lock (writer) and ill_lock must be held and the thread must be
333  * a writer on the associated ipsq,.
334  *
335  * To add or delete an ill to the system, the ill_g_lock must be held as
336  * writer and the thread must be a writer on the associated ipsq.
337  *
338  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
339  * must be a writer on the associated ipsq.
340  *
341  * Lock hierarchy
342  *
343  * Some lock hierarchy scenarios are listed below.
344  *
345  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
346  * ill_g_lock -> illgrp_lock -> ill_lock
347  * ill_g_lock -> ill_lock(s) -> phyint_lock
348  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ip_addr_avail_lock
350  * conn_lock -> irb_lock -> ill_lock -> ire_lock
351  * ill_g_lock -> ip_g_nd_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * IPsec scenarios
358  *
359  * ipsa_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ipsa_lock
362  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
363  *
364  * Trusted Solaris scenarios
365  *
366  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
367  * igsa_lock -> gcdb_lock
368  * gcgrp_rwlock -> ire_lock
369  * gcgrp_rwlock -> gcdb_lock
370  *
371  *
372  * Routing/forwarding table locking notes:
373  *
374  * Lock acquisition order: Radix tree lock, irb_lock.
375  * Requirements:
376  * i.  Walker must not hold any locks during the walker callback.
377  * ii  Walker must not see a truncated tree during the walk because of any node
378  *     deletion.
379  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
380  *     in many places in the code to walk the irb list. Thus even if all the
381  *     ires in a bucket have been deleted, we still can't free the radix node
382  *     until the ires have actually been inactive'd (freed).
383  *
384  * Tree traversal - Need to hold the global tree lock in read mode.
385  * Before dropping the global tree lock, need to either increment the ire_refcnt
386  * to ensure that the radix node can't be deleted.
387  *
388  * Tree add - Need to hold the global tree lock in write mode to add a
389  * radix node. To prevent the node from being deleted, increment the
390  * irb_refcnt, after the node is added to the tree. The ire itself is
391  * added later while holding the irb_lock, but not the tree lock.
392  *
393  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
394  * All associated ires must be inactive (i.e. freed), and irb_refcnt
395  * must be zero.
396  *
397  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
398  * global tree lock (read mode) for traversal.
399  *
400  * IPsec notes :
401  *
402  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
403  * in front of the actual packet. For outbound datagrams, the M_CTL
404  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
405  * information used by the IPsec code for applying the right level of
406  * protection. The information initialized by IP in the ipsec_out_t
407  * is determined by the per-socket policy or global policy in the system.
408  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
409  * ipsec_info.h) which starts out with nothing in it. It gets filled
410  * with the right information if it goes through the AH/ESP code, which
411  * happens if the incoming packet is secure. The information initialized
412  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
413  * the policy requirements needed by per-socket policy or global policy
414  * is met or not.
415  *
416  * If there is both per-socket policy (set using setsockopt) and there
417  * is also global policy match for the 5 tuples of the socket,
418  * ipsec_override_policy() makes the decision of which one to use.
419  *
420  * For fully connected sockets i.e dst, src [addr, port] is known,
421  * conn_policy_cached is set indicating that policy has been cached.
422  * conn_in_enforce_policy may or may not be set depending on whether
423  * there is a global policy match or per-socket policy match.
424  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
425  * Once the right policy is set on the conn_t, policy cannot change for
426  * this socket. This makes life simpler for TCP (UDP ?) where
427  * re-transmissions go out with the same policy. For symmetry, policy
428  * is cached for fully connected UDP sockets also. Thus if policy is cached,
429  * it also implies that policy is latched i.e policy cannot change
430  * on these sockets. As we have the right policy on the conn, we don't
431  * have to lookup global policy for every outbound and inbound datagram
432  * and thus serving as an optimization. Note that a global policy change
433  * does not affect fully connected sockets if they have policy. If fully
434  * connected sockets did not have any policy associated with it, global
435  * policy change may affect them.
436  *
437  * IP Flow control notes:
438  *
439  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
440  * cannot be sent down to the driver by IP, because of a canput failure, IP
441  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
442  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
443  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
444  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
445  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
446  * the queued messages, and removes the conn from the drain list, if all
447  * messages were drained. It also qenables the next conn in the drain list to
448  * continue the drain process.
449  *
450  * In reality the drain list is not a single list, but a configurable number
451  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
452  * list. If the ip_wsrv of the next qenabled conn does not run, because the
453  * stream closes, ip_close takes responsibility to qenable the next conn in
454  * the drain list. The directly called ip_wput path always does a putq, if
455  * it cannot putnext. Thus synchronization problems are handled between
456  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
457  * functions that manipulate this drain list. Furthermore conn_drain_insert
458  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
459  * running on a queue at any time. conn_drain_tail can be simultaneously called
460  * from both ip_wsrv and ip_close.
461  *
462  * IPQOS notes:
463  *
464  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
465  * and IPQoS modules. IPPF includes hooks in IP at different control points
466  * (callout positions) which direct packets to IPQoS modules for policy
467  * processing. Policies, if present, are global.
468  *
469  * The callout positions are located in the following paths:
470  *		o local_in (packets destined for this host)
471  *		o local_out (packets orginating from this host )
472  *		o fwd_in  (packets forwarded by this m/c - inbound)
473  *		o fwd_out (packets forwarded by this m/c - outbound)
474  * Hooks at these callout points can be enabled/disabled using the ndd variable
475  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
476  * By default all the callout positions are enabled.
477  *
478  * Outbound (local_out)
479  * Hooks are placed in ip_wput_ire and ipsec_out_process.
480  *
481  * Inbound (local_in)
482  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
483  * TCP and UDP fanout routines.
484  *
485  * Forwarding (in and out)
486  * Hooks are placed in ip_rput_forward.
487  *
488  * IP Policy Framework processing (IPPF processing)
489  * Policy processing for a packet is initiated by ip_process, which ascertains
490  * that the classifier (ipgpc) is loaded and configured, failing which the
491  * packet resumes normal processing in IP. If the clasifier is present, the
492  * packet is acted upon by one or more IPQoS modules (action instances), per
493  * filters configured in ipgpc and resumes normal IP processing thereafter.
494  * An action instance can drop a packet in course of its processing.
495  *
496  * A boolean variable, ip_policy, is used in all the fanout routines that can
497  * invoke ip_process for a packet. This variable indicates if the packet should
498  * to be sent for policy processing. The variable is set to B_TRUE by default,
499  * i.e. when the routines are invoked in the normal ip procesing path for a
500  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
501  * ip_policy is set to B_FALSE for all the routines called in these two
502  * functions because, in the former case,  we don't process loopback traffic
503  * currently while in the latter, the packets have already been processed in
504  * icmp_inbound.
505  *
506  * Zones notes:
507  *
508  * The partitioning rules for networking are as follows:
509  * 1) Packets coming from a zone must have a source address belonging to that
510  * zone.
511  * 2) Packets coming from a zone can only be sent on a physical interface on
512  * which the zone has an IP address.
513  * 3) Between two zones on the same machine, packet delivery is only allowed if
514  * there's a matching route for the destination and zone in the forwarding
515  * table.
516  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
517  * different zones can bind to the same port with the wildcard address
518  * (INADDR_ANY).
519  *
520  * The granularity of interface partitioning is at the logical interface level.
521  * Therefore, every zone has its own IP addresses, and incoming packets can be
522  * attributed to a zone unambiguously. A logical interface is placed into a zone
523  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
524  * structure. Rule (1) is implemented by modifying the source address selection
525  * algorithm so that the list of eligible addresses is filtered based on the
526  * sending process zone.
527  *
528  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
529  * across all zones, depending on their type. Here is the break-up:
530  *
531  * IRE type				Shared/exclusive
532  * --------				----------------
533  * IRE_BROADCAST			Exclusive
534  * IRE_DEFAULT (default routes)		Shared (*)
535  * IRE_LOCAL				Exclusive (x)
536  * IRE_LOOPBACK				Exclusive
537  * IRE_PREFIX (net routes)		Shared (*)
538  * IRE_CACHE				Exclusive
539  * IRE_IF_NORESOLVER (interface routes)	Exclusive
540  * IRE_IF_RESOLVER (interface routes)	Exclusive
541  * IRE_HOST (host routes)		Shared (*)
542  *
543  * (*) A zone can only use a default or off-subnet route if the gateway is
544  * directly reachable from the zone, that is, if the gateway's address matches
545  * one of the zone's logical interfaces.
546  *
547  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
548  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
549  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
550  * address of the zone itself (the destination). Since IRE_LOCAL is used
551  * for communication between zones, ip_wput_ire has special logic to set
552  * the right source address when sending using an IRE_LOCAL.
553  *
554  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
555  * ire_cache_lookup restricts loopback using an IRE_LOCAL
556  * between zone to the case when L2 would have conceptually looped the packet
557  * back, i.e. the loopback which is required since neither Ethernet drivers
558  * nor Ethernet hardware loops them back. This is the case when the normal
559  * routes (ignoring IREs with different zoneids) would send out the packet on
560  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
561  * associated.
562  *
563  * Multiple zones can share a common broadcast address; typically all zones
564  * share the 255.255.255.255 address. Incoming as well as locally originated
565  * broadcast packets must be dispatched to all the zones on the broadcast
566  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
567  * since some zones may not be on the 10.16.72/24 network. To handle this, each
568  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
569  * sent to every zone that has an IRE_BROADCAST entry for the destination
570  * address on the input ill, see conn_wantpacket().
571  *
572  * Applications in different zones can join the same multicast group address.
573  * For IPv4, group memberships are per-logical interface, so they're already
574  * inherently part of a zone. For IPv6, group memberships are per-physical
575  * interface, so we distinguish IPv6 group memberships based on group address,
576  * interface and zoneid. In both cases, received multicast packets are sent to
577  * every zone for which a group membership entry exists. On IPv6 we need to
578  * check that the target zone still has an address on the receiving physical
579  * interface; it could have been removed since the application issued the
580  * IPV6_JOIN_GROUP.
581  */
582 
583 /*
584  * Squeue Fanout flags:
585  *	0: No fanout.
586  *	1: Fanout across all squeues
587  */
588 boolean_t	ip_squeue_fanout = 0;
589 
590 /*
591  * Maximum dups allowed per packet.
592  */
593 uint_t ip_max_frag_dups = 10;
594 
595 #define	IS_SIMPLE_IPH(ipha)						\
596 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
597 
598 /* RFC1122 Conformance */
599 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
600 
601 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
602 
603 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
604 
605 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
606 		    cred_t *credp, boolean_t isv6);
607 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
608 
609 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
610 		    ip_stack_t *);
611 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
612 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
613 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
614 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
615 		    mblk_t *, int, ip_stack_t *);
616 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
617 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
618 		    ill_t *, zoneid_t);
619 static void	icmp_options_update(ipha_t *);
620 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
621 		    ip_stack_t *);
622 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
623 		    zoneid_t zoneid, ip_stack_t *);
624 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
625 static void	icmp_redirect(ill_t *, mblk_t *);
626 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
627 		    ip_stack_t *);
628 
629 static void	ip_arp_news(queue_t *, mblk_t *);
630 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
631 		    ip_stack_t *);
632 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
633 char		*ip_dot_addr(ipaddr_t, char *);
634 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
635 int		ip_close(queue_t *, int);
636 static char	*ip_dot_saddr(uchar_t *, char *);
637 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
638 		    boolean_t, boolean_t, ill_t *, zoneid_t);
639 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
640 		    boolean_t, boolean_t, zoneid_t);
641 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
642 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
643 static void	ip_lrput(queue_t *, mblk_t *);
644 ipaddr_t	ip_net_mask(ipaddr_t);
645 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
646 		    ip_stack_t *);
647 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
648 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
649 char		*ip_nv_lookup(nv_t *, int);
650 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
651 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
652 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
654     ipndp_t *, size_t);
655 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
656 void	ip_rput(queue_t *, mblk_t *);
657 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
658 		    void *dummy_arg);
659 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
660 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
661     ip_stack_t *);
662 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
663 			    ire_t *, ip_stack_t *);
664 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
665 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
666 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
667     ip_stack_t *);
668 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
669 		    uint16_t *);
670 int		ip_snmp_get(queue_t *, mblk_t *, int);
671 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
672 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
673 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
674 		    ip_stack_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
677 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
681 		    ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
683 		    ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
701 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
702 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
703 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
704 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
705 static boolean_t	ip_source_route_included(ipha_t *);
706 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
707 
708 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
709 		    zoneid_t, ip_stack_t *);
710 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
711 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
712 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
713 		    zoneid_t, ip_stack_t *);
714 
715 static void	conn_drain_init(ip_stack_t *);
716 static void	conn_drain_fini(ip_stack_t *);
717 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
718 
719 static void	conn_walk_drain(ip_stack_t *);
720 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
721     zoneid_t);
722 
723 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
724 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
725 static void	ip_stack_fini(netstackid_t stackid, void *arg);
726 
727 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
728     zoneid_t);
729 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
730     void *dummy_arg);
731 
732 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
733 
734 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
735     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
736     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
737 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
738 
739 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
740 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
741     caddr_t, cred_t *);
742 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
743     caddr_t cp, cred_t *cr);
744 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
745     cred_t *);
746 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static squeue_func_t ip_squeue_switch(int);
753 
754 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
755 static void	ip_kstat_fini(netstackid_t, kstat_t *);
756 static int	ip_kstat_update(kstat_t *kp, int rw);
757 static void	*icmp_kstat_init(netstackid_t);
758 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
759 static int	icmp_kstat_update(kstat_t *kp, int rw);
760 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
761 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
762 
763 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
764 
765 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
766     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
767 
768 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
769     ipha_t *, ill_t *, boolean_t);
770 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
771 
772 /* How long, in seconds, we allow frags to hang around. */
773 #define	IP_FRAG_TIMEOUT	60
774 
775 /*
776  * Threshold which determines whether MDT should be used when
777  * generating IP fragments; payload size must be greater than
778  * this threshold for MDT to take place.
779  */
780 #define	IP_WPUT_FRAG_MDT_MIN	32768
781 
782 /* Setable in /etc/system only */
783 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
784 
785 static long ip_rput_pullups;
786 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
787 
788 vmem_t *ip_minor_arena;
789 
790 int	ip_debug;
791 
792 #ifdef DEBUG
793 uint32_t ipsechw_debug = 0;
794 #endif
795 
796 /*
797  * Multirouting/CGTP stuff
798  */
799 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
800 
801 /*
802  * XXX following really should only be in a header. Would need more
803  * header and .c clean up first.
804  */
805 extern optdb_obj_t	ip_opt_obj;
806 
807 ulong_t ip_squeue_enter_unbound = 0;
808 
809 /*
810  * Named Dispatch Parameter Table.
811  * All of these are alterable, within the min/max values given, at run time.
812  */
813 static ipparam_t	lcl_param_arr[] = {
814 	/* min	max	value	name */
815 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
816 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
817 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
818 	{  0,	1,	0,	"ip_respond_to_timestamp"},
819 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
820 	{  0,	1,	1,	"ip_send_redirects"},
821 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
822 	{  0,	10,	0,	"ip_debug"},
823 	{  0,	10,	0,	"ip_mrtdebug"},
824 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
825 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
826 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
827 	{  1,	255,	255,	"ip_def_ttl" },
828 	{  0,	1,	0,	"ip_forward_src_routed"},
829 	{  0,	256,	32,	"ip_wroff_extra" },
830 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
831 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
832 	{  0,	1,	1,	"ip_path_mtu_discovery" },
833 	{  0,	240,	30,	"ip_ignore_delete_time" },
834 	{  0,	1,	0,	"ip_ignore_redirect" },
835 	{  0,	1,	1,	"ip_output_queue" },
836 	{  1,	254,	1,	"ip_broadcast_ttl" },
837 	{  0,	99999,	100,	"ip_icmp_err_interval" },
838 	{  1,	99999,	10,	"ip_icmp_err_burst" },
839 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
840 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
841 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
842 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
843 	{  0,	1,	1,	"icmp_accept_clear_messages" },
844 	{  0,	1,	1,	"igmp_accept_clear_messages" },
845 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
846 				"ip_ndp_delay_first_probe_time"},
847 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
848 				"ip_ndp_max_unicast_solicit"},
849 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
850 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
851 	{  0,	1,	0,	"ip6_forward_src_routed"},
852 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
853 	{  0,	1,	1,	"ip6_send_redirects"},
854 	{  0,	1,	0,	"ip6_ignore_redirect" },
855 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
856 
857 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
858 
859 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
860 
861 	{  0,	1,	1,	"pim_accept_clear_messages" },
862 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
863 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
864 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
865 	{  0,	15,	0,	"ip_policy_mask" },
866 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
867 	{  0,	255,	1,	"ip_multirt_ttl" },
868 	{  0,	1,	1,	"ip_multidata_outbound" },
869 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
870 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
871 	{  0,	1000,	1,	"ip_max_temp_defend" },
872 	{  0,	1000,	3,	"ip_max_defend" },
873 	{  0,	999999,	30,	"ip_defend_interval" },
874 	{  0,	3600000, 300000, "ip_dup_recovery" },
875 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
876 	{  0,	1,	1,	"ip_lso_outbound" },
877 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
878 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
879 #ifdef DEBUG
880 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
881 #else
882 	{  0,	0,	0,	"" },
883 #endif
884 };
885 
886 /*
887  * Extended NDP table
888  * The addresses for the first two are filled in to be ips_ip_g_forward
889  * and ips_ipv6_forward at init time.
890  */
891 static ipndp_t	lcl_ndp_arr[] = {
892 	/* getf			setf		data			name */
893 #define	IPNDP_IP_FORWARDING_OFFSET	0
894 	{  ip_param_generic_get,	ip_forward_set,	NULL,
895 	    "ip_forwarding" },
896 #define	IPNDP_IP6_FORWARDING_OFFSET	1
897 	{  ip_param_generic_get,	ip_forward_set,	NULL,
898 	    "ip6_forwarding" },
899 	{  ip_ill_report,	NULL,		NULL,
900 	    "ip_ill_status" },
901 	{  ip_ipif_report,	NULL,		NULL,
902 	    "ip_ipif_status" },
903 	{  ip_ire_report,	NULL,		NULL,
904 	    "ipv4_ire_status" },
905 	{  ip_ire_report_v6,	NULL,		NULL,
906 	    "ipv6_ire_status" },
907 	{  ip_conn_report,	NULL,		NULL,
908 	    "ip_conn_status" },
909 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
910 	    "ip_rput_pullups" },
911 	{  ndp_report,		NULL,		NULL,
912 	    "ip_ndp_cache_report" },
913 	{  ip_srcid_report,	NULL,		NULL,
914 	    "ip_srcid_status" },
915 	{ ip_param_generic_get, ip_squeue_profile_set,
916 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
917 	{ ip_param_generic_get, ip_squeue_bind_set,
918 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
919 	{ ip_param_generic_get, ip_input_proc_set,
920 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
921 	{ ip_param_generic_get, ip_int_set,
922 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
923 #define	IPNDP_CGTP_FILTER_OFFSET	14
924 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
925 	    "ip_cgtp_filter" },
926 	{ ip_param_generic_get, ip_int_set,
927 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
928 #define	IPNDP_IPMP_HOOK_OFFSET	16
929 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
930 	    "ipmp_hook_emulation" },
931 };
932 
933 /*
934  * Table of IP ioctls encoding the various properties of the ioctl and
935  * indexed based on the last byte of the ioctl command. Occasionally there
936  * is a clash, and there is more than 1 ioctl with the same last byte.
937  * In such a case 1 ioctl is encoded in the ndx table and the remaining
938  * ioctls are encoded in the misc table. An entry in the ndx table is
939  * retrieved by indexing on the last byte of the ioctl command and comparing
940  * the ioctl command with the value in the ndx table. In the event of a
941  * mismatch the misc table is then searched sequentially for the desired
942  * ioctl command.
943  *
944  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
945  */
946 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
947 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 
958 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
959 			MISC_CMD, ip_siocaddrt, NULL },
960 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
961 			MISC_CMD, ip_siocdelrt, NULL },
962 
963 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
964 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
965 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
966 			IF_CMD, ip_sioctl_get_addr, NULL },
967 
968 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
969 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
970 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
971 			IPI_GET_CMD | IPI_REPL,
972 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
973 
974 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
975 			IPI_PRIV | IPI_WR | IPI_REPL,
976 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
977 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
978 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
979 			IF_CMD, ip_sioctl_get_flags, NULL },
980 
981 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
982 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
983 
984 	/* copyin size cannot be coded for SIOCGIFCONF */
985 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
986 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
987 
988 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
989 			IF_CMD, ip_sioctl_mtu, NULL },
990 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
991 			IF_CMD, ip_sioctl_get_mtu, NULL },
992 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
993 			IPI_GET_CMD | IPI_REPL,
994 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
995 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
996 			IF_CMD, ip_sioctl_brdaddr, NULL },
997 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
998 			IPI_GET_CMD | IPI_REPL,
999 			IF_CMD, ip_sioctl_get_netmask, NULL },
1000 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1001 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1002 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1003 			IPI_GET_CMD | IPI_REPL,
1004 			IF_CMD, ip_sioctl_get_metric, NULL },
1005 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1006 			IF_CMD, ip_sioctl_metric, NULL },
1007 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1008 
1009 	/* See 166-168 below for extended SIOC*XARP ioctls */
1010 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1011 			ARP_CMD, ip_sioctl_arp, NULL },
1012 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1013 			ARP_CMD, ip_sioctl_arp, NULL },
1014 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1015 			ARP_CMD, ip_sioctl_arp, NULL },
1016 
1017 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 
1039 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1040 			MISC_CMD, if_unitsel, if_unitsel_restart },
1041 
1042 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1062 			IPI_PRIV | IPI_WR | IPI_MODOK,
1063 			IF_CMD, ip_sioctl_sifname, NULL },
1064 
1065 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 
1079 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1080 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1081 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1082 			IF_CMD, ip_sioctl_get_muxid, NULL },
1083 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1084 			IPI_PRIV | IPI_WR | IPI_REPL,
1085 			IF_CMD, ip_sioctl_muxid, NULL },
1086 
1087 	/* Both if and lif variants share same func */
1088 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1089 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1090 	/* Both if and lif variants share same func */
1091 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1092 			IPI_PRIV | IPI_WR | IPI_REPL,
1093 			IF_CMD, ip_sioctl_slifindex, NULL },
1094 
1095 	/* copyin size cannot be coded for SIOCGIFCONF */
1096 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1097 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1098 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 
1116 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1117 			IPI_PRIV | IPI_WR | IPI_REPL,
1118 			LIF_CMD, ip_sioctl_removeif,
1119 			ip_sioctl_removeif_restart },
1120 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1121 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1122 			LIF_CMD, ip_sioctl_addif, NULL },
1123 #define	SIOCLIFADDR_NDX 112
1124 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1125 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1126 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1127 			IPI_GET_CMD | IPI_REPL,
1128 			LIF_CMD, ip_sioctl_get_addr, NULL },
1129 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1130 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1131 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1132 			IPI_GET_CMD | IPI_REPL,
1133 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1134 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1135 			IPI_PRIV | IPI_WR | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1137 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1138 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_get_flags, NULL },
1140 
1141 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 
1144 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1145 			ip_sioctl_get_lifconf, NULL },
1146 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1147 			LIF_CMD, ip_sioctl_mtu, NULL },
1148 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1149 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1150 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1151 			IPI_GET_CMD | IPI_REPL,
1152 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1153 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1154 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1155 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1156 			IPI_GET_CMD | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1158 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1159 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1160 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1161 			IPI_GET_CMD | IPI_REPL,
1162 			LIF_CMD, ip_sioctl_get_metric, NULL },
1163 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1164 			LIF_CMD, ip_sioctl_metric, NULL },
1165 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1166 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1167 			LIF_CMD, ip_sioctl_slifname,
1168 			ip_sioctl_slifname_restart },
1169 
1170 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1171 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1172 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1173 			IPI_GET_CMD | IPI_REPL,
1174 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1175 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1176 			IPI_PRIV | IPI_WR | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_muxid, NULL },
1178 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1179 			IPI_GET_CMD | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1181 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1182 			IPI_PRIV | IPI_WR | IPI_REPL,
1183 			LIF_CMD, ip_sioctl_slifindex, 0 },
1184 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1185 			LIF_CMD, ip_sioctl_token, NULL },
1186 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1187 			IPI_GET_CMD | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_get_token, NULL },
1189 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1190 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1191 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_REPL,
1193 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1194 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1195 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1196 
1197 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1198 			IPI_GET_CMD | IPI_REPL,
1199 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1200 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1201 			LIF_CMD, ip_siocdelndp_v6, NULL },
1202 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1203 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1204 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1205 			LIF_CMD, ip_siocsetndp_v6, NULL },
1206 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1207 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1208 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1209 			MISC_CMD, ip_sioctl_tonlink, NULL },
1210 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1211 			MISC_CMD, ip_sioctl_tmysite, NULL },
1212 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1213 			TUN_CMD, ip_sioctl_tunparam, NULL },
1214 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1215 			IPI_PRIV | IPI_WR,
1216 			TUN_CMD, ip_sioctl_tunparam, NULL },
1217 
1218 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1219 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1222 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 
1224 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1225 			IPI_PRIV | IPI_WR | IPI_REPL,
1226 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1227 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1228 			IPI_PRIV | IPI_WR | IPI_REPL,
1229 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1230 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR,
1232 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1233 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1234 			IPI_GET_CMD | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1236 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1237 			IPI_GET_CMD | IPI_REPL,
1238 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1239 
1240 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1241 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1242 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1243 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1244 
1245 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1246 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1247 
1248 	/* These are handled in ip_sioctl_copyin_setup itself */
1249 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1250 			MISC_CMD, NULL, NULL },
1251 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1252 			MISC_CMD, NULL, NULL },
1253 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1254 
1255 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1256 			ip_sioctl_get_lifconf, NULL },
1257 
1258 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1259 			XARP_CMD, ip_sioctl_arp, NULL },
1260 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1261 			XARP_CMD, ip_sioctl_arp, NULL },
1262 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1263 			XARP_CMD, ip_sioctl_arp, NULL },
1264 
1265 	/* SIOCPOPSOCKFS is not handled by IP */
1266 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1267 
1268 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1269 			IPI_GET_CMD | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1271 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1272 			IPI_PRIV | IPI_WR | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_slifzone,
1274 			ip_sioctl_slifzone_restart },
1275 	/* 172-174 are SCTP ioctls and not handled by IP */
1276 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1277 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1278 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1279 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1280 			IPI_GET_CMD, LIF_CMD,
1281 			ip_sioctl_get_lifusesrc, 0 },
1282 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1283 			IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_slifusesrc,
1285 			NULL },
1286 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1287 			ip_sioctl_get_lifsrcof, NULL },
1288 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1289 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1290 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1291 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1292 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1293 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1294 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1295 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1296 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1297 			ip_sioctl_set_ipmpfailback, NULL }
1298 };
1299 
1300 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1301 
1302 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1303 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1304 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1305 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1306 		TUN_CMD, ip_sioctl_tunparam, NULL },
1307 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1314 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1315 		MISC_CMD, mrt_ioctl},
1316 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1317 		MISC_CMD, mrt_ioctl},
1318 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1319 		MISC_CMD, mrt_ioctl}
1320 };
1321 
1322 int ip_misc_ioctl_count =
1323     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1324 
1325 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1326 					/* Settable in /etc/system */
1327 /* Defined in ip_ire.c */
1328 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1329 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1330 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1331 
1332 static nv_t	ire_nv_arr[] = {
1333 	{ IRE_BROADCAST, "BROADCAST" },
1334 	{ IRE_LOCAL, "LOCAL" },
1335 	{ IRE_LOOPBACK, "LOOPBACK" },
1336 	{ IRE_CACHE, "CACHE" },
1337 	{ IRE_DEFAULT, "DEFAULT" },
1338 	{ IRE_PREFIX, "PREFIX" },
1339 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1340 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1341 	{ IRE_HOST, "HOST" },
1342 	{ 0 }
1343 };
1344 
1345 nv_t	*ire_nv_tbl = ire_nv_arr;
1346 
1347 /* Defined in ip_netinfo.c */
1348 extern ddi_taskq_t	*eventq_queue_nic;
1349 
1350 /* Simple ICMP IP Header Template */
1351 static ipha_t icmp_ipha = {
1352 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1353 };
1354 
1355 struct module_info ip_mod_info = {
1356 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1357 };
1358 
1359 /*
1360  * Duplicate static symbols within a module confuses mdb; so we avoid the
1361  * problem by making the symbols here distinct from those in udp.c.
1362  */
1363 
1364 /*
1365  * Entry points for IP as a device and as a module.
1366  * FIXME: down the road we might want a separate module and driver qinit.
1367  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1368  */
1369 static struct qinit iprinitv4 = {
1370 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1371 	&ip_mod_info
1372 };
1373 
1374 struct qinit iprinitv6 = {
1375 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1376 	&ip_mod_info
1377 };
1378 
1379 static struct qinit ipwinitv4 = {
1380 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1381 	&ip_mod_info
1382 };
1383 
1384 struct qinit ipwinitv6 = {
1385 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1386 	&ip_mod_info
1387 };
1388 
1389 static struct qinit iplrinit = {
1390 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1391 	&ip_mod_info
1392 };
1393 
1394 static struct qinit iplwinit = {
1395 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1396 	&ip_mod_info
1397 };
1398 
1399 /* For AF_INET aka /dev/ip */
1400 struct streamtab ipinfov4 = {
1401 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1402 };
1403 
1404 /* For AF_INET6 aka /dev/ip6 */
1405 struct streamtab ipinfov6 = {
1406 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1407 };
1408 
1409 #ifdef	DEBUG
1410 static boolean_t skip_sctp_cksum = B_FALSE;
1411 #endif
1412 
1413 /*
1414  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1415  * ip_rput_v6(), ip_output(), etc.  If the message
1416  * block already has a M_CTL at the front of it, then simply set the zoneid
1417  * appropriately.
1418  */
1419 mblk_t *
1420 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1421 {
1422 	mblk_t		*first_mp;
1423 	ipsec_out_t	*io;
1424 
1425 	ASSERT(zoneid != ALL_ZONES);
1426 	if (mp->b_datap->db_type == M_CTL) {
1427 		io = (ipsec_out_t *)mp->b_rptr;
1428 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1429 		io->ipsec_out_zoneid = zoneid;
1430 		return (mp);
1431 	}
1432 
1433 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1434 	if (first_mp == NULL)
1435 		return (NULL);
1436 	io = (ipsec_out_t *)first_mp->b_rptr;
1437 	/* This is not a secure packet */
1438 	io->ipsec_out_secure = B_FALSE;
1439 	io->ipsec_out_zoneid = zoneid;
1440 	first_mp->b_cont = mp;
1441 	return (first_mp);
1442 }
1443 
1444 /*
1445  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1446  */
1447 mblk_t *
1448 ip_copymsg(mblk_t *mp)
1449 {
1450 	mblk_t *nmp;
1451 	ipsec_info_t *in;
1452 
1453 	if (mp->b_datap->db_type != M_CTL)
1454 		return (copymsg(mp));
1455 
1456 	in = (ipsec_info_t *)mp->b_rptr;
1457 
1458 	/*
1459 	 * Note that M_CTL is also used for delivering ICMP error messages
1460 	 * upstream to transport layers.
1461 	 */
1462 	if (in->ipsec_info_type != IPSEC_OUT &&
1463 	    in->ipsec_info_type != IPSEC_IN)
1464 		return (copymsg(mp));
1465 
1466 	nmp = copymsg(mp->b_cont);
1467 
1468 	if (in->ipsec_info_type == IPSEC_OUT) {
1469 		return (ipsec_out_tag(mp, nmp,
1470 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1471 	} else {
1472 		return (ipsec_in_tag(mp, nmp,
1473 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1474 	}
1475 }
1476 
1477 /* Generate an ICMP fragmentation needed message. */
1478 static void
1479 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1480     ip_stack_t *ipst)
1481 {
1482 	icmph_t	icmph;
1483 	mblk_t *first_mp;
1484 	boolean_t mctl_present;
1485 
1486 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1487 
1488 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1489 		if (mctl_present)
1490 			freeb(first_mp);
1491 		return;
1492 	}
1493 
1494 	bzero(&icmph, sizeof (icmph_t));
1495 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1496 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1497 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1498 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1499 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1500 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1501 	    ipst);
1502 }
1503 
1504 /*
1505  * icmp_inbound deals with ICMP messages in the following ways.
1506  *
1507  * 1) It needs to send a reply back and possibly delivering it
1508  *    to the "interested" upper clients.
1509  * 2) It needs to send it to the upper clients only.
1510  * 3) It needs to change some values in IP only.
1511  * 4) It needs to change some values in IP and upper layers e.g TCP.
1512  *
1513  * We need to accomodate icmp messages coming in clear until we get
1514  * everything secure from the wire. If icmp_accept_clear_messages
1515  * is zero we check with the global policy and act accordingly. If
1516  * it is non-zero, we accept the message without any checks. But
1517  * *this does not mean* that this will be delivered to the upper
1518  * clients. By accepting we might send replies back, change our MTU
1519  * value etc. but delivery to the ULP/clients depends on their policy
1520  * dispositions.
1521  *
1522  * We handle the above 4 cases in the context of IPsec in the
1523  * following way :
1524  *
1525  * 1) Send the reply back in the same way as the request came in.
1526  *    If it came in encrypted, it goes out encrypted. If it came in
1527  *    clear, it goes out in clear. Thus, this will prevent chosen
1528  *    plain text attack.
1529  * 2) The client may or may not expect things to come in secure.
1530  *    If it comes in secure, the policy constraints are checked
1531  *    before delivering it to the upper layers. If it comes in
1532  *    clear, ipsec_inbound_accept_clear will decide whether to
1533  *    accept this in clear or not. In both the cases, if the returned
1534  *    message (IP header + 8 bytes) that caused the icmp message has
1535  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1536  *    sending up. If there are only 8 bytes of returned message, then
1537  *    upper client will not be notified.
1538  * 3) Check with global policy to see whether it matches the constaints.
1539  *    But this will be done only if icmp_accept_messages_in_clear is
1540  *    zero.
1541  * 4) If we need to change both in IP and ULP, then the decision taken
1542  *    while affecting the values in IP and while delivering up to TCP
1543  *    should be the same.
1544  *
1545  * 	There are two cases.
1546  *
1547  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1548  *	   failed), we will not deliver it to the ULP, even though they
1549  *	   are *willing* to accept in *clear*. This is fine as our global
1550  *	   disposition to icmp messages asks us reject the datagram.
1551  *
1552  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1553  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1554  *	   to deliver it to ULP (policy failed), it can lead to
1555  *	   consistency problems. The cases known at this time are
1556  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1557  *	   values :
1558  *
1559  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1560  *	     and Upper layer rejects. Then the communication will
1561  *	     come to a stop. This is solved by making similar decisions
1562  *	     at both levels. Currently, when we are unable to deliver
1563  *	     to the Upper Layer (due to policy failures) while IP has
1564  *	     adjusted ire_max_frag, the next outbound datagram would
1565  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1566  *	     will be with the right level of protection. Thus the right
1567  *	     value will be communicated even if we are not able to
1568  *	     communicate when we get from the wire initially. But this
1569  *	     assumes there would be at least one outbound datagram after
1570  *	     IP has adjusted its ire_max_frag value. To make things
1571  *	     simpler, we accept in clear after the validation of
1572  *	     AH/ESP headers.
1573  *
1574  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1575  *	     upper layer depending on the level of protection the upper
1576  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1577  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1578  *	     should be accepted in clear when the Upper layer expects secure.
1579  *	     Thus the communication may get aborted by some bad ICMP
1580  *	     packets.
1581  *
1582  * IPQoS Notes:
1583  * The only instance when a packet is sent for processing is when there
1584  * isn't an ICMP client and if we are interested in it.
1585  * If there is a client, IPPF processing will take place in the
1586  * ip_fanout_proto routine.
1587  *
1588  * Zones notes:
1589  * The packet is only processed in the context of the specified zone: typically
1590  * only this zone will reply to an echo request, and only interested clients in
1591  * this zone will receive a copy of the packet. This means that the caller must
1592  * call icmp_inbound() for each relevant zone.
1593  */
1594 static void
1595 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1596     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1597     ill_t *recv_ill, zoneid_t zoneid)
1598 {
1599 	icmph_t	*icmph;
1600 	ipha_t	*ipha;
1601 	int	iph_hdr_length;
1602 	int	hdr_length;
1603 	boolean_t	interested;
1604 	uint32_t	ts;
1605 	uchar_t	*wptr;
1606 	ipif_t	*ipif;
1607 	mblk_t *first_mp;
1608 	ipsec_in_t *ii;
1609 	ire_t *src_ire;
1610 	boolean_t onlink;
1611 	timestruc_t now;
1612 	uint32_t ill_index;
1613 	ip_stack_t *ipst;
1614 
1615 	ASSERT(ill != NULL);
1616 	ipst = ill->ill_ipst;
1617 
1618 	first_mp = mp;
1619 	if (mctl_present) {
1620 		mp = first_mp->b_cont;
1621 		ASSERT(mp != NULL);
1622 	}
1623 
1624 	ipha = (ipha_t *)mp->b_rptr;
1625 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1626 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1627 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1628 		if (first_mp == NULL)
1629 			return;
1630 	}
1631 
1632 	/*
1633 	 * On a labeled system, we have to check whether the zone itself is
1634 	 * permitted to receive raw traffic.
1635 	 */
1636 	if (is_system_labeled()) {
1637 		if (zoneid == ALL_ZONES)
1638 			zoneid = tsol_packet_to_zoneid(mp);
1639 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1640 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1641 			    zoneid));
1642 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1643 			freemsg(first_mp);
1644 			return;
1645 		}
1646 	}
1647 
1648 	/*
1649 	 * We have accepted the ICMP message. It means that we will
1650 	 * respond to the packet if needed. It may not be delivered
1651 	 * to the upper client depending on the policy constraints
1652 	 * and the disposition in ipsec_inbound_accept_clear.
1653 	 */
1654 
1655 	ASSERT(ill != NULL);
1656 
1657 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1658 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1659 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1660 		/* Last chance to get real. */
1661 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1662 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1663 			freemsg(first_mp);
1664 			return;
1665 		}
1666 		/* Refresh iph following the pullup. */
1667 		ipha = (ipha_t *)mp->b_rptr;
1668 	}
1669 	/* ICMP header checksum, including checksum field, should be zero. */
1670 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1671 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1672 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1673 		freemsg(first_mp);
1674 		return;
1675 	}
1676 	/* The IP header will always be a multiple of four bytes */
1677 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1678 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1679 	    icmph->icmph_code));
1680 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1681 	/* We will set "interested" to "true" if we want a copy */
1682 	interested = B_FALSE;
1683 	switch (icmph->icmph_type) {
1684 	case ICMP_ECHO_REPLY:
1685 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1686 		break;
1687 	case ICMP_DEST_UNREACHABLE:
1688 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1689 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1690 		interested = B_TRUE;	/* Pass up to transport */
1691 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1692 		break;
1693 	case ICMP_SOURCE_QUENCH:
1694 		interested = B_TRUE;	/* Pass up to transport */
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1696 		break;
1697 	case ICMP_REDIRECT:
1698 		if (!ipst->ips_ip_ignore_redirect)
1699 			interested = B_TRUE;
1700 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1701 		break;
1702 	case ICMP_ECHO_REQUEST:
1703 		/*
1704 		 * Whether to respond to echo requests that come in as IP
1705 		 * broadcasts or as IP multicast is subject to debate
1706 		 * (what isn't?).  We aim to please, you pick it.
1707 		 * Default is do it.
1708 		 */
1709 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1710 			/* unicast: always respond */
1711 			interested = B_TRUE;
1712 		} else if (CLASSD(ipha->ipha_dst)) {
1713 			/* multicast: respond based on tunable */
1714 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1715 		} else if (broadcast) {
1716 			/* broadcast: respond based on tunable */
1717 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1718 		}
1719 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1720 		break;
1721 	case ICMP_ROUTER_ADVERTISEMENT:
1722 	case ICMP_ROUTER_SOLICITATION:
1723 		break;
1724 	case ICMP_TIME_EXCEEDED:
1725 		interested = B_TRUE;	/* Pass up to transport */
1726 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1727 		break;
1728 	case ICMP_PARAM_PROBLEM:
1729 		interested = B_TRUE;	/* Pass up to transport */
1730 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1731 		break;
1732 	case ICMP_TIME_STAMP_REQUEST:
1733 		/* Response to Time Stamp Requests is local policy. */
1734 		if (ipst->ips_ip_g_resp_to_timestamp &&
1735 		    /* So is whether to respond if it was an IP broadcast. */
1736 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1737 			int tstamp_len = 3 * sizeof (uint32_t);
1738 
1739 			if (wptr +  tstamp_len > mp->b_wptr) {
1740 				if (!pullupmsg(mp, wptr + tstamp_len -
1741 				    mp->b_rptr)) {
1742 					BUMP_MIB(ill->ill_ip_mib,
1743 					    ipIfStatsInDiscards);
1744 					freemsg(first_mp);
1745 					return;
1746 				}
1747 				/* Refresh ipha following the pullup. */
1748 				ipha = (ipha_t *)mp->b_rptr;
1749 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1750 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1751 			}
1752 			interested = B_TRUE;
1753 		}
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1755 		break;
1756 	case ICMP_TIME_STAMP_REPLY:
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1758 		break;
1759 	case ICMP_INFO_REQUEST:
1760 		/* Per RFC 1122 3.2.2.7, ignore this. */
1761 	case ICMP_INFO_REPLY:
1762 		break;
1763 	case ICMP_ADDRESS_MASK_REQUEST:
1764 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1765 		    !broadcast) &&
1766 		    /* TODO m_pullup of complete header? */
1767 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1768 			interested = B_TRUE;
1769 		}
1770 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1771 		break;
1772 	case ICMP_ADDRESS_MASK_REPLY:
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1774 		break;
1775 	default:
1776 		interested = B_TRUE;	/* Pass up to transport */
1777 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1778 		break;
1779 	}
1780 	/* See if there is an ICMP client. */
1781 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1782 		/* If there is an ICMP client and we want one too, copy it. */
1783 		mblk_t *first_mp1;
1784 
1785 		if (!interested) {
1786 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1787 			    ip_policy, recv_ill, zoneid);
1788 			return;
1789 		}
1790 		first_mp1 = ip_copymsg(first_mp);
1791 		if (first_mp1 != NULL) {
1792 			ip_fanout_proto(q, first_mp1, ill, ipha,
1793 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1794 		}
1795 	} else if (!interested) {
1796 		freemsg(first_mp);
1797 		return;
1798 	} else {
1799 		/*
1800 		 * Initiate policy processing for this packet if ip_policy
1801 		 * is true.
1802 		 */
1803 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1804 			ill_index = ill->ill_phyint->phyint_ifindex;
1805 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1806 			if (mp == NULL) {
1807 				if (mctl_present) {
1808 					freeb(first_mp);
1809 				}
1810 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1811 				return;
1812 			}
1813 		}
1814 	}
1815 	/* We want to do something with it. */
1816 	/* Check db_ref to make sure we can modify the packet. */
1817 	if (mp->b_datap->db_ref > 1) {
1818 		mblk_t	*first_mp1;
1819 
1820 		first_mp1 = ip_copymsg(first_mp);
1821 		freemsg(first_mp);
1822 		if (!first_mp1) {
1823 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1824 			return;
1825 		}
1826 		first_mp = first_mp1;
1827 		if (mctl_present) {
1828 			mp = first_mp->b_cont;
1829 			ASSERT(mp != NULL);
1830 		} else {
1831 			mp = first_mp;
1832 		}
1833 		ipha = (ipha_t *)mp->b_rptr;
1834 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1835 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1836 	}
1837 	switch (icmph->icmph_type) {
1838 	case ICMP_ADDRESS_MASK_REQUEST:
1839 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1840 		if (ipif == NULL) {
1841 			freemsg(first_mp);
1842 			return;
1843 		}
1844 		/*
1845 		 * outging interface must be IPv4
1846 		 */
1847 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1848 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1849 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1850 		ipif_refrele(ipif);
1851 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1852 		break;
1853 	case ICMP_ECHO_REQUEST:
1854 		icmph->icmph_type = ICMP_ECHO_REPLY;
1855 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1856 		break;
1857 	case ICMP_TIME_STAMP_REQUEST: {
1858 		uint32_t *tsp;
1859 
1860 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1861 		tsp = (uint32_t *)wptr;
1862 		tsp++;		/* Skip past 'originate time' */
1863 		/* Compute # of milliseconds since midnight */
1864 		gethrestime(&now);
1865 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1866 		    now.tv_nsec / (NANOSEC / MILLISEC);
1867 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1868 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1869 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1870 		break;
1871 	}
1872 	default:
1873 		ipha = (ipha_t *)&icmph[1];
1874 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1875 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1876 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1877 				freemsg(first_mp);
1878 				return;
1879 			}
1880 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1881 			ipha = (ipha_t *)&icmph[1];
1882 		}
1883 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1884 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1885 			freemsg(first_mp);
1886 			return;
1887 		}
1888 		hdr_length = IPH_HDR_LENGTH(ipha);
1889 		if (hdr_length < sizeof (ipha_t)) {
1890 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1891 			freemsg(first_mp);
1892 			return;
1893 		}
1894 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1895 			if (!pullupmsg(mp,
1896 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1897 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1898 				freemsg(first_mp);
1899 				return;
1900 			}
1901 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1902 			ipha = (ipha_t *)&icmph[1];
1903 		}
1904 		switch (icmph->icmph_type) {
1905 		case ICMP_REDIRECT:
1906 			/*
1907 			 * As there is no upper client to deliver, we don't
1908 			 * need the first_mp any more.
1909 			 */
1910 			if (mctl_present) {
1911 				freeb(first_mp);
1912 			}
1913 			icmp_redirect(ill, mp);
1914 			return;
1915 		case ICMP_DEST_UNREACHABLE:
1916 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1917 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1918 				    zoneid, mp, iph_hdr_length, ipst)) {
1919 					freemsg(first_mp);
1920 					return;
1921 				}
1922 				/*
1923 				 * icmp_inbound_too_big() may alter mp.
1924 				 * Resynch ipha and icmph accordingly.
1925 				 */
1926 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1927 				ipha = (ipha_t *)&icmph[1];
1928 			}
1929 			/* FALLTHRU */
1930 		default :
1931 			/*
1932 			 * IPQoS notes: Since we have already done IPQoS
1933 			 * processing we don't want to do it again in
1934 			 * the fanout routines called by
1935 			 * icmp_inbound_error_fanout, hence the last
1936 			 * argument, ip_policy, is B_FALSE.
1937 			 */
1938 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1939 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1940 			    B_FALSE, recv_ill, zoneid);
1941 		}
1942 		return;
1943 	}
1944 	/* Send out an ICMP packet */
1945 	icmph->icmph_checksum = 0;
1946 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1947 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1948 		ipif_t	*ipif_chosen;
1949 		/*
1950 		 * Make it look like it was directed to us, so we don't look
1951 		 * like a fool with a broadcast or multicast source address.
1952 		 */
1953 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1954 		/*
1955 		 * Make sure that we haven't grabbed an interface that's DOWN.
1956 		 */
1957 		if (ipif != NULL) {
1958 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1959 			    ipha->ipha_src, zoneid);
1960 			if (ipif_chosen != NULL) {
1961 				ipif_refrele(ipif);
1962 				ipif = ipif_chosen;
1963 			}
1964 		}
1965 		if (ipif == NULL) {
1966 			ip0dbg(("icmp_inbound: "
1967 			    "No source for broadcast/multicast:\n"
1968 			    "\tsrc 0x%x dst 0x%x ill %p "
1969 			    "ipif_lcl_addr 0x%x\n",
1970 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1971 			    (void *)ill,
1972 			    ill->ill_ipif->ipif_lcl_addr));
1973 			freemsg(first_mp);
1974 			return;
1975 		}
1976 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1977 		ipha->ipha_dst = ipif->ipif_src_addr;
1978 		ipif_refrele(ipif);
1979 	}
1980 	/* Reset time to live. */
1981 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1982 	{
1983 		/* Swap source and destination addresses */
1984 		ipaddr_t tmp;
1985 
1986 		tmp = ipha->ipha_src;
1987 		ipha->ipha_src = ipha->ipha_dst;
1988 		ipha->ipha_dst = tmp;
1989 	}
1990 	ipha->ipha_ident = 0;
1991 	if (!IS_SIMPLE_IPH(ipha))
1992 		icmp_options_update(ipha);
1993 
1994 	/*
1995 	 * ICMP echo replies should go out on the same interface
1996 	 * the request came on as probes used by in.mpathd for detecting
1997 	 * NIC failures are ECHO packets. We turn-off load spreading
1998 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1999 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2000 	 * function. This is in turn handled by ip_wput and ip_newroute
2001 	 * to make sure that the packet goes out on the interface it came
2002 	 * in on. If we don't turnoff load spreading, the packets might get
2003 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2004 	 * to go out and in.mpathd would wrongly detect a failure or
2005 	 * mis-detect a NIC failure for link failure. As load spreading
2006 	 * can happen only if ill_group is not NULL, we do only for
2007 	 * that case and this does not affect the normal case.
2008 	 *
2009 	 * We turn off load spreading only on echo packets that came from
2010 	 * on-link hosts. If the interface route has been deleted, this will
2011 	 * not be enforced as we can't do much. For off-link hosts, as the
2012 	 * default routes in IPv4 does not typically have an ire_ipif
2013 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2014 	 * Moreover, expecting a default route through this interface may
2015 	 * not be correct. We use ipha_dst because of the swap above.
2016 	 */
2017 	onlink = B_FALSE;
2018 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2019 		/*
2020 		 * First, we need to make sure that it is not one of our
2021 		 * local addresses. If we set onlink when it is one of
2022 		 * our local addresses, we will end up creating IRE_CACHES
2023 		 * for one of our local addresses. Then, we will never
2024 		 * accept packets for them afterwards.
2025 		 */
2026 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2027 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2028 		if (src_ire == NULL) {
2029 			ipif = ipif_get_next_ipif(NULL, ill);
2030 			if (ipif == NULL) {
2031 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2032 				freemsg(mp);
2033 				return;
2034 			}
2035 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2036 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2037 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2038 			ipif_refrele(ipif);
2039 			if (src_ire != NULL) {
2040 				onlink = B_TRUE;
2041 				ire_refrele(src_ire);
2042 			}
2043 		} else {
2044 			ire_refrele(src_ire);
2045 		}
2046 	}
2047 	if (!mctl_present) {
2048 		/*
2049 		 * This packet should go out the same way as it
2050 		 * came in i.e in clear. To make sure that global
2051 		 * policy will not be applied to this in ip_wput_ire,
2052 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2053 		 */
2054 		ASSERT(first_mp == mp);
2055 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2056 		if (first_mp == NULL) {
2057 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2058 			freemsg(mp);
2059 			return;
2060 		}
2061 		ii = (ipsec_in_t *)first_mp->b_rptr;
2062 
2063 		/* This is not a secure packet */
2064 		ii->ipsec_in_secure = B_FALSE;
2065 		if (onlink) {
2066 			ii->ipsec_in_attach_if = B_TRUE;
2067 			ii->ipsec_in_ill_index =
2068 			    ill->ill_phyint->phyint_ifindex;
2069 			ii->ipsec_in_rill_index =
2070 			    recv_ill->ill_phyint->phyint_ifindex;
2071 		}
2072 		first_mp->b_cont = mp;
2073 	} else if (onlink) {
2074 		ii = (ipsec_in_t *)first_mp->b_rptr;
2075 		ii->ipsec_in_attach_if = B_TRUE;
2076 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2077 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2078 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2079 	} else {
2080 		ii = (ipsec_in_t *)first_mp->b_rptr;
2081 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2082 	}
2083 	ii->ipsec_in_zoneid = zoneid;
2084 	ASSERT(zoneid != ALL_ZONES);
2085 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2086 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2087 		return;
2088 	}
2089 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2090 	put(WR(q), first_mp);
2091 }
2092 
2093 static ipaddr_t
2094 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2095 {
2096 	conn_t *connp;
2097 	connf_t *connfp;
2098 	ipaddr_t nexthop_addr = INADDR_ANY;
2099 	int hdr_length = IPH_HDR_LENGTH(ipha);
2100 	uint16_t *up;
2101 	uint32_t ports;
2102 	ip_stack_t *ipst = ill->ill_ipst;
2103 
2104 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2105 	switch (ipha->ipha_protocol) {
2106 		case IPPROTO_TCP:
2107 		{
2108 			tcph_t *tcph;
2109 
2110 			/* do a reverse lookup */
2111 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2112 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2113 			    TCPS_LISTEN, ipst);
2114 			break;
2115 		}
2116 		case IPPROTO_UDP:
2117 		{
2118 			uint32_t dstport, srcport;
2119 
2120 			((uint16_t *)&ports)[0] = up[1];
2121 			((uint16_t *)&ports)[1] = up[0];
2122 
2123 			/* Extract ports in net byte order */
2124 			dstport = htons(ntohl(ports) & 0xFFFF);
2125 			srcport = htons(ntohl(ports) >> 16);
2126 
2127 			connfp = &ipst->ips_ipcl_udp_fanout[
2128 			    IPCL_UDP_HASH(dstport, ipst)];
2129 			mutex_enter(&connfp->connf_lock);
2130 			connp = connfp->connf_head;
2131 
2132 			/* do a reverse lookup */
2133 			while ((connp != NULL) &&
2134 			    (!IPCL_UDP_MATCH(connp, dstport,
2135 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2136 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2137 				connp = connp->conn_next;
2138 			}
2139 			if (connp != NULL)
2140 				CONN_INC_REF(connp);
2141 			mutex_exit(&connfp->connf_lock);
2142 			break;
2143 		}
2144 		case IPPROTO_SCTP:
2145 		{
2146 			in6_addr_t map_src, map_dst;
2147 
2148 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2149 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2150 			((uint16_t *)&ports)[0] = up[1];
2151 			((uint16_t *)&ports)[1] = up[0];
2152 
2153 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2154 			    zoneid, ipst->ips_netstack->netstack_sctp);
2155 			if (connp == NULL) {
2156 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2157 				    zoneid, ports, ipha, ipst);
2158 			} else {
2159 				CONN_INC_REF(connp);
2160 				SCTP_REFRELE(CONN2SCTP(connp));
2161 			}
2162 			break;
2163 		}
2164 		default:
2165 		{
2166 			ipha_t ripha;
2167 
2168 			ripha.ipha_src = ipha->ipha_dst;
2169 			ripha.ipha_dst = ipha->ipha_src;
2170 			ripha.ipha_protocol = ipha->ipha_protocol;
2171 
2172 			connfp = &ipst->ips_ipcl_proto_fanout[
2173 			    ipha->ipha_protocol];
2174 			mutex_enter(&connfp->connf_lock);
2175 			connp = connfp->connf_head;
2176 			for (connp = connfp->connf_head; connp != NULL;
2177 			    connp = connp->conn_next) {
2178 				if (IPCL_PROTO_MATCH(connp,
2179 				    ipha->ipha_protocol, &ripha, ill,
2180 				    0, zoneid)) {
2181 					CONN_INC_REF(connp);
2182 					break;
2183 				}
2184 			}
2185 			mutex_exit(&connfp->connf_lock);
2186 		}
2187 	}
2188 	if (connp != NULL) {
2189 		if (connp->conn_nexthop_set)
2190 			nexthop_addr = connp->conn_nexthop_v4;
2191 		CONN_DEC_REF(connp);
2192 	}
2193 	return (nexthop_addr);
2194 }
2195 
2196 /* Table from RFC 1191 */
2197 static int icmp_frag_size_table[] =
2198 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2199 
2200 /*
2201  * Process received ICMP Packet too big.
2202  * After updating any IRE it does the fanout to any matching transport streams.
2203  * Assumes the message has been pulled up till the IP header that caused
2204  * the error.
2205  *
2206  * Returns B_FALSE on failure and B_TRUE on success.
2207  */
2208 static boolean_t
2209 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2210     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2211     ip_stack_t *ipst)
2212 {
2213 	ire_t	*ire, *first_ire;
2214 	int	mtu;
2215 	int	hdr_length;
2216 	ipaddr_t nexthop_addr;
2217 
2218 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2219 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2220 	ASSERT(ill != NULL);
2221 
2222 	hdr_length = IPH_HDR_LENGTH(ipha);
2223 
2224 	/* Drop if the original packet contained a source route */
2225 	if (ip_source_route_included(ipha)) {
2226 		return (B_FALSE);
2227 	}
2228 	/*
2229 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2230 	 * header.
2231 	 */
2232 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2233 	    mp->b_wptr) {
2234 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2235 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2236 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2237 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2238 			return (B_FALSE);
2239 		}
2240 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2241 		ipha = (ipha_t *)&icmph[1];
2242 	}
2243 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2244 	if (nexthop_addr != INADDR_ANY) {
2245 		/* nexthop set */
2246 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2247 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2248 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2249 	} else {
2250 		/* nexthop not set */
2251 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2252 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2253 	}
2254 
2255 	if (!first_ire) {
2256 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2257 		    ntohl(ipha->ipha_dst)));
2258 		return (B_FALSE);
2259 	}
2260 	/* Check for MTU discovery advice as described in RFC 1191 */
2261 	mtu = ntohs(icmph->icmph_du_mtu);
2262 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2263 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2264 	    ire = ire->ire_next) {
2265 		/*
2266 		 * Look for the connection to which this ICMP message is
2267 		 * directed. If it has the IP_NEXTHOP option set, then the
2268 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2269 		 * option. Else the search is limited to regular IREs.
2270 		 */
2271 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2272 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2273 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2274 		    (nexthop_addr != INADDR_ANY)))
2275 			continue;
2276 
2277 		mutex_enter(&ire->ire_lock);
2278 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2279 			/* Reduce the IRE max frag value as advised. */
2280 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2281 			    mtu, ire->ire_max_frag));
2282 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2283 		} else {
2284 			uint32_t length;
2285 			int	i;
2286 
2287 			/*
2288 			 * Use the table from RFC 1191 to figure out
2289 			 * the next "plateau" based on the length in
2290 			 * the original IP packet.
2291 			 */
2292 			length = ntohs(ipha->ipha_length);
2293 			if (ire->ire_max_frag <= length &&
2294 			    ire->ire_max_frag >= length - hdr_length) {
2295 				/*
2296 				 * Handle broken BSD 4.2 systems that
2297 				 * return the wrong iph_length in ICMP
2298 				 * errors.
2299 				 */
2300 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2301 				    length, ire->ire_max_frag));
2302 				length -= hdr_length;
2303 			}
2304 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2305 				if (length > icmp_frag_size_table[i])
2306 					break;
2307 			}
2308 			if (i == A_CNT(icmp_frag_size_table)) {
2309 				/* Smaller than 68! */
2310 				ip1dbg(("Too big for packet size %d\n",
2311 				    length));
2312 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2313 				ire->ire_frag_flag = 0;
2314 			} else {
2315 				mtu = icmp_frag_size_table[i];
2316 				ip1dbg(("Calculated mtu %d, packet size %d, "
2317 				    "before %d", mtu, length,
2318 				    ire->ire_max_frag));
2319 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2320 				ip1dbg((", after %d\n", ire->ire_max_frag));
2321 			}
2322 			/* Record the new max frag size for the ULP. */
2323 			icmph->icmph_du_zero = 0;
2324 			icmph->icmph_du_mtu =
2325 			    htons((uint16_t)ire->ire_max_frag);
2326 		}
2327 		mutex_exit(&ire->ire_lock);
2328 	}
2329 	rw_exit(&first_ire->ire_bucket->irb_lock);
2330 	ire_refrele(first_ire);
2331 	return (B_TRUE);
2332 }
2333 
2334 /*
2335  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2336  * calls this function.
2337  */
2338 static mblk_t *
2339 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2340 {
2341 	ipha_t *ipha;
2342 	icmph_t *icmph;
2343 	ipha_t *in_ipha;
2344 	int length;
2345 
2346 	ASSERT(mp->b_datap->db_type == M_DATA);
2347 
2348 	/*
2349 	 * For Self-encapsulated packets, we added an extra IP header
2350 	 * without the options. Inner IP header is the one from which
2351 	 * the outer IP header was formed. Thus, we need to remove the
2352 	 * outer IP header. To do this, we pullup the whole message
2353 	 * and overlay whatever follows the outer IP header over the
2354 	 * outer IP header.
2355 	 */
2356 
2357 	if (!pullupmsg(mp, -1))
2358 		return (NULL);
2359 
2360 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2361 	ipha = (ipha_t *)&icmph[1];
2362 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2363 
2364 	/*
2365 	 * The length that we want to overlay is following the inner
2366 	 * IP header. Subtracting the IP header + icmp header + outer
2367 	 * IP header's length should give us the length that we want to
2368 	 * overlay.
2369 	 */
2370 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2371 	    hdr_length;
2372 	/*
2373 	 * Overlay whatever follows the inner header over the
2374 	 * outer header.
2375 	 */
2376 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2377 
2378 	/* Set the wptr to account for the outer header */
2379 	mp->b_wptr -= hdr_length;
2380 	return (mp);
2381 }
2382 
2383 /*
2384  * Try to pass the ICMP message upstream in case the ULP cares.
2385  *
2386  * If the packet that caused the ICMP error is secure, we send
2387  * it to AH/ESP to make sure that the attached packet has a
2388  * valid association. ipha in the code below points to the
2389  * IP header of the packet that caused the error.
2390  *
2391  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2392  * in the context of IPsec. Normally we tell the upper layer
2393  * whenever we send the ire (including ip_bind), the IPsec header
2394  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2395  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2396  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2397  * same thing. As TCP has the IPsec options size that needs to be
2398  * adjusted, we just pass the MTU unchanged.
2399  *
2400  * IFN could have been generated locally or by some router.
2401  *
2402  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2403  *	    This happens because IP adjusted its value of MTU on an
2404  *	    earlier IFN message and could not tell the upper layer,
2405  *	    the new adjusted value of MTU e.g. Packet was encrypted
2406  *	    or there was not enough information to fanout to upper
2407  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2408  *	    generates the IFN, where IPsec processing has *not* been
2409  *	    done.
2410  *
2411  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2412  *	    could have generated this. This happens because ire_max_frag
2413  *	    value in IP was set to a new value, while the IPsec processing
2414  *	    was being done and after we made the fragmentation check in
2415  *	    ip_wput_ire. Thus on return from IPsec processing,
2416  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2417  *	    and generates the IFN. As IPsec processing is over, we fanout
2418  *	    to AH/ESP to remove the header.
2419  *
2420  *	    In both these cases, ipsec_in_loopback will be set indicating
2421  *	    that IFN was generated locally.
2422  *
2423  * ROUTER : IFN could be secure or non-secure.
2424  *
2425  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2426  *	      packet in error has AH/ESP headers to validate the AH/ESP
2427  *	      headers. AH/ESP will verify whether there is a valid SA or
2428  *	      not and send it back. We will fanout again if we have more
2429  *	      data in the packet.
2430  *
2431  *	      If the packet in error does not have AH/ESP, we handle it
2432  *	      like any other case.
2433  *
2434  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2435  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2436  *	      for validation. AH/ESP will verify whether there is a
2437  *	      valid SA or not and send it back. We will fanout again if
2438  *	      we have more data in the packet.
2439  *
2440  *	      If the packet in error does not have AH/ESP, we handle it
2441  *	      like any other case.
2442  */
2443 static void
2444 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2445     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2446     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2447     zoneid_t zoneid)
2448 {
2449 	uint16_t *up;	/* Pointer to ports in ULP header */
2450 	uint32_t ports;	/* reversed ports for fanout */
2451 	ipha_t ripha;	/* With reversed addresses */
2452 	mblk_t *first_mp;
2453 	ipsec_in_t *ii;
2454 	tcph_t	*tcph;
2455 	conn_t	*connp;
2456 	ip_stack_t *ipst;
2457 
2458 	ASSERT(ill != NULL);
2459 
2460 	ASSERT(recv_ill != NULL);
2461 	ipst = recv_ill->ill_ipst;
2462 
2463 	first_mp = mp;
2464 	if (mctl_present) {
2465 		mp = first_mp->b_cont;
2466 		ASSERT(mp != NULL);
2467 
2468 		ii = (ipsec_in_t *)first_mp->b_rptr;
2469 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2470 	} else {
2471 		ii = NULL;
2472 	}
2473 
2474 	switch (ipha->ipha_protocol) {
2475 	case IPPROTO_UDP:
2476 		/*
2477 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2478 		 * transport header.
2479 		 */
2480 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2481 		    mp->b_wptr) {
2482 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2483 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2484 				goto discard_pkt;
2485 			}
2486 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2487 			ipha = (ipha_t *)&icmph[1];
2488 		}
2489 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2490 
2491 		/*
2492 		 * Attempt to find a client stream based on port.
2493 		 * Note that we do a reverse lookup since the header is
2494 		 * in the form we sent it out.
2495 		 * The ripha header is only used for the IP_UDP_MATCH and we
2496 		 * only set the src and dst addresses and protocol.
2497 		 */
2498 		ripha.ipha_src = ipha->ipha_dst;
2499 		ripha.ipha_dst = ipha->ipha_src;
2500 		ripha.ipha_protocol = ipha->ipha_protocol;
2501 		((uint16_t *)&ports)[0] = up[1];
2502 		((uint16_t *)&ports)[1] = up[0];
2503 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2504 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2505 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2506 		    icmph->icmph_type, icmph->icmph_code));
2507 
2508 		/* Have to change db_type after any pullupmsg */
2509 		DB_TYPE(mp) = M_CTL;
2510 
2511 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2512 		    mctl_present, ip_policy, recv_ill, zoneid);
2513 		return;
2514 
2515 	case IPPROTO_TCP:
2516 		/*
2517 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2518 		 * transport header.
2519 		 */
2520 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2521 		    mp->b_wptr) {
2522 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2523 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2524 				goto discard_pkt;
2525 			}
2526 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2527 			ipha = (ipha_t *)&icmph[1];
2528 		}
2529 		/*
2530 		 * Find a TCP client stream for this packet.
2531 		 * Note that we do a reverse lookup since the header is
2532 		 * in the form we sent it out.
2533 		 */
2534 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2535 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2536 		    ipst);
2537 		if (connp == NULL)
2538 			goto discard_pkt;
2539 
2540 		/* Have to change db_type after any pullupmsg */
2541 		DB_TYPE(mp) = M_CTL;
2542 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2543 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2544 		return;
2545 
2546 	case IPPROTO_SCTP:
2547 		/*
2548 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2549 		 * transport header.
2550 		 */
2551 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2552 		    mp->b_wptr) {
2553 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2554 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2555 				goto discard_pkt;
2556 			}
2557 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2558 			ipha = (ipha_t *)&icmph[1];
2559 		}
2560 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2561 		/*
2562 		 * Find a SCTP client stream for this packet.
2563 		 * Note that we do a reverse lookup since the header is
2564 		 * in the form we sent it out.
2565 		 * The ripha header is only used for the matching and we
2566 		 * only set the src and dst addresses, protocol, and version.
2567 		 */
2568 		ripha.ipha_src = ipha->ipha_dst;
2569 		ripha.ipha_dst = ipha->ipha_src;
2570 		ripha.ipha_protocol = ipha->ipha_protocol;
2571 		ripha.ipha_version_and_hdr_length =
2572 		    ipha->ipha_version_and_hdr_length;
2573 		((uint16_t *)&ports)[0] = up[1];
2574 		((uint16_t *)&ports)[1] = up[0];
2575 
2576 		/* Have to change db_type after any pullupmsg */
2577 		DB_TYPE(mp) = M_CTL;
2578 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2579 		    mctl_present, ip_policy, zoneid);
2580 		return;
2581 
2582 	case IPPROTO_ESP:
2583 	case IPPROTO_AH: {
2584 		int ipsec_rc;
2585 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2586 
2587 		/*
2588 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2589 		 * We will re-use the IPSEC_IN if it is already present as
2590 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2591 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2592 		 * one and attach it in the front.
2593 		 */
2594 		if (ii != NULL) {
2595 			/*
2596 			 * ip_fanout_proto_again converts the ICMP errors
2597 			 * that come back from AH/ESP to M_DATA so that
2598 			 * if it is non-AH/ESP and we do a pullupmsg in
2599 			 * this function, it would work. Convert it back
2600 			 * to M_CTL before we send up as this is a ICMP
2601 			 * error. This could have been generated locally or
2602 			 * by some router. Validate the inner IPsec
2603 			 * headers.
2604 			 *
2605 			 * NOTE : ill_index is used by ip_fanout_proto_again
2606 			 * to locate the ill.
2607 			 */
2608 			ASSERT(ill != NULL);
2609 			ii->ipsec_in_ill_index =
2610 			    ill->ill_phyint->phyint_ifindex;
2611 			ii->ipsec_in_rill_index =
2612 			    recv_ill->ill_phyint->phyint_ifindex;
2613 			DB_TYPE(first_mp->b_cont) = M_CTL;
2614 		} else {
2615 			/*
2616 			 * IPSEC_IN is not present. We attach a ipsec_in
2617 			 * message and send up to IPsec for validating
2618 			 * and removing the IPsec headers. Clear
2619 			 * ipsec_in_secure so that when we return
2620 			 * from IPsec, we don't mistakenly think that this
2621 			 * is a secure packet came from the network.
2622 			 *
2623 			 * NOTE : ill_index is used by ip_fanout_proto_again
2624 			 * to locate the ill.
2625 			 */
2626 			ASSERT(first_mp == mp);
2627 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2628 			if (first_mp == NULL) {
2629 				freemsg(mp);
2630 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2631 				return;
2632 			}
2633 			ii = (ipsec_in_t *)first_mp->b_rptr;
2634 
2635 			/* This is not a secure packet */
2636 			ii->ipsec_in_secure = B_FALSE;
2637 			first_mp->b_cont = mp;
2638 			DB_TYPE(mp) = M_CTL;
2639 			ASSERT(ill != NULL);
2640 			ii->ipsec_in_ill_index =
2641 			    ill->ill_phyint->phyint_ifindex;
2642 			ii->ipsec_in_rill_index =
2643 			    recv_ill->ill_phyint->phyint_ifindex;
2644 		}
2645 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2646 
2647 		if (!ipsec_loaded(ipss)) {
2648 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2649 			return;
2650 		}
2651 
2652 		if (ipha->ipha_protocol == IPPROTO_ESP)
2653 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2654 		else
2655 			ipsec_rc = ipsecah_icmp_error(first_mp);
2656 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2657 			return;
2658 
2659 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2660 		return;
2661 	}
2662 	default:
2663 		/*
2664 		 * The ripha header is only used for the lookup and we
2665 		 * only set the src and dst addresses and protocol.
2666 		 */
2667 		ripha.ipha_src = ipha->ipha_dst;
2668 		ripha.ipha_dst = ipha->ipha_src;
2669 		ripha.ipha_protocol = ipha->ipha_protocol;
2670 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2671 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2672 		    ntohl(ipha->ipha_dst),
2673 		    icmph->icmph_type, icmph->icmph_code));
2674 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2675 			ipha_t *in_ipha;
2676 
2677 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2678 			    mp->b_wptr) {
2679 				if (!pullupmsg(mp, (uchar_t *)ipha +
2680 				    hdr_length + sizeof (ipha_t) -
2681 				    mp->b_rptr)) {
2682 					goto discard_pkt;
2683 				}
2684 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2685 				ipha = (ipha_t *)&icmph[1];
2686 			}
2687 			/*
2688 			 * Caller has verified that length has to be
2689 			 * at least the size of IP header.
2690 			 */
2691 			ASSERT(hdr_length >= sizeof (ipha_t));
2692 			/*
2693 			 * Check the sanity of the inner IP header like
2694 			 * we did for the outer header.
2695 			 */
2696 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2697 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2698 				goto discard_pkt;
2699 			}
2700 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2701 				goto discard_pkt;
2702 			}
2703 			/* Check for Self-encapsulated tunnels */
2704 			if (in_ipha->ipha_src == ipha->ipha_src &&
2705 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2706 
2707 				mp = icmp_inbound_self_encap_error(mp,
2708 				    iph_hdr_length, hdr_length);
2709 				if (mp == NULL)
2710 					goto discard_pkt;
2711 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2712 				ipha = (ipha_t *)&icmph[1];
2713 				hdr_length = IPH_HDR_LENGTH(ipha);
2714 				/*
2715 				 * The packet in error is self-encapsualted.
2716 				 * And we are finding it further encapsulated
2717 				 * which we could not have possibly generated.
2718 				 */
2719 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2720 					goto discard_pkt;
2721 				}
2722 				icmp_inbound_error_fanout(q, ill, first_mp,
2723 				    icmph, ipha, iph_hdr_length, hdr_length,
2724 				    mctl_present, ip_policy, recv_ill, zoneid);
2725 				return;
2726 			}
2727 		}
2728 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2729 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2730 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2731 		    ii != NULL &&
2732 		    ii->ipsec_in_loopback &&
2733 		    ii->ipsec_in_secure) {
2734 			/*
2735 			 * For IP tunnels that get a looped-back
2736 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2737 			 * reported new MTU to take into account the IPsec
2738 			 * headers protecting this configured tunnel.
2739 			 *
2740 			 * This allows the tunnel module (tun.c) to blindly
2741 			 * accept the MTU reported in an ICMP "too big"
2742 			 * message.
2743 			 *
2744 			 * Non-looped back ICMP messages will just be
2745 			 * handled by the security protocols (if needed),
2746 			 * and the first subsequent packet will hit this
2747 			 * path.
2748 			 */
2749 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2750 			    ipsec_in_extra_length(first_mp));
2751 		}
2752 		/* Have to change db_type after any pullupmsg */
2753 		DB_TYPE(mp) = M_CTL;
2754 
2755 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2756 		    ip_policy, recv_ill, zoneid);
2757 		return;
2758 	}
2759 	/* NOTREACHED */
2760 discard_pkt:
2761 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2762 drop_pkt:;
2763 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2764 	freemsg(first_mp);
2765 }
2766 
2767 /*
2768  * Common IP options parser.
2769  *
2770  * Setup routine: fill in *optp with options-parsing state, then
2771  * tail-call ipoptp_next to return the first option.
2772  */
2773 uint8_t
2774 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2775 {
2776 	uint32_t totallen; /* total length of all options */
2777 
2778 	totallen = ipha->ipha_version_and_hdr_length -
2779 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2780 	totallen <<= 2;
2781 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2782 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2783 	optp->ipoptp_flags = 0;
2784 	return (ipoptp_next(optp));
2785 }
2786 
2787 /*
2788  * Common IP options parser: extract next option.
2789  */
2790 uint8_t
2791 ipoptp_next(ipoptp_t *optp)
2792 {
2793 	uint8_t *end = optp->ipoptp_end;
2794 	uint8_t *cur = optp->ipoptp_next;
2795 	uint8_t opt, len, pointer;
2796 
2797 	/*
2798 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2799 	 * has been corrupted.
2800 	 */
2801 	ASSERT(cur <= end);
2802 
2803 	if (cur == end)
2804 		return (IPOPT_EOL);
2805 
2806 	opt = cur[IPOPT_OPTVAL];
2807 
2808 	/*
2809 	 * Skip any NOP options.
2810 	 */
2811 	while (opt == IPOPT_NOP) {
2812 		cur++;
2813 		if (cur == end)
2814 			return (IPOPT_EOL);
2815 		opt = cur[IPOPT_OPTVAL];
2816 	}
2817 
2818 	if (opt == IPOPT_EOL)
2819 		return (IPOPT_EOL);
2820 
2821 	/*
2822 	 * Option requiring a length.
2823 	 */
2824 	if ((cur + 1) >= end) {
2825 		optp->ipoptp_flags |= IPOPTP_ERROR;
2826 		return (IPOPT_EOL);
2827 	}
2828 	len = cur[IPOPT_OLEN];
2829 	if (len < 2) {
2830 		optp->ipoptp_flags |= IPOPTP_ERROR;
2831 		return (IPOPT_EOL);
2832 	}
2833 	optp->ipoptp_cur = cur;
2834 	optp->ipoptp_len = len;
2835 	optp->ipoptp_next = cur + len;
2836 	if (cur + len > end) {
2837 		optp->ipoptp_flags |= IPOPTP_ERROR;
2838 		return (IPOPT_EOL);
2839 	}
2840 
2841 	/*
2842 	 * For the options which require a pointer field, make sure
2843 	 * its there, and make sure it points to either something
2844 	 * inside this option, or the end of the option.
2845 	 */
2846 	switch (opt) {
2847 	case IPOPT_RR:
2848 	case IPOPT_TS:
2849 	case IPOPT_LSRR:
2850 	case IPOPT_SSRR:
2851 		if (len <= IPOPT_OFFSET) {
2852 			optp->ipoptp_flags |= IPOPTP_ERROR;
2853 			return (opt);
2854 		}
2855 		pointer = cur[IPOPT_OFFSET];
2856 		if (pointer - 1 > len) {
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 			return (opt);
2859 		}
2860 		break;
2861 	}
2862 
2863 	/*
2864 	 * Sanity check the pointer field based on the type of the
2865 	 * option.
2866 	 */
2867 	switch (opt) {
2868 	case IPOPT_RR:
2869 	case IPOPT_SSRR:
2870 	case IPOPT_LSRR:
2871 		if (pointer < IPOPT_MINOFF_SR)
2872 			optp->ipoptp_flags |= IPOPTP_ERROR;
2873 		break;
2874 	case IPOPT_TS:
2875 		if (pointer < IPOPT_MINOFF_IT)
2876 			optp->ipoptp_flags |= IPOPTP_ERROR;
2877 		/*
2878 		 * Note that the Internet Timestamp option also
2879 		 * contains two four bit fields (the Overflow field,
2880 		 * and the Flag field), which follow the pointer
2881 		 * field.  We don't need to check that these fields
2882 		 * fall within the length of the option because this
2883 		 * was implicitely done above.  We've checked that the
2884 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2885 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2886 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2887 		 */
2888 		ASSERT(len > IPOPT_POS_OV_FLG);
2889 		break;
2890 	}
2891 
2892 	return (opt);
2893 }
2894 
2895 /*
2896  * Use the outgoing IP header to create an IP_OPTIONS option the way
2897  * it was passed down from the application.
2898  */
2899 int
2900 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2901 {
2902 	ipoptp_t	opts;
2903 	const uchar_t	*opt;
2904 	uint8_t		optval;
2905 	uint8_t		optlen;
2906 	uint32_t	len = 0;
2907 	uchar_t	*buf1 = buf;
2908 
2909 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2910 	len += IP_ADDR_LEN;
2911 	bzero(buf1, IP_ADDR_LEN);
2912 
2913 	/*
2914 	 * OK to cast away const here, as we don't store through the returned
2915 	 * opts.ipoptp_cur pointer.
2916 	 */
2917 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2918 	    optval != IPOPT_EOL;
2919 	    optval = ipoptp_next(&opts)) {
2920 		int	off;
2921 
2922 		opt = opts.ipoptp_cur;
2923 		optlen = opts.ipoptp_len;
2924 		switch (optval) {
2925 		case IPOPT_SSRR:
2926 		case IPOPT_LSRR:
2927 
2928 			/*
2929 			 * Insert ipha_dst as the first entry in the source
2930 			 * route and move down the entries on step.
2931 			 * The last entry gets placed at buf1.
2932 			 */
2933 			buf[IPOPT_OPTVAL] = optval;
2934 			buf[IPOPT_OLEN] = optlen;
2935 			buf[IPOPT_OFFSET] = optlen;
2936 
2937 			off = optlen - IP_ADDR_LEN;
2938 			if (off < 0) {
2939 				/* No entries in source route */
2940 				break;
2941 			}
2942 			/* Last entry in source route */
2943 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2944 			off -= IP_ADDR_LEN;
2945 
2946 			while (off > 0) {
2947 				bcopy(opt + off,
2948 				    buf + off + IP_ADDR_LEN,
2949 				    IP_ADDR_LEN);
2950 				off -= IP_ADDR_LEN;
2951 			}
2952 			/* ipha_dst into first slot */
2953 			bcopy(&ipha->ipha_dst,
2954 			    buf + off + IP_ADDR_LEN,
2955 			    IP_ADDR_LEN);
2956 			buf += optlen;
2957 			len += optlen;
2958 			break;
2959 
2960 		case IPOPT_COMSEC:
2961 		case IPOPT_SECURITY:
2962 			/* if passing up a label is not ok, then remove */
2963 			if (is_system_labeled())
2964 				break;
2965 			/* FALLTHROUGH */
2966 		default:
2967 			bcopy(opt, buf, optlen);
2968 			buf += optlen;
2969 			len += optlen;
2970 			break;
2971 		}
2972 	}
2973 done:
2974 	/* Pad the resulting options */
2975 	while (len & 0x3) {
2976 		*buf++ = IPOPT_EOL;
2977 		len++;
2978 	}
2979 	return (len);
2980 }
2981 
2982 /*
2983  * Update any record route or timestamp options to include this host.
2984  * Reverse any source route option.
2985  * This routine assumes that the options are well formed i.e. that they
2986  * have already been checked.
2987  */
2988 static void
2989 icmp_options_update(ipha_t *ipha)
2990 {
2991 	ipoptp_t	opts;
2992 	uchar_t		*opt;
2993 	uint8_t		optval;
2994 	ipaddr_t	src;		/* Our local address */
2995 	ipaddr_t	dst;
2996 
2997 	ip2dbg(("icmp_options_update\n"));
2998 	src = ipha->ipha_src;
2999 	dst = ipha->ipha_dst;
3000 
3001 	for (optval = ipoptp_first(&opts, ipha);
3002 	    optval != IPOPT_EOL;
3003 	    optval = ipoptp_next(&opts)) {
3004 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3005 		opt = opts.ipoptp_cur;
3006 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3007 		    optval, opts.ipoptp_len));
3008 		switch (optval) {
3009 			int off1, off2;
3010 		case IPOPT_SSRR:
3011 		case IPOPT_LSRR:
3012 			/*
3013 			 * Reverse the source route.  The first entry
3014 			 * should be the next to last one in the current
3015 			 * source route (the last entry is our address).
3016 			 * The last entry should be the final destination.
3017 			 */
3018 			off1 = IPOPT_MINOFF_SR - 1;
3019 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3020 			if (off2 < 0) {
3021 				/* No entries in source route */
3022 				ip1dbg((
3023 				    "icmp_options_update: bad src route\n"));
3024 				break;
3025 			}
3026 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3027 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3028 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3029 			off2 -= IP_ADDR_LEN;
3030 
3031 			while (off1 < off2) {
3032 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3033 				bcopy((char *)opt + off2, (char *)opt + off1,
3034 				    IP_ADDR_LEN);
3035 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3036 				off1 += IP_ADDR_LEN;
3037 				off2 -= IP_ADDR_LEN;
3038 			}
3039 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3040 			break;
3041 		}
3042 	}
3043 }
3044 
3045 /*
3046  * Process received ICMP Redirect messages.
3047  */
3048 static void
3049 icmp_redirect(ill_t *ill, mblk_t *mp)
3050 {
3051 	ipha_t	*ipha;
3052 	int	iph_hdr_length;
3053 	icmph_t	*icmph;
3054 	ipha_t	*ipha_err;
3055 	ire_t	*ire;
3056 	ire_t	*prev_ire;
3057 	ire_t	*save_ire;
3058 	ipaddr_t  src, dst, gateway;
3059 	iulp_t	ulp_info = { 0 };
3060 	int	error;
3061 	ip_stack_t *ipst;
3062 
3063 	ASSERT(ill != NULL);
3064 	ipst = ill->ill_ipst;
3065 
3066 	ipha = (ipha_t *)mp->b_rptr;
3067 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3068 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3069 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3070 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3071 		freemsg(mp);
3072 		return;
3073 	}
3074 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3075 	ipha_err = (ipha_t *)&icmph[1];
3076 	src = ipha->ipha_src;
3077 	dst = ipha_err->ipha_dst;
3078 	gateway = icmph->icmph_rd_gateway;
3079 	/* Make sure the new gateway is reachable somehow. */
3080 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3081 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3082 	/*
3083 	 * Make sure we had a route for the dest in question and that
3084 	 * that route was pointing to the old gateway (the source of the
3085 	 * redirect packet.)
3086 	 */
3087 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3088 	    NULL, MATCH_IRE_GW, ipst);
3089 	/*
3090 	 * Check that
3091 	 *	the redirect was not from ourselves
3092 	 *	the new gateway and the old gateway are directly reachable
3093 	 */
3094 	if (!prev_ire ||
3095 	    !ire ||
3096 	    ire->ire_type == IRE_LOCAL) {
3097 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3098 		freemsg(mp);
3099 		if (ire != NULL)
3100 			ire_refrele(ire);
3101 		if (prev_ire != NULL)
3102 			ire_refrele(prev_ire);
3103 		return;
3104 	}
3105 
3106 	/*
3107 	 * Should we use the old ULP info to create the new gateway?  From
3108 	 * a user's perspective, we should inherit the info so that it
3109 	 * is a "smooth" transition.  If we do not do that, then new
3110 	 * connections going thru the new gateway will have no route metrics,
3111 	 * which is counter-intuitive to user.  From a network point of
3112 	 * view, this may or may not make sense even though the new gateway
3113 	 * is still directly connected to us so the route metrics should not
3114 	 * change much.
3115 	 *
3116 	 * But if the old ire_uinfo is not initialized, we do another
3117 	 * recursive lookup on the dest using the new gateway.  There may
3118 	 * be a route to that.  If so, use it to initialize the redirect
3119 	 * route.
3120 	 */
3121 	if (prev_ire->ire_uinfo.iulp_set) {
3122 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3123 	} else {
3124 		ire_t *tmp_ire;
3125 		ire_t *sire;
3126 
3127 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3128 		    ALL_ZONES, 0, NULL,
3129 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3130 		    ipst);
3131 		if (sire != NULL) {
3132 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3133 			/*
3134 			 * If sire != NULL, ire_ftable_lookup() should not
3135 			 * return a NULL value.
3136 			 */
3137 			ASSERT(tmp_ire != NULL);
3138 			ire_refrele(tmp_ire);
3139 			ire_refrele(sire);
3140 		} else if (tmp_ire != NULL) {
3141 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3142 			    sizeof (iulp_t));
3143 			ire_refrele(tmp_ire);
3144 		}
3145 	}
3146 	if (prev_ire->ire_type == IRE_CACHE)
3147 		ire_delete(prev_ire);
3148 	ire_refrele(prev_ire);
3149 	/*
3150 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3151 	 * require TOS routing
3152 	 */
3153 	switch (icmph->icmph_code) {
3154 	case 0:
3155 	case 1:
3156 		/* TODO: TOS specificity for cases 2 and 3 */
3157 	case 2:
3158 	case 3:
3159 		break;
3160 	default:
3161 		freemsg(mp);
3162 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3163 		ire_refrele(ire);
3164 		return;
3165 	}
3166 	/*
3167 	 * Create a Route Association.  This will allow us to remember that
3168 	 * someone we believe told us to use the particular gateway.
3169 	 */
3170 	save_ire = ire;
3171 	ire = ire_create(
3172 	    (uchar_t *)&dst,			/* dest addr */
3173 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3174 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3175 	    (uchar_t *)&gateway,		/* gateway addr */
3176 	    &save_ire->ire_max_frag,		/* max frag */
3177 	    NULL,				/* no src nce */
3178 	    NULL,				/* no rfq */
3179 	    NULL,				/* no stq */
3180 	    IRE_HOST,
3181 	    NULL,				/* ipif */
3182 	    0,					/* cmask */
3183 	    0,					/* phandle */
3184 	    0,					/* ihandle */
3185 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3186 	    &ulp_info,
3187 	    NULL,				/* tsol_gc_t */
3188 	    NULL,				/* gcgrp */
3189 	    ipst);
3190 
3191 	if (ire == NULL) {
3192 		freemsg(mp);
3193 		ire_refrele(save_ire);
3194 		return;
3195 	}
3196 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3197 	ire_refrele(save_ire);
3198 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3199 
3200 	if (error == 0) {
3201 		ire_refrele(ire);		/* Held in ire_add_v4 */
3202 		/* tell routing sockets that we received a redirect */
3203 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3204 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3205 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3206 	}
3207 
3208 	/*
3209 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3210 	 * This together with the added IRE has the effect of
3211 	 * modifying an existing redirect.
3212 	 */
3213 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3214 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3215 	if (prev_ire != NULL) {
3216 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3217 			ire_delete(prev_ire);
3218 		ire_refrele(prev_ire);
3219 	}
3220 
3221 	freemsg(mp);
3222 }
3223 
3224 /*
3225  * Generate an ICMP parameter problem message.
3226  */
3227 static void
3228 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3229 	ip_stack_t *ipst)
3230 {
3231 	icmph_t	icmph;
3232 	boolean_t mctl_present;
3233 	mblk_t *first_mp;
3234 
3235 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3236 
3237 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3238 		if (mctl_present)
3239 			freeb(first_mp);
3240 		return;
3241 	}
3242 
3243 	bzero(&icmph, sizeof (icmph_t));
3244 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3245 	icmph.icmph_pp_ptr = ptr;
3246 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3247 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3248 	    ipst);
3249 }
3250 
3251 /*
3252  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3253  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3254  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3255  * an icmp error packet can be sent.
3256  * Assigns an appropriate source address to the packet. If ipha_dst is
3257  * one of our addresses use it for source. Otherwise pick a source based
3258  * on a route lookup back to ipha_src.
3259  * Note that ipha_src must be set here since the
3260  * packet is likely to arrive on an ill queue in ip_wput() which will
3261  * not set a source address.
3262  */
3263 static void
3264 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3265     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3266 {
3267 	ipaddr_t dst;
3268 	icmph_t	*icmph;
3269 	ipha_t	*ipha;
3270 	uint_t	len_needed;
3271 	size_t	msg_len;
3272 	mblk_t	*mp1;
3273 	ipaddr_t src;
3274 	ire_t	*ire;
3275 	mblk_t *ipsec_mp;
3276 	ipsec_out_t	*io = NULL;
3277 
3278 	if (mctl_present) {
3279 		/*
3280 		 * If it is :
3281 		 *
3282 		 * 1) a IPSEC_OUT, then this is caused by outbound
3283 		 *    datagram originating on this host. IPsec processing
3284 		 *    may or may not have been done. Refer to comments above
3285 		 *    icmp_inbound_error_fanout for details.
3286 		 *
3287 		 * 2) a IPSEC_IN if we are generating a icmp_message
3288 		 *    for an incoming datagram destined for us i.e called
3289 		 *    from ip_fanout_send_icmp.
3290 		 */
3291 		ipsec_info_t *in;
3292 		ipsec_mp = mp;
3293 		mp = ipsec_mp->b_cont;
3294 
3295 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3296 		ipha = (ipha_t *)mp->b_rptr;
3297 
3298 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3299 		    in->ipsec_info_type == IPSEC_IN);
3300 
3301 		if (in->ipsec_info_type == IPSEC_IN) {
3302 			/*
3303 			 * Convert the IPSEC_IN to IPSEC_OUT.
3304 			 */
3305 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3306 				BUMP_MIB(&ipst->ips_ip_mib,
3307 				    ipIfStatsOutDiscards);
3308 				return;
3309 			}
3310 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3311 		} else {
3312 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3313 			io = (ipsec_out_t *)in;
3314 			/*
3315 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3316 			 * ire lookup.
3317 			 */
3318 			io->ipsec_out_proc_begin = B_FALSE;
3319 		}
3320 		ASSERT(zoneid == io->ipsec_out_zoneid);
3321 		ASSERT(zoneid != ALL_ZONES);
3322 	} else {
3323 		/*
3324 		 * This is in clear. The icmp message we are building
3325 		 * here should go out in clear.
3326 		 *
3327 		 * Pardon the convolution of it all, but it's easier to
3328 		 * allocate a "use cleartext" IPSEC_IN message and convert
3329 		 * it than it is to allocate a new one.
3330 		 */
3331 		ipsec_in_t *ii;
3332 		ASSERT(DB_TYPE(mp) == M_DATA);
3333 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3334 		if (ipsec_mp == NULL) {
3335 			freemsg(mp);
3336 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3337 			return;
3338 		}
3339 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3340 
3341 		/* This is not a secure packet */
3342 		ii->ipsec_in_secure = B_FALSE;
3343 		/*
3344 		 * For trusted extensions using a shared IP address we can
3345 		 * send using any zoneid.
3346 		 */
3347 		if (zoneid == ALL_ZONES)
3348 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3349 		else
3350 			ii->ipsec_in_zoneid = zoneid;
3351 		ipsec_mp->b_cont = mp;
3352 		ipha = (ipha_t *)mp->b_rptr;
3353 		/*
3354 		 * Convert the IPSEC_IN to IPSEC_OUT.
3355 		 */
3356 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3357 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3358 			return;
3359 		}
3360 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3361 	}
3362 
3363 	/* Remember our eventual destination */
3364 	dst = ipha->ipha_src;
3365 
3366 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3367 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3368 	if (ire != NULL &&
3369 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3370 		src = ipha->ipha_dst;
3371 	} else {
3372 		if (ire != NULL)
3373 			ire_refrele(ire);
3374 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3375 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3376 		    ipst);
3377 		if (ire == NULL) {
3378 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3379 			freemsg(ipsec_mp);
3380 			return;
3381 		}
3382 		src = ire->ire_src_addr;
3383 	}
3384 
3385 	if (ire != NULL)
3386 		ire_refrele(ire);
3387 
3388 	/*
3389 	 * Check if we can send back more then 8 bytes in addition to
3390 	 * the IP header.  We try to send 64 bytes of data and the internal
3391 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3392 	 */
3393 	len_needed = IPH_HDR_LENGTH(ipha);
3394 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3395 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3396 
3397 		if (!pullupmsg(mp, -1)) {
3398 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3399 			freemsg(ipsec_mp);
3400 			return;
3401 		}
3402 		ipha = (ipha_t *)mp->b_rptr;
3403 
3404 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3405 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3406 			    len_needed));
3407 		} else {
3408 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3409 
3410 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3411 			len_needed += ip_hdr_length_v6(mp, ip6h);
3412 		}
3413 	}
3414 	len_needed += ipst->ips_ip_icmp_return;
3415 	msg_len = msgdsize(mp);
3416 	if (msg_len > len_needed) {
3417 		(void) adjmsg(mp, len_needed - msg_len);
3418 		msg_len = len_needed;
3419 	}
3420 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3421 	if (mp1 == NULL) {
3422 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3423 		freemsg(ipsec_mp);
3424 		return;
3425 	}
3426 	mp1->b_cont = mp;
3427 	mp = mp1;
3428 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3429 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3430 	    io->ipsec_out_type == IPSEC_OUT);
3431 	ipsec_mp->b_cont = mp;
3432 
3433 	/*
3434 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3435 	 * node generates be accepted in peace by all on-host destinations.
3436 	 * If we do NOT assume that all on-host destinations trust
3437 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3438 	 * (Look for ipsec_out_icmp_loopback).
3439 	 */
3440 	io->ipsec_out_icmp_loopback = B_TRUE;
3441 
3442 	ipha = (ipha_t *)mp->b_rptr;
3443 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3444 	*ipha = icmp_ipha;
3445 	ipha->ipha_src = src;
3446 	ipha->ipha_dst = dst;
3447 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3448 	msg_len += sizeof (icmp_ipha) + len;
3449 	if (msg_len > IP_MAXPACKET) {
3450 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3451 		msg_len = IP_MAXPACKET;
3452 	}
3453 	ipha->ipha_length = htons((uint16_t)msg_len);
3454 	icmph = (icmph_t *)&ipha[1];
3455 	bcopy(stuff, icmph, len);
3456 	icmph->icmph_checksum = 0;
3457 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3458 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3459 	put(q, ipsec_mp);
3460 }
3461 
3462 /*
3463  * Determine if an ICMP error packet can be sent given the rate limit.
3464  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3465  * in milliseconds) and a burst size. Burst size number of packets can
3466  * be sent arbitrarely closely spaced.
3467  * The state is tracked using two variables to implement an approximate
3468  * token bucket filter:
3469  *	icmp_pkt_err_last - lbolt value when the last burst started
3470  *	icmp_pkt_err_sent - number of packets sent in current burst
3471  */
3472 boolean_t
3473 icmp_err_rate_limit(ip_stack_t *ipst)
3474 {
3475 	clock_t now = TICK_TO_MSEC(lbolt);
3476 	uint_t refilled; /* Number of packets refilled in tbf since last */
3477 	/* Guard against changes by loading into local variable */
3478 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3479 
3480 	if (err_interval == 0)
3481 		return (B_FALSE);
3482 
3483 	if (ipst->ips_icmp_pkt_err_last > now) {
3484 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3485 		ipst->ips_icmp_pkt_err_last = 0;
3486 		ipst->ips_icmp_pkt_err_sent = 0;
3487 	}
3488 	/*
3489 	 * If we are in a burst update the token bucket filter.
3490 	 * Update the "last" time to be close to "now" but make sure
3491 	 * we don't loose precision.
3492 	 */
3493 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3494 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3495 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3496 			ipst->ips_icmp_pkt_err_sent = 0;
3497 		} else {
3498 			ipst->ips_icmp_pkt_err_sent -= refilled;
3499 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3500 		}
3501 	}
3502 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3503 		/* Start of new burst */
3504 		ipst->ips_icmp_pkt_err_last = now;
3505 	}
3506 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3507 		ipst->ips_icmp_pkt_err_sent++;
3508 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3509 		    ipst->ips_icmp_pkt_err_sent));
3510 		return (B_FALSE);
3511 	}
3512 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3513 	return (B_TRUE);
3514 }
3515 
3516 /*
3517  * Check if it is ok to send an IPv4 ICMP error packet in
3518  * response to the IPv4 packet in mp.
3519  * Free the message and return null if no
3520  * ICMP error packet should be sent.
3521  */
3522 static mblk_t *
3523 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3524 {
3525 	icmph_t	*icmph;
3526 	ipha_t	*ipha;
3527 	uint_t	len_needed;
3528 	ire_t	*src_ire;
3529 	ire_t	*dst_ire;
3530 
3531 	if (!mp)
3532 		return (NULL);
3533 	ipha = (ipha_t *)mp->b_rptr;
3534 	if (ip_csum_hdr(ipha)) {
3535 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3536 		freemsg(mp);
3537 		return (NULL);
3538 	}
3539 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3540 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3541 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3542 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3543 	if (src_ire != NULL || dst_ire != NULL ||
3544 	    CLASSD(ipha->ipha_dst) ||
3545 	    CLASSD(ipha->ipha_src) ||
3546 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3547 		/* Note: only errors to the fragment with offset 0 */
3548 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3549 		freemsg(mp);
3550 		if (src_ire != NULL)
3551 			ire_refrele(src_ire);
3552 		if (dst_ire != NULL)
3553 			ire_refrele(dst_ire);
3554 		return (NULL);
3555 	}
3556 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3557 		/*
3558 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3559 		 * errors in response to any ICMP errors.
3560 		 */
3561 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3562 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3563 			if (!pullupmsg(mp, len_needed)) {
3564 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3565 				freemsg(mp);
3566 				return (NULL);
3567 			}
3568 			ipha = (ipha_t *)mp->b_rptr;
3569 		}
3570 		icmph = (icmph_t *)
3571 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3572 		switch (icmph->icmph_type) {
3573 		case ICMP_DEST_UNREACHABLE:
3574 		case ICMP_SOURCE_QUENCH:
3575 		case ICMP_TIME_EXCEEDED:
3576 		case ICMP_PARAM_PROBLEM:
3577 		case ICMP_REDIRECT:
3578 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3579 			freemsg(mp);
3580 			return (NULL);
3581 		default:
3582 			break;
3583 		}
3584 	}
3585 	/*
3586 	 * If this is a labeled system, then check to see if we're allowed to
3587 	 * send a response to this particular sender.  If not, then just drop.
3588 	 */
3589 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3590 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3591 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3592 		freemsg(mp);
3593 		return (NULL);
3594 	}
3595 	if (icmp_err_rate_limit(ipst)) {
3596 		/*
3597 		 * Only send ICMP error packets every so often.
3598 		 * This should be done on a per port/source basis,
3599 		 * but for now this will suffice.
3600 		 */
3601 		freemsg(mp);
3602 		return (NULL);
3603 	}
3604 	return (mp);
3605 }
3606 
3607 /*
3608  * Generate an ICMP redirect message.
3609  */
3610 static void
3611 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3612 {
3613 	icmph_t	icmph;
3614 
3615 	/*
3616 	 * We are called from ip_rput where we could
3617 	 * not have attached an IPSEC_IN.
3618 	 */
3619 	ASSERT(mp->b_datap->db_type == M_DATA);
3620 
3621 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3622 		return;
3623 	}
3624 
3625 	bzero(&icmph, sizeof (icmph_t));
3626 	icmph.icmph_type = ICMP_REDIRECT;
3627 	icmph.icmph_code = 1;
3628 	icmph.icmph_rd_gateway = gateway;
3629 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3630 	/* Redirects sent by router, and router is global zone */
3631 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3632 }
3633 
3634 /*
3635  * Generate an ICMP time exceeded message.
3636  */
3637 void
3638 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3639     ip_stack_t *ipst)
3640 {
3641 	icmph_t	icmph;
3642 	boolean_t mctl_present;
3643 	mblk_t *first_mp;
3644 
3645 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3646 
3647 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3648 		if (mctl_present)
3649 			freeb(first_mp);
3650 		return;
3651 	}
3652 
3653 	bzero(&icmph, sizeof (icmph_t));
3654 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3655 	icmph.icmph_code = code;
3656 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3657 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3658 	    ipst);
3659 }
3660 
3661 /*
3662  * Generate an ICMP unreachable message.
3663  */
3664 void
3665 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3666     ip_stack_t *ipst)
3667 {
3668 	icmph_t	icmph;
3669 	mblk_t *first_mp;
3670 	boolean_t mctl_present;
3671 
3672 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3673 
3674 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3675 		if (mctl_present)
3676 			freeb(first_mp);
3677 		return;
3678 	}
3679 
3680 	bzero(&icmph, sizeof (icmph_t));
3681 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3682 	icmph.icmph_code = code;
3683 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3684 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3685 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3686 	    zoneid, ipst);
3687 }
3688 
3689 /*
3690  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3691  * duplicate.  As long as someone else holds the address, the interface will
3692  * stay down.  When that conflict goes away, the interface is brought back up.
3693  * This is done so that accidental shutdowns of addresses aren't made
3694  * permanent.  Your server will recover from a failure.
3695  *
3696  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3697  * user space process (dhcpagent).
3698  *
3699  * Recovery completes if ARP reports that the address is now ours (via
3700  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3701  *
3702  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3703  */
3704 static void
3705 ipif_dup_recovery(void *arg)
3706 {
3707 	ipif_t *ipif = arg;
3708 	ill_t *ill = ipif->ipif_ill;
3709 	mblk_t *arp_add_mp;
3710 	mblk_t *arp_del_mp;
3711 	area_t *area;
3712 	ip_stack_t *ipst = ill->ill_ipst;
3713 
3714 	ipif->ipif_recovery_id = 0;
3715 
3716 	/*
3717 	 * No lock needed for moving or condemned check, as this is just an
3718 	 * optimization.
3719 	 */
3720 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3721 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3722 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3723 		/* No reason to try to bring this address back. */
3724 		return;
3725 	}
3726 
3727 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3728 		goto alloc_fail;
3729 
3730 	if (ipif->ipif_arp_del_mp == NULL) {
3731 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3732 			goto alloc_fail;
3733 		ipif->ipif_arp_del_mp = arp_del_mp;
3734 	}
3735 
3736 	/* Setting the 'unverified' flag restarts DAD */
3737 	area = (area_t *)arp_add_mp->b_rptr;
3738 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3739 	    ACE_F_UNVERIFIED;
3740 	putnext(ill->ill_rq, arp_add_mp);
3741 	return;
3742 
3743 alloc_fail:
3744 	/*
3745 	 * On allocation failure, just restart the timer.  Note that the ipif
3746 	 * is down here, so no other thread could be trying to start a recovery
3747 	 * timer.  The ill_lock protects the condemned flag and the recovery
3748 	 * timer ID.
3749 	 */
3750 	freemsg(arp_add_mp);
3751 	mutex_enter(&ill->ill_lock);
3752 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3753 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3754 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3755 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3756 	}
3757 	mutex_exit(&ill->ill_lock);
3758 }
3759 
3760 /*
3761  * This is for exclusive changes due to ARP.  Either tear down an interface due
3762  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3763  */
3764 /* ARGSUSED */
3765 static void
3766 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3767 {
3768 	ill_t	*ill = rq->q_ptr;
3769 	arh_t *arh;
3770 	ipaddr_t src;
3771 	ipif_t	*ipif;
3772 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3773 	char hbuf[MAC_STR_LEN];
3774 	char sbuf[INET_ADDRSTRLEN];
3775 	const char *failtype;
3776 	boolean_t bring_up;
3777 	ip_stack_t *ipst = ill->ill_ipst;
3778 
3779 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3780 	case AR_CN_READY:
3781 		failtype = NULL;
3782 		bring_up = B_TRUE;
3783 		break;
3784 	case AR_CN_FAILED:
3785 		failtype = "in use";
3786 		bring_up = B_FALSE;
3787 		break;
3788 	default:
3789 		failtype = "claimed";
3790 		bring_up = B_FALSE;
3791 		break;
3792 	}
3793 
3794 	arh = (arh_t *)mp->b_cont->b_rptr;
3795 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3796 
3797 	/* Handle failures due to probes */
3798 	if (src == 0) {
3799 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3800 		    IP_ADDR_LEN);
3801 	}
3802 
3803 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3804 	    sizeof (hbuf));
3805 	(void) ip_dot_addr(src, sbuf);
3806 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3807 
3808 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3809 		    ipif->ipif_lcl_addr != src) {
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If we failed on a recovery probe, then restart the timer to
3815 		 * try again later.
3816 		 */
3817 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3818 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3819 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3820 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3821 		    ipst->ips_ip_dup_recovery > 0 &&
3822 		    ipif->ipif_recovery_id == 0) {
3823 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3824 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3825 			continue;
3826 		}
3827 
3828 		/*
3829 		 * If what we're trying to do has already been done, then do
3830 		 * nothing.
3831 		 */
3832 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3833 			continue;
3834 
3835 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3836 
3837 		if (failtype == NULL) {
3838 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3839 			    ibuf);
3840 		} else {
3841 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3842 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3843 		}
3844 
3845 		if (bring_up) {
3846 			ASSERT(ill->ill_dl_up);
3847 			/*
3848 			 * Free up the ARP delete message so we can allocate
3849 			 * a fresh one through the normal path.
3850 			 */
3851 			freemsg(ipif->ipif_arp_del_mp);
3852 			ipif->ipif_arp_del_mp = NULL;
3853 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3854 			    EINPROGRESS) {
3855 				ipif->ipif_addr_ready = 1;
3856 				(void) ipif_up_done(ipif);
3857 			}
3858 			continue;
3859 		}
3860 
3861 		mutex_enter(&ill->ill_lock);
3862 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3863 		ipif->ipif_flags |= IPIF_DUPLICATE;
3864 		ill->ill_ipif_dup_count++;
3865 		mutex_exit(&ill->ill_lock);
3866 		/*
3867 		 * Already exclusive on the ill; no need to handle deferred
3868 		 * processing here.
3869 		 */
3870 		(void) ipif_down(ipif, NULL, NULL);
3871 		ipif_down_tail(ipif);
3872 		mutex_enter(&ill->ill_lock);
3873 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3874 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3875 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3876 		    ipst->ips_ip_dup_recovery > 0) {
3877 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3878 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3879 		}
3880 		mutex_exit(&ill->ill_lock);
3881 	}
3882 	freemsg(mp);
3883 }
3884 
3885 /* ARGSUSED */
3886 static void
3887 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3888 {
3889 	ill_t	*ill = rq->q_ptr;
3890 	arh_t *arh;
3891 	ipaddr_t src;
3892 	ipif_t	*ipif;
3893 
3894 	arh = (arh_t *)mp->b_cont->b_rptr;
3895 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3896 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3897 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3898 			(void) ipif_resolver_up(ipif, Res_act_defend);
3899 	}
3900 	freemsg(mp);
3901 }
3902 
3903 /*
3904  * News from ARP.  ARP sends notification of interesting events down
3905  * to its clients using M_CTL messages with the interesting ARP packet
3906  * attached via b_cont.
3907  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3908  * queue as opposed to ARP sending the message to all the clients, i.e. all
3909  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3910  * table if a cache IRE is found to delete all the entries for the address in
3911  * the packet.
3912  */
3913 static void
3914 ip_arp_news(queue_t *q, mblk_t *mp)
3915 {
3916 	arcn_t		*arcn;
3917 	arh_t		*arh;
3918 	ire_t		*ire = NULL;
3919 	char		hbuf[MAC_STR_LEN];
3920 	char		sbuf[INET_ADDRSTRLEN];
3921 	ipaddr_t	src;
3922 	in6_addr_t	v6src;
3923 	boolean_t	isv6 = B_FALSE;
3924 	ipif_t		*ipif;
3925 	ill_t		*ill;
3926 	ip_stack_t	*ipst;
3927 
3928 	if (CONN_Q(q)) {
3929 		conn_t *connp = Q_TO_CONN(q);
3930 
3931 		ipst = connp->conn_netstack->netstack_ip;
3932 	} else {
3933 		ill_t *ill = (ill_t *)q->q_ptr;
3934 
3935 		ipst = ill->ill_ipst;
3936 	}
3937 
3938 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3939 		if (q->q_next) {
3940 			putnext(q, mp);
3941 		} else
3942 			freemsg(mp);
3943 		return;
3944 	}
3945 	arh = (arh_t *)mp->b_cont->b_rptr;
3946 	/* Is it one we are interested in? */
3947 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3948 		isv6 = B_TRUE;
3949 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3950 		    IPV6_ADDR_LEN);
3951 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3952 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3953 		    IP_ADDR_LEN);
3954 	} else {
3955 		freemsg(mp);
3956 		return;
3957 	}
3958 
3959 	ill = q->q_ptr;
3960 
3961 	arcn = (arcn_t *)mp->b_rptr;
3962 	switch (arcn->arcn_code) {
3963 	case AR_CN_BOGON:
3964 		/*
3965 		 * Someone is sending ARP packets with a source protocol
3966 		 * address that we have published and for which we believe our
3967 		 * entry is authoritative and (when ill_arp_extend is set)
3968 		 * verified to be unique on the network.
3969 		 *
3970 		 * The ARP module internally handles the cases where the sender
3971 		 * is just probing (for DAD) and where the hardware address of
3972 		 * a non-authoritative entry has changed.  Thus, these are the
3973 		 * real conflicts, and we have to do resolution.
3974 		 *
3975 		 * We back away quickly from the address if it's from DHCP or
3976 		 * otherwise temporary and hasn't been used recently (or at
3977 		 * all).  We'd like to include "deprecated" addresses here as
3978 		 * well (as there's no real reason to defend something we're
3979 		 * discarding), but IPMP "reuses" this flag to mean something
3980 		 * other than the standard meaning.
3981 		 *
3982 		 * If the ARP module above is not extended (meaning that it
3983 		 * doesn't know how to defend the address), then we just log
3984 		 * the problem as we always did and continue on.  It's not
3985 		 * right, but there's little else we can do, and those old ATM
3986 		 * users are going away anyway.
3987 		 */
3988 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3989 		    hbuf, sizeof (hbuf));
3990 		(void) ip_dot_addr(src, sbuf);
3991 		if (isv6) {
3992 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3993 			    ipst);
3994 		} else {
3995 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3996 		}
3997 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3998 			uint32_t now;
3999 			uint32_t maxage;
4000 			clock_t lused;
4001 			uint_t maxdefense;
4002 			uint_t defs;
4003 
4004 			/*
4005 			 * First, figure out if this address hasn't been used
4006 			 * in a while.  If it hasn't, then it's a better
4007 			 * candidate for abandoning.
4008 			 */
4009 			ipif = ire->ire_ipif;
4010 			ASSERT(ipif != NULL);
4011 			now = gethrestime_sec();
4012 			maxage = now - ire->ire_create_time;
4013 			if (maxage > ipst->ips_ip_max_temp_idle)
4014 				maxage = ipst->ips_ip_max_temp_idle;
4015 			lused = drv_hztousec(ddi_get_lbolt() -
4016 			    ire->ire_last_used_time) / MICROSEC + 1;
4017 			if (lused >= maxage && (ipif->ipif_flags &
4018 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4019 				maxdefense = ipst->ips_ip_max_temp_defend;
4020 			else
4021 				maxdefense = ipst->ips_ip_max_defend;
4022 
4023 			/*
4024 			 * Now figure out how many times we've defended
4025 			 * ourselves.  Ignore defenses that happened long in
4026 			 * the past.
4027 			 */
4028 			mutex_enter(&ire->ire_lock);
4029 			if ((defs = ire->ire_defense_count) > 0 &&
4030 			    now - ire->ire_defense_time >
4031 			    ipst->ips_ip_defend_interval) {
4032 				ire->ire_defense_count = defs = 0;
4033 			}
4034 			ire->ire_defense_count++;
4035 			ire->ire_defense_time = now;
4036 			mutex_exit(&ire->ire_lock);
4037 			ill_refhold(ill);
4038 			ire_refrele(ire);
4039 
4040 			/*
4041 			 * If we've defended ourselves too many times already,
4042 			 * then give up and tear down the interface(s) using
4043 			 * this address.  Otherwise, defend by sending out a
4044 			 * gratuitous ARP.
4045 			 */
4046 			if (defs >= maxdefense && ill->ill_arp_extend) {
4047 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4048 				    B_FALSE);
4049 			} else {
4050 				cmn_err(CE_WARN,
4051 				    "node %s is using our IP address %s on %s",
4052 				    hbuf, sbuf, ill->ill_name);
4053 				/*
4054 				 * If this is an old (ATM) ARP module, then
4055 				 * don't try to defend the address.  Remain
4056 				 * compatible with the old behavior.  Defend
4057 				 * only with new ARP.
4058 				 */
4059 				if (ill->ill_arp_extend) {
4060 					qwriter_ip(ill, q, mp, ip_arp_defend,
4061 					    NEW_OP, B_FALSE);
4062 				} else {
4063 					ill_refrele(ill);
4064 				}
4065 			}
4066 			return;
4067 		}
4068 		cmn_err(CE_WARN,
4069 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4070 		    hbuf, sbuf, ill->ill_name);
4071 		if (ire != NULL)
4072 			ire_refrele(ire);
4073 		break;
4074 	case AR_CN_ANNOUNCE:
4075 		if (isv6) {
4076 			/*
4077 			 * For XRESOLV interfaces.
4078 			 * Delete the IRE cache entry and NCE for this
4079 			 * v6 address
4080 			 */
4081 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4082 			/*
4083 			 * If v6src is a non-zero, it's a router address
4084 			 * as below. Do the same sort of thing to clean
4085 			 * out off-net IRE_CACHE entries that go through
4086 			 * the router.
4087 			 */
4088 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4089 				ire_walk_v6(ire_delete_cache_gw_v6,
4090 				    (char *)&v6src, ALL_ZONES, ipst);
4091 			}
4092 		} else {
4093 			nce_hw_map_t hwm;
4094 
4095 			/*
4096 			 * ARP gives us a copy of any packet where it thinks
4097 			 * the address has changed, so that we can update our
4098 			 * caches.  We're responsible for caching known answers
4099 			 * in the current design.  We check whether the
4100 			 * hardware address really has changed in all of our
4101 			 * entries that have cached this mapping, and if so, we
4102 			 * blow them away.  This way we will immediately pick
4103 			 * up the rare case of a host changing hardware
4104 			 * address.
4105 			 */
4106 			if (src == 0)
4107 				break;
4108 			hwm.hwm_addr = src;
4109 			hwm.hwm_hwlen = arh->arh_hlen;
4110 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4111 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4112 			ndp_walk_common(ipst->ips_ndp4, NULL,
4113 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4114 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4115 		}
4116 		break;
4117 	case AR_CN_READY:
4118 		/* No external v6 resolver has a contract to use this */
4119 		if (isv6)
4120 			break;
4121 		/* If the link is down, we'll retry this later */
4122 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4123 			break;
4124 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4125 		    NULL, NULL, ipst);
4126 		if (ipif != NULL) {
4127 			/*
4128 			 * If this is a duplicate recovery, then we now need to
4129 			 * go exclusive to bring this thing back up.
4130 			 */
4131 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4132 			    IPIF_DUPLICATE) {
4133 				ipif_refrele(ipif);
4134 				ill_refhold(ill);
4135 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4136 				    B_FALSE);
4137 				return;
4138 			}
4139 			/*
4140 			 * If this is the first notice that this address is
4141 			 * ready, then let the user know now.
4142 			 */
4143 			if ((ipif->ipif_flags & IPIF_UP) &&
4144 			    !ipif->ipif_addr_ready) {
4145 				ipif_mask_reply(ipif);
4146 				ip_rts_ifmsg(ipif);
4147 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4148 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4149 			}
4150 			ipif->ipif_addr_ready = 1;
4151 			ipif_refrele(ipif);
4152 		}
4153 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4154 		if (ire != NULL) {
4155 			ire->ire_defense_count = 0;
4156 			ire_refrele(ire);
4157 		}
4158 		break;
4159 	case AR_CN_FAILED:
4160 		/* No external v6 resolver has a contract to use this */
4161 		if (isv6)
4162 			break;
4163 		ill_refhold(ill);
4164 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4165 		return;
4166 	}
4167 	freemsg(mp);
4168 }
4169 
4170 /*
4171  * Create a mblk suitable for carrying the interface index and/or source link
4172  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4173  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4174  * application.
4175  */
4176 mblk_t *
4177 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4178     ip_stack_t *ipst)
4179 {
4180 	mblk_t		*mp;
4181 	ip_pktinfo_t	*pinfo;
4182 	ipha_t *ipha;
4183 	struct ether_header *pether;
4184 
4185 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4186 	if (mp == NULL) {
4187 		ip1dbg(("ip_add_info: allocation failure.\n"));
4188 		return (data_mp);
4189 	}
4190 
4191 	ipha	= (ipha_t *)data_mp->b_rptr;
4192 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4193 	bzero(pinfo, sizeof (ip_pktinfo_t));
4194 	pinfo->ip_pkt_flags = (uchar_t)flags;
4195 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4196 
4197 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4198 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4199 	if (flags & IPF_RECVADDR) {
4200 		ipif_t	*ipif;
4201 		ire_t	*ire;
4202 
4203 		/*
4204 		 * Only valid for V4
4205 		 */
4206 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4207 		    (IPV4_VERSION << 4));
4208 
4209 		ipif = ipif_get_next_ipif(NULL, ill);
4210 		if (ipif != NULL) {
4211 			/*
4212 			 * Since a decision has already been made to deliver the
4213 			 * packet, there is no need to test for SECATTR and
4214 			 * ZONEONLY.
4215 			 * When a multicast packet is transmitted
4216 			 * a cache entry is created for the multicast address.
4217 			 * When delivering a copy of the packet or when new
4218 			 * packets are received we do not want to match on the
4219 			 * cached entry so explicitly match on
4220 			 * IRE_LOCAL and IRE_LOOPBACK
4221 			 */
4222 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4223 			    IRE_LOCAL | IRE_LOOPBACK,
4224 			    ipif, zoneid, NULL,
4225 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4226 			if (ire == NULL) {
4227 				/*
4228 				 * packet must have come on a different
4229 				 * interface.
4230 				 * Since a decision has already been made to
4231 				 * deliver the packet, there is no need to test
4232 				 * for SECATTR and ZONEONLY.
4233 				 * Only match on local and broadcast ire's.
4234 				 * See detailed comment above.
4235 				 */
4236 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4237 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4238 				    NULL, MATCH_IRE_TYPE, ipst);
4239 			}
4240 
4241 			if (ire == NULL) {
4242 				/*
4243 				 * This is either a multicast packet or
4244 				 * the address has been removed since
4245 				 * the packet was received.
4246 				 * Return INADDR_ANY so that normal source
4247 				 * selection occurs for the response.
4248 				 */
4249 
4250 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4251 			} else {
4252 				pinfo->ip_pkt_match_addr.s_addr =
4253 				    ire->ire_src_addr;
4254 				ire_refrele(ire);
4255 			}
4256 			ipif_refrele(ipif);
4257 		} else {
4258 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4259 		}
4260 	}
4261 
4262 	pether = (struct ether_header *)((char *)ipha
4263 	    - sizeof (struct ether_header));
4264 	/*
4265 	 * Make sure the interface is an ethernet type, since this option
4266 	 * is currently supported only on this type of interface. Also make
4267 	 * sure we are pointing correctly above db_base.
4268 	 */
4269 
4270 	if ((flags & IPF_RECVSLLA) &&
4271 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4272 	    (ill->ill_type == IFT_ETHER) &&
4273 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4274 
4275 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4276 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4277 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4278 	} else {
4279 		/*
4280 		 * Clear the bit. Indicate to upper layer that IP is not
4281 		 * sending this ancillary info.
4282 		 */
4283 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4284 	}
4285 
4286 	mp->b_datap->db_type = M_CTL;
4287 	mp->b_wptr += sizeof (ip_pktinfo_t);
4288 	mp->b_cont = data_mp;
4289 
4290 	return (mp);
4291 }
4292 
4293 /*
4294  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4295  * part of the bind request.
4296  */
4297 
4298 boolean_t
4299 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4300 {
4301 	ipsec_in_t *ii;
4302 
4303 	ASSERT(policy_mp != NULL);
4304 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4305 
4306 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4307 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4308 
4309 	connp->conn_policy = ii->ipsec_in_policy;
4310 	ii->ipsec_in_policy = NULL;
4311 
4312 	if (ii->ipsec_in_action != NULL) {
4313 		if (connp->conn_latch == NULL) {
4314 			connp->conn_latch = iplatch_create();
4315 			if (connp->conn_latch == NULL)
4316 				return (B_FALSE);
4317 		}
4318 		ipsec_latch_inbound(connp->conn_latch, ii);
4319 	}
4320 	return (B_TRUE);
4321 }
4322 
4323 /*
4324  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4325  * and to arrange for power-fanout assist.  The ULP is identified by
4326  * adding a single byte at the end of the original bind message.
4327  * A ULP other than UDP or TCP that wishes to be recognized passes
4328  * down a bind with a zero length address.
4329  *
4330  * The binding works as follows:
4331  * - A zero byte address means just bind to the protocol.
4332  * - A four byte address is treated as a request to validate
4333  *   that the address is a valid local address, appropriate for
4334  *   an application to bind to. This does not affect any fanout
4335  *   information in IP.
4336  * - A sizeof sin_t byte address is used to bind to only the local address
4337  *   and port.
4338  * - A sizeof ipa_conn_t byte address contains complete fanout information
4339  *   consisting of local and remote addresses and ports.  In
4340  *   this case, the addresses are both validated as appropriate
4341  *   for this operation, and, if so, the information is retained
4342  *   for use in the inbound fanout.
4343  *
4344  * The ULP (except in the zero-length bind) can append an
4345  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4346  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4347  * a copy of the source or destination IRE (source for local bind;
4348  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4349  * policy information contained should be copied on to the conn.
4350  *
4351  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4352  */
4353 mblk_t *
4354 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4355 {
4356 	ssize_t		len;
4357 	struct T_bind_req	*tbr;
4358 	sin_t		*sin;
4359 	ipa_conn_t	*ac;
4360 	uchar_t		*ucp;
4361 	mblk_t		*mp1;
4362 	boolean_t	ire_requested;
4363 	boolean_t	ipsec_policy_set = B_FALSE;
4364 	int		error = 0;
4365 	int		protocol;
4366 	ipa_conn_x_t	*acx;
4367 
4368 	ASSERT(!connp->conn_af_isv6);
4369 	connp->conn_pkt_isv6 = B_FALSE;
4370 
4371 	len = MBLKL(mp);
4372 	if (len < (sizeof (*tbr) + 1)) {
4373 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4374 		    "ip_bind: bogus msg, len %ld", len);
4375 		/* XXX: Need to return something better */
4376 		goto bad_addr;
4377 	}
4378 	/* Back up and extract the protocol identifier. */
4379 	mp->b_wptr--;
4380 	protocol = *mp->b_wptr & 0xFF;
4381 	tbr = (struct T_bind_req *)mp->b_rptr;
4382 	/* Reset the message type in preparation for shipping it back. */
4383 	DB_TYPE(mp) = M_PCPROTO;
4384 
4385 	connp->conn_ulp = (uint8_t)protocol;
4386 
4387 	/*
4388 	 * Check for a zero length address.  This is from a protocol that
4389 	 * wants to register to receive all packets of its type.
4390 	 */
4391 	if (tbr->ADDR_length == 0) {
4392 		/*
4393 		 * These protocols are now intercepted in ip_bind_v6().
4394 		 * Reject protocol-level binds here for now.
4395 		 *
4396 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4397 		 * so that the protocol type cannot be SCTP.
4398 		 */
4399 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4400 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4401 			goto bad_addr;
4402 		}
4403 
4404 		/*
4405 		 *
4406 		 * The udp module never sends down a zero-length address,
4407 		 * and allowing this on a labeled system will break MLP
4408 		 * functionality.
4409 		 */
4410 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4411 			goto bad_addr;
4412 
4413 		if (connp->conn_mac_exempt)
4414 			goto bad_addr;
4415 
4416 		/* No hash here really.  The table is big enough. */
4417 		connp->conn_srcv6 = ipv6_all_zeros;
4418 
4419 		ipcl_proto_insert(connp, protocol);
4420 
4421 		tbr->PRIM_type = T_BIND_ACK;
4422 		return (mp);
4423 	}
4424 
4425 	/* Extract the address pointer from the message. */
4426 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4427 	    tbr->ADDR_length);
4428 	if (ucp == NULL) {
4429 		ip1dbg(("ip_bind: no address\n"));
4430 		goto bad_addr;
4431 	}
4432 	if (!OK_32PTR(ucp)) {
4433 		ip1dbg(("ip_bind: unaligned address\n"));
4434 		goto bad_addr;
4435 	}
4436 	/*
4437 	 * Check for trailing mps.
4438 	 */
4439 
4440 	mp1 = mp->b_cont;
4441 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4442 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4443 
4444 	switch (tbr->ADDR_length) {
4445 	default:
4446 		ip1dbg(("ip_bind: bad address length %d\n",
4447 		    (int)tbr->ADDR_length));
4448 		goto bad_addr;
4449 
4450 	case IP_ADDR_LEN:
4451 		/* Verification of local address only */
4452 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4453 		    ire_requested, ipsec_policy_set, B_FALSE);
4454 		break;
4455 
4456 	case sizeof (sin_t):
4457 		sin = (sin_t *)ucp;
4458 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4459 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4460 		break;
4461 
4462 	case sizeof (ipa_conn_t):
4463 		ac = (ipa_conn_t *)ucp;
4464 		/* For raw socket, the local port is not set. */
4465 		if (ac->ac_lport == 0)
4466 			ac->ac_lport = connp->conn_lport;
4467 		/* Always verify destination reachability. */
4468 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4469 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4470 		    ipsec_policy_set, B_TRUE, B_TRUE);
4471 		break;
4472 
4473 	case sizeof (ipa_conn_x_t):
4474 		acx = (ipa_conn_x_t *)ucp;
4475 		/*
4476 		 * Whether or not to verify destination reachability depends
4477 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4478 		 */
4479 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4480 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4481 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4482 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4483 		break;
4484 	}
4485 	if (error == EINPROGRESS)
4486 		return (NULL);
4487 	else if (error != 0)
4488 		goto bad_addr;
4489 	/*
4490 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4491 	 * We can't do this in ip_bind_insert_ire because the policy
4492 	 * may not have been inherited at that point in time and hence
4493 	 * conn_out_enforce_policy may not be set.
4494 	 */
4495 	mp1 = mp->b_cont;
4496 	if (ire_requested && connp->conn_out_enforce_policy &&
4497 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4498 		ire_t *ire = (ire_t *)mp1->b_rptr;
4499 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4500 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4501 	}
4502 
4503 	/* Send it home. */
4504 	mp->b_datap->db_type = M_PCPROTO;
4505 	tbr->PRIM_type = T_BIND_ACK;
4506 	return (mp);
4507 
4508 bad_addr:
4509 	/*
4510 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4511 	 * a unix errno.
4512 	 */
4513 	if (error > 0)
4514 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4515 	else
4516 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4517 	return (mp);
4518 }
4519 
4520 /*
4521  * Here address is verified to be a valid local address.
4522  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4523  * address is also considered a valid local address.
4524  * In the case of a broadcast/multicast address, however, the
4525  * upper protocol is expected to reset the src address
4526  * to 0 if it sees a IRE_BROADCAST type returned so that
4527  * no packets are emitted with broadcast/multicast address as
4528  * source address (that violates hosts requirements RFC1122)
4529  * The addresses valid for bind are:
4530  *	(1) - INADDR_ANY (0)
4531  *	(2) - IP address of an UP interface
4532  *	(3) - IP address of a DOWN interface
4533  *	(4) - valid local IP broadcast addresses. In this case
4534  *	the conn will only receive packets destined to
4535  *	the specified broadcast address.
4536  *	(5) - a multicast address. In this case
4537  *	the conn will only receive packets destined to
4538  *	the specified multicast address. Note: the
4539  *	application still has to issue an
4540  *	IP_ADD_MEMBERSHIP socket option.
4541  *
4542  * On error, return -1 for TBADADDR otherwise pass the
4543  * errno with TSYSERR reply.
4544  *
4545  * In all the above cases, the bound address must be valid in the current zone.
4546  * When the address is loopback, multicast or broadcast, there might be many
4547  * matching IREs so bind has to look up based on the zone.
4548  *
4549  * Note: lport is in network byte order.
4550  */
4551 int
4552 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4553     boolean_t ire_requested, boolean_t ipsec_policy_set,
4554     boolean_t fanout_insert)
4555 {
4556 	int		error = 0;
4557 	ire_t		*src_ire;
4558 	mblk_t		*policy_mp;
4559 	ipif_t		*ipif;
4560 	zoneid_t	zoneid;
4561 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4562 
4563 	if (ipsec_policy_set) {
4564 		policy_mp = mp->b_cont;
4565 	}
4566 
4567 	/*
4568 	 * If it was previously connected, conn_fully_bound would have
4569 	 * been set.
4570 	 */
4571 	connp->conn_fully_bound = B_FALSE;
4572 
4573 	src_ire = NULL;
4574 	ipif = NULL;
4575 
4576 	zoneid = IPCL_ZONEID(connp);
4577 
4578 	if (src_addr) {
4579 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4580 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4581 		/*
4582 		 * If an address other than 0.0.0.0 is requested,
4583 		 * we verify that it is a valid address for bind
4584 		 * Note: Following code is in if-else-if form for
4585 		 * readability compared to a condition check.
4586 		 */
4587 		/* LINTED - statement has no consequent */
4588 		if (IRE_IS_LOCAL(src_ire)) {
4589 			/*
4590 			 * (2) Bind to address of local UP interface
4591 			 */
4592 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4593 			/*
4594 			 * (4) Bind to broadcast address
4595 			 * Note: permitted only from transports that
4596 			 * request IRE
4597 			 */
4598 			if (!ire_requested)
4599 				error = EADDRNOTAVAIL;
4600 		} else {
4601 			/*
4602 			 * (3) Bind to address of local DOWN interface
4603 			 * (ipif_lookup_addr() looks up all interfaces
4604 			 * but we do not get here for UP interfaces
4605 			 * - case (2) above)
4606 			 * We put the protocol byte back into the mblk
4607 			 * since we may come back via ip_wput_nondata()
4608 			 * later with this mblk if ipif_lookup_addr chooses
4609 			 * to defer processing.
4610 			 */
4611 			*mp->b_wptr++ = (char)connp->conn_ulp;
4612 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4613 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4614 			    &error, ipst)) != NULL) {
4615 				ipif_refrele(ipif);
4616 			} else if (error == EINPROGRESS) {
4617 				if (src_ire != NULL)
4618 					ire_refrele(src_ire);
4619 				return (EINPROGRESS);
4620 			} else if (CLASSD(src_addr)) {
4621 				error = 0;
4622 				if (src_ire != NULL)
4623 					ire_refrele(src_ire);
4624 				/*
4625 				 * (5) bind to multicast address.
4626 				 * Fake out the IRE returned to upper
4627 				 * layer to be a broadcast IRE.
4628 				 */
4629 				src_ire = ire_ctable_lookup(
4630 				    INADDR_BROADCAST, INADDR_ANY,
4631 				    IRE_BROADCAST, NULL, zoneid, NULL,
4632 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4633 				    ipst);
4634 				if (src_ire == NULL || !ire_requested)
4635 					error = EADDRNOTAVAIL;
4636 			} else {
4637 				/*
4638 				 * Not a valid address for bind
4639 				 */
4640 				error = EADDRNOTAVAIL;
4641 			}
4642 			/*
4643 			 * Just to keep it consistent with the processing in
4644 			 * ip_bind_v4()
4645 			 */
4646 			mp->b_wptr--;
4647 		}
4648 		if (error) {
4649 			/* Red Alert!  Attempting to be a bogon! */
4650 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4651 			    ntohl(src_addr)));
4652 			goto bad_addr;
4653 		}
4654 	}
4655 
4656 	/*
4657 	 * Allow setting new policies. For example, disconnects come
4658 	 * down as ipa_t bind. As we would have set conn_policy_cached
4659 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4660 	 * can change after the disconnect.
4661 	 */
4662 	connp->conn_policy_cached = B_FALSE;
4663 
4664 	/*
4665 	 * If not fanout_insert this was just an address verification
4666 	 */
4667 	if (fanout_insert) {
4668 		/*
4669 		 * The addresses have been verified. Time to insert in
4670 		 * the correct fanout list.
4671 		 */
4672 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4673 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4674 		connp->conn_lport = lport;
4675 		connp->conn_fport = 0;
4676 		/*
4677 		 * Do we need to add a check to reject Multicast packets
4678 		 */
4679 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4680 	}
4681 
4682 	if (error == 0) {
4683 		if (ire_requested) {
4684 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4685 				error = -1;
4686 				/* Falls through to bad_addr */
4687 			}
4688 		} else if (ipsec_policy_set) {
4689 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4690 				error = -1;
4691 				/* Falls through to bad_addr */
4692 			}
4693 		}
4694 	}
4695 bad_addr:
4696 	if (error != 0) {
4697 		if (connp->conn_anon_port) {
4698 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4699 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4700 			    B_FALSE);
4701 		}
4702 		connp->conn_mlp_type = mlptSingle;
4703 	}
4704 	if (src_ire != NULL)
4705 		IRE_REFRELE(src_ire);
4706 	if (ipsec_policy_set) {
4707 		ASSERT(policy_mp == mp->b_cont);
4708 		ASSERT(policy_mp != NULL);
4709 		freeb(policy_mp);
4710 		/*
4711 		 * As of now assume that nothing else accompanies
4712 		 * IPSEC_POLICY_SET.
4713 		 */
4714 		mp->b_cont = NULL;
4715 	}
4716 	return (error);
4717 }
4718 
4719 /*
4720  * Verify that both the source and destination addresses
4721  * are valid.  If verify_dst is false, then the destination address may be
4722  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4723  * destination reachability, while tunnels do not.
4724  * Note that we allow connect to broadcast and multicast
4725  * addresses when ire_requested is set. Thus the ULP
4726  * has to check for IRE_BROADCAST and multicast.
4727  *
4728  * Returns zero if ok.
4729  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4730  * (for use with TSYSERR reply).
4731  *
4732  * Note: lport and fport are in network byte order.
4733  */
4734 int
4735 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4736     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4737     boolean_t ire_requested, boolean_t ipsec_policy_set,
4738     boolean_t fanout_insert, boolean_t verify_dst)
4739 {
4740 	ire_t		*src_ire;
4741 	ire_t		*dst_ire;
4742 	int		error = 0;
4743 	int 		protocol;
4744 	mblk_t		*policy_mp;
4745 	ire_t		*sire = NULL;
4746 	ire_t		*md_dst_ire = NULL;
4747 	ire_t		*lso_dst_ire = NULL;
4748 	ill_t		*ill = NULL;
4749 	zoneid_t	zoneid;
4750 	ipaddr_t	src_addr = *src_addrp;
4751 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4752 
4753 	src_ire = dst_ire = NULL;
4754 	protocol = *mp->b_wptr & 0xFF;
4755 
4756 	/*
4757 	 * If we never got a disconnect before, clear it now.
4758 	 */
4759 	connp->conn_fully_bound = B_FALSE;
4760 
4761 	if (ipsec_policy_set) {
4762 		policy_mp = mp->b_cont;
4763 	}
4764 
4765 	zoneid = IPCL_ZONEID(connp);
4766 
4767 	if (CLASSD(dst_addr)) {
4768 		/* Pick up an IRE_BROADCAST */
4769 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4770 		    NULL, zoneid, MBLK_GETLABEL(mp),
4771 		    (MATCH_IRE_RECURSIVE |
4772 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4773 		    MATCH_IRE_SECATTR), ipst);
4774 	} else {
4775 		/*
4776 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4777 		 * and onlink ipif is not found set ENETUNREACH error.
4778 		 */
4779 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4780 			ipif_t *ipif;
4781 
4782 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4783 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4784 			if (ipif == NULL) {
4785 				error = ENETUNREACH;
4786 				goto bad_addr;
4787 			}
4788 			ipif_refrele(ipif);
4789 		}
4790 
4791 		if (connp->conn_nexthop_set) {
4792 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4793 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4794 			    MATCH_IRE_SECATTR, ipst);
4795 		} else {
4796 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4797 			    &sire, zoneid, MBLK_GETLABEL(mp),
4798 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4799 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4800 			    MATCH_IRE_SECATTR), ipst);
4801 		}
4802 	}
4803 	/*
4804 	 * dst_ire can't be a broadcast when not ire_requested.
4805 	 * We also prevent ire's with src address INADDR_ANY to
4806 	 * be used, which are created temporarily for
4807 	 * sending out packets from endpoints that have
4808 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4809 	 * reachable.  If verify_dst is false, the destination needn't be
4810 	 * reachable.
4811 	 *
4812 	 * If we match on a reject or black hole, then we've got a
4813 	 * local failure.  May as well fail out the connect() attempt,
4814 	 * since it's never going to succeed.
4815 	 */
4816 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4817 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4818 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4819 		/*
4820 		 * If we're verifying destination reachability, we always want
4821 		 * to complain here.
4822 		 *
4823 		 * If we're not verifying destination reachability but the
4824 		 * destination has a route, we still want to fail on the
4825 		 * temporary address and broadcast address tests.
4826 		 */
4827 		if (verify_dst || (dst_ire != NULL)) {
4828 			if (ip_debug > 2) {
4829 				pr_addr_dbg("ip_bind_connected: bad connected "
4830 				    "dst %s\n", AF_INET, &dst_addr);
4831 			}
4832 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4833 				error = ENETUNREACH;
4834 			else
4835 				error = EHOSTUNREACH;
4836 			goto bad_addr;
4837 		}
4838 	}
4839 
4840 	/*
4841 	 * We now know that routing will allow us to reach the destination.
4842 	 * Check whether Trusted Solaris policy allows communication with this
4843 	 * host, and pretend that the destination is unreachable if not.
4844 	 *
4845 	 * This is never a problem for TCP, since that transport is known to
4846 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4847 	 * handling.  If the remote is unreachable, it will be detected at that
4848 	 * point, so there's no reason to check it here.
4849 	 *
4850 	 * Note that for sendto (and other datagram-oriented friends), this
4851 	 * check is done as part of the data path label computation instead.
4852 	 * The check here is just to make non-TCP connect() report the right
4853 	 * error.
4854 	 */
4855 	if (dst_ire != NULL && is_system_labeled() &&
4856 	    !IPCL_IS_TCP(connp) &&
4857 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4858 	    connp->conn_mac_exempt, ipst) != 0) {
4859 		error = EHOSTUNREACH;
4860 		if (ip_debug > 2) {
4861 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4862 			    AF_INET, &dst_addr);
4863 		}
4864 		goto bad_addr;
4865 	}
4866 
4867 	/*
4868 	 * If the app does a connect(), it means that it will most likely
4869 	 * send more than 1 packet to the destination.  It makes sense
4870 	 * to clear the temporary flag.
4871 	 */
4872 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4873 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4874 		irb_t *irb = dst_ire->ire_bucket;
4875 
4876 		rw_enter(&irb->irb_lock, RW_WRITER);
4877 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4878 		irb->irb_tmp_ire_cnt--;
4879 		rw_exit(&irb->irb_lock);
4880 	}
4881 
4882 	/*
4883 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4884 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4885 	 * eligibility tests for passive connects are handled separately
4886 	 * through tcp_adapt_ire().  We do this before the source address
4887 	 * selection, because dst_ire may change after a call to
4888 	 * ipif_select_source().  This is a best-effort check, as the
4889 	 * packet for this connection may not actually go through
4890 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4891 	 * calling ip_newroute().  This is why we further check on the
4892 	 * IRE during LSO/Multidata packet transmission in
4893 	 * tcp_lsosend()/tcp_multisend().
4894 	 */
4895 	if (!ipsec_policy_set && dst_ire != NULL &&
4896 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4897 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4898 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4899 			lso_dst_ire = dst_ire;
4900 			IRE_REFHOLD(lso_dst_ire);
4901 		} else if (ipst->ips_ip_multidata_outbound &&
4902 		    ILL_MDT_CAPABLE(ill)) {
4903 			md_dst_ire = dst_ire;
4904 			IRE_REFHOLD(md_dst_ire);
4905 		}
4906 	}
4907 
4908 	if (dst_ire != NULL &&
4909 	    dst_ire->ire_type == IRE_LOCAL &&
4910 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4911 		/*
4912 		 * If the IRE belongs to a different zone, look for a matching
4913 		 * route in the forwarding table and use the source address from
4914 		 * that route.
4915 		 */
4916 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4917 		    zoneid, 0, NULL,
4918 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4919 		    MATCH_IRE_RJ_BHOLE, ipst);
4920 		if (src_ire == NULL) {
4921 			error = EHOSTUNREACH;
4922 			goto bad_addr;
4923 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4924 			if (!(src_ire->ire_type & IRE_HOST))
4925 				error = ENETUNREACH;
4926 			else
4927 				error = EHOSTUNREACH;
4928 			goto bad_addr;
4929 		}
4930 		if (src_addr == INADDR_ANY)
4931 			src_addr = src_ire->ire_src_addr;
4932 		ire_refrele(src_ire);
4933 		src_ire = NULL;
4934 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4935 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4936 			src_addr = sire->ire_src_addr;
4937 			ire_refrele(dst_ire);
4938 			dst_ire = sire;
4939 			sire = NULL;
4940 		} else {
4941 			/*
4942 			 * Pick a source address so that a proper inbound
4943 			 * load spreading would happen.
4944 			 */
4945 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4946 			ipif_t *src_ipif = NULL;
4947 			ire_t *ipif_ire;
4948 
4949 			/*
4950 			 * Supply a local source address such that inbound
4951 			 * load spreading happens.
4952 			 *
4953 			 * Determine the best source address on this ill for
4954 			 * the destination.
4955 			 *
4956 			 * 1) For broadcast, we should return a broadcast ire
4957 			 *    found above so that upper layers know that the
4958 			 *    destination address is a broadcast address.
4959 			 *
4960 			 * 2) If this is part of a group, select a better
4961 			 *    source address so that better inbound load
4962 			 *    balancing happens. Do the same if the ipif
4963 			 *    is DEPRECATED.
4964 			 *
4965 			 * 3) If the outgoing interface is part of a usesrc
4966 			 *    group, then try selecting a source address from
4967 			 *    the usesrc ILL.
4968 			 */
4969 			if ((dst_ire->ire_zoneid != zoneid &&
4970 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4971 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4972 			    ((dst_ill->ill_group != NULL) ||
4973 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4974 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4975 				/*
4976 				 * If the destination is reachable via a
4977 				 * given gateway, the selected source address
4978 				 * should be in the same subnet as the gateway.
4979 				 * Otherwise, the destination is not reachable.
4980 				 *
4981 				 * If there are no interfaces on the same subnet
4982 				 * as the destination, ipif_select_source gives
4983 				 * first non-deprecated interface which might be
4984 				 * on a different subnet than the gateway.
4985 				 * This is not desirable. Hence pass the dst_ire
4986 				 * source address to ipif_select_source.
4987 				 * It is sure that the destination is reachable
4988 				 * with the dst_ire source address subnet.
4989 				 * So passing dst_ire source address to
4990 				 * ipif_select_source will make sure that the
4991 				 * selected source will be on the same subnet
4992 				 * as dst_ire source address.
4993 				 */
4994 				ipaddr_t saddr =
4995 				    dst_ire->ire_ipif->ipif_src_addr;
4996 				src_ipif = ipif_select_source(dst_ill,
4997 				    saddr, zoneid);
4998 				if (src_ipif != NULL) {
4999 					if (IS_VNI(src_ipif->ipif_ill)) {
5000 						/*
5001 						 * For VNI there is no
5002 						 * interface route
5003 						 */
5004 						src_addr =
5005 						    src_ipif->ipif_src_addr;
5006 					} else {
5007 						ipif_ire =
5008 						    ipif_to_ire(src_ipif);
5009 						if (ipif_ire != NULL) {
5010 							IRE_REFRELE(dst_ire);
5011 							dst_ire = ipif_ire;
5012 						}
5013 						src_addr =
5014 						    dst_ire->ire_src_addr;
5015 					}
5016 					ipif_refrele(src_ipif);
5017 				} else {
5018 					src_addr = dst_ire->ire_src_addr;
5019 				}
5020 			} else {
5021 				src_addr = dst_ire->ire_src_addr;
5022 			}
5023 		}
5024 	}
5025 
5026 	/*
5027 	 * We do ire_route_lookup() here (and not
5028 	 * interface lookup as we assert that
5029 	 * src_addr should only come from an
5030 	 * UP interface for hard binding.
5031 	 */
5032 	ASSERT(src_ire == NULL);
5033 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5034 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5035 	/* src_ire must be a local|loopback */
5036 	if (!IRE_IS_LOCAL(src_ire)) {
5037 		if (ip_debug > 2) {
5038 			pr_addr_dbg("ip_bind_connected: bad connected "
5039 			    "src %s\n", AF_INET, &src_addr);
5040 		}
5041 		error = EADDRNOTAVAIL;
5042 		goto bad_addr;
5043 	}
5044 
5045 	/*
5046 	 * If the source address is a loopback address, the
5047 	 * destination had best be local or multicast.
5048 	 * The transports that can't handle multicast will reject
5049 	 * those addresses.
5050 	 */
5051 	if (src_ire->ire_type == IRE_LOOPBACK &&
5052 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5053 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5054 		error = -1;
5055 		goto bad_addr;
5056 	}
5057 
5058 	/*
5059 	 * Allow setting new policies. For example, disconnects come
5060 	 * down as ipa_t bind. As we would have set conn_policy_cached
5061 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5062 	 * can change after the disconnect.
5063 	 */
5064 	connp->conn_policy_cached = B_FALSE;
5065 
5066 	/*
5067 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5068 	 * can handle their passed-in conn's.
5069 	 */
5070 
5071 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5072 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5073 	connp->conn_lport = lport;
5074 	connp->conn_fport = fport;
5075 	*src_addrp = src_addr;
5076 
5077 	ASSERT(!(ipsec_policy_set && ire_requested));
5078 	if (ire_requested) {
5079 		iulp_t *ulp_info = NULL;
5080 
5081 		/*
5082 		 * Note that sire will not be NULL if this is an off-link
5083 		 * connection and there is not cache for that dest yet.
5084 		 *
5085 		 * XXX Because of an existing bug, if there are multiple
5086 		 * default routes, the IRE returned now may not be the actual
5087 		 * default route used (default routes are chosen in a
5088 		 * round robin fashion).  So if the metrics for different
5089 		 * default routes are different, we may return the wrong
5090 		 * metrics.  This will not be a problem if the existing
5091 		 * bug is fixed.
5092 		 */
5093 		if (sire != NULL) {
5094 			ulp_info = &(sire->ire_uinfo);
5095 		}
5096 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5097 			error = -1;
5098 			goto bad_addr;
5099 		}
5100 	} else if (ipsec_policy_set) {
5101 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5102 			error = -1;
5103 			goto bad_addr;
5104 		}
5105 	}
5106 
5107 	/*
5108 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5109 	 * we'll cache that.  If we don't, we'll inherit global policy.
5110 	 *
5111 	 * We can't insert until the conn reflects the policy. Note that
5112 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5113 	 * connections where we don't have a policy. This is to prevent
5114 	 * global policy lookups in the inbound path.
5115 	 *
5116 	 * If we insert before we set conn_policy_cached,
5117 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5118 	 * because global policy cound be non-empty. We normally call
5119 	 * ipsec_check_policy() for conn_policy_cached connections only if
5120 	 * ipc_in_enforce_policy is set. But in this case,
5121 	 * conn_policy_cached can get set anytime since we made the
5122 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5123 	 * called, which will make the above assumption false.  Thus, we
5124 	 * need to insert after we set conn_policy_cached.
5125 	 */
5126 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5127 		goto bad_addr;
5128 
5129 	if (fanout_insert) {
5130 		/*
5131 		 * The addresses have been verified. Time to insert in
5132 		 * the correct fanout list.
5133 		 */
5134 		error = ipcl_conn_insert(connp, protocol, src_addr,
5135 		    dst_addr, connp->conn_ports);
5136 	}
5137 
5138 	if (error == 0) {
5139 		connp->conn_fully_bound = B_TRUE;
5140 		/*
5141 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5142 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5143 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5144 		 * ip_xxinfo_return(), which performs further checks
5145 		 * against them and upon success, returns the LSO/MDT info
5146 		 * mblk which we will attach to the bind acknowledgment.
5147 		 */
5148 		if (lso_dst_ire != NULL) {
5149 			mblk_t *lsoinfo_mp;
5150 
5151 			ASSERT(ill->ill_lso_capab != NULL);
5152 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5153 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5154 				linkb(mp, lsoinfo_mp);
5155 		} else if (md_dst_ire != NULL) {
5156 			mblk_t *mdinfo_mp;
5157 
5158 			ASSERT(ill->ill_mdt_capab != NULL);
5159 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5160 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5161 				linkb(mp, mdinfo_mp);
5162 		}
5163 	}
5164 bad_addr:
5165 	if (ipsec_policy_set) {
5166 		ASSERT(policy_mp == mp->b_cont);
5167 		ASSERT(policy_mp != NULL);
5168 		freeb(policy_mp);
5169 		/*
5170 		 * As of now assume that nothing else accompanies
5171 		 * IPSEC_POLICY_SET.
5172 		 */
5173 		mp->b_cont = NULL;
5174 	}
5175 	if (src_ire != NULL)
5176 		IRE_REFRELE(src_ire);
5177 	if (dst_ire != NULL)
5178 		IRE_REFRELE(dst_ire);
5179 	if (sire != NULL)
5180 		IRE_REFRELE(sire);
5181 	if (md_dst_ire != NULL)
5182 		IRE_REFRELE(md_dst_ire);
5183 	if (lso_dst_ire != NULL)
5184 		IRE_REFRELE(lso_dst_ire);
5185 	return (error);
5186 }
5187 
5188 /*
5189  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5190  * Prefers dst_ire over src_ire.
5191  */
5192 static boolean_t
5193 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5194 {
5195 	mblk_t	*mp1;
5196 	ire_t *ret_ire = NULL;
5197 
5198 	mp1 = mp->b_cont;
5199 	ASSERT(mp1 != NULL);
5200 
5201 	if (ire != NULL) {
5202 		/*
5203 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5204 		 * appended mblk. Its <upper protocol>'s
5205 		 * job to make sure there is room.
5206 		 */
5207 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5208 			return (0);
5209 
5210 		mp1->b_datap->db_type = IRE_DB_TYPE;
5211 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5212 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5213 		ret_ire = (ire_t *)mp1->b_rptr;
5214 		/*
5215 		 * Pass the latest setting of the ip_path_mtu_discovery and
5216 		 * copy the ulp info if any.
5217 		 */
5218 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5219 		    IPH_DF : 0;
5220 		if (ulp_info != NULL) {
5221 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5222 			    sizeof (iulp_t));
5223 		}
5224 		ret_ire->ire_mp = mp1;
5225 	} else {
5226 		/*
5227 		 * No IRE was found. Remove IRE mblk.
5228 		 */
5229 		mp->b_cont = mp1->b_cont;
5230 		freeb(mp1);
5231 	}
5232 
5233 	return (1);
5234 }
5235 
5236 /*
5237  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5238  * the final piece where we don't.  Return a pointer to the first mblk in the
5239  * result, and update the pointer to the next mblk to chew on.  If anything
5240  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5241  * NULL pointer.
5242  */
5243 mblk_t *
5244 ip_carve_mp(mblk_t **mpp, ssize_t len)
5245 {
5246 	mblk_t	*mp0;
5247 	mblk_t	*mp1;
5248 	mblk_t	*mp2;
5249 
5250 	if (!len || !mpp || !(mp0 = *mpp))
5251 		return (NULL);
5252 	/* If we aren't going to consume the first mblk, we need a dup. */
5253 	if (mp0->b_wptr - mp0->b_rptr > len) {
5254 		mp1 = dupb(mp0);
5255 		if (mp1) {
5256 			/* Partition the data between the two mblks. */
5257 			mp1->b_wptr = mp1->b_rptr + len;
5258 			mp0->b_rptr = mp1->b_wptr;
5259 			/*
5260 			 * after adjustments if mblk not consumed is now
5261 			 * unaligned, try to align it. If this fails free
5262 			 * all messages and let upper layer recover.
5263 			 */
5264 			if (!OK_32PTR(mp0->b_rptr)) {
5265 				if (!pullupmsg(mp0, -1)) {
5266 					freemsg(mp0);
5267 					freemsg(mp1);
5268 					*mpp = NULL;
5269 					return (NULL);
5270 				}
5271 			}
5272 		}
5273 		return (mp1);
5274 	}
5275 	/* Eat through as many mblks as we need to get len bytes. */
5276 	len -= mp0->b_wptr - mp0->b_rptr;
5277 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5278 		if (mp2->b_wptr - mp2->b_rptr > len) {
5279 			/*
5280 			 * We won't consume the entire last mblk.  Like
5281 			 * above, dup and partition it.
5282 			 */
5283 			mp1->b_cont = dupb(mp2);
5284 			mp1 = mp1->b_cont;
5285 			if (!mp1) {
5286 				/*
5287 				 * Trouble.  Rather than go to a lot of
5288 				 * trouble to clean up, we free the messages.
5289 				 * This won't be any worse than losing it on
5290 				 * the wire.
5291 				 */
5292 				freemsg(mp0);
5293 				freemsg(mp2);
5294 				*mpp = NULL;
5295 				return (NULL);
5296 			}
5297 			mp1->b_wptr = mp1->b_rptr + len;
5298 			mp2->b_rptr = mp1->b_wptr;
5299 			/*
5300 			 * after adjustments if mblk not consumed is now
5301 			 * unaligned, try to align it. If this fails free
5302 			 * all messages and let upper layer recover.
5303 			 */
5304 			if (!OK_32PTR(mp2->b_rptr)) {
5305 				if (!pullupmsg(mp2, -1)) {
5306 					freemsg(mp0);
5307 					freemsg(mp2);
5308 					*mpp = NULL;
5309 					return (NULL);
5310 				}
5311 			}
5312 			*mpp = mp2;
5313 			return (mp0);
5314 		}
5315 		/* Decrement len by the amount we just got. */
5316 		len -= mp2->b_wptr - mp2->b_rptr;
5317 	}
5318 	/*
5319 	 * len should be reduced to zero now.  If not our caller has
5320 	 * screwed up.
5321 	 */
5322 	if (len) {
5323 		/* Shouldn't happen! */
5324 		freemsg(mp0);
5325 		*mpp = NULL;
5326 		return (NULL);
5327 	}
5328 	/*
5329 	 * We consumed up to exactly the end of an mblk.  Detach the part
5330 	 * we are returning from the rest of the chain.
5331 	 */
5332 	mp1->b_cont = NULL;
5333 	*mpp = mp2;
5334 	return (mp0);
5335 }
5336 
5337 /* The ill stream is being unplumbed. Called from ip_close */
5338 int
5339 ip_modclose(ill_t *ill)
5340 {
5341 	boolean_t success;
5342 	ipsq_t	*ipsq;
5343 	ipif_t	*ipif;
5344 	queue_t	*q = ill->ill_rq;
5345 	ip_stack_t	*ipst = ill->ill_ipst;
5346 	clock_t timeout;
5347 
5348 	/*
5349 	 * Wait for the ACKs of all deferred control messages to be processed.
5350 	 * In particular, we wait for a potential capability reset initiated
5351 	 * in ip_sioctl_plink() to complete before proceeding.
5352 	 *
5353 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5354 	 * in case the driver never replies.
5355 	 */
5356 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5357 	mutex_enter(&ill->ill_lock);
5358 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5359 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5360 			/* Timeout */
5361 			break;
5362 		}
5363 	}
5364 	mutex_exit(&ill->ill_lock);
5365 
5366 	/*
5367 	 * Forcibly enter the ipsq after some delay. This is to take
5368 	 * care of the case when some ioctl does not complete because
5369 	 * we sent a control message to the driver and it did not
5370 	 * send us a reply. We want to be able to at least unplumb
5371 	 * and replumb rather than force the user to reboot the system.
5372 	 */
5373 	success = ipsq_enter(ill, B_FALSE);
5374 
5375 	/*
5376 	 * Open/close/push/pop is guaranteed to be single threaded
5377 	 * per stream by STREAMS. FS guarantees that all references
5378 	 * from top are gone before close is called. So there can't
5379 	 * be another close thread that has set CONDEMNED on this ill.
5380 	 * and cause ipsq_enter to return failure.
5381 	 */
5382 	ASSERT(success);
5383 	ipsq = ill->ill_phyint->phyint_ipsq;
5384 
5385 	/*
5386 	 * Mark it condemned. No new reference will be made to this ill.
5387 	 * Lookup functions will return an error. Threads that try to
5388 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5389 	 * that the refcnt will drop down to zero.
5390 	 */
5391 	mutex_enter(&ill->ill_lock);
5392 	ill->ill_state_flags |= ILL_CONDEMNED;
5393 	for (ipif = ill->ill_ipif; ipif != NULL;
5394 	    ipif = ipif->ipif_next) {
5395 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5396 	}
5397 	/*
5398 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5399 	 * returns  error if ILL_CONDEMNED is set
5400 	 */
5401 	cv_broadcast(&ill->ill_cv);
5402 	mutex_exit(&ill->ill_lock);
5403 
5404 	/*
5405 	 * Send all the deferred DLPI messages downstream which came in
5406 	 * during the small window right before ipsq_enter(). We do this
5407 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5408 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5409 	 */
5410 	ill_dlpi_send_deferred(ill);
5411 
5412 	/*
5413 	 * Shut down fragmentation reassembly.
5414 	 * ill_frag_timer won't start a timer again.
5415 	 * Now cancel any existing timer
5416 	 */
5417 	(void) untimeout(ill->ill_frag_timer_id);
5418 	(void) ill_frag_timeout(ill, 0);
5419 
5420 	/*
5421 	 * If MOVE was in progress, clear the
5422 	 * move_in_progress fields also.
5423 	 */
5424 	if (ill->ill_move_in_progress) {
5425 		ILL_CLEAR_MOVE(ill);
5426 	}
5427 
5428 	/*
5429 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5430 	 * this ill. Then wait for the refcnts to drop to zero.
5431 	 * ill_is_quiescent checks whether the ill is really quiescent.
5432 	 * Then make sure that threads that are waiting to enter the
5433 	 * ipsq have seen the error returned by ipsq_enter and have
5434 	 * gone away. Then we call ill_delete_tail which does the
5435 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5436 	 */
5437 	ill_delete(ill);
5438 	mutex_enter(&ill->ill_lock);
5439 	while (!ill_is_quiescent(ill))
5440 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5441 	while (ill->ill_waiters)
5442 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5443 
5444 	mutex_exit(&ill->ill_lock);
5445 
5446 	/*
5447 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5448 	 * it held until the end of the function since the cleanup
5449 	 * below needs to be able to use the ip_stack_t.
5450 	 */
5451 	netstack_hold(ipst->ips_netstack);
5452 
5453 	/* qprocsoff is called in ill_delete_tail */
5454 	ill_delete_tail(ill);
5455 	ASSERT(ill->ill_ipst == NULL);
5456 
5457 	/*
5458 	 * Walk through all upper (conn) streams and qenable
5459 	 * those that have queued data.
5460 	 * close synchronization needs this to
5461 	 * be done to ensure that all upper layers blocked
5462 	 * due to flow control to the closing device
5463 	 * get unblocked.
5464 	 */
5465 	ip1dbg(("ip_wsrv: walking\n"));
5466 	conn_walk_drain(ipst);
5467 
5468 	mutex_enter(&ipst->ips_ip_mi_lock);
5469 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5470 	mutex_exit(&ipst->ips_ip_mi_lock);
5471 
5472 	/*
5473 	 * credp could be null if the open didn't succeed and ip_modopen
5474 	 * itself calls ip_close.
5475 	 */
5476 	if (ill->ill_credp != NULL)
5477 		crfree(ill->ill_credp);
5478 
5479 	mutex_enter(&ill->ill_lock);
5480 	ill_nic_info_dispatch(ill);
5481 	mutex_exit(&ill->ill_lock);
5482 
5483 	/*
5484 	 * Now we are done with the module close pieces that
5485 	 * need the netstack_t.
5486 	 */
5487 	netstack_rele(ipst->ips_netstack);
5488 
5489 	mi_close_free((IDP)ill);
5490 	q->q_ptr = WR(q)->q_ptr = NULL;
5491 
5492 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5493 
5494 	return (0);
5495 }
5496 
5497 /*
5498  * This is called as part of close() for IP, UDP, ICMP, and RTS
5499  * in order to quiesce the conn.
5500  */
5501 void
5502 ip_quiesce_conn(conn_t *connp)
5503 {
5504 	boolean_t	drain_cleanup_reqd = B_FALSE;
5505 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5506 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5507 	ip_stack_t	*ipst;
5508 
5509 	ASSERT(!IPCL_IS_TCP(connp));
5510 	ipst = connp->conn_netstack->netstack_ip;
5511 
5512 	/*
5513 	 * Mark the conn as closing, and this conn must not be
5514 	 * inserted in future into any list. Eg. conn_drain_insert(),
5515 	 * won't insert this conn into the conn_drain_list.
5516 	 * Similarly ill_pending_mp_add() will not add any mp to
5517 	 * the pending mp list, after this conn has started closing.
5518 	 *
5519 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5520 	 * cannot get set henceforth.
5521 	 */
5522 	mutex_enter(&connp->conn_lock);
5523 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5524 	connp->conn_state_flags |= CONN_CLOSING;
5525 	if (connp->conn_idl != NULL)
5526 		drain_cleanup_reqd = B_TRUE;
5527 	if (connp->conn_oper_pending_ill != NULL)
5528 		conn_ioctl_cleanup_reqd = B_TRUE;
5529 	if (connp->conn_ilg_inuse != 0)
5530 		ilg_cleanup_reqd = B_TRUE;
5531 	mutex_exit(&connp->conn_lock);
5532 
5533 	if (conn_ioctl_cleanup_reqd)
5534 		conn_ioctl_cleanup(connp);
5535 
5536 	if (is_system_labeled() && connp->conn_anon_port) {
5537 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5538 		    connp->conn_mlp_type, connp->conn_ulp,
5539 		    ntohs(connp->conn_lport), B_FALSE);
5540 		connp->conn_anon_port = 0;
5541 	}
5542 	connp->conn_mlp_type = mlptSingle;
5543 
5544 	/*
5545 	 * Remove this conn from any fanout list it is on.
5546 	 * and then wait for any threads currently operating
5547 	 * on this endpoint to finish
5548 	 */
5549 	ipcl_hash_remove(connp);
5550 
5551 	/*
5552 	 * Remove this conn from the drain list, and do
5553 	 * any other cleanup that may be required.
5554 	 * (Only non-tcp streams may have a non-null conn_idl.
5555 	 * TCP streams are never flow controlled, and
5556 	 * conn_idl will be null)
5557 	 */
5558 	if (drain_cleanup_reqd)
5559 		conn_drain_tail(connp, B_TRUE);
5560 
5561 	if (connp == ipst->ips_ip_g_mrouter)
5562 		(void) ip_mrouter_done(NULL, ipst);
5563 
5564 	if (ilg_cleanup_reqd)
5565 		ilg_delete_all(connp);
5566 
5567 	conn_delete_ire(connp, NULL);
5568 
5569 	/*
5570 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5571 	 * callers from write side can't be there now because close
5572 	 * is in progress. The only other caller is ipcl_walk
5573 	 * which checks for the condemned flag.
5574 	 */
5575 	mutex_enter(&connp->conn_lock);
5576 	connp->conn_state_flags |= CONN_CONDEMNED;
5577 	while (connp->conn_ref != 1)
5578 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5579 	connp->conn_state_flags |= CONN_QUIESCED;
5580 	mutex_exit(&connp->conn_lock);
5581 }
5582 
5583 /* ARGSUSED */
5584 int
5585 ip_close(queue_t *q, int flags)
5586 {
5587 	conn_t		*connp;
5588 
5589 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5590 
5591 	/*
5592 	 * Call the appropriate delete routine depending on whether this is
5593 	 * a module or device.
5594 	 */
5595 	if (WR(q)->q_next != NULL) {
5596 		/* This is a module close */
5597 		return (ip_modclose((ill_t *)q->q_ptr));
5598 	}
5599 
5600 	connp = q->q_ptr;
5601 	ip_quiesce_conn(connp);
5602 
5603 	qprocsoff(q);
5604 
5605 	/*
5606 	 * Now we are truly single threaded on this stream, and can
5607 	 * delete the things hanging off the connp, and finally the connp.
5608 	 * We removed this connp from the fanout list, it cannot be
5609 	 * accessed thru the fanouts, and we already waited for the
5610 	 * conn_ref to drop to 0. We are already in close, so
5611 	 * there cannot be any other thread from the top. qprocsoff
5612 	 * has completed, and service has completed or won't run in
5613 	 * future.
5614 	 */
5615 	ASSERT(connp->conn_ref == 1);
5616 
5617 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5618 
5619 	connp->conn_ref--;
5620 	ipcl_conn_destroy(connp);
5621 
5622 	q->q_ptr = WR(q)->q_ptr = NULL;
5623 	return (0);
5624 }
5625 
5626 /*
5627  * Wapper around putnext() so that ip_rts_request can merely use
5628  * conn_recv.
5629  */
5630 /*ARGSUSED2*/
5631 static void
5632 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5633 {
5634 	conn_t *connp = (conn_t *)arg1;
5635 
5636 	putnext(connp->conn_rq, mp);
5637 }
5638 
5639 /* Return the IP checksum for the IP header at "iph". */
5640 uint16_t
5641 ip_csum_hdr(ipha_t *ipha)
5642 {
5643 	uint16_t	*uph;
5644 	uint32_t	sum;
5645 	int		opt_len;
5646 
5647 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5648 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5649 	uph = (uint16_t *)ipha;
5650 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5651 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5652 	if (opt_len > 0) {
5653 		do {
5654 			sum += uph[10];
5655 			sum += uph[11];
5656 			uph += 2;
5657 		} while (--opt_len);
5658 	}
5659 	sum = (sum & 0xFFFF) + (sum >> 16);
5660 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5661 	if (sum == 0xffff)
5662 		sum = 0;
5663 	return ((uint16_t)sum);
5664 }
5665 
5666 /*
5667  * Called when the module is about to be unloaded
5668  */
5669 void
5670 ip_ddi_destroy(void)
5671 {
5672 	tnet_fini();
5673 
5674 	icmp_ddi_destroy();
5675 	rts_ddi_destroy();
5676 	udp_ddi_destroy();
5677 	sctp_ddi_g_destroy();
5678 	tcp_ddi_g_destroy();
5679 	ipsec_policy_g_destroy();
5680 	ipcl_g_destroy();
5681 	ip_net_g_destroy();
5682 	ip_ire_g_fini();
5683 	inet_minor_destroy(ip_minor_arena);
5684 
5685 #ifdef DEBUG
5686 	list_destroy(&ip_thread_list);
5687 	rw_destroy(&ip_thread_rwlock);
5688 	tsd_destroy(&ip_thread_data);
5689 #endif
5690 
5691 	netstack_unregister(NS_IP);
5692 }
5693 
5694 /*
5695  * First step in cleanup.
5696  */
5697 /* ARGSUSED */
5698 static void
5699 ip_stack_shutdown(netstackid_t stackid, void *arg)
5700 {
5701 	ip_stack_t *ipst = (ip_stack_t *)arg;
5702 
5703 #ifdef NS_DEBUG
5704 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5705 #endif
5706 
5707 	/* Get rid of loopback interfaces and their IREs */
5708 	ip_loopback_cleanup(ipst);
5709 }
5710 
5711 /*
5712  * Free the IP stack instance.
5713  */
5714 static void
5715 ip_stack_fini(netstackid_t stackid, void *arg)
5716 {
5717 	ip_stack_t *ipst = (ip_stack_t *)arg;
5718 	int ret;
5719 
5720 #ifdef NS_DEBUG
5721 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5722 #endif
5723 	ipv4_hook_destroy(ipst);
5724 	ipv6_hook_destroy(ipst);
5725 	ip_net_destroy(ipst);
5726 
5727 	rw_destroy(&ipst->ips_srcid_lock);
5728 
5729 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5730 	ipst->ips_ip_mibkp = NULL;
5731 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5732 	ipst->ips_icmp_mibkp = NULL;
5733 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5734 	ipst->ips_ip_kstat = NULL;
5735 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5736 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5737 	ipst->ips_ip6_kstat = NULL;
5738 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5739 
5740 	nd_free(&ipst->ips_ip_g_nd);
5741 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5742 	ipst->ips_param_arr = NULL;
5743 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5744 	ipst->ips_ndp_arr = NULL;
5745 
5746 	ip_mrouter_stack_destroy(ipst);
5747 
5748 	mutex_destroy(&ipst->ips_ip_mi_lock);
5749 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5750 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5751 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5752 
5753 	ret = untimeout(ipst->ips_igmp_timeout_id);
5754 	if (ret == -1) {
5755 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5756 	} else {
5757 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5758 		ipst->ips_igmp_timeout_id = 0;
5759 	}
5760 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5761 	if (ret == -1) {
5762 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5763 	} else {
5764 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5765 		ipst->ips_igmp_slowtimeout_id = 0;
5766 	}
5767 	ret = untimeout(ipst->ips_mld_timeout_id);
5768 	if (ret == -1) {
5769 		ASSERT(ipst->ips_mld_timeout_id == 0);
5770 	} else {
5771 		ASSERT(ipst->ips_mld_timeout_id != 0);
5772 		ipst->ips_mld_timeout_id = 0;
5773 	}
5774 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5775 	if (ret == -1) {
5776 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5777 	} else {
5778 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5779 		ipst->ips_mld_slowtimeout_id = 0;
5780 	}
5781 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5782 	if (ret == -1) {
5783 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5784 	} else {
5785 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5786 		ipst->ips_ip_ire_expire_id = 0;
5787 	}
5788 
5789 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5790 	mutex_destroy(&ipst->ips_mld_timer_lock);
5791 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5792 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5793 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5794 	rw_destroy(&ipst->ips_ill_g_lock);
5795 
5796 	ip_ire_fini(ipst);
5797 	ip6_asp_free(ipst);
5798 	conn_drain_fini(ipst);
5799 	ipcl_destroy(ipst);
5800 
5801 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5802 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5803 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5804 	ipst->ips_ndp4 = NULL;
5805 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5806 	ipst->ips_ndp6 = NULL;
5807 
5808 	if (ipst->ips_loopback_ksp != NULL) {
5809 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5810 		ipst->ips_loopback_ksp = NULL;
5811 	}
5812 
5813 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5814 	ipst->ips_phyint_g_list = NULL;
5815 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5816 	ipst->ips_ill_g_heads = NULL;
5817 
5818 	kmem_free(ipst, sizeof (*ipst));
5819 }
5820 
5821 /*
5822  * This function is called from the TSD destructor, and is used to debug
5823  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5824  * details.
5825  */
5826 static void
5827 ip_thread_exit(void *phash)
5828 {
5829 	th_hash_t *thh = phash;
5830 
5831 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5832 	list_remove(&ip_thread_list, thh);
5833 	rw_exit(&ip_thread_rwlock);
5834 	mod_hash_destroy_hash(thh->thh_hash);
5835 	kmem_free(thh, sizeof (*thh));
5836 }
5837 
5838 /*
5839  * Called when the IP kernel module is loaded into the kernel
5840  */
5841 void
5842 ip_ddi_init(void)
5843 {
5844 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5845 
5846 	/*
5847 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5848 	 * initial devices: ip, ip6, tcp, tcp6.
5849 	 */
5850 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5851 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5852 		cmn_err(CE_PANIC,
5853 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5854 	}
5855 
5856 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5857 
5858 	ipcl_g_init();
5859 	ip_ire_g_init();
5860 	ip_net_g_init();
5861 
5862 #ifdef DEBUG
5863 	tsd_create(&ip_thread_data, ip_thread_exit);
5864 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5865 	list_create(&ip_thread_list, sizeof (th_hash_t),
5866 	    offsetof(th_hash_t, thh_link));
5867 #endif
5868 
5869 	/*
5870 	 * We want to be informed each time a stack is created or
5871 	 * destroyed in the kernel, so we can maintain the
5872 	 * set of udp_stack_t's.
5873 	 */
5874 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5875 	    ip_stack_fini);
5876 
5877 	ipsec_policy_g_init();
5878 	tcp_ddi_g_init();
5879 	sctp_ddi_g_init();
5880 
5881 	tnet_init();
5882 
5883 	udp_ddi_init();
5884 	rts_ddi_init();
5885 	icmp_ddi_init();
5886 }
5887 
5888 /*
5889  * Initialize the IP stack instance.
5890  */
5891 static void *
5892 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5893 {
5894 	ip_stack_t	*ipst;
5895 	ipparam_t	*pa;
5896 	ipndp_t		*na;
5897 
5898 #ifdef NS_DEBUG
5899 	printf("ip_stack_init(stack %d)\n", stackid);
5900 #endif
5901 
5902 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5903 	ipst->ips_netstack = ns;
5904 
5905 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5906 	    KM_SLEEP);
5907 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5908 	    KM_SLEEP);
5909 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5910 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5911 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5912 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5913 
5914 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5915 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5916 	ipst->ips_igmp_deferred_next = INFINITY;
5917 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5918 	ipst->ips_mld_deferred_next = INFINITY;
5919 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5920 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5921 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5922 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5923 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5924 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5925 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5926 
5927 	ipcl_init(ipst);
5928 	ip_ire_init(ipst);
5929 	ip6_asp_init(ipst);
5930 	ipif_init(ipst);
5931 	conn_drain_init(ipst);
5932 	ip_mrouter_stack_init(ipst);
5933 
5934 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5935 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5936 
5937 	ipst->ips_ip_multirt_log_interval = 1000;
5938 
5939 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5940 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5941 	ipst->ips_ill_index = 1;
5942 
5943 	ipst->ips_saved_ip_g_forward = -1;
5944 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5945 
5946 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5947 	ipst->ips_param_arr = pa;
5948 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5949 
5950 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5951 	ipst->ips_ndp_arr = na;
5952 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5953 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5954 	    (caddr_t)&ipst->ips_ip_g_forward;
5955 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5956 	    (caddr_t)&ipst->ips_ipv6_forward;
5957 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5958 	    "ip_cgtp_filter") == 0);
5959 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5960 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5961 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5962 	    "ipmp_hook_emulation") == 0);
5963 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5964 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5965 
5966 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5967 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5968 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5969 
5970 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5971 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5972 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5973 	ipst->ips_ip6_kstat =
5974 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5975 
5976 	ipst->ips_ipmp_enable_failback = B_TRUE;
5977 
5978 	ipst->ips_ip_src_id = 1;
5979 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5980 
5981 	ip_net_init(ipst, ns);
5982 	ipv4_hook_init(ipst);
5983 	ipv6_hook_init(ipst);
5984 
5985 	return (ipst);
5986 }
5987 
5988 /*
5989  * Allocate and initialize a DLPI template of the specified length.  (May be
5990  * called as writer.)
5991  */
5992 mblk_t *
5993 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5994 {
5995 	mblk_t	*mp;
5996 
5997 	mp = allocb(len, BPRI_MED);
5998 	if (!mp)
5999 		return (NULL);
6000 
6001 	/*
6002 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6003 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6004 	 * that other DLPI are M_PROTO.
6005 	 */
6006 	if (prim == DL_INFO_REQ) {
6007 		mp->b_datap->db_type = M_PCPROTO;
6008 	} else {
6009 		mp->b_datap->db_type = M_PROTO;
6010 	}
6011 
6012 	mp->b_wptr = mp->b_rptr + len;
6013 	bzero(mp->b_rptr, len);
6014 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6015 	return (mp);
6016 }
6017 
6018 const char *
6019 dlpi_prim_str(int prim)
6020 {
6021 	switch (prim) {
6022 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6023 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6024 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6025 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6026 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6027 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6028 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6029 	case DL_OK_ACK:		return ("DL_OK_ACK");
6030 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6031 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6032 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6033 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6034 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6035 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6036 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6037 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6038 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6039 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6040 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6041 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6042 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6043 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6044 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6045 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6046 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6047 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6048 	default:		return ("<unknown primitive>");
6049 	}
6050 }
6051 
6052 const char *
6053 dlpi_err_str(int err)
6054 {
6055 	switch (err) {
6056 	case DL_ACCESS:		return ("DL_ACCESS");
6057 	case DL_BADADDR:	return ("DL_BADADDR");
6058 	case DL_BADCORR:	return ("DL_BADCORR");
6059 	case DL_BADDATA:	return ("DL_BADDATA");
6060 	case DL_BADPPA:		return ("DL_BADPPA");
6061 	case DL_BADPRIM:	return ("DL_BADPRIM");
6062 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6063 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6064 	case DL_BADSAP:		return ("DL_BADSAP");
6065 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6066 	case DL_BOUND:		return ("DL_BOUND");
6067 	case DL_INITFAILED:	return ("DL_INITFAILED");
6068 	case DL_NOADDR:		return ("DL_NOADDR");
6069 	case DL_NOTINIT:	return ("DL_NOTINIT");
6070 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6071 	case DL_SYSERR:		return ("DL_SYSERR");
6072 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6073 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6074 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6075 	case DL_TOOMANY:	return ("DL_TOOMANY");
6076 	case DL_NOTENAB:	return ("DL_NOTENAB");
6077 	case DL_BUSY:		return ("DL_BUSY");
6078 	case DL_NOAUTO:		return ("DL_NOAUTO");
6079 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6080 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6081 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6082 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6083 	case DL_PENDING:	return ("DL_PENDING");
6084 	default:		return ("<unknown error>");
6085 	}
6086 }
6087 
6088 /*
6089  * Debug formatting routine.  Returns a character string representation of the
6090  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6091  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6092  *
6093  * Once the ndd table-printing interfaces are removed, this can be changed to
6094  * standard dotted-decimal form.
6095  */
6096 char *
6097 ip_dot_addr(ipaddr_t addr, char *buf)
6098 {
6099 	uint8_t *ap = (uint8_t *)&addr;
6100 
6101 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6102 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6103 	return (buf);
6104 }
6105 
6106 /*
6107  * Write the given MAC address as a printable string in the usual colon-
6108  * separated format.
6109  */
6110 const char *
6111 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6112 {
6113 	char *bp;
6114 
6115 	if (alen == 0 || buflen < 4)
6116 		return ("?");
6117 	bp = buf;
6118 	for (;;) {
6119 		/*
6120 		 * If there are more MAC address bytes available, but we won't
6121 		 * have any room to print them, then add "..." to the string
6122 		 * instead.  See below for the 'magic number' explanation.
6123 		 */
6124 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6125 			(void) strcpy(bp, "...");
6126 			break;
6127 		}
6128 		(void) sprintf(bp, "%02x", *addr++);
6129 		bp += 2;
6130 		if (--alen == 0)
6131 			break;
6132 		*bp++ = ':';
6133 		buflen -= 3;
6134 		/*
6135 		 * At this point, based on the first 'if' statement above,
6136 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6137 		 * buflen >= 4.  The first case leaves room for the final "xx"
6138 		 * number and trailing NUL byte.  The second leaves room for at
6139 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6140 		 * that statement.
6141 		 */
6142 	}
6143 	return (buf);
6144 }
6145 
6146 /*
6147  * Send an ICMP error after patching up the packet appropriately.  Returns
6148  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6149  */
6150 static boolean_t
6151 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6152     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6153     zoneid_t zoneid, ip_stack_t *ipst)
6154 {
6155 	ipha_t *ipha;
6156 	mblk_t *first_mp;
6157 	boolean_t secure;
6158 	unsigned char db_type;
6159 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6160 
6161 	first_mp = mp;
6162 	if (mctl_present) {
6163 		mp = mp->b_cont;
6164 		secure = ipsec_in_is_secure(first_mp);
6165 		ASSERT(mp != NULL);
6166 	} else {
6167 		/*
6168 		 * If this is an ICMP error being reported - which goes
6169 		 * up as M_CTLs, we need to convert them to M_DATA till
6170 		 * we finish checking with global policy because
6171 		 * ipsec_check_global_policy() assumes M_DATA as clear
6172 		 * and M_CTL as secure.
6173 		 */
6174 		db_type = DB_TYPE(mp);
6175 		DB_TYPE(mp) = M_DATA;
6176 		secure = B_FALSE;
6177 	}
6178 	/*
6179 	 * We are generating an icmp error for some inbound packet.
6180 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6181 	 * Before we generate an error, check with global policy
6182 	 * to see whether this is allowed to enter the system. As
6183 	 * there is no "conn", we are checking with global policy.
6184 	 */
6185 	ipha = (ipha_t *)mp->b_rptr;
6186 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6187 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6188 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6189 		if (first_mp == NULL)
6190 			return (B_FALSE);
6191 	}
6192 
6193 	if (!mctl_present)
6194 		DB_TYPE(mp) = db_type;
6195 
6196 	if (flags & IP_FF_SEND_ICMP) {
6197 		if (flags & IP_FF_HDR_COMPLETE) {
6198 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6199 				freemsg(first_mp);
6200 				return (B_TRUE);
6201 			}
6202 		}
6203 		if (flags & IP_FF_CKSUM) {
6204 			/*
6205 			 * Have to correct checksum since
6206 			 * the packet might have been
6207 			 * fragmented and the reassembly code in ip_rput
6208 			 * does not restore the IP checksum.
6209 			 */
6210 			ipha->ipha_hdr_checksum = 0;
6211 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6212 		}
6213 		switch (icmp_type) {
6214 		case ICMP_DEST_UNREACHABLE:
6215 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6216 			    ipst);
6217 			break;
6218 		default:
6219 			freemsg(first_mp);
6220 			break;
6221 		}
6222 	} else {
6223 		freemsg(first_mp);
6224 		return (B_FALSE);
6225 	}
6226 
6227 	return (B_TRUE);
6228 }
6229 
6230 /*
6231  * Used to send an ICMP error message when a packet is received for
6232  * a protocol that is not supported. The mblk passed as argument
6233  * is consumed by this function.
6234  */
6235 void
6236 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6237     ip_stack_t *ipst)
6238 {
6239 	mblk_t *mp;
6240 	ipha_t *ipha;
6241 	ill_t *ill;
6242 	ipsec_in_t *ii;
6243 
6244 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6245 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6246 
6247 	mp = ipsec_mp->b_cont;
6248 	ipsec_mp->b_cont = NULL;
6249 	ipha = (ipha_t *)mp->b_rptr;
6250 	/* Get ill from index in ipsec_in_t. */
6251 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6252 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6253 	    ipst);
6254 	if (ill != NULL) {
6255 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6256 			if (ip_fanout_send_icmp(q, mp, flags,
6257 			    ICMP_DEST_UNREACHABLE,
6258 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6259 				BUMP_MIB(ill->ill_ip_mib,
6260 				    ipIfStatsInUnknownProtos);
6261 			}
6262 		} else {
6263 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6264 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6265 			    0, B_FALSE, zoneid, ipst)) {
6266 				BUMP_MIB(ill->ill_ip_mib,
6267 				    ipIfStatsInUnknownProtos);
6268 			}
6269 		}
6270 		ill_refrele(ill);
6271 	} else { /* re-link for the freemsg() below. */
6272 		ipsec_mp->b_cont = mp;
6273 	}
6274 
6275 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6276 	freemsg(ipsec_mp);
6277 }
6278 
6279 /*
6280  * See if the inbound datagram has had IPsec processing applied to it.
6281  */
6282 boolean_t
6283 ipsec_in_is_secure(mblk_t *ipsec_mp)
6284 {
6285 	ipsec_in_t *ii;
6286 
6287 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6288 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6289 
6290 	if (ii->ipsec_in_loopback) {
6291 		return (ii->ipsec_in_secure);
6292 	} else {
6293 		return (ii->ipsec_in_ah_sa != NULL ||
6294 		    ii->ipsec_in_esp_sa != NULL ||
6295 		    ii->ipsec_in_decaps);
6296 	}
6297 }
6298 
6299 /*
6300  * Handle protocols with which IP is less intimate.  There
6301  * can be more than one stream bound to a particular
6302  * protocol.  When this is the case, normally each one gets a copy
6303  * of any incoming packets.
6304  *
6305  * IPsec NOTE :
6306  *
6307  * Don't allow a secure packet going up a non-secure connection.
6308  * We don't allow this because
6309  *
6310  * 1) Reply might go out in clear which will be dropped at
6311  *    the sending side.
6312  * 2) If the reply goes out in clear it will give the
6313  *    adversary enough information for getting the key in
6314  *    most of the cases.
6315  *
6316  * Moreover getting a secure packet when we expect clear
6317  * implies that SA's were added without checking for
6318  * policy on both ends. This should not happen once ISAKMP
6319  * is used to negotiate SAs as SAs will be added only after
6320  * verifying the policy.
6321  *
6322  * NOTE : If the packet was tunneled and not multicast we only send
6323  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6324  * back to delivering packets to AF_INET6 raw sockets.
6325  *
6326  * IPQoS Notes:
6327  * Once we have determined the client, invoke IPPF processing.
6328  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6329  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6330  * ip_policy will be false.
6331  *
6332  * Zones notes:
6333  * Currently only applications in the global zone can create raw sockets for
6334  * protocols other than ICMP. So unlike the broadcast / multicast case of
6335  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6336  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6337  */
6338 static void
6339 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6340     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6341     zoneid_t zoneid)
6342 {
6343 	queue_t	*rq;
6344 	mblk_t	*mp1, *first_mp1;
6345 	uint_t	protocol = ipha->ipha_protocol;
6346 	ipaddr_t dst;
6347 	boolean_t one_only;
6348 	mblk_t *first_mp = mp;
6349 	boolean_t secure;
6350 	uint32_t ill_index;
6351 	conn_t	*connp, *first_connp, *next_connp;
6352 	connf_t	*connfp;
6353 	boolean_t shared_addr;
6354 	mib2_ipIfStatsEntry_t *mibptr;
6355 	ip_stack_t *ipst = recv_ill->ill_ipst;
6356 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6357 
6358 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6359 	if (mctl_present) {
6360 		mp = first_mp->b_cont;
6361 		secure = ipsec_in_is_secure(first_mp);
6362 		ASSERT(mp != NULL);
6363 	} else {
6364 		secure = B_FALSE;
6365 	}
6366 	dst = ipha->ipha_dst;
6367 	/*
6368 	 * If the packet was tunneled and not multicast we only send to it
6369 	 * the first match.
6370 	 */
6371 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6372 	    !CLASSD(dst));
6373 
6374 	shared_addr = (zoneid == ALL_ZONES);
6375 	if (shared_addr) {
6376 		/*
6377 		 * We don't allow multilevel ports for raw IP, so no need to
6378 		 * check for that here.
6379 		 */
6380 		zoneid = tsol_packet_to_zoneid(mp);
6381 	}
6382 
6383 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6384 	mutex_enter(&connfp->connf_lock);
6385 	connp = connfp->connf_head;
6386 	for (connp = connfp->connf_head; connp != NULL;
6387 	    connp = connp->conn_next) {
6388 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6389 		    zoneid) &&
6390 		    (!is_system_labeled() ||
6391 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6392 		    connp))) {
6393 			break;
6394 		}
6395 	}
6396 
6397 	if (connp == NULL || connp->conn_upq == NULL) {
6398 		/*
6399 		 * No one bound to these addresses.  Is
6400 		 * there a client that wants all
6401 		 * unclaimed datagrams?
6402 		 */
6403 		mutex_exit(&connfp->connf_lock);
6404 		/*
6405 		 * Check for IPPROTO_ENCAP...
6406 		 */
6407 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6408 			/*
6409 			 * If an IPsec mblk is here on a multicast
6410 			 * tunnel (using ip_mroute stuff), check policy here,
6411 			 * THEN ship off to ip_mroute_decap().
6412 			 *
6413 			 * BTW,  If I match a configured IP-in-IP
6414 			 * tunnel, this path will not be reached, and
6415 			 * ip_mroute_decap will never be called.
6416 			 */
6417 			first_mp = ipsec_check_global_policy(first_mp, connp,
6418 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6419 			if (first_mp != NULL) {
6420 				if (mctl_present)
6421 					freeb(first_mp);
6422 				ip_mroute_decap(q, mp, ill);
6423 			} /* Else we already freed everything! */
6424 		} else {
6425 			/*
6426 			 * Otherwise send an ICMP protocol unreachable.
6427 			 */
6428 			if (ip_fanout_send_icmp(q, first_mp, flags,
6429 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6430 			    mctl_present, zoneid, ipst)) {
6431 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6432 			}
6433 		}
6434 		return;
6435 	}
6436 	CONN_INC_REF(connp);
6437 	first_connp = connp;
6438 
6439 	/*
6440 	 * Only send message to one tunnel driver by immediately
6441 	 * terminating the loop.
6442 	 */
6443 	connp = one_only ? NULL : connp->conn_next;
6444 
6445 	for (;;) {
6446 		while (connp != NULL) {
6447 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6448 			    flags, zoneid) &&
6449 			    (!is_system_labeled() ||
6450 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6451 			    shared_addr, connp)))
6452 				break;
6453 			connp = connp->conn_next;
6454 		}
6455 
6456 		/*
6457 		 * Copy the packet.
6458 		 */
6459 		if (connp == NULL || connp->conn_upq == NULL ||
6460 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6461 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6462 			/*
6463 			 * No more interested clients or memory
6464 			 * allocation failed
6465 			 */
6466 			connp = first_connp;
6467 			break;
6468 		}
6469 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6470 		CONN_INC_REF(connp);
6471 		mutex_exit(&connfp->connf_lock);
6472 		rq = connp->conn_rq;
6473 		if (!canputnext(rq)) {
6474 			if (flags & IP_FF_RAWIP) {
6475 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6476 			} else {
6477 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6478 			}
6479 
6480 			freemsg(first_mp1);
6481 		} else {
6482 			/*
6483 			 * Don't enforce here if we're an actual tunnel -
6484 			 * let "tun" do it instead.
6485 			 */
6486 			if (!IPCL_IS_IPTUN(connp) &&
6487 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6488 			    secure)) {
6489 				first_mp1 = ipsec_check_inbound_policy
6490 				    (first_mp1, connp, ipha, NULL,
6491 				    mctl_present);
6492 			}
6493 			if (first_mp1 != NULL) {
6494 				int in_flags = 0;
6495 				/*
6496 				 * ip_fanout_proto also gets called from
6497 				 * icmp_inbound_error_fanout, in which case
6498 				 * the msg type is M_CTL.  Don't add info
6499 				 * in this case for the time being. In future
6500 				 * when there is a need for knowing the
6501 				 * inbound iface index for ICMP error msgs,
6502 				 * then this can be changed.
6503 				 */
6504 				if (connp->conn_recvif)
6505 					in_flags = IPF_RECVIF;
6506 				/*
6507 				 * The ULP may support IP_RECVPKTINFO for both
6508 				 * IP v4 and v6 so pass the appropriate argument
6509 				 * based on conn IP version.
6510 				 */
6511 				if (connp->conn_ip_recvpktinfo) {
6512 					if (connp->conn_af_isv6) {
6513 						/*
6514 						 * V6 only needs index
6515 						 */
6516 						in_flags |= IPF_RECVIF;
6517 					} else {
6518 						/*
6519 						 * V4 needs index +
6520 						 * matching address.
6521 						 */
6522 						in_flags |= IPF_RECVADDR;
6523 					}
6524 				}
6525 				if ((in_flags != 0) &&
6526 				    (mp->b_datap->db_type != M_CTL)) {
6527 					/*
6528 					 * the actual data will be
6529 					 * contained in b_cont upon
6530 					 * successful return of the
6531 					 * following call else
6532 					 * original mblk is returned
6533 					 */
6534 					ASSERT(recv_ill != NULL);
6535 					mp1 = ip_add_info(mp1, recv_ill,
6536 					    in_flags, IPCL_ZONEID(connp), ipst);
6537 				}
6538 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6539 				if (mctl_present)
6540 					freeb(first_mp1);
6541 				(connp->conn_recv)(connp, mp1, NULL);
6542 			}
6543 		}
6544 		mutex_enter(&connfp->connf_lock);
6545 		/* Follow the next pointer before releasing the conn. */
6546 		next_connp = connp->conn_next;
6547 		CONN_DEC_REF(connp);
6548 		connp = next_connp;
6549 	}
6550 
6551 	/* Last one.  Send it upstream. */
6552 	mutex_exit(&connfp->connf_lock);
6553 
6554 	/*
6555 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6556 	 * will be set to false.
6557 	 */
6558 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6559 		ill_index = ill->ill_phyint->phyint_ifindex;
6560 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6561 		if (mp == NULL) {
6562 			CONN_DEC_REF(connp);
6563 			if (mctl_present) {
6564 				freeb(first_mp);
6565 			}
6566 			return;
6567 		}
6568 	}
6569 
6570 	rq = connp->conn_rq;
6571 	if (!canputnext(rq)) {
6572 		if (flags & IP_FF_RAWIP) {
6573 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6574 		} else {
6575 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6576 		}
6577 
6578 		freemsg(first_mp);
6579 	} else {
6580 		if (IPCL_IS_IPTUN(connp)) {
6581 			/*
6582 			 * Tunneled packet.  We enforce policy in the tunnel
6583 			 * module itself.
6584 			 *
6585 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6586 			 * a policy check.
6587 			 * FIXME to use conn_recv for tun later.
6588 			 */
6589 			putnext(rq, first_mp);
6590 			CONN_DEC_REF(connp);
6591 			return;
6592 		}
6593 
6594 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6595 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6596 			    ipha, NULL, mctl_present);
6597 		}
6598 
6599 		if (first_mp != NULL) {
6600 			int in_flags = 0;
6601 
6602 			/*
6603 			 * ip_fanout_proto also gets called
6604 			 * from icmp_inbound_error_fanout, in
6605 			 * which case the msg type is M_CTL.
6606 			 * Don't add info in this case for time
6607 			 * being. In future when there is a
6608 			 * need for knowing the inbound iface
6609 			 * index for ICMP error msgs, then this
6610 			 * can be changed
6611 			 */
6612 			if (connp->conn_recvif)
6613 				in_flags = IPF_RECVIF;
6614 			if (connp->conn_ip_recvpktinfo) {
6615 				if (connp->conn_af_isv6) {
6616 					/*
6617 					 * V6 only needs index
6618 					 */
6619 					in_flags |= IPF_RECVIF;
6620 				} else {
6621 					/*
6622 					 * V4 needs index +
6623 					 * matching address.
6624 					 */
6625 					in_flags |= IPF_RECVADDR;
6626 				}
6627 			}
6628 			if ((in_flags != 0) &&
6629 			    (mp->b_datap->db_type != M_CTL)) {
6630 
6631 				/*
6632 				 * the actual data will be contained in
6633 				 * b_cont upon successful return
6634 				 * of the following call else original
6635 				 * mblk is returned
6636 				 */
6637 				ASSERT(recv_ill != NULL);
6638 				mp = ip_add_info(mp, recv_ill,
6639 				    in_flags, IPCL_ZONEID(connp), ipst);
6640 			}
6641 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6642 			(connp->conn_recv)(connp, mp, NULL);
6643 			if (mctl_present)
6644 				freeb(first_mp);
6645 		}
6646 	}
6647 	CONN_DEC_REF(connp);
6648 }
6649 
6650 /*
6651  * Fanout for TCP packets
6652  * The caller puts <fport, lport> in the ports parameter.
6653  *
6654  * IPQoS Notes
6655  * Before sending it to the client, invoke IPPF processing.
6656  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6657  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6658  * ip_policy is false.
6659  */
6660 static void
6661 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6662     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6663 {
6664 	mblk_t  *first_mp;
6665 	boolean_t secure;
6666 	uint32_t ill_index;
6667 	int	ip_hdr_len;
6668 	tcph_t	*tcph;
6669 	boolean_t syn_present = B_FALSE;
6670 	conn_t	*connp;
6671 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6672 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6673 
6674 	ASSERT(recv_ill != NULL);
6675 
6676 	first_mp = mp;
6677 	if (mctl_present) {
6678 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6679 		mp = first_mp->b_cont;
6680 		secure = ipsec_in_is_secure(first_mp);
6681 		ASSERT(mp != NULL);
6682 	} else {
6683 		secure = B_FALSE;
6684 	}
6685 
6686 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6687 
6688 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6689 	    zoneid, ipst)) == NULL) {
6690 		/*
6691 		 * No connected connection or listener. Send a
6692 		 * TH_RST via tcp_xmit_listeners_reset.
6693 		 */
6694 
6695 		/* Initiate IPPf processing, if needed. */
6696 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6697 			uint32_t ill_index;
6698 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6699 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6700 			if (first_mp == NULL)
6701 				return;
6702 		}
6703 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6704 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6705 		    zoneid));
6706 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6707 		    ipst->ips_netstack->netstack_tcp, NULL);
6708 		return;
6709 	}
6710 
6711 	/*
6712 	 * Allocate the SYN for the TCP connection here itself
6713 	 */
6714 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6715 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6716 		if (IPCL_IS_TCP(connp)) {
6717 			squeue_t *sqp;
6718 
6719 			/*
6720 			 * For fused tcp loopback, assign the eager's
6721 			 * squeue to be that of the active connect's.
6722 			 * Note that we don't check for IP_FF_LOOPBACK
6723 			 * here since this routine gets called only
6724 			 * for loopback (unlike the IPv6 counterpart).
6725 			 */
6726 			ASSERT(Q_TO_CONN(q) != NULL);
6727 			if (do_tcp_fusion &&
6728 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6729 			    !secure &&
6730 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6731 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6732 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6733 				sqp = Q_TO_CONN(q)->conn_sqp;
6734 			} else {
6735 				sqp = IP_SQUEUE_GET(lbolt);
6736 			}
6737 
6738 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6739 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6740 			syn_present = B_TRUE;
6741 		}
6742 	}
6743 
6744 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6745 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6746 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6747 		if ((flags & TH_RST) || (flags & TH_URG)) {
6748 			CONN_DEC_REF(connp);
6749 			freemsg(first_mp);
6750 			return;
6751 		}
6752 		if (flags & TH_ACK) {
6753 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6754 			    ipst->ips_netstack->netstack_tcp, connp);
6755 			CONN_DEC_REF(connp);
6756 			return;
6757 		}
6758 
6759 		CONN_DEC_REF(connp);
6760 		freemsg(first_mp);
6761 		return;
6762 	}
6763 
6764 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6765 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6766 		    NULL, mctl_present);
6767 		if (first_mp == NULL) {
6768 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6769 			CONN_DEC_REF(connp);
6770 			return;
6771 		}
6772 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6773 			ASSERT(syn_present);
6774 			if (mctl_present) {
6775 				ASSERT(first_mp != mp);
6776 				first_mp->b_datap->db_struioflag |=
6777 				    STRUIO_POLICY;
6778 			} else {
6779 				ASSERT(first_mp == mp);
6780 				mp->b_datap->db_struioflag &=
6781 				    ~STRUIO_EAGER;
6782 				mp->b_datap->db_struioflag |=
6783 				    STRUIO_POLICY;
6784 			}
6785 		} else {
6786 			/*
6787 			 * Discard first_mp early since we're dealing with a
6788 			 * fully-connected conn_t and tcp doesn't do policy in
6789 			 * this case.
6790 			 */
6791 			if (mctl_present) {
6792 				freeb(first_mp);
6793 				mctl_present = B_FALSE;
6794 			}
6795 			first_mp = mp;
6796 		}
6797 	}
6798 
6799 	/*
6800 	 * Initiate policy processing here if needed. If we get here from
6801 	 * icmp_inbound_error_fanout, ip_policy is false.
6802 	 */
6803 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6804 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6805 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6806 		if (mp == NULL) {
6807 			CONN_DEC_REF(connp);
6808 			if (mctl_present)
6809 				freeb(first_mp);
6810 			return;
6811 		} else if (mctl_present) {
6812 			ASSERT(first_mp != mp);
6813 			first_mp->b_cont = mp;
6814 		} else {
6815 			first_mp = mp;
6816 		}
6817 	}
6818 
6819 
6820 
6821 	/* Handle socket options. */
6822 	if (!syn_present &&
6823 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6824 		/* Add header */
6825 		ASSERT(recv_ill != NULL);
6826 		/*
6827 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6828 		 * IPF_RECVIF.
6829 		 */
6830 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6831 		    ipst);
6832 		if (mp == NULL) {
6833 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6834 			CONN_DEC_REF(connp);
6835 			if (mctl_present)
6836 				freeb(first_mp);
6837 			return;
6838 		} else if (mctl_present) {
6839 			/*
6840 			 * ip_add_info might return a new mp.
6841 			 */
6842 			ASSERT(first_mp != mp);
6843 			first_mp->b_cont = mp;
6844 		} else {
6845 			first_mp = mp;
6846 		}
6847 	}
6848 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6849 	if (IPCL_IS_TCP(connp)) {
6850 		/* do not drain, certain use cases can blow the stack */
6851 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6852 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6853 	} else {
6854 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6855 		(connp->conn_recv)(connp, first_mp, NULL);
6856 		CONN_DEC_REF(connp);
6857 	}
6858 }
6859 
6860 /*
6861  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6862  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6863  * is not consumed.
6864  *
6865  * One of four things can happen, all of which affect the passed-in mblk:
6866  *
6867  * 1.) ICMP messages that go through here just get returned TRUE.
6868  *
6869  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6870  *
6871  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6872  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6873  *
6874  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6875  */
6876 static boolean_t
6877 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6878     ipsec_stack_t *ipss)
6879 {
6880 	int shift, plen, iph_len;
6881 	ipha_t *ipha;
6882 	udpha_t *udpha;
6883 	uint32_t *spi;
6884 	uint8_t *orptr;
6885 	boolean_t udp_pkt, free_ire;
6886 
6887 	if (DB_TYPE(mp) == M_CTL) {
6888 		/*
6889 		 * ICMP message with UDP inside.  Don't bother stripping, just
6890 		 * send it up.
6891 		 *
6892 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6893 		 * to ignore errors set by ICMP anyway ('cause they might be
6894 		 * forged), but that's the app's decision, not ours.
6895 		 */
6896 
6897 		/* Bunch of reality checks for DEBUG kernels... */
6898 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6899 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6900 
6901 		return (B_TRUE);
6902 	}
6903 
6904 	ipha = (ipha_t *)mp->b_rptr;
6905 	iph_len = IPH_HDR_LENGTH(ipha);
6906 	plen = ntohs(ipha->ipha_length);
6907 
6908 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6909 		/*
6910 		 * Most likely a keepalive for the benefit of an intervening
6911 		 * NAT.  These aren't for us, per se, so drop it.
6912 		 *
6913 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6914 		 * byte packets (keepalives are 1-byte), but we'll drop them
6915 		 * also.
6916 		 */
6917 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6918 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6919 		return (B_FALSE);
6920 	}
6921 
6922 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6923 		/* might as well pull it all up - it might be ESP. */
6924 		if (!pullupmsg(mp, -1)) {
6925 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6926 			    DROPPER(ipss, ipds_esp_nomem),
6927 			    &ipss->ipsec_dropper);
6928 			return (B_FALSE);
6929 		}
6930 
6931 		ipha = (ipha_t *)mp->b_rptr;
6932 	}
6933 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6934 	if (*spi == 0) {
6935 		/* UDP packet - remove 0-spi. */
6936 		shift = sizeof (uint32_t);
6937 	} else {
6938 		/* ESP-in-UDP packet - reduce to ESP. */
6939 		ipha->ipha_protocol = IPPROTO_ESP;
6940 		shift = sizeof (udpha_t);
6941 	}
6942 
6943 	/* Fix IP header */
6944 	ipha->ipha_length = htons(plen - shift);
6945 	ipha->ipha_hdr_checksum = 0;
6946 
6947 	orptr = mp->b_rptr;
6948 	mp->b_rptr += shift;
6949 
6950 	if (*spi == 0) {
6951 		ASSERT((uint8_t *)ipha == orptr);
6952 		udpha = (udpha_t *)(orptr + iph_len);
6953 		udpha->uha_length = htons(plen - shift - iph_len);
6954 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6955 		udp_pkt = B_TRUE;
6956 	} else {
6957 		udp_pkt = B_FALSE;
6958 	}
6959 	ovbcopy(orptr, orptr + shift, iph_len);
6960 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6961 		ipha = (ipha_t *)(orptr + shift);
6962 
6963 		free_ire = (ire == NULL);
6964 		if (free_ire) {
6965 			/* Re-acquire ire. */
6966 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6967 			    ipss->ipsec_netstack->netstack_ip);
6968 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6969 				if (ire != NULL)
6970 					ire_refrele(ire);
6971 				/*
6972 				 * Do a regular freemsg(), as this is an IP
6973 				 * error (no local route) not an IPsec one.
6974 				 */
6975 				freemsg(mp);
6976 			}
6977 		}
6978 
6979 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6980 		if (free_ire)
6981 			ire_refrele(ire);
6982 	}
6983 
6984 	return (udp_pkt);
6985 }
6986 
6987 /*
6988  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6989  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6990  * Caller is responsible for dropping references to the conn, and freeing
6991  * first_mp.
6992  *
6993  * IPQoS Notes
6994  * Before sending it to the client, invoke IPPF processing. Policy processing
6995  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6996  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6997  * ip_wput_local, ip_policy is false.
6998  */
6999 static void
7000 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7001     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7002     boolean_t ip_policy)
7003 {
7004 	boolean_t	mctl_present = (first_mp != NULL);
7005 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7006 	uint32_t	ill_index;
7007 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7008 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7009 
7010 	ASSERT(ill != NULL);
7011 
7012 	if (mctl_present)
7013 		first_mp->b_cont = mp;
7014 	else
7015 		first_mp = mp;
7016 
7017 	if (CONN_UDP_FLOWCTLD(connp)) {
7018 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7019 		freemsg(first_mp);
7020 		return;
7021 	}
7022 
7023 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7024 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7025 		    NULL, mctl_present);
7026 		if (first_mp == NULL) {
7027 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7028 			return;	/* Freed by ipsec_check_inbound_policy(). */
7029 		}
7030 	}
7031 	if (mctl_present)
7032 		freeb(first_mp);
7033 
7034 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7035 	if (connp->conn_udp->udp_nat_t_endpoint) {
7036 		if (mctl_present) {
7037 			/* mctl_present *shouldn't* happen. */
7038 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7039 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7040 			    &ipss->ipsec_dropper);
7041 			return;
7042 		}
7043 
7044 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7045 			return;
7046 	}
7047 
7048 	/* Handle options. */
7049 	if (connp->conn_recvif)
7050 		in_flags = IPF_RECVIF;
7051 	/*
7052 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7053 	 * passed to ip_add_info is based on IP version of connp.
7054 	 */
7055 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7056 		if (connp->conn_af_isv6) {
7057 			/*
7058 			 * V6 only needs index
7059 			 */
7060 			in_flags |= IPF_RECVIF;
7061 		} else {
7062 			/*
7063 			 * V4 needs index + matching address.
7064 			 */
7065 			in_flags |= IPF_RECVADDR;
7066 		}
7067 	}
7068 
7069 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7070 		in_flags |= IPF_RECVSLLA;
7071 
7072 	/*
7073 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7074 	 * freed if the packet is dropped. The caller will do so.
7075 	 */
7076 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7077 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7078 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7079 		if (mp == NULL) {
7080 			return;
7081 		}
7082 	}
7083 	if ((in_flags != 0) &&
7084 	    (mp->b_datap->db_type != M_CTL)) {
7085 		/*
7086 		 * The actual data will be contained in b_cont
7087 		 * upon successful return of the following call
7088 		 * else original mblk is returned
7089 		 */
7090 		ASSERT(recv_ill != NULL);
7091 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7092 		    ipst);
7093 	}
7094 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7095 	/* Send it upstream */
7096 	(connp->conn_recv)(connp, mp, NULL);
7097 }
7098 
7099 /*
7100  * Fanout for UDP packets.
7101  * The caller puts <fport, lport> in the ports parameter.
7102  *
7103  * If SO_REUSEADDR is set all multicast and broadcast packets
7104  * will be delivered to all streams bound to the same port.
7105  *
7106  * Zones notes:
7107  * Multicast and broadcast packets will be distributed to streams in all zones.
7108  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7109  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7110  * packets. To maintain this behavior with multiple zones, the conns are grouped
7111  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7112  * each zone. If unset, all the following conns in the same zone are skipped.
7113  */
7114 static void
7115 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7116     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7117     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7118 {
7119 	uint32_t	dstport, srcport;
7120 	ipaddr_t	dst;
7121 	mblk_t		*first_mp;
7122 	boolean_t	secure;
7123 	in6_addr_t	v6src;
7124 	conn_t		*connp;
7125 	connf_t		*connfp;
7126 	conn_t		*first_connp;
7127 	conn_t		*next_connp;
7128 	mblk_t		*mp1, *first_mp1;
7129 	ipaddr_t	src;
7130 	zoneid_t	last_zoneid;
7131 	boolean_t	reuseaddr;
7132 	boolean_t	shared_addr;
7133 	ip_stack_t	*ipst;
7134 
7135 	ASSERT(recv_ill != NULL);
7136 	ipst = recv_ill->ill_ipst;
7137 
7138 	first_mp = mp;
7139 	if (mctl_present) {
7140 		mp = first_mp->b_cont;
7141 		first_mp->b_cont = NULL;
7142 		secure = ipsec_in_is_secure(first_mp);
7143 		ASSERT(mp != NULL);
7144 	} else {
7145 		first_mp = NULL;
7146 		secure = B_FALSE;
7147 	}
7148 
7149 	/* Extract ports in net byte order */
7150 	dstport = htons(ntohl(ports) & 0xFFFF);
7151 	srcport = htons(ntohl(ports) >> 16);
7152 	dst = ipha->ipha_dst;
7153 	src = ipha->ipha_src;
7154 
7155 	shared_addr = (zoneid == ALL_ZONES);
7156 	if (shared_addr) {
7157 		/*
7158 		 * No need to handle exclusive-stack zones since ALL_ZONES
7159 		 * only applies to the shared stack.
7160 		 */
7161 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7162 		if (zoneid == ALL_ZONES)
7163 			zoneid = tsol_packet_to_zoneid(mp);
7164 	}
7165 
7166 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7167 	mutex_enter(&connfp->connf_lock);
7168 	connp = connfp->connf_head;
7169 	if (!broadcast && !CLASSD(dst)) {
7170 		/*
7171 		 * Not broadcast or multicast. Send to the one (first)
7172 		 * client we find. No need to check conn_wantpacket()
7173 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7174 		 * IPv4 unicast packets.
7175 		 */
7176 		while ((connp != NULL) &&
7177 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7178 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7179 			connp = connp->conn_next;
7180 		}
7181 
7182 		if (connp == NULL || connp->conn_upq == NULL)
7183 			goto notfound;
7184 
7185 		if (is_system_labeled() &&
7186 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7187 		    connp))
7188 			goto notfound;
7189 
7190 		CONN_INC_REF(connp);
7191 		mutex_exit(&connfp->connf_lock);
7192 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7193 		    flags, recv_ill, ip_policy);
7194 		IP_STAT(ipst, ip_udp_fannorm);
7195 		CONN_DEC_REF(connp);
7196 		return;
7197 	}
7198 
7199 	/*
7200 	 * Broadcast and multicast case
7201 	 *
7202 	 * Need to check conn_wantpacket().
7203 	 * If SO_REUSEADDR has been set on the first we send the
7204 	 * packet to all clients that have joined the group and
7205 	 * match the port.
7206 	 */
7207 
7208 	while (connp != NULL) {
7209 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7210 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7211 		    (!is_system_labeled() ||
7212 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7213 		    connp)))
7214 			break;
7215 		connp = connp->conn_next;
7216 	}
7217 
7218 	if (connp == NULL || connp->conn_upq == NULL)
7219 		goto notfound;
7220 
7221 	first_connp = connp;
7222 	/*
7223 	 * When SO_REUSEADDR is not set, send the packet only to the first
7224 	 * matching connection in its zone by keeping track of the zoneid.
7225 	 */
7226 	reuseaddr = first_connp->conn_reuseaddr;
7227 	last_zoneid = first_connp->conn_zoneid;
7228 
7229 	CONN_INC_REF(connp);
7230 	connp = connp->conn_next;
7231 	for (;;) {
7232 		while (connp != NULL) {
7233 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7234 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7235 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7236 			    (!is_system_labeled() ||
7237 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7238 			    shared_addr, connp)))
7239 				break;
7240 			connp = connp->conn_next;
7241 		}
7242 		/*
7243 		 * Just copy the data part alone. The mctl part is
7244 		 * needed just for verifying policy and it is never
7245 		 * sent up.
7246 		 */
7247 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7248 		    ((mp1 = copymsg(mp)) == NULL))) {
7249 			/*
7250 			 * No more interested clients or memory
7251 			 * allocation failed
7252 			 */
7253 			connp = first_connp;
7254 			break;
7255 		}
7256 		if (connp->conn_zoneid != last_zoneid) {
7257 			/*
7258 			 * Update the zoneid so that the packet isn't sent to
7259 			 * any more conns in the same zone unless SO_REUSEADDR
7260 			 * is set.
7261 			 */
7262 			reuseaddr = connp->conn_reuseaddr;
7263 			last_zoneid = connp->conn_zoneid;
7264 		}
7265 		if (first_mp != NULL) {
7266 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7267 			    ipsec_info_type == IPSEC_IN);
7268 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7269 			    ipst->ips_netstack);
7270 			if (first_mp1 == NULL) {
7271 				freemsg(mp1);
7272 				connp = first_connp;
7273 				break;
7274 			}
7275 		} else {
7276 			first_mp1 = NULL;
7277 		}
7278 		CONN_INC_REF(connp);
7279 		mutex_exit(&connfp->connf_lock);
7280 		/*
7281 		 * IPQoS notes: We don't send the packet for policy
7282 		 * processing here, will do it for the last one (below).
7283 		 * i.e. we do it per-packet now, but if we do policy
7284 		 * processing per-conn, then we would need to do it
7285 		 * here too.
7286 		 */
7287 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7288 		    ipha, flags, recv_ill, B_FALSE);
7289 		mutex_enter(&connfp->connf_lock);
7290 		/* Follow the next pointer before releasing the conn. */
7291 		next_connp = connp->conn_next;
7292 		IP_STAT(ipst, ip_udp_fanmb);
7293 		CONN_DEC_REF(connp);
7294 		connp = next_connp;
7295 	}
7296 
7297 	/* Last one.  Send it upstream. */
7298 	mutex_exit(&connfp->connf_lock);
7299 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7300 	    recv_ill, ip_policy);
7301 	IP_STAT(ipst, ip_udp_fanmb);
7302 	CONN_DEC_REF(connp);
7303 	return;
7304 
7305 notfound:
7306 
7307 	mutex_exit(&connfp->connf_lock);
7308 	IP_STAT(ipst, ip_udp_fanothers);
7309 	/*
7310 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7311 	 * have already been matched above, since they live in the IPv4
7312 	 * fanout tables. This implies we only need to
7313 	 * check for IPv6 in6addr_any endpoints here.
7314 	 * Thus we compare using ipv6_all_zeros instead of the destination
7315 	 * address, except for the multicast group membership lookup which
7316 	 * uses the IPv4 destination.
7317 	 */
7318 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7319 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7320 	mutex_enter(&connfp->connf_lock);
7321 	connp = connfp->connf_head;
7322 	if (!broadcast && !CLASSD(dst)) {
7323 		while (connp != NULL) {
7324 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7325 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7326 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7327 			    !connp->conn_ipv6_v6only)
7328 				break;
7329 			connp = connp->conn_next;
7330 		}
7331 
7332 		if (connp != NULL && is_system_labeled() &&
7333 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7334 		    connp))
7335 			connp = NULL;
7336 
7337 		if (connp == NULL || connp->conn_upq == NULL) {
7338 			/*
7339 			 * No one bound to this port.  Is
7340 			 * there a client that wants all
7341 			 * unclaimed datagrams?
7342 			 */
7343 			mutex_exit(&connfp->connf_lock);
7344 
7345 			if (mctl_present)
7346 				first_mp->b_cont = mp;
7347 			else
7348 				first_mp = mp;
7349 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7350 			    connf_head != NULL) {
7351 				ip_fanout_proto(q, first_mp, ill, ipha,
7352 				    flags | IP_FF_RAWIP, mctl_present,
7353 				    ip_policy, recv_ill, zoneid);
7354 			} else {
7355 				if (ip_fanout_send_icmp(q, first_mp, flags,
7356 				    ICMP_DEST_UNREACHABLE,
7357 				    ICMP_PORT_UNREACHABLE,
7358 				    mctl_present, zoneid, ipst)) {
7359 					BUMP_MIB(ill->ill_ip_mib,
7360 					    udpIfStatsNoPorts);
7361 				}
7362 			}
7363 			return;
7364 		}
7365 
7366 		CONN_INC_REF(connp);
7367 		mutex_exit(&connfp->connf_lock);
7368 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7369 		    flags, recv_ill, ip_policy);
7370 		CONN_DEC_REF(connp);
7371 		return;
7372 	}
7373 	/*
7374 	 * IPv4 multicast packet being delivered to an AF_INET6
7375 	 * in6addr_any endpoint.
7376 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7377 	 * and not conn_wantpacket_v6() since any multicast membership is
7378 	 * for an IPv4-mapped multicast address.
7379 	 * The packet is sent to all clients in all zones that have joined the
7380 	 * group and match the port.
7381 	 */
7382 	while (connp != NULL) {
7383 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7384 		    srcport, v6src) &&
7385 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7386 		    (!is_system_labeled() ||
7387 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7388 		    connp)))
7389 			break;
7390 		connp = connp->conn_next;
7391 	}
7392 
7393 	if (connp == NULL || connp->conn_upq == NULL) {
7394 		/*
7395 		 * No one bound to this port.  Is
7396 		 * there a client that wants all
7397 		 * unclaimed datagrams?
7398 		 */
7399 		mutex_exit(&connfp->connf_lock);
7400 
7401 		if (mctl_present)
7402 			first_mp->b_cont = mp;
7403 		else
7404 			first_mp = mp;
7405 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7406 		    NULL) {
7407 			ip_fanout_proto(q, first_mp, ill, ipha,
7408 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7409 			    recv_ill, zoneid);
7410 		} else {
7411 			/*
7412 			 * We used to attempt to send an icmp error here, but
7413 			 * since this is known to be a multicast packet
7414 			 * and we don't send icmp errors in response to
7415 			 * multicast, just drop the packet and give up sooner.
7416 			 */
7417 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7418 			freemsg(first_mp);
7419 		}
7420 		return;
7421 	}
7422 
7423 	first_connp = connp;
7424 
7425 	CONN_INC_REF(connp);
7426 	connp = connp->conn_next;
7427 	for (;;) {
7428 		while (connp != NULL) {
7429 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7430 			    ipv6_all_zeros, srcport, v6src) &&
7431 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7432 			    (!is_system_labeled() ||
7433 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7434 			    shared_addr, connp)))
7435 				break;
7436 			connp = connp->conn_next;
7437 		}
7438 		/*
7439 		 * Just copy the data part alone. The mctl part is
7440 		 * needed just for verifying policy and it is never
7441 		 * sent up.
7442 		 */
7443 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7444 		    ((mp1 = copymsg(mp)) == NULL))) {
7445 			/*
7446 			 * No more intested clients or memory
7447 			 * allocation failed
7448 			 */
7449 			connp = first_connp;
7450 			break;
7451 		}
7452 		if (first_mp != NULL) {
7453 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7454 			    ipsec_info_type == IPSEC_IN);
7455 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7456 			    ipst->ips_netstack);
7457 			if (first_mp1 == NULL) {
7458 				freemsg(mp1);
7459 				connp = first_connp;
7460 				break;
7461 			}
7462 		} else {
7463 			first_mp1 = NULL;
7464 		}
7465 		CONN_INC_REF(connp);
7466 		mutex_exit(&connfp->connf_lock);
7467 		/*
7468 		 * IPQoS notes: We don't send the packet for policy
7469 		 * processing here, will do it for the last one (below).
7470 		 * i.e. we do it per-packet now, but if we do policy
7471 		 * processing per-conn, then we would need to do it
7472 		 * here too.
7473 		 */
7474 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7475 		    ipha, flags, recv_ill, B_FALSE);
7476 		mutex_enter(&connfp->connf_lock);
7477 		/* Follow the next pointer before releasing the conn. */
7478 		next_connp = connp->conn_next;
7479 		CONN_DEC_REF(connp);
7480 		connp = next_connp;
7481 	}
7482 
7483 	/* Last one.  Send it upstream. */
7484 	mutex_exit(&connfp->connf_lock);
7485 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7486 	    recv_ill, ip_policy);
7487 	CONN_DEC_REF(connp);
7488 }
7489 
7490 /*
7491  * Complete the ip_wput header so that it
7492  * is possible to generate ICMP
7493  * errors.
7494  */
7495 int
7496 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7497 {
7498 	ire_t *ire;
7499 
7500 	if (ipha->ipha_src == INADDR_ANY) {
7501 		ire = ire_lookup_local(zoneid, ipst);
7502 		if (ire == NULL) {
7503 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7504 			return (1);
7505 		}
7506 		ipha->ipha_src = ire->ire_addr;
7507 		ire_refrele(ire);
7508 	}
7509 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7510 	ipha->ipha_hdr_checksum = 0;
7511 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7512 	return (0);
7513 }
7514 
7515 /*
7516  * Nobody should be sending
7517  * packets up this stream
7518  */
7519 static void
7520 ip_lrput(queue_t *q, mblk_t *mp)
7521 {
7522 	mblk_t *mp1;
7523 
7524 	switch (mp->b_datap->db_type) {
7525 	case M_FLUSH:
7526 		/* Turn around */
7527 		if (*mp->b_rptr & FLUSHW) {
7528 			*mp->b_rptr &= ~FLUSHR;
7529 			qreply(q, mp);
7530 			return;
7531 		}
7532 		break;
7533 	}
7534 	/* Could receive messages that passed through ar_rput */
7535 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7536 		mp1->b_prev = mp1->b_next = NULL;
7537 	freemsg(mp);
7538 }
7539 
7540 /* Nobody should be sending packets down this stream */
7541 /* ARGSUSED */
7542 void
7543 ip_lwput(queue_t *q, mblk_t *mp)
7544 {
7545 	freemsg(mp);
7546 }
7547 
7548 /*
7549  * Move the first hop in any source route to ipha_dst and remove that part of
7550  * the source route.  Called by other protocols.  Errors in option formatting
7551  * are ignored - will be handled by ip_wput_options Return the final
7552  * destination (either ipha_dst or the last entry in a source route.)
7553  */
7554 ipaddr_t
7555 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7556 {
7557 	ipoptp_t	opts;
7558 	uchar_t		*opt;
7559 	uint8_t		optval;
7560 	uint8_t		optlen;
7561 	ipaddr_t	dst;
7562 	int		i;
7563 	ire_t		*ire;
7564 	ip_stack_t	*ipst = ns->netstack_ip;
7565 
7566 	ip2dbg(("ip_massage_options\n"));
7567 	dst = ipha->ipha_dst;
7568 	for (optval = ipoptp_first(&opts, ipha);
7569 	    optval != IPOPT_EOL;
7570 	    optval = ipoptp_next(&opts)) {
7571 		opt = opts.ipoptp_cur;
7572 		switch (optval) {
7573 			uint8_t off;
7574 		case IPOPT_SSRR:
7575 		case IPOPT_LSRR:
7576 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7577 				ip1dbg(("ip_massage_options: bad src route\n"));
7578 				break;
7579 			}
7580 			optlen = opts.ipoptp_len;
7581 			off = opt[IPOPT_OFFSET];
7582 			off--;
7583 		redo_srr:
7584 			if (optlen < IP_ADDR_LEN ||
7585 			    off > optlen - IP_ADDR_LEN) {
7586 				/* End of source route */
7587 				ip1dbg(("ip_massage_options: end of SR\n"));
7588 				break;
7589 			}
7590 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7591 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7592 			    ntohl(dst)));
7593 			/*
7594 			 * Check if our address is present more than
7595 			 * once as consecutive hops in source route.
7596 			 * XXX verify per-interface ip_forwarding
7597 			 * for source route?
7598 			 */
7599 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7600 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7601 			if (ire != NULL) {
7602 				ire_refrele(ire);
7603 				off += IP_ADDR_LEN;
7604 				goto redo_srr;
7605 			}
7606 			if (dst == htonl(INADDR_LOOPBACK)) {
7607 				ip1dbg(("ip_massage_options: loopback addr in "
7608 				    "source route!\n"));
7609 				break;
7610 			}
7611 			/*
7612 			 * Update ipha_dst to be the first hop and remove the
7613 			 * first hop from the source route (by overwriting
7614 			 * part of the option with NOP options).
7615 			 */
7616 			ipha->ipha_dst = dst;
7617 			/* Put the last entry in dst */
7618 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7619 			    3;
7620 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7621 
7622 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7623 			    ntohl(dst)));
7624 			/* Move down and overwrite */
7625 			opt[IP_ADDR_LEN] = opt[0];
7626 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7627 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7628 			for (i = 0; i < IP_ADDR_LEN; i++)
7629 				opt[i] = IPOPT_NOP;
7630 			break;
7631 		}
7632 	}
7633 	return (dst);
7634 }
7635 
7636 /*
7637  * Return the network mask
7638  * associated with the specified address.
7639  */
7640 ipaddr_t
7641 ip_net_mask(ipaddr_t addr)
7642 {
7643 	uchar_t	*up = (uchar_t *)&addr;
7644 	ipaddr_t mask = 0;
7645 	uchar_t	*maskp = (uchar_t *)&mask;
7646 
7647 #if defined(__i386) || defined(__amd64)
7648 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7649 #endif
7650 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7651 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7652 #endif
7653 	if (CLASSD(addr)) {
7654 		maskp[0] = 0xF0;
7655 		return (mask);
7656 	}
7657 	if (addr == 0)
7658 		return (0);
7659 	maskp[0] = 0xFF;
7660 	if ((up[0] & 0x80) == 0)
7661 		return (mask);
7662 
7663 	maskp[1] = 0xFF;
7664 	if ((up[0] & 0xC0) == 0x80)
7665 		return (mask);
7666 
7667 	maskp[2] = 0xFF;
7668 	if ((up[0] & 0xE0) == 0xC0)
7669 		return (mask);
7670 
7671 	/* Must be experimental or multicast, indicate as much */
7672 	return ((ipaddr_t)0);
7673 }
7674 
7675 /*
7676  * Select an ill for the packet by considering load spreading across
7677  * a different ill in the group if dst_ill is part of some group.
7678  */
7679 ill_t *
7680 ip_newroute_get_dst_ill(ill_t *dst_ill)
7681 {
7682 	ill_t *ill;
7683 
7684 	/*
7685 	 * We schedule irrespective of whether the source address is
7686 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7687 	 */
7688 	ill = illgrp_scheduler(dst_ill);
7689 	if (ill == NULL)
7690 		return (NULL);
7691 
7692 	/*
7693 	 * For groups with names ip_sioctl_groupname ensures that all
7694 	 * ills are of same type. For groups without names, ifgrp_insert
7695 	 * ensures this.
7696 	 */
7697 	ASSERT(dst_ill->ill_type == ill->ill_type);
7698 
7699 	return (ill);
7700 }
7701 
7702 /*
7703  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7704  */
7705 ill_t *
7706 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7707     ip_stack_t *ipst)
7708 {
7709 	ill_t *ret_ill;
7710 
7711 	ASSERT(ifindex != 0);
7712 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7713 	    ipst);
7714 	if (ret_ill == NULL ||
7715 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7716 		if (isv6) {
7717 			if (ill != NULL) {
7718 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7719 			} else {
7720 				BUMP_MIB(&ipst->ips_ip6_mib,
7721 				    ipIfStatsOutDiscards);
7722 			}
7723 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7724 			    "bad ifindex %d.\n", ifindex));
7725 		} else {
7726 			if (ill != NULL) {
7727 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7728 			} else {
7729 				BUMP_MIB(&ipst->ips_ip_mib,
7730 				    ipIfStatsOutDiscards);
7731 			}
7732 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7733 			    "bad ifindex %d.\n", ifindex));
7734 		}
7735 		if (ret_ill != NULL)
7736 			ill_refrele(ret_ill);
7737 		freemsg(first_mp);
7738 		return (NULL);
7739 	}
7740 
7741 	return (ret_ill);
7742 }
7743 
7744 /*
7745  * IPv4 -
7746  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7747  * out a packet to a destination address for which we do not have specific
7748  * (or sufficient) routing information.
7749  *
7750  * NOTE : These are the scopes of some of the variables that point at IRE,
7751  *	  which needs to be followed while making any future modifications
7752  *	  to avoid memory leaks.
7753  *
7754  *	- ire and sire are the entries looked up initially by
7755  *	  ire_ftable_lookup.
7756  *	- ipif_ire is used to hold the interface ire associated with
7757  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7758  *	  it before branching out to error paths.
7759  *	- save_ire is initialized before ire_create, so that ire returned
7760  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7761  *	  before breaking out of the switch.
7762  *
7763  *	Thus on failures, we have to REFRELE only ire and sire, if they
7764  *	are not NULL.
7765  */
7766 void
7767 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7768     zoneid_t zoneid, ip_stack_t *ipst)
7769 {
7770 	areq_t	*areq;
7771 	ipaddr_t gw = 0;
7772 	ire_t	*ire = NULL;
7773 	mblk_t	*res_mp;
7774 	ipaddr_t *addrp;
7775 	ipaddr_t nexthop_addr;
7776 	ipif_t  *src_ipif = NULL;
7777 	ill_t	*dst_ill = NULL;
7778 	ipha_t  *ipha;
7779 	ire_t	*sire = NULL;
7780 	mblk_t	*first_mp;
7781 	ire_t	*save_ire;
7782 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7783 	ushort_t ire_marks = 0;
7784 	boolean_t mctl_present;
7785 	ipsec_out_t *io;
7786 	mblk_t	*saved_mp;
7787 	ire_t	*first_sire = NULL;
7788 	mblk_t	*copy_mp = NULL;
7789 	mblk_t	*xmit_mp = NULL;
7790 	ipaddr_t save_dst;
7791 	uint32_t multirt_flags =
7792 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7793 	boolean_t multirt_is_resolvable;
7794 	boolean_t multirt_resolve_next;
7795 	boolean_t do_attach_ill = B_FALSE;
7796 	boolean_t ip_nexthop = B_FALSE;
7797 	tsol_ire_gw_secattr_t *attrp = NULL;
7798 	tsol_gcgrp_t *gcgrp = NULL;
7799 	tsol_gcgrp_addr_t ga;
7800 
7801 	if (ip_debug > 2) {
7802 		/* ip1dbg */
7803 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7804 	}
7805 
7806 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7807 	if (mctl_present) {
7808 		io = (ipsec_out_t *)first_mp->b_rptr;
7809 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7810 		ASSERT(zoneid == io->ipsec_out_zoneid);
7811 		ASSERT(zoneid != ALL_ZONES);
7812 	}
7813 
7814 	ipha = (ipha_t *)mp->b_rptr;
7815 
7816 	/* All multicast lookups come through ip_newroute_ipif() */
7817 	if (CLASSD(dst)) {
7818 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7819 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7820 		freemsg(first_mp);
7821 		return;
7822 	}
7823 
7824 	if (mctl_present && io->ipsec_out_attach_if) {
7825 		/* ip_grab_attach_ill returns a held ill */
7826 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7827 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7828 
7829 		/* Failure case frees things for us. */
7830 		if (attach_ill == NULL)
7831 			return;
7832 
7833 		/*
7834 		 * Check if we need an ire that will not be
7835 		 * looked up by anybody else i.e. HIDDEN.
7836 		 */
7837 		if (ill_is_probeonly(attach_ill))
7838 			ire_marks = IRE_MARK_HIDDEN;
7839 	}
7840 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7841 		ip_nexthop = B_TRUE;
7842 		nexthop_addr = io->ipsec_out_nexthop_addr;
7843 	}
7844 	/*
7845 	 * If this IRE is created for forwarding or it is not for
7846 	 * traffic for congestion controlled protocols, mark it as temporary.
7847 	 */
7848 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7849 		ire_marks |= IRE_MARK_TEMPORARY;
7850 
7851 	/*
7852 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7853 	 * chain until it gets the most specific information available.
7854 	 * For example, we know that there is no IRE_CACHE for this dest,
7855 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7856 	 * ire_ftable_lookup will look up the gateway, etc.
7857 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7858 	 * to the destination, of equal netmask length in the forward table,
7859 	 * will be recursively explored. If no information is available
7860 	 * for the final gateway of that route, we force the returned ire
7861 	 * to be equal to sire using MATCH_IRE_PARENT.
7862 	 * At least, in this case we have a starting point (in the buckets)
7863 	 * to look for other routes to the destination in the forward table.
7864 	 * This is actually used only for multirouting, where a list
7865 	 * of routes has to be processed in sequence.
7866 	 *
7867 	 * In the process of coming up with the most specific information,
7868 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7869 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7870 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7871 	 * Two caveats when handling incomplete ire's in ip_newroute:
7872 	 * - we should be careful when accessing its ire_nce (specifically
7873 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7874 	 * - not all legacy code path callers are prepared to handle
7875 	 *   incomplete ire's, so we should not create/add incomplete
7876 	 *   ire_cache entries here. (See discussion about temporary solution
7877 	 *   further below).
7878 	 *
7879 	 * In order to minimize packet dropping, and to preserve existing
7880 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7881 	 * gateway, and instead use the IF_RESOLVER ire to send out
7882 	 * another request to ARP (this is achieved by passing the
7883 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7884 	 * arp response comes back in ip_wput_nondata, we will create
7885 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7886 	 *
7887 	 * Note that this is a temporary solution; the correct solution is
7888 	 * to create an incomplete  per-dst ire_cache entry, and send the
7889 	 * packet out when the gw's nce is resolved. In order to achieve this,
7890 	 * all packet processing must have been completed prior to calling
7891 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7892 	 * to be modified to accomodate this solution.
7893 	 */
7894 	if (ip_nexthop) {
7895 		/*
7896 		 * The first time we come here, we look for an IRE_INTERFACE
7897 		 * entry for the specified nexthop, set the dst to be the
7898 		 * nexthop address and create an IRE_CACHE entry for the
7899 		 * nexthop. The next time around, we are able to find an
7900 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7901 		 * nexthop address and create an IRE_CACHE entry for the
7902 		 * destination address via the specified nexthop.
7903 		 */
7904 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7905 		    MBLK_GETLABEL(mp), ipst);
7906 		if (ire != NULL) {
7907 			gw = nexthop_addr;
7908 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7909 		} else {
7910 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7911 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7912 			    MBLK_GETLABEL(mp),
7913 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7914 			    ipst);
7915 			if (ire != NULL) {
7916 				dst = nexthop_addr;
7917 			}
7918 		}
7919 	} else if (attach_ill == NULL) {
7920 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7921 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7922 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7923 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7924 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7925 		    ipst);
7926 	} else {
7927 		/*
7928 		 * attach_ill is set only for communicating with
7929 		 * on-link hosts. So, don't look for DEFAULT.
7930 		 */
7931 		ipif_t	*attach_ipif;
7932 
7933 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7934 		if (attach_ipif == NULL) {
7935 			ill_refrele(attach_ill);
7936 			goto icmp_err_ret;
7937 		}
7938 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7939 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7940 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7941 		    MATCH_IRE_SECATTR, ipst);
7942 		ipif_refrele(attach_ipif);
7943 	}
7944 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7945 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7946 
7947 	/*
7948 	 * This loop is run only once in most cases.
7949 	 * We loop to resolve further routes only when the destination
7950 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7951 	 */
7952 	do {
7953 		/* Clear the previous iteration's values */
7954 		if (src_ipif != NULL) {
7955 			ipif_refrele(src_ipif);
7956 			src_ipif = NULL;
7957 		}
7958 		if (dst_ill != NULL) {
7959 			ill_refrele(dst_ill);
7960 			dst_ill = NULL;
7961 		}
7962 
7963 		multirt_resolve_next = B_FALSE;
7964 		/*
7965 		 * We check if packets have to be multirouted.
7966 		 * In this case, given the current <ire, sire> couple,
7967 		 * we look for the next suitable <ire, sire>.
7968 		 * This check is done in ire_multirt_lookup(),
7969 		 * which applies various criteria to find the next route
7970 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7971 		 * unchanged if it detects it has not been tried yet.
7972 		 */
7973 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7974 			ip3dbg(("ip_newroute: starting next_resolution "
7975 			    "with first_mp %p, tag %d\n",
7976 			    (void *)first_mp,
7977 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7978 
7979 			ASSERT(sire != NULL);
7980 			multirt_is_resolvable =
7981 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7982 			    MBLK_GETLABEL(mp), ipst);
7983 
7984 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7985 			    "ire %p, sire %p\n",
7986 			    multirt_is_resolvable,
7987 			    (void *)ire, (void *)sire));
7988 
7989 			if (!multirt_is_resolvable) {
7990 				/*
7991 				 * No more multirt route to resolve; give up
7992 				 * (all routes resolved or no more
7993 				 * resolvable routes).
7994 				 */
7995 				if (ire != NULL) {
7996 					ire_refrele(ire);
7997 					ire = NULL;
7998 				}
7999 			} else {
8000 				ASSERT(sire != NULL);
8001 				ASSERT(ire != NULL);
8002 				/*
8003 				 * We simply use first_sire as a flag that
8004 				 * indicates if a resolvable multirt route
8005 				 * has already been found.
8006 				 * If it is not the case, we may have to send
8007 				 * an ICMP error to report that the
8008 				 * destination is unreachable.
8009 				 * We do not IRE_REFHOLD first_sire.
8010 				 */
8011 				if (first_sire == NULL) {
8012 					first_sire = sire;
8013 				}
8014 			}
8015 		}
8016 		if (ire == NULL) {
8017 			if (ip_debug > 3) {
8018 				/* ip2dbg */
8019 				pr_addr_dbg("ip_newroute: "
8020 				    "can't resolve %s\n", AF_INET, &dst);
8021 			}
8022 			ip3dbg(("ip_newroute: "
8023 			    "ire %p, sire %p, first_sire %p\n",
8024 			    (void *)ire, (void *)sire, (void *)first_sire));
8025 
8026 			if (sire != NULL) {
8027 				ire_refrele(sire);
8028 				sire = NULL;
8029 			}
8030 
8031 			if (first_sire != NULL) {
8032 				/*
8033 				 * At least one multirt route has been found
8034 				 * in the same call to ip_newroute();
8035 				 * there is no need to report an ICMP error.
8036 				 * first_sire was not IRE_REFHOLDed.
8037 				 */
8038 				MULTIRT_DEBUG_UNTAG(first_mp);
8039 				freemsg(first_mp);
8040 				return;
8041 			}
8042 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8043 			    RTA_DST, ipst);
8044 			if (attach_ill != NULL)
8045 				ill_refrele(attach_ill);
8046 			goto icmp_err_ret;
8047 		}
8048 
8049 		/*
8050 		 * Verify that the returned IRE does not have either
8051 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8052 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8053 		 */
8054 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8055 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8056 			if (attach_ill != NULL)
8057 				ill_refrele(attach_ill);
8058 			goto icmp_err_ret;
8059 		}
8060 		/*
8061 		 * Increment the ire_ob_pkt_count field for ire if it is an
8062 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8063 		 * increment the same for the parent IRE, sire, if it is some
8064 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8065 		 */
8066 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8067 			UPDATE_OB_PKT_COUNT(ire);
8068 			ire->ire_last_used_time = lbolt;
8069 		}
8070 
8071 		if (sire != NULL) {
8072 			gw = sire->ire_gateway_addr;
8073 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8074 			    IRE_INTERFACE)) == 0);
8075 			UPDATE_OB_PKT_COUNT(sire);
8076 			sire->ire_last_used_time = lbolt;
8077 		}
8078 		/*
8079 		 * We have a route to reach the destination.
8080 		 *
8081 		 * 1) If the interface is part of ill group, try to get a new
8082 		 *    ill taking load spreading into account.
8083 		 *
8084 		 * 2) After selecting the ill, get a source address that
8085 		 *    might create good inbound load spreading.
8086 		 *    ipif_select_source does this for us.
8087 		 *
8088 		 * If the application specified the ill (ifindex), we still
8089 		 * load spread. Only if the packets needs to go out
8090 		 * specifically on a given ill e.g. binding to
8091 		 * IPIF_NOFAILOVER address, then we don't try to use a
8092 		 * different ill for load spreading.
8093 		 */
8094 		if (attach_ill == NULL) {
8095 			/*
8096 			 * Don't perform outbound load spreading in the
8097 			 * case of an RTF_MULTIRT route, as we actually
8098 			 * typically want to replicate outgoing packets
8099 			 * through particular interfaces.
8100 			 */
8101 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8102 				dst_ill = ire->ire_ipif->ipif_ill;
8103 				/* for uniformity */
8104 				ill_refhold(dst_ill);
8105 			} else {
8106 				/*
8107 				 * If we are here trying to create an IRE_CACHE
8108 				 * for an offlink destination and have the
8109 				 * IRE_CACHE for the next hop and the latter is
8110 				 * using virtual IP source address selection i.e
8111 				 * it's ire->ire_ipif is pointing to a virtual
8112 				 * network interface (vni) then
8113 				 * ip_newroute_get_dst_ll() will return the vni
8114 				 * interface as the dst_ill. Since the vni is
8115 				 * virtual i.e not associated with any physical
8116 				 * interface, it cannot be the dst_ill, hence
8117 				 * in such a case call ip_newroute_get_dst_ll()
8118 				 * with the stq_ill instead of the ire_ipif ILL.
8119 				 * The function returns a refheld ill.
8120 				 */
8121 				if ((ire->ire_type == IRE_CACHE) &&
8122 				    IS_VNI(ire->ire_ipif->ipif_ill))
8123 					dst_ill = ip_newroute_get_dst_ill(
8124 					    ire->ire_stq->q_ptr);
8125 				else
8126 					dst_ill = ip_newroute_get_dst_ill(
8127 					    ire->ire_ipif->ipif_ill);
8128 			}
8129 			if (dst_ill == NULL) {
8130 				if (ip_debug > 2) {
8131 					pr_addr_dbg("ip_newroute: "
8132 					    "no dst ill for dst"
8133 					    " %s\n", AF_INET, &dst);
8134 				}
8135 				goto icmp_err_ret;
8136 			}
8137 		} else {
8138 			dst_ill = ire->ire_ipif->ipif_ill;
8139 			/* for uniformity */
8140 			ill_refhold(dst_ill);
8141 			/*
8142 			 * We should have found a route matching ill as we
8143 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8144 			 * Rather than asserting, when there is a mismatch,
8145 			 * we just drop the packet.
8146 			 */
8147 			if (dst_ill != attach_ill) {
8148 				ip0dbg(("ip_newroute: Packet dropped as "
8149 				    "IPIF_NOFAILOVER ill is %s, "
8150 				    "ire->ire_ipif->ipif_ill is %s\n",
8151 				    attach_ill->ill_name,
8152 				    dst_ill->ill_name));
8153 				ill_refrele(attach_ill);
8154 				goto icmp_err_ret;
8155 			}
8156 		}
8157 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8158 		if (attach_ill != NULL) {
8159 			ill_refrele(attach_ill);
8160 			attach_ill = NULL;
8161 			do_attach_ill = B_TRUE;
8162 		}
8163 		ASSERT(dst_ill != NULL);
8164 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8165 
8166 		/*
8167 		 * Pick the best source address from dst_ill.
8168 		 *
8169 		 * 1) If it is part of a multipathing group, we would
8170 		 *    like to spread the inbound packets across different
8171 		 *    interfaces. ipif_select_source picks a random source
8172 		 *    across the different ills in the group.
8173 		 *
8174 		 * 2) If it is not part of a multipathing group, we try
8175 		 *    to pick the source address from the destination
8176 		 *    route. Clustering assumes that when we have multiple
8177 		 *    prefixes hosted on an interface, the prefix of the
8178 		 *    source address matches the prefix of the destination
8179 		 *    route. We do this only if the address is not
8180 		 *    DEPRECATED.
8181 		 *
8182 		 * 3) If the conn is in a different zone than the ire, we
8183 		 *    need to pick a source address from the right zone.
8184 		 *
8185 		 * NOTE : If we hit case (1) above, the prefix of the source
8186 		 *	  address picked may not match the prefix of the
8187 		 *	  destination routes prefix as ipif_select_source
8188 		 *	  does not look at "dst" while picking a source
8189 		 *	  address.
8190 		 *	  If we want the same behavior as (2), we will need
8191 		 *	  to change the behavior of ipif_select_source.
8192 		 */
8193 		ASSERT(src_ipif == NULL);
8194 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8195 			/*
8196 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8197 			 * Check that the ipif matching the requested source
8198 			 * address still exists.
8199 			 */
8200 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8201 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8202 		}
8203 		if (src_ipif == NULL) {
8204 			ire_marks |= IRE_MARK_USESRC_CHECK;
8205 			if ((dst_ill->ill_group != NULL) ||
8206 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8207 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8208 			    ire->ire_zoneid != ALL_ZONES) ||
8209 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8210 				/*
8211 				 * If the destination is reachable via a
8212 				 * given gateway, the selected source address
8213 				 * should be in the same subnet as the gateway.
8214 				 * Otherwise, the destination is not reachable.
8215 				 *
8216 				 * If there are no interfaces on the same subnet
8217 				 * as the destination, ipif_select_source gives
8218 				 * first non-deprecated interface which might be
8219 				 * on a different subnet than the gateway.
8220 				 * This is not desirable. Hence pass the dst_ire
8221 				 * source address to ipif_select_source.
8222 				 * It is sure that the destination is reachable
8223 				 * with the dst_ire source address subnet.
8224 				 * So passing dst_ire source address to
8225 				 * ipif_select_source will make sure that the
8226 				 * selected source will be on the same subnet
8227 				 * as dst_ire source address.
8228 				 */
8229 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8230 				src_ipif = ipif_select_source(dst_ill, saddr,
8231 				    zoneid);
8232 				if (src_ipif == NULL) {
8233 					if (ip_debug > 2) {
8234 						pr_addr_dbg("ip_newroute: "
8235 						    "no src for dst %s ",
8236 						    AF_INET, &dst);
8237 						printf("through interface %s\n",
8238 						    dst_ill->ill_name);
8239 					}
8240 					goto icmp_err_ret;
8241 				}
8242 			} else {
8243 				src_ipif = ire->ire_ipif;
8244 				ASSERT(src_ipif != NULL);
8245 				/* hold src_ipif for uniformity */
8246 				ipif_refhold(src_ipif);
8247 			}
8248 		}
8249 
8250 		/*
8251 		 * Assign a source address while we have the conn.
8252 		 * We can't have ip_wput_ire pick a source address when the
8253 		 * packet returns from arp since we need to look at
8254 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8255 		 * going through arp.
8256 		 *
8257 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8258 		 *	  it uses ip6i to store this information.
8259 		 */
8260 		if (ipha->ipha_src == INADDR_ANY &&
8261 		    (connp == NULL || !connp->conn_unspec_src)) {
8262 			ipha->ipha_src = src_ipif->ipif_src_addr;
8263 		}
8264 		if (ip_debug > 3) {
8265 			/* ip2dbg */
8266 			pr_addr_dbg("ip_newroute: first hop %s\n",
8267 			    AF_INET, &gw);
8268 		}
8269 		ip2dbg(("\tire type %s (%d)\n",
8270 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8271 
8272 		/*
8273 		 * The TTL of multirouted packets is bounded by the
8274 		 * ip_multirt_ttl ndd variable.
8275 		 */
8276 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8277 			/* Force TTL of multirouted packets */
8278 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8279 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8280 				ip2dbg(("ip_newroute: forcing multirt TTL "
8281 				    "to %d (was %d), dst 0x%08x\n",
8282 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8283 				    ntohl(sire->ire_addr)));
8284 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8285 			}
8286 		}
8287 		/*
8288 		 * At this point in ip_newroute(), ire is either the
8289 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8290 		 * destination or an IRE_INTERFACE type that should be used
8291 		 * to resolve an on-subnet destination or an on-subnet
8292 		 * next-hop gateway.
8293 		 *
8294 		 * In the IRE_CACHE case, we have the following :
8295 		 *
8296 		 * 1) src_ipif - used for getting a source address.
8297 		 *
8298 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8299 		 *    means packets using this IRE_CACHE will go out on
8300 		 *    dst_ill.
8301 		 *
8302 		 * 3) The IRE sire will point to the prefix that is the
8303 		 *    longest  matching route for the destination. These
8304 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8305 		 *
8306 		 *    The newly created IRE_CACHE entry for the off-subnet
8307 		 *    destination is tied to both the prefix route and the
8308 		 *    interface route used to resolve the next-hop gateway
8309 		 *    via the ire_phandle and ire_ihandle fields,
8310 		 *    respectively.
8311 		 *
8312 		 * In the IRE_INTERFACE case, we have the following :
8313 		 *
8314 		 * 1) src_ipif - used for getting a source address.
8315 		 *
8316 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8317 		 *    means packets using the IRE_CACHE that we will build
8318 		 *    here will go out on dst_ill.
8319 		 *
8320 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8321 		 *    to be created will only be tied to the IRE_INTERFACE
8322 		 *    that was derived from the ire_ihandle field.
8323 		 *
8324 		 *    If sire is non-NULL, it means the destination is
8325 		 *    off-link and we will first create the IRE_CACHE for the
8326 		 *    gateway. Next time through ip_newroute, we will create
8327 		 *    the IRE_CACHE for the final destination as described
8328 		 *    above.
8329 		 *
8330 		 * In both cases, after the current resolution has been
8331 		 * completed (or possibly initialised, in the IRE_INTERFACE
8332 		 * case), the loop may be re-entered to attempt the resolution
8333 		 * of another RTF_MULTIRT route.
8334 		 *
8335 		 * When an IRE_CACHE entry for the off-subnet destination is
8336 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8337 		 * for further processing in emission loops.
8338 		 */
8339 		save_ire = ire;
8340 		switch (ire->ire_type) {
8341 		case IRE_CACHE: {
8342 			ire_t	*ipif_ire;
8343 
8344 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8345 			if (gw == 0)
8346 				gw = ire->ire_gateway_addr;
8347 			/*
8348 			 * We need 3 ire's to create a new cache ire for an
8349 			 * off-link destination from the cache ire of the
8350 			 * gateway.
8351 			 *
8352 			 *	1. The prefix ire 'sire' (Note that this does
8353 			 *	   not apply to the conn_nexthop_set case)
8354 			 *	2. The cache ire of the gateway 'ire'
8355 			 *	3. The interface ire 'ipif_ire'
8356 			 *
8357 			 * We have (1) and (2). We lookup (3) below.
8358 			 *
8359 			 * If there is no interface route to the gateway,
8360 			 * it is a race condition, where we found the cache
8361 			 * but the interface route has been deleted.
8362 			 */
8363 			if (ip_nexthop) {
8364 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8365 			} else {
8366 				ipif_ire =
8367 				    ire_ihandle_lookup_offlink(ire, sire);
8368 			}
8369 			if (ipif_ire == NULL) {
8370 				ip1dbg(("ip_newroute: "
8371 				    "ire_ihandle_lookup_offlink failed\n"));
8372 				goto icmp_err_ret;
8373 			}
8374 
8375 			/*
8376 			 * Check cached gateway IRE for any security
8377 			 * attributes; if found, associate the gateway
8378 			 * credentials group to the destination IRE.
8379 			 */
8380 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8381 				mutex_enter(&attrp->igsa_lock);
8382 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8383 					GCGRP_REFHOLD(gcgrp);
8384 				mutex_exit(&attrp->igsa_lock);
8385 			}
8386 
8387 			/*
8388 			 * XXX For the source of the resolver mp,
8389 			 * we are using the same DL_UNITDATA_REQ
8390 			 * (from save_ire->ire_nce->nce_res_mp)
8391 			 * though the save_ire is not pointing at the same ill.
8392 			 * This is incorrect. We need to send it up to the
8393 			 * resolver to get the right res_mp. For ethernets
8394 			 * this may be okay (ill_type == DL_ETHER).
8395 			 */
8396 
8397 			ire = ire_create(
8398 			    (uchar_t *)&dst,		/* dest address */
8399 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8400 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8401 			    (uchar_t *)&gw,		/* gateway address */
8402 			    &save_ire->ire_max_frag,
8403 			    save_ire->ire_nce,		/* src nce */
8404 			    dst_ill->ill_rq,		/* recv-from queue */
8405 			    dst_ill->ill_wq,		/* send-to queue */
8406 			    IRE_CACHE,			/* IRE type */
8407 			    src_ipif,
8408 			    (sire != NULL) ?
8409 			    sire->ire_mask : 0, 	/* Parent mask */
8410 			    (sire != NULL) ?
8411 			    sire->ire_phandle : 0,	/* Parent handle */
8412 			    ipif_ire->ire_ihandle,	/* Interface handle */
8413 			    (sire != NULL) ? (sire->ire_flags &
8414 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8415 			    (sire != NULL) ?
8416 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8417 			    NULL,
8418 			    gcgrp,
8419 			    ipst);
8420 
8421 			if (ire == NULL) {
8422 				if (gcgrp != NULL) {
8423 					GCGRP_REFRELE(gcgrp);
8424 					gcgrp = NULL;
8425 				}
8426 				ire_refrele(ipif_ire);
8427 				ire_refrele(save_ire);
8428 				break;
8429 			}
8430 
8431 			/* reference now held by IRE */
8432 			gcgrp = NULL;
8433 
8434 			ire->ire_marks |= ire_marks;
8435 
8436 			/*
8437 			 * Prevent sire and ipif_ire from getting deleted.
8438 			 * The newly created ire is tied to both of them via
8439 			 * the phandle and ihandle respectively.
8440 			 */
8441 			if (sire != NULL) {
8442 				IRB_REFHOLD(sire->ire_bucket);
8443 				/* Has it been removed already ? */
8444 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8445 					IRB_REFRELE(sire->ire_bucket);
8446 					ire_refrele(ipif_ire);
8447 					ire_refrele(save_ire);
8448 					break;
8449 				}
8450 			}
8451 
8452 			IRB_REFHOLD(ipif_ire->ire_bucket);
8453 			/* Has it been removed already ? */
8454 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8455 				IRB_REFRELE(ipif_ire->ire_bucket);
8456 				if (sire != NULL)
8457 					IRB_REFRELE(sire->ire_bucket);
8458 				ire_refrele(ipif_ire);
8459 				ire_refrele(save_ire);
8460 				break;
8461 			}
8462 
8463 			xmit_mp = first_mp;
8464 			/*
8465 			 * In the case of multirouting, a copy
8466 			 * of the packet is done before its sending.
8467 			 * The copy is used to attempt another
8468 			 * route resolution, in a next loop.
8469 			 */
8470 			if (ire->ire_flags & RTF_MULTIRT) {
8471 				copy_mp = copymsg(first_mp);
8472 				if (copy_mp != NULL) {
8473 					xmit_mp = copy_mp;
8474 					MULTIRT_DEBUG_TAG(first_mp);
8475 				}
8476 			}
8477 			ire_add_then_send(q, ire, xmit_mp);
8478 			ire_refrele(save_ire);
8479 
8480 			/* Assert that sire is not deleted yet. */
8481 			if (sire != NULL) {
8482 				ASSERT(sire->ire_ptpn != NULL);
8483 				IRB_REFRELE(sire->ire_bucket);
8484 			}
8485 
8486 			/* Assert that ipif_ire is not deleted yet. */
8487 			ASSERT(ipif_ire->ire_ptpn != NULL);
8488 			IRB_REFRELE(ipif_ire->ire_bucket);
8489 			ire_refrele(ipif_ire);
8490 
8491 			/*
8492 			 * If copy_mp is not NULL, multirouting was
8493 			 * requested. We loop to initiate a next
8494 			 * route resolution attempt, starting from sire.
8495 			 */
8496 			if (copy_mp != NULL) {
8497 				/*
8498 				 * Search for the next unresolved
8499 				 * multirt route.
8500 				 */
8501 				copy_mp = NULL;
8502 				ipif_ire = NULL;
8503 				ire = NULL;
8504 				multirt_resolve_next = B_TRUE;
8505 				continue;
8506 			}
8507 			if (sire != NULL)
8508 				ire_refrele(sire);
8509 			ipif_refrele(src_ipif);
8510 			ill_refrele(dst_ill);
8511 			return;
8512 		}
8513 		case IRE_IF_NORESOLVER: {
8514 
8515 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8516 			    dst_ill->ill_resolver_mp == NULL) {
8517 				ip1dbg(("ip_newroute: dst_ill %p "
8518 				    "for IRE_IF_NORESOLVER ire %p has "
8519 				    "no ill_resolver_mp\n",
8520 				    (void *)dst_ill, (void *)ire));
8521 				break;
8522 			}
8523 
8524 			/*
8525 			 * TSol note: We are creating the ire cache for the
8526 			 * destination 'dst'. If 'dst' is offlink, going
8527 			 * through the first hop 'gw', the security attributes
8528 			 * of 'dst' must be set to point to the gateway
8529 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8530 			 * is possible that 'dst' is a potential gateway that is
8531 			 * referenced by some route that has some security
8532 			 * attributes. Thus in the former case, we need to do a
8533 			 * gcgrp_lookup of 'gw' while in the latter case we
8534 			 * need to do gcgrp_lookup of 'dst' itself.
8535 			 */
8536 			ga.ga_af = AF_INET;
8537 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8538 			    &ga.ga_addr);
8539 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8540 
8541 			ire = ire_create(
8542 			    (uchar_t *)&dst,		/* dest address */
8543 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8544 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8545 			    (uchar_t *)&gw,		/* gateway address */
8546 			    &save_ire->ire_max_frag,
8547 			    NULL,			/* no src nce */
8548 			    dst_ill->ill_rq,		/* recv-from queue */
8549 			    dst_ill->ill_wq,		/* send-to queue */
8550 			    IRE_CACHE,
8551 			    src_ipif,
8552 			    save_ire->ire_mask,		/* Parent mask */
8553 			    (sire != NULL) ?		/* Parent handle */
8554 			    sire->ire_phandle : 0,
8555 			    save_ire->ire_ihandle,	/* Interface handle */
8556 			    (sire != NULL) ? sire->ire_flags &
8557 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8558 			    &(save_ire->ire_uinfo),
8559 			    NULL,
8560 			    gcgrp,
8561 			    ipst);
8562 
8563 			if (ire == NULL) {
8564 				if (gcgrp != NULL) {
8565 					GCGRP_REFRELE(gcgrp);
8566 					gcgrp = NULL;
8567 				}
8568 				ire_refrele(save_ire);
8569 				break;
8570 			}
8571 
8572 			/* reference now held by IRE */
8573 			gcgrp = NULL;
8574 
8575 			ire->ire_marks |= ire_marks;
8576 
8577 			/* Prevent save_ire from getting deleted */
8578 			IRB_REFHOLD(save_ire->ire_bucket);
8579 			/* Has it been removed already ? */
8580 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8581 				IRB_REFRELE(save_ire->ire_bucket);
8582 				ire_refrele(save_ire);
8583 				break;
8584 			}
8585 
8586 			/*
8587 			 * In the case of multirouting, a copy
8588 			 * of the packet is made before it is sent.
8589 			 * The copy is used in the next
8590 			 * loop to attempt another resolution.
8591 			 */
8592 			xmit_mp = first_mp;
8593 			if ((sire != NULL) &&
8594 			    (sire->ire_flags & RTF_MULTIRT)) {
8595 				copy_mp = copymsg(first_mp);
8596 				if (copy_mp != NULL) {
8597 					xmit_mp = copy_mp;
8598 					MULTIRT_DEBUG_TAG(first_mp);
8599 				}
8600 			}
8601 			ire_add_then_send(q, ire, xmit_mp);
8602 
8603 			/* Assert that it is not deleted yet. */
8604 			ASSERT(save_ire->ire_ptpn != NULL);
8605 			IRB_REFRELE(save_ire->ire_bucket);
8606 			ire_refrele(save_ire);
8607 
8608 			if (copy_mp != NULL) {
8609 				/*
8610 				 * If we found a (no)resolver, we ignore any
8611 				 * trailing top priority IRE_CACHE in further
8612 				 * loops. This ensures that we do not omit any
8613 				 * (no)resolver.
8614 				 * This IRE_CACHE, if any, will be processed
8615 				 * by another thread entering ip_newroute().
8616 				 * IRE_CACHE entries, if any, will be processed
8617 				 * by another thread entering ip_newroute(),
8618 				 * (upon resolver response, for instance).
8619 				 * This aims to force parallel multirt
8620 				 * resolutions as soon as a packet must be sent.
8621 				 * In the best case, after the tx of only one
8622 				 * packet, all reachable routes are resolved.
8623 				 * Otherwise, the resolution of all RTF_MULTIRT
8624 				 * routes would require several emissions.
8625 				 */
8626 				multirt_flags &= ~MULTIRT_CACHEGW;
8627 
8628 				/*
8629 				 * Search for the next unresolved multirt
8630 				 * route.
8631 				 */
8632 				copy_mp = NULL;
8633 				save_ire = NULL;
8634 				ire = NULL;
8635 				multirt_resolve_next = B_TRUE;
8636 				continue;
8637 			}
8638 
8639 			/*
8640 			 * Don't need sire anymore
8641 			 */
8642 			if (sire != NULL)
8643 				ire_refrele(sire);
8644 
8645 			ipif_refrele(src_ipif);
8646 			ill_refrele(dst_ill);
8647 			return;
8648 		}
8649 		case IRE_IF_RESOLVER:
8650 			/*
8651 			 * We can't build an IRE_CACHE yet, but at least we
8652 			 * found a resolver that can help.
8653 			 */
8654 			res_mp = dst_ill->ill_resolver_mp;
8655 			if (!OK_RESOLVER_MP(res_mp))
8656 				break;
8657 
8658 			/*
8659 			 * To be at this point in the code with a non-zero gw
8660 			 * means that dst is reachable through a gateway that
8661 			 * we have never resolved.  By changing dst to the gw
8662 			 * addr we resolve the gateway first.
8663 			 * When ire_add_then_send() tries to put the IP dg
8664 			 * to dst, it will reenter ip_newroute() at which
8665 			 * time we will find the IRE_CACHE for the gw and
8666 			 * create another IRE_CACHE in case IRE_CACHE above.
8667 			 */
8668 			if (gw != INADDR_ANY) {
8669 				/*
8670 				 * The source ipif that was determined above was
8671 				 * relative to the destination address, not the
8672 				 * gateway's. If src_ipif was not taken out of
8673 				 * the IRE_IF_RESOLVER entry, we'll need to call
8674 				 * ipif_select_source() again.
8675 				 */
8676 				if (src_ipif != ire->ire_ipif) {
8677 					ipif_refrele(src_ipif);
8678 					src_ipif = ipif_select_source(dst_ill,
8679 					    gw, zoneid);
8680 					if (src_ipif == NULL) {
8681 						if (ip_debug > 2) {
8682 							pr_addr_dbg(
8683 							    "ip_newroute: no "
8684 							    "src for gw %s ",
8685 							    AF_INET, &gw);
8686 							printf("through "
8687 							    "interface %s\n",
8688 							    dst_ill->ill_name);
8689 						}
8690 						goto icmp_err_ret;
8691 					}
8692 				}
8693 				save_dst = dst;
8694 				dst = gw;
8695 				gw = INADDR_ANY;
8696 			}
8697 
8698 			/*
8699 			 * We obtain a partial IRE_CACHE which we will pass
8700 			 * along with the resolver query.  When the response
8701 			 * comes back it will be there ready for us to add.
8702 			 * The ire_max_frag is atomically set under the
8703 			 * irebucket lock in ire_add_v[46].
8704 			 */
8705 
8706 			ire = ire_create_mp(
8707 			    (uchar_t *)&dst,		/* dest address */
8708 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8709 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8710 			    (uchar_t *)&gw,		/* gateway address */
8711 			    NULL,			/* ire_max_frag */
8712 			    NULL,			/* no src nce */
8713 			    dst_ill->ill_rq,		/* recv-from queue */
8714 			    dst_ill->ill_wq,		/* send-to queue */
8715 			    IRE_CACHE,
8716 			    src_ipif,			/* Interface ipif */
8717 			    save_ire->ire_mask,		/* Parent mask */
8718 			    0,
8719 			    save_ire->ire_ihandle,	/* Interface handle */
8720 			    0,				/* flags if any */
8721 			    &(save_ire->ire_uinfo),
8722 			    NULL,
8723 			    NULL,
8724 			    ipst);
8725 
8726 			if (ire == NULL) {
8727 				ire_refrele(save_ire);
8728 				break;
8729 			}
8730 
8731 			if ((sire != NULL) &&
8732 			    (sire->ire_flags & RTF_MULTIRT)) {
8733 				copy_mp = copymsg(first_mp);
8734 				if (copy_mp != NULL)
8735 					MULTIRT_DEBUG_TAG(copy_mp);
8736 			}
8737 
8738 			ire->ire_marks |= ire_marks;
8739 
8740 			/*
8741 			 * Construct message chain for the resolver
8742 			 * of the form:
8743 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8744 			 * Packet could contain a IPSEC_OUT mp.
8745 			 *
8746 			 * NOTE : ire will be added later when the response
8747 			 * comes back from ARP. If the response does not
8748 			 * come back, ARP frees the packet. For this reason,
8749 			 * we can't REFHOLD the bucket of save_ire to prevent
8750 			 * deletions. We may not be able to REFRELE the bucket
8751 			 * if the response never comes back. Thus, before
8752 			 * adding the ire, ire_add_v4 will make sure that the
8753 			 * interface route does not get deleted. This is the
8754 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8755 			 * where we can always prevent deletions because of
8756 			 * the synchronous nature of adding IRES i.e
8757 			 * ire_add_then_send is called after creating the IRE.
8758 			 */
8759 			ASSERT(ire->ire_mp != NULL);
8760 			ire->ire_mp->b_cont = first_mp;
8761 			/* Have saved_mp handy, for cleanup if canput fails */
8762 			saved_mp = mp;
8763 			mp = copyb(res_mp);
8764 			if (mp == NULL) {
8765 				/* Prepare for cleanup */
8766 				mp = saved_mp; /* pkt */
8767 				ire_delete(ire); /* ire_mp */
8768 				ire = NULL;
8769 				ire_refrele(save_ire);
8770 				if (copy_mp != NULL) {
8771 					MULTIRT_DEBUG_UNTAG(copy_mp);
8772 					freemsg(copy_mp);
8773 					copy_mp = NULL;
8774 				}
8775 				break;
8776 			}
8777 			linkb(mp, ire->ire_mp);
8778 
8779 			/*
8780 			 * Fill in the source and dest addrs for the resolver.
8781 			 * NOTE: this depends on memory layouts imposed by
8782 			 * ill_init().
8783 			 */
8784 			areq = (areq_t *)mp->b_rptr;
8785 			addrp = (ipaddr_t *)((char *)areq +
8786 			    areq->areq_sender_addr_offset);
8787 			if (do_attach_ill) {
8788 				/*
8789 				 * This is bind to no failover case.
8790 				 * arp packet also must go out on attach_ill.
8791 				 */
8792 				ASSERT(ipha->ipha_src != NULL);
8793 				*addrp = ipha->ipha_src;
8794 			} else {
8795 				*addrp = save_ire->ire_src_addr;
8796 			}
8797 
8798 			ire_refrele(save_ire);
8799 			addrp = (ipaddr_t *)((char *)areq +
8800 			    areq->areq_target_addr_offset);
8801 			*addrp = dst;
8802 			/* Up to the resolver. */
8803 			if (canputnext(dst_ill->ill_rq) &&
8804 			    !(dst_ill->ill_arp_closing)) {
8805 				putnext(dst_ill->ill_rq, mp);
8806 				ire = NULL;
8807 				if (copy_mp != NULL) {
8808 					/*
8809 					 * If we found a resolver, we ignore
8810 					 * any trailing top priority IRE_CACHE
8811 					 * in the further loops. This ensures
8812 					 * that we do not omit any resolver.
8813 					 * IRE_CACHE entries, if any, will be
8814 					 * processed next time we enter
8815 					 * ip_newroute().
8816 					 */
8817 					multirt_flags &= ~MULTIRT_CACHEGW;
8818 					/*
8819 					 * Search for the next unresolved
8820 					 * multirt route.
8821 					 */
8822 					first_mp = copy_mp;
8823 					copy_mp = NULL;
8824 					/* Prepare the next resolution loop. */
8825 					mp = first_mp;
8826 					EXTRACT_PKT_MP(mp, first_mp,
8827 					    mctl_present);
8828 					if (mctl_present)
8829 						io = (ipsec_out_t *)
8830 						    first_mp->b_rptr;
8831 					ipha = (ipha_t *)mp->b_rptr;
8832 
8833 					ASSERT(sire != NULL);
8834 
8835 					dst = save_dst;
8836 					multirt_resolve_next = B_TRUE;
8837 					continue;
8838 				}
8839 
8840 				if (sire != NULL)
8841 					ire_refrele(sire);
8842 
8843 				/*
8844 				 * The response will come back in ip_wput
8845 				 * with db_type IRE_DB_TYPE.
8846 				 */
8847 				ipif_refrele(src_ipif);
8848 				ill_refrele(dst_ill);
8849 				return;
8850 			} else {
8851 				/* Prepare for cleanup */
8852 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8853 				    mp);
8854 				mp->b_cont = NULL;
8855 				freeb(mp); /* areq */
8856 				/*
8857 				 * this is an ire that is not added to the
8858 				 * cache. ire_freemblk will handle the release
8859 				 * of any resources associated with the ire.
8860 				 */
8861 				ire_delete(ire); /* ire_mp */
8862 				mp = saved_mp; /* pkt */
8863 				ire = NULL;
8864 				if (copy_mp != NULL) {
8865 					MULTIRT_DEBUG_UNTAG(copy_mp);
8866 					freemsg(copy_mp);
8867 					copy_mp = NULL;
8868 				}
8869 				break;
8870 			}
8871 		default:
8872 			break;
8873 		}
8874 	} while (multirt_resolve_next);
8875 
8876 	ip1dbg(("ip_newroute: dropped\n"));
8877 	/* Did this packet originate externally? */
8878 	if (mp->b_prev) {
8879 		mp->b_next = NULL;
8880 		mp->b_prev = NULL;
8881 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8882 	} else {
8883 		if (dst_ill != NULL) {
8884 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8885 		} else {
8886 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8887 		}
8888 	}
8889 	ASSERT(copy_mp == NULL);
8890 	MULTIRT_DEBUG_UNTAG(first_mp);
8891 	freemsg(first_mp);
8892 	if (ire != NULL)
8893 		ire_refrele(ire);
8894 	if (sire != NULL)
8895 		ire_refrele(sire);
8896 	if (src_ipif != NULL)
8897 		ipif_refrele(src_ipif);
8898 	if (dst_ill != NULL)
8899 		ill_refrele(dst_ill);
8900 	return;
8901 
8902 icmp_err_ret:
8903 	ip1dbg(("ip_newroute: no route\n"));
8904 	if (src_ipif != NULL)
8905 		ipif_refrele(src_ipif);
8906 	if (dst_ill != NULL)
8907 		ill_refrele(dst_ill);
8908 	if (sire != NULL)
8909 		ire_refrele(sire);
8910 	/* Did this packet originate externally? */
8911 	if (mp->b_prev) {
8912 		mp->b_next = NULL;
8913 		mp->b_prev = NULL;
8914 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8915 		q = WR(q);
8916 	} else {
8917 		/*
8918 		 * There is no outgoing ill, so just increment the
8919 		 * system MIB.
8920 		 */
8921 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8922 		/*
8923 		 * Since ip_wput() isn't close to finished, we fill
8924 		 * in enough of the header for credible error reporting.
8925 		 */
8926 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8927 			/* Failed */
8928 			MULTIRT_DEBUG_UNTAG(first_mp);
8929 			freemsg(first_mp);
8930 			if (ire != NULL)
8931 				ire_refrele(ire);
8932 			return;
8933 		}
8934 	}
8935 
8936 	/*
8937 	 * At this point we will have ire only if RTF_BLACKHOLE
8938 	 * or RTF_REJECT flags are set on the IRE. It will not
8939 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8940 	 */
8941 	if (ire != NULL) {
8942 		if (ire->ire_flags & RTF_BLACKHOLE) {
8943 			ire_refrele(ire);
8944 			MULTIRT_DEBUG_UNTAG(first_mp);
8945 			freemsg(first_mp);
8946 			return;
8947 		}
8948 		ire_refrele(ire);
8949 	}
8950 	if (ip_source_routed(ipha, ipst)) {
8951 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8952 		    zoneid, ipst);
8953 		return;
8954 	}
8955 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8956 }
8957 
8958 ip_opt_info_t zero_info;
8959 
8960 /*
8961  * IPv4 -
8962  * ip_newroute_ipif is called by ip_wput_multicast and
8963  * ip_rput_forward_multicast whenever we need to send
8964  * out a packet to a destination address for which we do not have specific
8965  * routing information. It is used when the packet will be sent out
8966  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8967  * socket option is set or icmp error message wants to go out on a particular
8968  * interface for a unicast packet.
8969  *
8970  * In most cases, the destination address is resolved thanks to the ipif
8971  * intrinsic resolver. However, there are some cases where the call to
8972  * ip_newroute_ipif must take into account the potential presence of
8973  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8974  * that uses the interface. This is specified through flags,
8975  * which can be a combination of:
8976  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8977  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8978  *   and flags. Additionally, the packet source address has to be set to
8979  *   the specified address. The caller is thus expected to set this flag
8980  *   if the packet has no specific source address yet.
8981  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8982  *   flag, the resulting ire will inherit the flag. All unresolved routes
8983  *   to the destination must be explored in the same call to
8984  *   ip_newroute_ipif().
8985  */
8986 static void
8987 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8988     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8989 {
8990 	areq_t	*areq;
8991 	ire_t	*ire = NULL;
8992 	mblk_t	*res_mp;
8993 	ipaddr_t *addrp;
8994 	mblk_t *first_mp;
8995 	ire_t	*save_ire = NULL;
8996 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8997 	ipif_t	*src_ipif = NULL;
8998 	ushort_t ire_marks = 0;
8999 	ill_t	*dst_ill = NULL;
9000 	boolean_t mctl_present;
9001 	ipsec_out_t *io;
9002 	ipha_t *ipha;
9003 	int	ihandle = 0;
9004 	mblk_t	*saved_mp;
9005 	ire_t   *fire = NULL;
9006 	mblk_t  *copy_mp = NULL;
9007 	boolean_t multirt_resolve_next;
9008 	ipaddr_t ipha_dst;
9009 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9010 
9011 	/*
9012 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9013 	 * here for uniformity
9014 	 */
9015 	ipif_refhold(ipif);
9016 
9017 	/*
9018 	 * This loop is run only once in most cases.
9019 	 * We loop to resolve further routes only when the destination
9020 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9021 	 */
9022 	do {
9023 		if (dst_ill != NULL) {
9024 			ill_refrele(dst_ill);
9025 			dst_ill = NULL;
9026 		}
9027 		if (src_ipif != NULL) {
9028 			ipif_refrele(src_ipif);
9029 			src_ipif = NULL;
9030 		}
9031 		multirt_resolve_next = B_FALSE;
9032 
9033 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9034 		    ipif->ipif_ill->ill_name));
9035 
9036 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9037 		if (mctl_present)
9038 			io = (ipsec_out_t *)first_mp->b_rptr;
9039 
9040 		ipha = (ipha_t *)mp->b_rptr;
9041 
9042 		/*
9043 		 * Save the packet destination address, we may need it after
9044 		 * the packet has been consumed.
9045 		 */
9046 		ipha_dst = ipha->ipha_dst;
9047 
9048 		/*
9049 		 * If the interface is a pt-pt interface we look for an
9050 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9051 		 * local_address and the pt-pt destination address. Otherwise
9052 		 * we just match the local address.
9053 		 * NOTE: dst could be different than ipha->ipha_dst in case
9054 		 * of sending igmp multicast packets over a point-to-point
9055 		 * connection.
9056 		 * Thus we must be careful enough to check ipha_dst to be a
9057 		 * multicast address, otherwise it will take xmit_if path for
9058 		 * multicast packets resulting into kernel stack overflow by
9059 		 * repeated calls to ip_newroute_ipif from ire_send().
9060 		 */
9061 		if (CLASSD(ipha_dst) &&
9062 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9063 			goto err_ret;
9064 		}
9065 
9066 		/*
9067 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9068 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9069 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9070 		 * propagate its flags to the new ire.
9071 		 */
9072 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9073 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9074 			ip2dbg(("ip_newroute_ipif: "
9075 			    "ipif_lookup_multi_ire("
9076 			    "ipif %p, dst %08x) = fire %p\n",
9077 			    (void *)ipif, ntohl(dst), (void *)fire));
9078 		}
9079 
9080 		if (mctl_present && io->ipsec_out_attach_if) {
9081 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9082 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9083 
9084 			/* Failure case frees things for us. */
9085 			if (attach_ill == NULL) {
9086 				ipif_refrele(ipif);
9087 				if (fire != NULL)
9088 					ire_refrele(fire);
9089 				return;
9090 			}
9091 
9092 			/*
9093 			 * Check if we need an ire that will not be
9094 			 * looked up by anybody else i.e. HIDDEN.
9095 			 */
9096 			if (ill_is_probeonly(attach_ill)) {
9097 				ire_marks = IRE_MARK_HIDDEN;
9098 			}
9099 			/*
9100 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9101 			 * case.
9102 			 */
9103 			dst_ill = ipif->ipif_ill;
9104 			/* attach_ill has been refheld by ip_grab_attach_ill */
9105 			ASSERT(dst_ill == attach_ill);
9106 		} else {
9107 			/*
9108 			 * If this is set by IP_XMIT_IF, then make sure that
9109 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9110 			 * specified ill.
9111 			 */
9112 			ASSERT((connp == NULL) ||
9113 			    (connp->conn_xmit_if_ill == NULL) ||
9114 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9115 			/*
9116 			 * If the interface belongs to an interface group,
9117 			 * make sure the next possible interface in the group
9118 			 * is used.  This encourages load spreading among
9119 			 * peers in an interface group.
9120 			 * Note: load spreading is disabled for RTF_MULTIRT
9121 			 * routes.
9122 			 */
9123 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9124 			    (fire->ire_flags & RTF_MULTIRT)) {
9125 				/*
9126 				 * Don't perform outbound load spreading
9127 				 * in the case of an RTF_MULTIRT issued route,
9128 				 * we actually typically want to replicate
9129 				 * outgoing packets through particular
9130 				 * interfaces.
9131 				 */
9132 				dst_ill = ipif->ipif_ill;
9133 				ill_refhold(dst_ill);
9134 			} else {
9135 				dst_ill = ip_newroute_get_dst_ill(
9136 				    ipif->ipif_ill);
9137 			}
9138 			if (dst_ill == NULL) {
9139 				if (ip_debug > 2) {
9140 					pr_addr_dbg("ip_newroute_ipif: "
9141 					    "no dst ill for dst %s\n",
9142 					    AF_INET, &dst);
9143 				}
9144 				goto err_ret;
9145 			}
9146 		}
9147 
9148 		/*
9149 		 * Pick a source address preferring non-deprecated ones.
9150 		 * Unlike ip_newroute, we don't do any source address
9151 		 * selection here since for multicast it really does not help
9152 		 * in inbound load spreading as in the unicast case.
9153 		 */
9154 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9155 		    (fire->ire_flags & RTF_SETSRC)) {
9156 			/*
9157 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9158 			 * on that interface. This ire has RTF_SETSRC flag, so
9159 			 * the source address of the packet must be changed.
9160 			 * Check that the ipif matching the requested source
9161 			 * address still exists.
9162 			 */
9163 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9164 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9165 		}
9166 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9167 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9168 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9169 		    (src_ipif == NULL)) {
9170 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9171 			if (src_ipif == NULL) {
9172 				if (ip_debug > 2) {
9173 					/* ip1dbg */
9174 					pr_addr_dbg("ip_newroute_ipif: "
9175 					    "no src for dst %s",
9176 					    AF_INET, &dst);
9177 				}
9178 				ip1dbg((" through interface %s\n",
9179 				    dst_ill->ill_name));
9180 				goto err_ret;
9181 			}
9182 			ipif_refrele(ipif);
9183 			ipif = src_ipif;
9184 			ipif_refhold(ipif);
9185 		}
9186 		if (src_ipif == NULL) {
9187 			src_ipif = ipif;
9188 			ipif_refhold(src_ipif);
9189 		}
9190 
9191 		/*
9192 		 * Assign a source address while we have the conn.
9193 		 * We can't have ip_wput_ire pick a source address when the
9194 		 * packet returns from arp since conn_unspec_src might be set
9195 		 * and we loose the conn when going through arp.
9196 		 */
9197 		if (ipha->ipha_src == INADDR_ANY &&
9198 		    (connp == NULL || !connp->conn_unspec_src)) {
9199 			ipha->ipha_src = src_ipif->ipif_src_addr;
9200 		}
9201 
9202 		/*
9203 		 * In the case of IP_XMIT_IF, it is possible that the
9204 		 * outgoing interface does not have an interface ire.
9205 		 */
9206 		if (CLASSD(ipha_dst) && (connp == NULL ||
9207 		    connp->conn_xmit_if_ill == NULL) &&
9208 		    infop->ip_opt_ill_index == 0) {
9209 			/* ipif_to_ire returns an held ire */
9210 			ire = ipif_to_ire(ipif);
9211 			if (ire == NULL)
9212 				goto err_ret;
9213 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9214 				goto err_ret;
9215 			/*
9216 			 * ihandle is needed when the ire is added to
9217 			 * cache table.
9218 			 */
9219 			save_ire = ire;
9220 			ihandle = save_ire->ire_ihandle;
9221 
9222 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9223 			    "flags %04x\n",
9224 			    (void *)ire, (void *)ipif, flags));
9225 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9226 			    (fire->ire_flags & RTF_MULTIRT)) {
9227 				/*
9228 				 * As requested by flags, an IRE_OFFSUBNET was
9229 				 * looked up on that interface. This ire has
9230 				 * RTF_MULTIRT flag, so the resolution loop will
9231 				 * be re-entered to resolve additional routes on
9232 				 * other interfaces. For that purpose, a copy of
9233 				 * the packet is performed at this point.
9234 				 */
9235 				fire->ire_last_used_time = lbolt;
9236 				copy_mp = copymsg(first_mp);
9237 				if (copy_mp) {
9238 					MULTIRT_DEBUG_TAG(copy_mp);
9239 				}
9240 			}
9241 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9242 			    (fire->ire_flags & RTF_SETSRC)) {
9243 				/*
9244 				 * As requested by flags, an IRE_OFFSUBET was
9245 				 * looked up on that interface. This ire has
9246 				 * RTF_SETSRC flag, so the source address of the
9247 				 * packet must be changed.
9248 				 */
9249 				ipha->ipha_src = fire->ire_src_addr;
9250 			}
9251 		} else {
9252 			ASSERT((connp == NULL) ||
9253 			    (connp->conn_xmit_if_ill != NULL) ||
9254 			    (connp->conn_dontroute) ||
9255 			    infop->ip_opt_ill_index != 0);
9256 			/*
9257 			 * The only ways we can come here are:
9258 			 * 1) IP_XMIT_IF socket option is set
9259 			 * 2) SO_DONTROUTE socket option is set
9260 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9261 			 * In all cases, the new ire will not be added
9262 			 * into cache table.
9263 			 */
9264 			ire_marks |= IRE_MARK_NOADD;
9265 		}
9266 
9267 		switch (ipif->ipif_net_type) {
9268 		case IRE_IF_NORESOLVER: {
9269 			/* We have what we need to build an IRE_CACHE. */
9270 
9271 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9272 			    (dst_ill->ill_resolver_mp == NULL)) {
9273 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9274 				    "for IRE_IF_NORESOLVER ire %p has "
9275 				    "no ill_resolver_mp\n",
9276 				    (void *)dst_ill, (void *)ire));
9277 				break;
9278 			}
9279 
9280 			/*
9281 			 * The new ire inherits the IRE_OFFSUBNET flags
9282 			 * and source address, if this was requested.
9283 			 */
9284 			ire = ire_create(
9285 			    (uchar_t *)&dst,		/* dest address */
9286 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9287 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9288 			    NULL,			/* gateway address */
9289 			    &ipif->ipif_mtu,
9290 			    NULL,			/* no src nce */
9291 			    dst_ill->ill_rq,		/* recv-from queue */
9292 			    dst_ill->ill_wq,		/* send-to queue */
9293 			    IRE_CACHE,
9294 			    src_ipif,
9295 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9296 			    (fire != NULL) ?		/* Parent handle */
9297 			    fire->ire_phandle : 0,
9298 			    ihandle,			/* Interface handle */
9299 			    (fire != NULL) ?
9300 			    (fire->ire_flags &
9301 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9302 			    (save_ire == NULL ? &ire_uinfo_null :
9303 			    &save_ire->ire_uinfo),
9304 			    NULL,
9305 			    NULL,
9306 			    ipst);
9307 
9308 			if (ire == NULL) {
9309 				if (save_ire != NULL)
9310 					ire_refrele(save_ire);
9311 				break;
9312 			}
9313 
9314 			ire->ire_marks |= ire_marks;
9315 
9316 			/*
9317 			 * If IRE_MARK_NOADD is set then we need to convert
9318 			 * the max_fragp to a useable value now. This is
9319 			 * normally done in ire_add_v[46]. We also need to
9320 			 * associate the ire with an nce (normally would be
9321 			 * done in ip_wput_nondata()).
9322 			 *
9323 			 * Note that IRE_MARK_NOADD packets created here
9324 			 * do not have a non-null ire_mp pointer. The null
9325 			 * value of ire_bucket indicates that they were
9326 			 * never added.
9327 			 */
9328 			if (ire->ire_marks & IRE_MARK_NOADD) {
9329 				uint_t  max_frag;
9330 
9331 				max_frag = *ire->ire_max_fragp;
9332 				ire->ire_max_fragp = NULL;
9333 				ire->ire_max_frag = max_frag;
9334 
9335 				if ((ire->ire_nce = ndp_lookup_v4(
9336 				    ire_to_ill(ire),
9337 				    (ire->ire_gateway_addr != INADDR_ANY ?
9338 				    &ire->ire_gateway_addr : &ire->ire_addr),
9339 				    B_FALSE)) == NULL) {
9340 					if (save_ire != NULL)
9341 						ire_refrele(save_ire);
9342 					break;
9343 				}
9344 				ASSERT(ire->ire_nce->nce_state ==
9345 				    ND_REACHABLE);
9346 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9347 			}
9348 
9349 			/* Prevent save_ire from getting deleted */
9350 			if (save_ire != NULL) {
9351 				IRB_REFHOLD(save_ire->ire_bucket);
9352 				/* Has it been removed already ? */
9353 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9354 					IRB_REFRELE(save_ire->ire_bucket);
9355 					ire_refrele(save_ire);
9356 					break;
9357 				}
9358 			}
9359 
9360 			ire_add_then_send(q, ire, first_mp);
9361 
9362 			/* Assert that save_ire is not deleted yet. */
9363 			if (save_ire != NULL) {
9364 				ASSERT(save_ire->ire_ptpn != NULL);
9365 				IRB_REFRELE(save_ire->ire_bucket);
9366 				ire_refrele(save_ire);
9367 				save_ire = NULL;
9368 			}
9369 			if (fire != NULL) {
9370 				ire_refrele(fire);
9371 				fire = NULL;
9372 			}
9373 
9374 			/*
9375 			 * the resolution loop is re-entered if this
9376 			 * was requested through flags and if we
9377 			 * actually are in a multirouting case.
9378 			 */
9379 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9380 				boolean_t need_resolve =
9381 				    ire_multirt_need_resolve(ipha_dst,
9382 				    MBLK_GETLABEL(copy_mp), ipst);
9383 				if (!need_resolve) {
9384 					MULTIRT_DEBUG_UNTAG(copy_mp);
9385 					freemsg(copy_mp);
9386 					copy_mp = NULL;
9387 				} else {
9388 					/*
9389 					 * ipif_lookup_group() calls
9390 					 * ire_lookup_multi() that uses
9391 					 * ire_ftable_lookup() to find
9392 					 * an IRE_INTERFACE for the group.
9393 					 * In the multirt case,
9394 					 * ire_lookup_multi() then invokes
9395 					 * ire_multirt_lookup() to find
9396 					 * the next resolvable ire.
9397 					 * As a result, we obtain an new
9398 					 * interface, derived from the
9399 					 * next ire.
9400 					 */
9401 					ipif_refrele(ipif);
9402 					ipif = ipif_lookup_group(ipha_dst,
9403 					    zoneid, ipst);
9404 					ip2dbg(("ip_newroute_ipif: "
9405 					    "multirt dst %08x, ipif %p\n",
9406 					    htonl(dst), (void *)ipif));
9407 					if (ipif != NULL) {
9408 						mp = copy_mp;
9409 						copy_mp = NULL;
9410 						multirt_resolve_next = B_TRUE;
9411 						continue;
9412 					} else {
9413 						freemsg(copy_mp);
9414 					}
9415 				}
9416 			}
9417 			if (ipif != NULL)
9418 				ipif_refrele(ipif);
9419 			ill_refrele(dst_ill);
9420 			ipif_refrele(src_ipif);
9421 			return;
9422 		}
9423 		case IRE_IF_RESOLVER:
9424 			/*
9425 			 * We can't build an IRE_CACHE yet, but at least
9426 			 * we found a resolver that can help.
9427 			 */
9428 			res_mp = dst_ill->ill_resolver_mp;
9429 			if (!OK_RESOLVER_MP(res_mp))
9430 				break;
9431 
9432 			/*
9433 			 * We obtain a partial IRE_CACHE which we will pass
9434 			 * along with the resolver query.  When the response
9435 			 * comes back it will be there ready for us to add.
9436 			 * The new ire inherits the IRE_OFFSUBNET flags
9437 			 * and source address, if this was requested.
9438 			 * The ire_max_frag is atomically set under the
9439 			 * irebucket lock in ire_add_v[46]. Only in the
9440 			 * case of IRE_MARK_NOADD, we set it here itself.
9441 			 */
9442 			ire = ire_create_mp(
9443 			    (uchar_t *)&dst,		/* dest address */
9444 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9445 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9446 			    NULL,			/* gateway address */
9447 			    (ire_marks & IRE_MARK_NOADD) ?
9448 			    ipif->ipif_mtu : 0,		/* max_frag */
9449 			    NULL,			/* no src nce */
9450 			    dst_ill->ill_rq,		/* recv-from queue */
9451 			    dst_ill->ill_wq,		/* send-to queue */
9452 			    IRE_CACHE,
9453 			    src_ipif,
9454 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9455 			    (fire != NULL) ?		/* Parent handle */
9456 			    fire->ire_phandle : 0,
9457 			    ihandle,			/* Interface handle */
9458 			    (fire != NULL) ?		/* flags if any */
9459 			    (fire->ire_flags &
9460 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9461 			    (save_ire == NULL ? &ire_uinfo_null :
9462 			    &save_ire->ire_uinfo),
9463 			    NULL,
9464 			    NULL,
9465 			    ipst);
9466 
9467 			if (save_ire != NULL) {
9468 				ire_refrele(save_ire);
9469 				save_ire = NULL;
9470 			}
9471 			if (ire == NULL)
9472 				break;
9473 
9474 			ire->ire_marks |= ire_marks;
9475 			/*
9476 			 * Construct message chain for the resolver of the
9477 			 * form:
9478 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9479 			 *
9480 			 * NOTE : ire will be added later when the response
9481 			 * comes back from ARP. If the response does not
9482 			 * come back, ARP frees the packet. For this reason,
9483 			 * we can't REFHOLD the bucket of save_ire to prevent
9484 			 * deletions. We may not be able to REFRELE the
9485 			 * bucket if the response never comes back.
9486 			 * Thus, before adding the ire, ire_add_v4 will make
9487 			 * sure that the interface route does not get deleted.
9488 			 * This is the only case unlike ip_newroute_v6,
9489 			 * ip_newroute_ipif_v6 where we can always prevent
9490 			 * deletions because ire_add_then_send is called after
9491 			 * creating the IRE.
9492 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9493 			 * does not add this IRE into the IRE CACHE.
9494 			 */
9495 			ASSERT(ire->ire_mp != NULL);
9496 			ire->ire_mp->b_cont = first_mp;
9497 			/* Have saved_mp handy, for cleanup if canput fails */
9498 			saved_mp = mp;
9499 			mp = copyb(res_mp);
9500 			if (mp == NULL) {
9501 				/* Prepare for cleanup */
9502 				mp = saved_mp; /* pkt */
9503 				ire_delete(ire); /* ire_mp */
9504 				ire = NULL;
9505 				if (copy_mp != NULL) {
9506 					MULTIRT_DEBUG_UNTAG(copy_mp);
9507 					freemsg(copy_mp);
9508 					copy_mp = NULL;
9509 				}
9510 				break;
9511 			}
9512 			linkb(mp, ire->ire_mp);
9513 
9514 			/*
9515 			 * Fill in the source and dest addrs for the resolver.
9516 			 * NOTE: this depends on memory layouts imposed by
9517 			 * ill_init().
9518 			 */
9519 			areq = (areq_t *)mp->b_rptr;
9520 			addrp = (ipaddr_t *)((char *)areq +
9521 			    areq->areq_sender_addr_offset);
9522 			*addrp = ire->ire_src_addr;
9523 			addrp = (ipaddr_t *)((char *)areq +
9524 			    areq->areq_target_addr_offset);
9525 			*addrp = dst;
9526 			/* Up to the resolver. */
9527 			if (canputnext(dst_ill->ill_rq) &&
9528 			    !(dst_ill->ill_arp_closing)) {
9529 				putnext(dst_ill->ill_rq, mp);
9530 				/*
9531 				 * The response will come back in ip_wput
9532 				 * with db_type IRE_DB_TYPE.
9533 				 */
9534 			} else {
9535 				mp->b_cont = NULL;
9536 				freeb(mp); /* areq */
9537 				ire_delete(ire); /* ire_mp */
9538 				saved_mp->b_next = NULL;
9539 				saved_mp->b_prev = NULL;
9540 				freemsg(first_mp); /* pkt */
9541 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9542 			}
9543 
9544 			if (fire != NULL) {
9545 				ire_refrele(fire);
9546 				fire = NULL;
9547 			}
9548 
9549 
9550 			/*
9551 			 * The resolution loop is re-entered if this was
9552 			 * requested through flags and we actually are
9553 			 * in a multirouting case.
9554 			 */
9555 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9556 				boolean_t need_resolve =
9557 				    ire_multirt_need_resolve(ipha_dst,
9558 				    MBLK_GETLABEL(copy_mp), ipst);
9559 				if (!need_resolve) {
9560 					MULTIRT_DEBUG_UNTAG(copy_mp);
9561 					freemsg(copy_mp);
9562 					copy_mp = NULL;
9563 				} else {
9564 					/*
9565 					 * ipif_lookup_group() calls
9566 					 * ire_lookup_multi() that uses
9567 					 * ire_ftable_lookup() to find
9568 					 * an IRE_INTERFACE for the group.
9569 					 * In the multirt case,
9570 					 * ire_lookup_multi() then invokes
9571 					 * ire_multirt_lookup() to find
9572 					 * the next resolvable ire.
9573 					 * As a result, we obtain an new
9574 					 * interface, derived from the
9575 					 * next ire.
9576 					 */
9577 					ipif_refrele(ipif);
9578 					ipif = ipif_lookup_group(ipha_dst,
9579 					    zoneid, ipst);
9580 					if (ipif != NULL) {
9581 						mp = copy_mp;
9582 						copy_mp = NULL;
9583 						multirt_resolve_next = B_TRUE;
9584 						continue;
9585 					} else {
9586 						freemsg(copy_mp);
9587 					}
9588 				}
9589 			}
9590 			if (ipif != NULL)
9591 				ipif_refrele(ipif);
9592 			ill_refrele(dst_ill);
9593 			ipif_refrele(src_ipif);
9594 			return;
9595 		default:
9596 			break;
9597 		}
9598 	} while (multirt_resolve_next);
9599 
9600 err_ret:
9601 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9602 	if (fire != NULL)
9603 		ire_refrele(fire);
9604 	ipif_refrele(ipif);
9605 	/* Did this packet originate externally? */
9606 	if (dst_ill != NULL)
9607 		ill_refrele(dst_ill);
9608 	if (src_ipif != NULL)
9609 		ipif_refrele(src_ipif);
9610 	if (mp->b_prev || mp->b_next) {
9611 		mp->b_next = NULL;
9612 		mp->b_prev = NULL;
9613 	} else {
9614 		/*
9615 		 * Since ip_wput() isn't close to finished, we fill
9616 		 * in enough of the header for credible error reporting.
9617 		 */
9618 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9619 			/* Failed */
9620 			freemsg(first_mp);
9621 			if (ire != NULL)
9622 				ire_refrele(ire);
9623 			return;
9624 		}
9625 	}
9626 	/*
9627 	 * At this point we will have ire only if RTF_BLACKHOLE
9628 	 * or RTF_REJECT flags are set on the IRE. It will not
9629 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9630 	 */
9631 	if (ire != NULL) {
9632 		if (ire->ire_flags & RTF_BLACKHOLE) {
9633 			ire_refrele(ire);
9634 			freemsg(first_mp);
9635 			return;
9636 		}
9637 		ire_refrele(ire);
9638 	}
9639 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9640 }
9641 
9642 /* Name/Value Table Lookup Routine */
9643 char *
9644 ip_nv_lookup(nv_t *nv, int value)
9645 {
9646 	if (!nv)
9647 		return (NULL);
9648 	for (; nv->nv_name; nv++) {
9649 		if (nv->nv_value == value)
9650 			return (nv->nv_name);
9651 	}
9652 	return ("unknown");
9653 }
9654 
9655 /*
9656  * This is a module open, i.e. this is a control stream for access
9657  * to a DLPI device.  We allocate an ill_t as the instance data in
9658  * this case.
9659  */
9660 int
9661 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9662 {
9663 	ill_t	*ill;
9664 	int	err;
9665 	zoneid_t zoneid;
9666 	netstack_t *ns;
9667 	ip_stack_t *ipst;
9668 
9669 	/*
9670 	 * Prevent unprivileged processes from pushing IP so that
9671 	 * they can't send raw IP.
9672 	 */
9673 	if (secpolicy_net_rawaccess(credp) != 0)
9674 		return (EPERM);
9675 
9676 	ns = netstack_find_by_cred(credp);
9677 	ASSERT(ns != NULL);
9678 	ipst = ns->netstack_ip;
9679 	ASSERT(ipst != NULL);
9680 
9681 	/*
9682 	 * For exclusive stacks we set the zoneid to zero
9683 	 * to make IP operate as if in the global zone.
9684 	 */
9685 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9686 		zoneid = GLOBAL_ZONEID;
9687 	else
9688 		zoneid = crgetzoneid(credp);
9689 
9690 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9691 	q->q_ptr = WR(q)->q_ptr = ill;
9692 	ill->ill_ipst = ipst;
9693 	ill->ill_zoneid = zoneid;
9694 
9695 	/*
9696 	 * ill_init initializes the ill fields and then sends down
9697 	 * down a DL_INFO_REQ after calling qprocson.
9698 	 */
9699 	err = ill_init(q, ill);
9700 	if (err != 0) {
9701 		mi_free(ill);
9702 		netstack_rele(ipst->ips_netstack);
9703 		q->q_ptr = NULL;
9704 		WR(q)->q_ptr = NULL;
9705 		return (err);
9706 	}
9707 
9708 	/* ill_init initializes the ipsq marking this thread as writer */
9709 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9710 	/* Wait for the DL_INFO_ACK */
9711 	mutex_enter(&ill->ill_lock);
9712 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9713 		/*
9714 		 * Return value of 0 indicates a pending signal.
9715 		 */
9716 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9717 		if (err == 0) {
9718 			mutex_exit(&ill->ill_lock);
9719 			(void) ip_close(q, 0);
9720 			return (EINTR);
9721 		}
9722 	}
9723 	mutex_exit(&ill->ill_lock);
9724 
9725 	/*
9726 	 * ip_rput_other could have set an error  in ill_error on
9727 	 * receipt of M_ERROR.
9728 	 */
9729 
9730 	err = ill->ill_error;
9731 	if (err != 0) {
9732 		(void) ip_close(q, 0);
9733 		return (err);
9734 	}
9735 
9736 	ill->ill_credp = credp;
9737 	crhold(credp);
9738 
9739 	mutex_enter(&ipst->ips_ip_mi_lock);
9740 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9741 	    credp);
9742 	mutex_exit(&ipst->ips_ip_mi_lock);
9743 	if (err) {
9744 		(void) ip_close(q, 0);
9745 		return (err);
9746 	}
9747 	return (0);
9748 }
9749 
9750 /* For /dev/ip aka AF_INET open */
9751 int
9752 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9753 {
9754 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9755 }
9756 
9757 /* For /dev/ip6 aka AF_INET6 open */
9758 int
9759 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9760 {
9761 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9762 }
9763 
9764 /* IP open routine. */
9765 int
9766 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9767     boolean_t isv6)
9768 {
9769 	conn_t 		*connp;
9770 	major_t		maj;
9771 	zoneid_t	zoneid;
9772 	netstack_t	*ns;
9773 	ip_stack_t	*ipst;
9774 
9775 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9776 
9777 	/* Allow reopen. */
9778 	if (q->q_ptr != NULL)
9779 		return (0);
9780 
9781 	if (sflag & MODOPEN) {
9782 		/* This is a module open */
9783 		return (ip_modopen(q, devp, flag, sflag, credp));
9784 	}
9785 
9786 	ns = netstack_find_by_cred(credp);
9787 	ASSERT(ns != NULL);
9788 	ipst = ns->netstack_ip;
9789 	ASSERT(ipst != NULL);
9790 
9791 	/*
9792 	 * For exclusive stacks we set the zoneid to zero
9793 	 * to make IP operate as if in the global zone.
9794 	 */
9795 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9796 		zoneid = GLOBAL_ZONEID;
9797 	else
9798 		zoneid = crgetzoneid(credp);
9799 
9800 	/*
9801 	 * We are opening as a device. This is an IP client stream, and we
9802 	 * allocate an conn_t as the instance data.
9803 	 */
9804 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9805 
9806 	/*
9807 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9808 	 * done by netstack_find_by_cred()
9809 	 */
9810 	netstack_rele(ipst->ips_netstack);
9811 
9812 	connp->conn_zoneid = zoneid;
9813 
9814 	connp->conn_upq = q;
9815 	q->q_ptr = WR(q)->q_ptr = connp;
9816 
9817 	if (flag & SO_SOCKSTR)
9818 		connp->conn_flags |= IPCL_SOCKET;
9819 
9820 	/* Minor tells us which /dev entry was opened */
9821 	if (isv6) {
9822 		connp->conn_flags |= IPCL_ISV6;
9823 		connp->conn_af_isv6 = B_TRUE;
9824 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9825 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9826 	} else {
9827 		connp->conn_af_isv6 = B_FALSE;
9828 		connp->conn_pkt_isv6 = B_FALSE;
9829 	}
9830 
9831 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9832 		/* CONN_DEC_REF takes care of netstack_rele() */
9833 		q->q_ptr = WR(q)->q_ptr = NULL;
9834 		CONN_DEC_REF(connp);
9835 		return (EBUSY);
9836 	}
9837 
9838 	maj = getemajor(*devp);
9839 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9840 
9841 	/*
9842 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9843 	 */
9844 	connp->conn_cred = credp;
9845 
9846 	/*
9847 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9848 	 */
9849 	connp->conn_recv = ip_conn_input;
9850 
9851 	crhold(connp->conn_cred);
9852 
9853 	/*
9854 	 * If the caller has the process-wide flag set, then default to MAC
9855 	 * exempt mode.  This allows read-down to unlabeled hosts.
9856 	 */
9857 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9858 		connp->conn_mac_exempt = B_TRUE;
9859 
9860 	connp->conn_rq = q;
9861 	connp->conn_wq = WR(q);
9862 
9863 	/* Non-zero default values */
9864 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9865 
9866 	/*
9867 	 * Make the conn globally visible to walkers
9868 	 */
9869 	ASSERT(connp->conn_ref == 1);
9870 	mutex_enter(&connp->conn_lock);
9871 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9872 	mutex_exit(&connp->conn_lock);
9873 
9874 	qprocson(q);
9875 
9876 	return (0);
9877 }
9878 
9879 /*
9880  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9881  * Note that there is no race since either ip_output function works - it
9882  * is just an optimization to enter the best ip_output routine directly.
9883  */
9884 void
9885 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9886     ip_stack_t *ipst)
9887 {
9888 	if (isv6)  {
9889 		if (bump_mib) {
9890 			BUMP_MIB(&ipst->ips_ip6_mib,
9891 			    ipIfStatsOutSwitchIPVersion);
9892 		}
9893 		connp->conn_send = ip_output_v6;
9894 		connp->conn_pkt_isv6 = B_TRUE;
9895 	} else {
9896 		if (bump_mib) {
9897 			BUMP_MIB(&ipst->ips_ip_mib,
9898 			    ipIfStatsOutSwitchIPVersion);
9899 		}
9900 		connp->conn_send = ip_output;
9901 		connp->conn_pkt_isv6 = B_FALSE;
9902 	}
9903 
9904 }
9905 
9906 /*
9907  * See if IPsec needs loading because of the options in mp.
9908  */
9909 static boolean_t
9910 ipsec_opt_present(mblk_t *mp)
9911 {
9912 	uint8_t *optcp, *next_optcp, *opt_endcp;
9913 	struct opthdr *opt;
9914 	struct T_opthdr *topt;
9915 	int opthdr_len;
9916 	t_uscalar_t optname, optlevel;
9917 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9918 	ipsec_req_t *ipsr;
9919 
9920 	/*
9921 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9922 	 * return TRUE.
9923 	 */
9924 
9925 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9926 	opt_endcp = optcp + tor->OPT_length;
9927 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9928 		opthdr_len = sizeof (struct T_opthdr);
9929 	} else {		/* O_OPTMGMT_REQ */
9930 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9931 		opthdr_len = sizeof (struct opthdr);
9932 	}
9933 	for (; optcp < opt_endcp; optcp = next_optcp) {
9934 		if (optcp + opthdr_len > opt_endcp)
9935 			return (B_FALSE);	/* Not enough option header. */
9936 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9937 			topt = (struct T_opthdr *)optcp;
9938 			optlevel = topt->level;
9939 			optname = topt->name;
9940 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9941 		} else {
9942 			opt = (struct opthdr *)optcp;
9943 			optlevel = opt->level;
9944 			optname = opt->name;
9945 			next_optcp = optcp + opthdr_len +
9946 			    _TPI_ALIGN_OPT(opt->len);
9947 		}
9948 		if ((next_optcp < optcp) || /* wraparound pointer space */
9949 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9950 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9951 			return (B_FALSE); /* bad option buffer */
9952 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9953 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9954 			/*
9955 			 * Check to see if it's an all-bypass or all-zeroes
9956 			 * IPsec request.  Don't bother loading IPsec if
9957 			 * the socket doesn't want to use it.  (A good example
9958 			 * is a bypass request.)
9959 			 *
9960 			 * Basically, if any of the non-NEVER bits are set,
9961 			 * load IPsec.
9962 			 */
9963 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9964 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9965 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9966 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9967 			    != 0)
9968 				return (B_TRUE);
9969 		}
9970 	}
9971 	return (B_FALSE);
9972 }
9973 
9974 /*
9975  * If conn is is waiting for ipsec to finish loading, kick it.
9976  */
9977 /* ARGSUSED */
9978 static void
9979 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9980 {
9981 	t_scalar_t	optreq_prim;
9982 	mblk_t		*mp;
9983 	cred_t		*cr;
9984 	int		err = 0;
9985 
9986 	/*
9987 	 * This function is called, after ipsec loading is complete.
9988 	 * Since IP checks exclusively and atomically (i.e it prevents
9989 	 * ipsec load from completing until ip_optcom_req completes)
9990 	 * whether ipsec load is complete, there cannot be a race with IP
9991 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9992 	 */
9993 	mutex_enter(&connp->conn_lock);
9994 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9995 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9996 		mp = connp->conn_ipsec_opt_mp;
9997 		connp->conn_ipsec_opt_mp = NULL;
9998 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9999 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10000 		mutex_exit(&connp->conn_lock);
10001 
10002 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10003 
10004 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10005 		if (optreq_prim == T_OPTMGMT_REQ) {
10006 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10007 			    &ip_opt_obj, B_FALSE);
10008 		} else {
10009 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10010 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10011 			    &ip_opt_obj, B_FALSE);
10012 		}
10013 		if (err != EINPROGRESS)
10014 			CONN_OPER_PENDING_DONE(connp);
10015 		return;
10016 	}
10017 	mutex_exit(&connp->conn_lock);
10018 }
10019 
10020 /*
10021  * Called from the ipsec_loader thread, outside any perimeter, to tell
10022  * ip qenable any of the queues waiting for the ipsec loader to
10023  * complete.
10024  */
10025 void
10026 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10027 {
10028 	netstack_t *ns = ipss->ipsec_netstack;
10029 
10030 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10031 }
10032 
10033 /*
10034  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10035  * determines the grp on which it has to become exclusive, queues the mp
10036  * and sq draining restarts the optmgmt
10037  */
10038 static boolean_t
10039 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10040 {
10041 	conn_t *connp = Q_TO_CONN(q);
10042 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10043 
10044 	/*
10045 	 * Take IPsec requests and treat them special.
10046 	 */
10047 	if (ipsec_opt_present(mp)) {
10048 		/* First check if IPsec is loaded. */
10049 		mutex_enter(&ipss->ipsec_loader_lock);
10050 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10051 			mutex_exit(&ipss->ipsec_loader_lock);
10052 			return (B_FALSE);
10053 		}
10054 		mutex_enter(&connp->conn_lock);
10055 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10056 
10057 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10058 		connp->conn_ipsec_opt_mp = mp;
10059 		mutex_exit(&connp->conn_lock);
10060 		mutex_exit(&ipss->ipsec_loader_lock);
10061 
10062 		ipsec_loader_loadnow(ipss);
10063 		return (B_TRUE);
10064 	}
10065 	return (B_FALSE);
10066 }
10067 
10068 /*
10069  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10070  * all of them are copied to the conn_t. If the req is "zero", the policy is
10071  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10072  * fields.
10073  * We keep only the latest setting of the policy and thus policy setting
10074  * is not incremental/cumulative.
10075  *
10076  * Requests to set policies with multiple alternative actions will
10077  * go through a different API.
10078  */
10079 int
10080 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10081 {
10082 	uint_t ah_req = 0;
10083 	uint_t esp_req = 0;
10084 	uint_t se_req = 0;
10085 	ipsec_selkey_t sel;
10086 	ipsec_act_t *actp = NULL;
10087 	uint_t nact;
10088 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10089 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10090 	ipsec_policy_root_t *pr;
10091 	ipsec_policy_head_t *ph;
10092 	int fam;
10093 	boolean_t is_pol_reset;
10094 	int error = 0;
10095 	netstack_t	*ns = connp->conn_netstack;
10096 	ip_stack_t	*ipst = ns->netstack_ip;
10097 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10098 
10099 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10100 
10101 	/*
10102 	 * The IP_SEC_OPT option does not allow variable length parameters,
10103 	 * hence a request cannot be NULL.
10104 	 */
10105 	if (req == NULL)
10106 		return (EINVAL);
10107 
10108 	ah_req = req->ipsr_ah_req;
10109 	esp_req = req->ipsr_esp_req;
10110 	se_req = req->ipsr_self_encap_req;
10111 
10112 	/*
10113 	 * Are we dealing with a request to reset the policy (i.e.
10114 	 * zero requests).
10115 	 */
10116 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10117 	    (esp_req & REQ_MASK) == 0 &&
10118 	    (se_req & REQ_MASK) == 0);
10119 
10120 	if (!is_pol_reset) {
10121 		/*
10122 		 * If we couldn't load IPsec, fail with "protocol
10123 		 * not supported".
10124 		 * IPsec may not have been loaded for a request with zero
10125 		 * policies, so we don't fail in this case.
10126 		 */
10127 		mutex_enter(&ipss->ipsec_loader_lock);
10128 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10129 			mutex_exit(&ipss->ipsec_loader_lock);
10130 			return (EPROTONOSUPPORT);
10131 		}
10132 		mutex_exit(&ipss->ipsec_loader_lock);
10133 
10134 		/*
10135 		 * Test for valid requests. Invalid algorithms
10136 		 * need to be tested by IPsec code because new
10137 		 * algorithms can be added dynamically.
10138 		 */
10139 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10140 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10141 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10142 			return (EINVAL);
10143 		}
10144 
10145 		/*
10146 		 * Only privileged users can issue these
10147 		 * requests.
10148 		 */
10149 		if (((ah_req & IPSEC_PREF_NEVER) ||
10150 		    (esp_req & IPSEC_PREF_NEVER) ||
10151 		    (se_req & IPSEC_PREF_NEVER)) &&
10152 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10153 			return (EPERM);
10154 		}
10155 
10156 		/*
10157 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10158 		 * are mutually exclusive.
10159 		 */
10160 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10161 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10162 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10163 			/* Both of them are set */
10164 			return (EINVAL);
10165 		}
10166 	}
10167 
10168 	mutex_enter(&connp->conn_lock);
10169 
10170 	/*
10171 	 * If we have already cached policies in ip_bind_connected*(), don't
10172 	 * let them change now. We cache policies for connections
10173 	 * whose src,dst [addr, port] is known.
10174 	 */
10175 	if (connp->conn_policy_cached) {
10176 		mutex_exit(&connp->conn_lock);
10177 		return (EINVAL);
10178 	}
10179 
10180 	/*
10181 	 * We have a zero policies, reset the connection policy if already
10182 	 * set. This will cause the connection to inherit the
10183 	 * global policy, if any.
10184 	 */
10185 	if (is_pol_reset) {
10186 		if (connp->conn_policy != NULL) {
10187 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10188 			connp->conn_policy = NULL;
10189 		}
10190 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10191 		connp->conn_in_enforce_policy = B_FALSE;
10192 		connp->conn_out_enforce_policy = B_FALSE;
10193 		mutex_exit(&connp->conn_lock);
10194 		return (0);
10195 	}
10196 
10197 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10198 	    ipst->ips_netstack);
10199 	if (ph == NULL)
10200 		goto enomem;
10201 
10202 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10203 	if (actp == NULL)
10204 		goto enomem;
10205 
10206 	/*
10207 	 * Always allocate IPv4 policy entries, since they can also
10208 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10209 	 */
10210 	bzero(&sel, sizeof (sel));
10211 	sel.ipsl_valid = IPSL_IPV4;
10212 
10213 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10214 	    ipst->ips_netstack);
10215 	if (pin4 == NULL)
10216 		goto enomem;
10217 
10218 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10219 	    ipst->ips_netstack);
10220 	if (pout4 == NULL)
10221 		goto enomem;
10222 
10223 	if (connp->conn_af_isv6) {
10224 		/*
10225 		 * We're looking at a v6 socket, also allocate the
10226 		 * v6-specific entries...
10227 		 */
10228 		sel.ipsl_valid = IPSL_IPV6;
10229 		pin6 = ipsec_policy_create(&sel, actp, nact,
10230 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10231 		if (pin6 == NULL)
10232 			goto enomem;
10233 
10234 		pout6 = ipsec_policy_create(&sel, actp, nact,
10235 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10236 		if (pout6 == NULL)
10237 			goto enomem;
10238 
10239 		/*
10240 		 * .. and file them away in the right place.
10241 		 */
10242 		fam = IPSEC_AF_V6;
10243 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10244 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10245 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10246 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10247 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10248 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10249 	}
10250 
10251 	ipsec_actvec_free(actp, nact);
10252 
10253 	/*
10254 	 * File the v4 policies.
10255 	 */
10256 	fam = IPSEC_AF_V4;
10257 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10258 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10259 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10260 
10261 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10262 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10263 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10264 
10265 	/*
10266 	 * If the requests need security, set enforce_policy.
10267 	 * If the requests are IPSEC_PREF_NEVER, one should
10268 	 * still set conn_out_enforce_policy so that an ipsec_out
10269 	 * gets attached in ip_wput. This is needed so that
10270 	 * for connections that we don't cache policy in ip_bind,
10271 	 * if global policy matches in ip_wput_attach_policy, we
10272 	 * don't wrongly inherit global policy. Similarly, we need
10273 	 * to set conn_in_enforce_policy also so that we don't verify
10274 	 * policy wrongly.
10275 	 */
10276 	if ((ah_req & REQ_MASK) != 0 ||
10277 	    (esp_req & REQ_MASK) != 0 ||
10278 	    (se_req & REQ_MASK) != 0) {
10279 		connp->conn_in_enforce_policy = B_TRUE;
10280 		connp->conn_out_enforce_policy = B_TRUE;
10281 		connp->conn_flags |= IPCL_CHECK_POLICY;
10282 	}
10283 
10284 	mutex_exit(&connp->conn_lock);
10285 	return (error);
10286 #undef REQ_MASK
10287 
10288 	/*
10289 	 * Common memory-allocation-failure exit path.
10290 	 */
10291 enomem:
10292 	mutex_exit(&connp->conn_lock);
10293 	if (actp != NULL)
10294 		ipsec_actvec_free(actp, nact);
10295 	if (pin4 != NULL)
10296 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10297 	if (pout4 != NULL)
10298 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10299 	if (pin6 != NULL)
10300 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10301 	if (pout6 != NULL)
10302 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10303 	return (ENOMEM);
10304 }
10305 
10306 /*
10307  * Only for options that pass in an IP addr. Currently only V4 options
10308  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10309  * So this function assumes level is IPPROTO_IP
10310  */
10311 int
10312 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10313     mblk_t *first_mp)
10314 {
10315 	ipif_t *ipif = NULL;
10316 	int error;
10317 	ill_t *ill;
10318 	int zoneid;
10319 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10320 
10321 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10322 
10323 	if (addr != INADDR_ANY || checkonly) {
10324 		ASSERT(connp != NULL);
10325 		zoneid = IPCL_ZONEID(connp);
10326 		if (option == IP_NEXTHOP) {
10327 			ipif = ipif_lookup_onlink_addr(addr,
10328 			    connp->conn_zoneid, ipst);
10329 		} else {
10330 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10331 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10332 			    &error, ipst);
10333 		}
10334 		if (ipif == NULL) {
10335 			if (error == EINPROGRESS)
10336 				return (error);
10337 			else if ((option == IP_MULTICAST_IF) ||
10338 			    (option == IP_NEXTHOP))
10339 				return (EHOSTUNREACH);
10340 			else
10341 				return (EINVAL);
10342 		} else if (checkonly) {
10343 			if (option == IP_MULTICAST_IF) {
10344 				ill = ipif->ipif_ill;
10345 				/* not supported by the virtual network iface */
10346 				if (IS_VNI(ill)) {
10347 					ipif_refrele(ipif);
10348 					return (EINVAL);
10349 				}
10350 			}
10351 			ipif_refrele(ipif);
10352 			return (0);
10353 		}
10354 		ill = ipif->ipif_ill;
10355 		mutex_enter(&connp->conn_lock);
10356 		mutex_enter(&ill->ill_lock);
10357 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10358 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10359 			mutex_exit(&ill->ill_lock);
10360 			mutex_exit(&connp->conn_lock);
10361 			ipif_refrele(ipif);
10362 			return (option == IP_MULTICAST_IF ?
10363 			    EHOSTUNREACH : EINVAL);
10364 		}
10365 	} else {
10366 		mutex_enter(&connp->conn_lock);
10367 	}
10368 
10369 	/* None of the options below are supported on the VNI */
10370 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10371 		mutex_exit(&ill->ill_lock);
10372 		mutex_exit(&connp->conn_lock);
10373 		ipif_refrele(ipif);
10374 		return (EINVAL);
10375 	}
10376 
10377 	switch (option) {
10378 	case IP_DONTFAILOVER_IF:
10379 		/*
10380 		 * This option is used by in.mpathd to ensure
10381 		 * that IPMP probe packets only go out on the
10382 		 * test interfaces. in.mpathd sets this option
10383 		 * on the non-failover interfaces.
10384 		 * For backward compatibility, this option
10385 		 * implicitly sets IP_MULTICAST_IF, as used
10386 		 * be done in bind(), so that ip_wput gets
10387 		 * this ipif to send mcast packets.
10388 		 */
10389 		if (ipif != NULL) {
10390 			ASSERT(addr != INADDR_ANY);
10391 			connp->conn_nofailover_ill = ipif->ipif_ill;
10392 			connp->conn_multicast_ipif = ipif;
10393 		} else {
10394 			ASSERT(addr == INADDR_ANY);
10395 			connp->conn_nofailover_ill = NULL;
10396 			connp->conn_multicast_ipif = NULL;
10397 		}
10398 		break;
10399 
10400 	case IP_MULTICAST_IF:
10401 		connp->conn_multicast_ipif = ipif;
10402 		break;
10403 	case IP_NEXTHOP:
10404 		connp->conn_nexthop_v4 = addr;
10405 		connp->conn_nexthop_set = B_TRUE;
10406 		break;
10407 	}
10408 
10409 	if (ipif != NULL) {
10410 		mutex_exit(&ill->ill_lock);
10411 		mutex_exit(&connp->conn_lock);
10412 		ipif_refrele(ipif);
10413 		return (0);
10414 	}
10415 	mutex_exit(&connp->conn_lock);
10416 	/* We succeded in cleared the option */
10417 	return (0);
10418 }
10419 
10420 /*
10421  * For options that pass in an ifindex specifying the ill. V6 options always
10422  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10423  */
10424 int
10425 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10426     int level, int option, mblk_t *first_mp)
10427 {
10428 	ill_t *ill = NULL;
10429 	int error = 0;
10430 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10431 
10432 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10433 	if (ifindex != 0) {
10434 		ASSERT(connp != NULL);
10435 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10436 		    first_mp, ip_restart_optmgmt, &error, ipst);
10437 		if (ill != NULL) {
10438 			if (checkonly) {
10439 				/* not supported by the virtual network iface */
10440 				if (IS_VNI(ill)) {
10441 					ill_refrele(ill);
10442 					return (EINVAL);
10443 				}
10444 				ill_refrele(ill);
10445 				return (0);
10446 			}
10447 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10448 			    0, NULL)) {
10449 				ill_refrele(ill);
10450 				ill = NULL;
10451 				mutex_enter(&connp->conn_lock);
10452 				goto setit;
10453 			}
10454 			mutex_enter(&connp->conn_lock);
10455 			mutex_enter(&ill->ill_lock);
10456 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10457 				mutex_exit(&ill->ill_lock);
10458 				mutex_exit(&connp->conn_lock);
10459 				ill_refrele(ill);
10460 				ill = NULL;
10461 				mutex_enter(&connp->conn_lock);
10462 			}
10463 			goto setit;
10464 		} else if (error == EINPROGRESS) {
10465 			return (error);
10466 		} else {
10467 			error = 0;
10468 		}
10469 	}
10470 	mutex_enter(&connp->conn_lock);
10471 setit:
10472 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10473 
10474 	/*
10475 	 * The options below assume that the ILL (if any) transmits and/or
10476 	 * receives traffic. Neither of which is true for the virtual network
10477 	 * interface, so fail setting these on a VNI.
10478 	 */
10479 	if (IS_VNI(ill)) {
10480 		ASSERT(ill != NULL);
10481 		mutex_exit(&ill->ill_lock);
10482 		mutex_exit(&connp->conn_lock);
10483 		ill_refrele(ill);
10484 		return (EINVAL);
10485 	}
10486 
10487 	if (level == IPPROTO_IP) {
10488 		switch (option) {
10489 		case IP_BOUND_IF:
10490 			connp->conn_incoming_ill = ill;
10491 			connp->conn_outgoing_ill = ill;
10492 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10493 			    0 : ifindex;
10494 			break;
10495 
10496 		case IP_XMIT_IF:
10497 			/*
10498 			 * Similar to IP_BOUND_IF, but this only
10499 			 * determines the outgoing interface for
10500 			 * unicast packets. Also no IRE_CACHE entry
10501 			 * is added for the destination of the
10502 			 * outgoing packets.
10503 			 */
10504 			connp->conn_xmit_if_ill = ill;
10505 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10506 			    0 : ifindex;
10507 			break;
10508 
10509 		case IP_MULTICAST_IF:
10510 			/*
10511 			 * This option is an internal special. The socket
10512 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10513 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10514 			 * specifies an ifindex and we try first on V6 ill's.
10515 			 * If we don't find one, we they try using on v4 ill's
10516 			 * intenally and we come here.
10517 			 */
10518 			if (!checkonly && ill != NULL) {
10519 				ipif_t	*ipif;
10520 				ipif = ill->ill_ipif;
10521 
10522 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10523 					mutex_exit(&ill->ill_lock);
10524 					mutex_exit(&connp->conn_lock);
10525 					ill_refrele(ill);
10526 					ill = NULL;
10527 					mutex_enter(&connp->conn_lock);
10528 				} else {
10529 					connp->conn_multicast_ipif = ipif;
10530 				}
10531 			}
10532 			break;
10533 		}
10534 	} else {
10535 		switch (option) {
10536 		case IPV6_BOUND_IF:
10537 			connp->conn_incoming_ill = ill;
10538 			connp->conn_outgoing_ill = ill;
10539 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10540 			    0 : ifindex;
10541 			break;
10542 
10543 		case IPV6_BOUND_PIF:
10544 			/*
10545 			 * Limit all transmit to this ill.
10546 			 * Unlike IPV6_BOUND_IF, using this option
10547 			 * prevents load spreading and failover from
10548 			 * happening when the interface is part of the
10549 			 * group. That's why we don't need to remember
10550 			 * the ifindex in orig_bound_ifindex as in
10551 			 * IPV6_BOUND_IF.
10552 			 */
10553 			connp->conn_outgoing_pill = ill;
10554 			break;
10555 
10556 		case IPV6_DONTFAILOVER_IF:
10557 			/*
10558 			 * This option is used by in.mpathd to ensure
10559 			 * that IPMP probe packets only go out on the
10560 			 * test interfaces. in.mpathd sets this option
10561 			 * on the non-failover interfaces.
10562 			 */
10563 			connp->conn_nofailover_ill = ill;
10564 			/*
10565 			 * For backward compatibility, this option
10566 			 * implicitly sets ip_multicast_ill as used in
10567 			 * IPV6_MULTICAST_IF so that ip_wput gets
10568 			 * this ill to send mcast packets.
10569 			 */
10570 			connp->conn_multicast_ill = ill;
10571 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10572 			    0 : ifindex;
10573 			break;
10574 
10575 		case IPV6_MULTICAST_IF:
10576 			/*
10577 			 * Set conn_multicast_ill to be the IPv6 ill.
10578 			 * Set conn_multicast_ipif to be an IPv4 ipif
10579 			 * for ifindex to make IPv4 mapped addresses
10580 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10581 			 * Even if no IPv6 ill exists for the ifindex
10582 			 * we need to check for an IPv4 ifindex in order
10583 			 * for this to work with mapped addresses. In that
10584 			 * case only set conn_multicast_ipif.
10585 			 */
10586 			if (!checkonly) {
10587 				if (ifindex == 0) {
10588 					connp->conn_multicast_ill = NULL;
10589 					connp->conn_orig_multicast_ifindex = 0;
10590 					connp->conn_multicast_ipif = NULL;
10591 				} else if (ill != NULL) {
10592 					connp->conn_multicast_ill = ill;
10593 					connp->conn_orig_multicast_ifindex =
10594 					    ifindex;
10595 				}
10596 			}
10597 			break;
10598 		}
10599 	}
10600 
10601 	if (ill != NULL) {
10602 		mutex_exit(&ill->ill_lock);
10603 		mutex_exit(&connp->conn_lock);
10604 		ill_refrele(ill);
10605 		return (0);
10606 	}
10607 	mutex_exit(&connp->conn_lock);
10608 	/*
10609 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10610 	 * locate the ill and could not set the option (ifindex != 0)
10611 	 */
10612 	return (ifindex == 0 ? 0 : EINVAL);
10613 }
10614 
10615 /* This routine sets socket options. */
10616 /* ARGSUSED */
10617 int
10618 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10619     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10620     void *dummy, cred_t *cr, mblk_t *first_mp)
10621 {
10622 	int		*i1 = (int *)invalp;
10623 	conn_t		*connp = Q_TO_CONN(q);
10624 	int		error = 0;
10625 	boolean_t	checkonly;
10626 	ire_t		*ire;
10627 	boolean_t	found;
10628 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10629 
10630 	switch (optset_context) {
10631 
10632 	case SETFN_OPTCOM_CHECKONLY:
10633 		checkonly = B_TRUE;
10634 		/*
10635 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10636 		 * inlen != 0 implies value supplied and
10637 		 * 	we have to "pretend" to set it.
10638 		 * inlen == 0 implies that there is no
10639 		 * 	value part in T_CHECK request and just validation
10640 		 * done elsewhere should be enough, we just return here.
10641 		 */
10642 		if (inlen == 0) {
10643 			*outlenp = 0;
10644 			return (0);
10645 		}
10646 		break;
10647 	case SETFN_OPTCOM_NEGOTIATE:
10648 	case SETFN_UD_NEGOTIATE:
10649 	case SETFN_CONN_NEGOTIATE:
10650 		checkonly = B_FALSE;
10651 		break;
10652 	default:
10653 		/*
10654 		 * We should never get here
10655 		 */
10656 		*outlenp = 0;
10657 		return (EINVAL);
10658 	}
10659 
10660 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10661 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10662 
10663 	/*
10664 	 * For fixed length options, no sanity check
10665 	 * of passed in length is done. It is assumed *_optcom_req()
10666 	 * routines do the right thing.
10667 	 */
10668 
10669 	switch (level) {
10670 	case SOL_SOCKET:
10671 		/*
10672 		 * conn_lock protects the bitfields, and is used to
10673 		 * set the fields atomically.
10674 		 */
10675 		switch (name) {
10676 		case SO_BROADCAST:
10677 			if (!checkonly) {
10678 				/* TODO: use value someplace? */
10679 				mutex_enter(&connp->conn_lock);
10680 				connp->conn_broadcast = *i1 ? 1 : 0;
10681 				mutex_exit(&connp->conn_lock);
10682 			}
10683 			break;	/* goto sizeof (int) option return */
10684 		case SO_USELOOPBACK:
10685 			if (!checkonly) {
10686 				/* TODO: use value someplace? */
10687 				mutex_enter(&connp->conn_lock);
10688 				connp->conn_loopback = *i1 ? 1 : 0;
10689 				mutex_exit(&connp->conn_lock);
10690 			}
10691 			break;	/* goto sizeof (int) option return */
10692 		case SO_DONTROUTE:
10693 			if (!checkonly) {
10694 				mutex_enter(&connp->conn_lock);
10695 				connp->conn_dontroute = *i1 ? 1 : 0;
10696 				mutex_exit(&connp->conn_lock);
10697 			}
10698 			break;	/* goto sizeof (int) option return */
10699 		case SO_REUSEADDR:
10700 			if (!checkonly) {
10701 				mutex_enter(&connp->conn_lock);
10702 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10703 				mutex_exit(&connp->conn_lock);
10704 			}
10705 			break;	/* goto sizeof (int) option return */
10706 		case SO_PROTOTYPE:
10707 			if (!checkonly) {
10708 				mutex_enter(&connp->conn_lock);
10709 				connp->conn_proto = *i1;
10710 				mutex_exit(&connp->conn_lock);
10711 			}
10712 			break;	/* goto sizeof (int) option return */
10713 		case SO_ALLZONES:
10714 			if (!checkonly) {
10715 				mutex_enter(&connp->conn_lock);
10716 				if (IPCL_IS_BOUND(connp)) {
10717 					mutex_exit(&connp->conn_lock);
10718 					return (EINVAL);
10719 				}
10720 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10721 				mutex_exit(&connp->conn_lock);
10722 			}
10723 			break;	/* goto sizeof (int) option return */
10724 		case SO_ANON_MLP:
10725 			if (!checkonly) {
10726 				mutex_enter(&connp->conn_lock);
10727 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10728 				mutex_exit(&connp->conn_lock);
10729 			}
10730 			break;	/* goto sizeof (int) option return */
10731 		case SO_MAC_EXEMPT:
10732 			if (secpolicy_net_mac_aware(cr) != 0 ||
10733 			    IPCL_IS_BOUND(connp))
10734 				return (EACCES);
10735 			if (!checkonly) {
10736 				mutex_enter(&connp->conn_lock);
10737 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10738 				mutex_exit(&connp->conn_lock);
10739 			}
10740 			break;	/* goto sizeof (int) option return */
10741 		default:
10742 			/*
10743 			 * "soft" error (negative)
10744 			 * option not handled at this level
10745 			 * Note: Do not modify *outlenp
10746 			 */
10747 			return (-EINVAL);
10748 		}
10749 		break;
10750 	case IPPROTO_IP:
10751 		switch (name) {
10752 		case IP_NEXTHOP:
10753 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10754 				return (EPERM);
10755 			/* FALLTHRU */
10756 		case IP_MULTICAST_IF:
10757 		case IP_DONTFAILOVER_IF: {
10758 			ipaddr_t addr = *i1;
10759 
10760 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10761 			    first_mp);
10762 			if (error != 0)
10763 				return (error);
10764 			break;	/* goto sizeof (int) option return */
10765 		}
10766 
10767 		case IP_MULTICAST_TTL:
10768 			/* Recorded in transport above IP */
10769 			*outvalp = *invalp;
10770 			*outlenp = sizeof (uchar_t);
10771 			return (0);
10772 		case IP_MULTICAST_LOOP:
10773 			if (!checkonly) {
10774 				mutex_enter(&connp->conn_lock);
10775 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10776 				mutex_exit(&connp->conn_lock);
10777 			}
10778 			*outvalp = *invalp;
10779 			*outlenp = sizeof (uchar_t);
10780 			return (0);
10781 		case IP_ADD_MEMBERSHIP:
10782 		case MCAST_JOIN_GROUP:
10783 		case IP_DROP_MEMBERSHIP:
10784 		case MCAST_LEAVE_GROUP: {
10785 			struct ip_mreq *mreqp;
10786 			struct group_req *greqp;
10787 			ire_t *ire;
10788 			boolean_t done = B_FALSE;
10789 			ipaddr_t group, ifaddr;
10790 			struct sockaddr_in *sin;
10791 			uint32_t *ifindexp;
10792 			boolean_t mcast_opt = B_TRUE;
10793 			mcast_record_t fmode;
10794 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10795 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10796 
10797 			switch (name) {
10798 			case IP_ADD_MEMBERSHIP:
10799 				mcast_opt = B_FALSE;
10800 				/* FALLTHRU */
10801 			case MCAST_JOIN_GROUP:
10802 				fmode = MODE_IS_EXCLUDE;
10803 				optfn = ip_opt_add_group;
10804 				break;
10805 
10806 			case IP_DROP_MEMBERSHIP:
10807 				mcast_opt = B_FALSE;
10808 				/* FALLTHRU */
10809 			case MCAST_LEAVE_GROUP:
10810 				fmode = MODE_IS_INCLUDE;
10811 				optfn = ip_opt_delete_group;
10812 				break;
10813 			}
10814 
10815 			if (mcast_opt) {
10816 				greqp = (struct group_req *)i1;
10817 				sin = (struct sockaddr_in *)&greqp->gr_group;
10818 				if (sin->sin_family != AF_INET) {
10819 					*outlenp = 0;
10820 					return (ENOPROTOOPT);
10821 				}
10822 				group = (ipaddr_t)sin->sin_addr.s_addr;
10823 				ifaddr = INADDR_ANY;
10824 				ifindexp = &greqp->gr_interface;
10825 			} else {
10826 				mreqp = (struct ip_mreq *)i1;
10827 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10828 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10829 				ifindexp = NULL;
10830 			}
10831 
10832 			/*
10833 			 * In the multirouting case, we need to replicate
10834 			 * the request on all interfaces that will take part
10835 			 * in replication.  We do so because multirouting is
10836 			 * reflective, thus we will probably receive multi-
10837 			 * casts on those interfaces.
10838 			 * The ip_multirt_apply_membership() succeeds if the
10839 			 * operation succeeds on at least one interface.
10840 			 */
10841 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10842 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10843 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10844 			if (ire != NULL) {
10845 				if (ire->ire_flags & RTF_MULTIRT) {
10846 					error = ip_multirt_apply_membership(
10847 					    optfn, ire, connp, checkonly, group,
10848 					    fmode, INADDR_ANY, first_mp);
10849 					done = B_TRUE;
10850 				}
10851 				ire_refrele(ire);
10852 			}
10853 			if (!done) {
10854 				error = optfn(connp, checkonly, group, ifaddr,
10855 				    ifindexp, fmode, INADDR_ANY, first_mp);
10856 			}
10857 			if (error) {
10858 				/*
10859 				 * EINPROGRESS is a soft error, needs retry
10860 				 * so don't make *outlenp zero.
10861 				 */
10862 				if (error != EINPROGRESS)
10863 					*outlenp = 0;
10864 				return (error);
10865 			}
10866 			/* OK return - copy input buffer into output buffer */
10867 			if (invalp != outvalp) {
10868 				/* don't trust bcopy for identical src/dst */
10869 				bcopy(invalp, outvalp, inlen);
10870 			}
10871 			*outlenp = inlen;
10872 			return (0);
10873 		}
10874 		case IP_BLOCK_SOURCE:
10875 		case IP_UNBLOCK_SOURCE:
10876 		case IP_ADD_SOURCE_MEMBERSHIP:
10877 		case IP_DROP_SOURCE_MEMBERSHIP:
10878 		case MCAST_BLOCK_SOURCE:
10879 		case MCAST_UNBLOCK_SOURCE:
10880 		case MCAST_JOIN_SOURCE_GROUP:
10881 		case MCAST_LEAVE_SOURCE_GROUP: {
10882 			struct ip_mreq_source *imreqp;
10883 			struct group_source_req *gsreqp;
10884 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10885 			uint32_t ifindex = 0;
10886 			mcast_record_t fmode;
10887 			struct sockaddr_in *sin;
10888 			ire_t *ire;
10889 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10890 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10891 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10892 
10893 			switch (name) {
10894 			case IP_BLOCK_SOURCE:
10895 				mcast_opt = B_FALSE;
10896 				/* FALLTHRU */
10897 			case MCAST_BLOCK_SOURCE:
10898 				fmode = MODE_IS_EXCLUDE;
10899 				optfn = ip_opt_add_group;
10900 				break;
10901 
10902 			case IP_UNBLOCK_SOURCE:
10903 				mcast_opt = B_FALSE;
10904 				/* FALLTHRU */
10905 			case MCAST_UNBLOCK_SOURCE:
10906 				fmode = MODE_IS_EXCLUDE;
10907 				optfn = ip_opt_delete_group;
10908 				break;
10909 
10910 			case IP_ADD_SOURCE_MEMBERSHIP:
10911 				mcast_opt = B_FALSE;
10912 				/* FALLTHRU */
10913 			case MCAST_JOIN_SOURCE_GROUP:
10914 				fmode = MODE_IS_INCLUDE;
10915 				optfn = ip_opt_add_group;
10916 				break;
10917 
10918 			case IP_DROP_SOURCE_MEMBERSHIP:
10919 				mcast_opt = B_FALSE;
10920 				/* FALLTHRU */
10921 			case MCAST_LEAVE_SOURCE_GROUP:
10922 				fmode = MODE_IS_INCLUDE;
10923 				optfn = ip_opt_delete_group;
10924 				break;
10925 			}
10926 
10927 			if (mcast_opt) {
10928 				gsreqp = (struct group_source_req *)i1;
10929 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10930 					*outlenp = 0;
10931 					return (ENOPROTOOPT);
10932 				}
10933 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10934 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10935 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10936 				src = (ipaddr_t)sin->sin_addr.s_addr;
10937 				ifindex = gsreqp->gsr_interface;
10938 			} else {
10939 				imreqp = (struct ip_mreq_source *)i1;
10940 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10941 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10942 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10943 			}
10944 
10945 			/*
10946 			 * In the multirouting case, we need to replicate
10947 			 * the request as noted in the mcast cases above.
10948 			 */
10949 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10950 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10951 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10952 			if (ire != NULL) {
10953 				if (ire->ire_flags & RTF_MULTIRT) {
10954 					error = ip_multirt_apply_membership(
10955 					    optfn, ire, connp, checkonly, grp,
10956 					    fmode, src, first_mp);
10957 					done = B_TRUE;
10958 				}
10959 				ire_refrele(ire);
10960 			}
10961 			if (!done) {
10962 				error = optfn(connp, checkonly, grp, ifaddr,
10963 				    &ifindex, fmode, src, first_mp);
10964 			}
10965 			if (error != 0) {
10966 				/*
10967 				 * EINPROGRESS is a soft error, needs retry
10968 				 * so don't make *outlenp zero.
10969 				 */
10970 				if (error != EINPROGRESS)
10971 					*outlenp = 0;
10972 				return (error);
10973 			}
10974 			/* OK return - copy input buffer into output buffer */
10975 			if (invalp != outvalp) {
10976 				bcopy(invalp, outvalp, inlen);
10977 			}
10978 			*outlenp = inlen;
10979 			return (0);
10980 		}
10981 		case IP_SEC_OPT:
10982 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10983 			if (error != 0) {
10984 				*outlenp = 0;
10985 				return (error);
10986 			}
10987 			break;
10988 		case IP_HDRINCL:
10989 		case IP_OPTIONS:
10990 		case T_IP_OPTIONS:
10991 		case IP_TOS:
10992 		case T_IP_TOS:
10993 		case IP_TTL:
10994 		case IP_RECVDSTADDR:
10995 		case IP_RECVOPTS:
10996 			/* OK return - copy input buffer into output buffer */
10997 			if (invalp != outvalp) {
10998 				/* don't trust bcopy for identical src/dst */
10999 				bcopy(invalp, outvalp, inlen);
11000 			}
11001 			*outlenp = inlen;
11002 			return (0);
11003 		case IP_RECVIF:
11004 			/* Retrieve the inbound interface index */
11005 			if (!checkonly) {
11006 				mutex_enter(&connp->conn_lock);
11007 				connp->conn_recvif = *i1 ? 1 : 0;
11008 				mutex_exit(&connp->conn_lock);
11009 			}
11010 			break;	/* goto sizeof (int) option return */
11011 		case IP_RECVPKTINFO:
11012 			if (!checkonly) {
11013 				mutex_enter(&connp->conn_lock);
11014 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11015 				mutex_exit(&connp->conn_lock);
11016 			}
11017 			break;	/* goto sizeof (int) option return */
11018 		case IP_RECVSLLA:
11019 			/* Retrieve the source link layer address */
11020 			if (!checkonly) {
11021 				mutex_enter(&connp->conn_lock);
11022 				connp->conn_recvslla = *i1 ? 1 : 0;
11023 				mutex_exit(&connp->conn_lock);
11024 			}
11025 			break;	/* goto sizeof (int) option return */
11026 		case MRT_INIT:
11027 		case MRT_DONE:
11028 		case MRT_ADD_VIF:
11029 		case MRT_DEL_VIF:
11030 		case MRT_ADD_MFC:
11031 		case MRT_DEL_MFC:
11032 		case MRT_ASSERT:
11033 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11034 				*outlenp = 0;
11035 				return (error);
11036 			}
11037 			error = ip_mrouter_set((int)name, q, checkonly,
11038 			    (uchar_t *)invalp, inlen, first_mp);
11039 			if (error) {
11040 				*outlenp = 0;
11041 				return (error);
11042 			}
11043 			/* OK return - copy input buffer into output buffer */
11044 			if (invalp != outvalp) {
11045 				/* don't trust bcopy for identical src/dst */
11046 				bcopy(invalp, outvalp, inlen);
11047 			}
11048 			*outlenp = inlen;
11049 			return (0);
11050 		case IP_BOUND_IF:
11051 		case IP_XMIT_IF:
11052 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11053 			    level, name, first_mp);
11054 			if (error != 0)
11055 				return (error);
11056 			break; 		/* goto sizeof (int) option return */
11057 
11058 		case IP_UNSPEC_SRC:
11059 			/* Allow sending with a zero source address */
11060 			if (!checkonly) {
11061 				mutex_enter(&connp->conn_lock);
11062 				connp->conn_unspec_src = *i1 ? 1 : 0;
11063 				mutex_exit(&connp->conn_lock);
11064 			}
11065 			break;	/* goto sizeof (int) option return */
11066 		default:
11067 			/*
11068 			 * "soft" error (negative)
11069 			 * option not handled at this level
11070 			 * Note: Do not modify *outlenp
11071 			 */
11072 			return (-EINVAL);
11073 		}
11074 		break;
11075 	case IPPROTO_IPV6:
11076 		switch (name) {
11077 		case IPV6_BOUND_IF:
11078 		case IPV6_BOUND_PIF:
11079 		case IPV6_DONTFAILOVER_IF:
11080 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11081 			    level, name, first_mp);
11082 			if (error != 0)
11083 				return (error);
11084 			break; 		/* goto sizeof (int) option return */
11085 
11086 		case IPV6_MULTICAST_IF:
11087 			/*
11088 			 * The only possible errors are EINPROGRESS and
11089 			 * EINVAL. EINPROGRESS will be restarted and is not
11090 			 * a hard error. We call this option on both V4 and V6
11091 			 * If both return EINVAL, then this call returns
11092 			 * EINVAL. If at least one of them succeeds we
11093 			 * return success.
11094 			 */
11095 			found = B_FALSE;
11096 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11097 			    level, name, first_mp);
11098 			if (error == EINPROGRESS)
11099 				return (error);
11100 			if (error == 0)
11101 				found = B_TRUE;
11102 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11103 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11104 			if (error == 0)
11105 				found = B_TRUE;
11106 			if (!found)
11107 				return (error);
11108 			break; 		/* goto sizeof (int) option return */
11109 
11110 		case IPV6_MULTICAST_HOPS:
11111 			/* Recorded in transport above IP */
11112 			break;	/* goto sizeof (int) option return */
11113 		case IPV6_MULTICAST_LOOP:
11114 			if (!checkonly) {
11115 				mutex_enter(&connp->conn_lock);
11116 				connp->conn_multicast_loop = *i1;
11117 				mutex_exit(&connp->conn_lock);
11118 			}
11119 			break;	/* goto sizeof (int) option return */
11120 		case IPV6_JOIN_GROUP:
11121 		case MCAST_JOIN_GROUP:
11122 		case IPV6_LEAVE_GROUP:
11123 		case MCAST_LEAVE_GROUP: {
11124 			struct ipv6_mreq *ip_mreqp;
11125 			struct group_req *greqp;
11126 			ire_t *ire;
11127 			boolean_t done = B_FALSE;
11128 			in6_addr_t groupv6;
11129 			uint32_t ifindex;
11130 			boolean_t mcast_opt = B_TRUE;
11131 			mcast_record_t fmode;
11132 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11133 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11134 
11135 			switch (name) {
11136 			case IPV6_JOIN_GROUP:
11137 				mcast_opt = B_FALSE;
11138 				/* FALLTHRU */
11139 			case MCAST_JOIN_GROUP:
11140 				fmode = MODE_IS_EXCLUDE;
11141 				optfn = ip_opt_add_group_v6;
11142 				break;
11143 
11144 			case IPV6_LEAVE_GROUP:
11145 				mcast_opt = B_FALSE;
11146 				/* FALLTHRU */
11147 			case MCAST_LEAVE_GROUP:
11148 				fmode = MODE_IS_INCLUDE;
11149 				optfn = ip_opt_delete_group_v6;
11150 				break;
11151 			}
11152 
11153 			if (mcast_opt) {
11154 				struct sockaddr_in *sin;
11155 				struct sockaddr_in6 *sin6;
11156 				greqp = (struct group_req *)i1;
11157 				if (greqp->gr_group.ss_family == AF_INET) {
11158 					sin = (struct sockaddr_in *)
11159 					    &(greqp->gr_group);
11160 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11161 					    &groupv6);
11162 				} else {
11163 					sin6 = (struct sockaddr_in6 *)
11164 					    &(greqp->gr_group);
11165 					groupv6 = sin6->sin6_addr;
11166 				}
11167 				ifindex = greqp->gr_interface;
11168 			} else {
11169 				ip_mreqp = (struct ipv6_mreq *)i1;
11170 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11171 				ifindex = ip_mreqp->ipv6mr_interface;
11172 			}
11173 			/*
11174 			 * In the multirouting case, we need to replicate
11175 			 * the request on all interfaces that will take part
11176 			 * in replication.  We do so because multirouting is
11177 			 * reflective, thus we will probably receive multi-
11178 			 * casts on those interfaces.
11179 			 * The ip_multirt_apply_membership_v6() succeeds if
11180 			 * the operation succeeds on at least one interface.
11181 			 */
11182 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11183 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11184 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11185 			if (ire != NULL) {
11186 				if (ire->ire_flags & RTF_MULTIRT) {
11187 					error = ip_multirt_apply_membership_v6(
11188 					    optfn, ire, connp, checkonly,
11189 					    &groupv6, fmode, &ipv6_all_zeros,
11190 					    first_mp);
11191 					done = B_TRUE;
11192 				}
11193 				ire_refrele(ire);
11194 			}
11195 			if (!done) {
11196 				error = optfn(connp, checkonly, &groupv6,
11197 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11198 			}
11199 			if (error) {
11200 				/*
11201 				 * EINPROGRESS is a soft error, needs retry
11202 				 * so don't make *outlenp zero.
11203 				 */
11204 				if (error != EINPROGRESS)
11205 					*outlenp = 0;
11206 				return (error);
11207 			}
11208 			/* OK return - copy input buffer into output buffer */
11209 			if (invalp != outvalp) {
11210 				/* don't trust bcopy for identical src/dst */
11211 				bcopy(invalp, outvalp, inlen);
11212 			}
11213 			*outlenp = inlen;
11214 			return (0);
11215 		}
11216 		case MCAST_BLOCK_SOURCE:
11217 		case MCAST_UNBLOCK_SOURCE:
11218 		case MCAST_JOIN_SOURCE_GROUP:
11219 		case MCAST_LEAVE_SOURCE_GROUP: {
11220 			struct group_source_req *gsreqp;
11221 			in6_addr_t v6grp, v6src;
11222 			uint32_t ifindex;
11223 			mcast_record_t fmode;
11224 			ire_t *ire;
11225 			boolean_t done = B_FALSE;
11226 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11227 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11228 
11229 			switch (name) {
11230 			case MCAST_BLOCK_SOURCE:
11231 				fmode = MODE_IS_EXCLUDE;
11232 				optfn = ip_opt_add_group_v6;
11233 				break;
11234 			case MCAST_UNBLOCK_SOURCE:
11235 				fmode = MODE_IS_EXCLUDE;
11236 				optfn = ip_opt_delete_group_v6;
11237 				break;
11238 			case MCAST_JOIN_SOURCE_GROUP:
11239 				fmode = MODE_IS_INCLUDE;
11240 				optfn = ip_opt_add_group_v6;
11241 				break;
11242 			case MCAST_LEAVE_SOURCE_GROUP:
11243 				fmode = MODE_IS_INCLUDE;
11244 				optfn = ip_opt_delete_group_v6;
11245 				break;
11246 			}
11247 
11248 			gsreqp = (struct group_source_req *)i1;
11249 			ifindex = gsreqp->gsr_interface;
11250 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11251 				struct sockaddr_in *s;
11252 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11253 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11254 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11255 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11256 			} else {
11257 				struct sockaddr_in6 *s6;
11258 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11259 				v6grp = s6->sin6_addr;
11260 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11261 				v6src = s6->sin6_addr;
11262 			}
11263 
11264 			/*
11265 			 * In the multirouting case, we need to replicate
11266 			 * the request as noted in the mcast cases above.
11267 			 */
11268 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11269 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11270 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11271 			if (ire != NULL) {
11272 				if (ire->ire_flags & RTF_MULTIRT) {
11273 					error = ip_multirt_apply_membership_v6(
11274 					    optfn, ire, connp, checkonly,
11275 					    &v6grp, fmode, &v6src, first_mp);
11276 					done = B_TRUE;
11277 				}
11278 				ire_refrele(ire);
11279 			}
11280 			if (!done) {
11281 				error = optfn(connp, checkonly, &v6grp,
11282 				    ifindex, fmode, &v6src, first_mp);
11283 			}
11284 			if (error != 0) {
11285 				/*
11286 				 * EINPROGRESS is a soft error, needs retry
11287 				 * so don't make *outlenp zero.
11288 				 */
11289 				if (error != EINPROGRESS)
11290 					*outlenp = 0;
11291 				return (error);
11292 			}
11293 			/* OK return - copy input buffer into output buffer */
11294 			if (invalp != outvalp) {
11295 				bcopy(invalp, outvalp, inlen);
11296 			}
11297 			*outlenp = inlen;
11298 			return (0);
11299 		}
11300 		case IPV6_UNICAST_HOPS:
11301 			/* Recorded in transport above IP */
11302 			break;	/* goto sizeof (int) option return */
11303 		case IPV6_UNSPEC_SRC:
11304 			/* Allow sending with a zero source address */
11305 			if (!checkonly) {
11306 				mutex_enter(&connp->conn_lock);
11307 				connp->conn_unspec_src = *i1 ? 1 : 0;
11308 				mutex_exit(&connp->conn_lock);
11309 			}
11310 			break;	/* goto sizeof (int) option return */
11311 		case IPV6_RECVPKTINFO:
11312 			if (!checkonly) {
11313 				mutex_enter(&connp->conn_lock);
11314 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11315 				mutex_exit(&connp->conn_lock);
11316 			}
11317 			break;	/* goto sizeof (int) option return */
11318 		case IPV6_RECVTCLASS:
11319 			if (!checkonly) {
11320 				if (*i1 < 0 || *i1 > 1) {
11321 					return (EINVAL);
11322 				}
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_ipv6_recvtclass = *i1;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;
11328 		case IPV6_RECVPATHMTU:
11329 			if (!checkonly) {
11330 				if (*i1 < 0 || *i1 > 1) {
11331 					return (EINVAL);
11332 				}
11333 				mutex_enter(&connp->conn_lock);
11334 				connp->conn_ipv6_recvpathmtu = *i1;
11335 				mutex_exit(&connp->conn_lock);
11336 			}
11337 			break;
11338 		case IPV6_RECVHOPLIMIT:
11339 			if (!checkonly) {
11340 				mutex_enter(&connp->conn_lock);
11341 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11342 				mutex_exit(&connp->conn_lock);
11343 			}
11344 			break;	/* goto sizeof (int) option return */
11345 		case IPV6_RECVHOPOPTS:
11346 			if (!checkonly) {
11347 				mutex_enter(&connp->conn_lock);
11348 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11349 				mutex_exit(&connp->conn_lock);
11350 			}
11351 			break;	/* goto sizeof (int) option return */
11352 		case IPV6_RECVDSTOPTS:
11353 			if (!checkonly) {
11354 				mutex_enter(&connp->conn_lock);
11355 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11356 				mutex_exit(&connp->conn_lock);
11357 			}
11358 			break;	/* goto sizeof (int) option return */
11359 		case IPV6_RECVRTHDR:
11360 			if (!checkonly) {
11361 				mutex_enter(&connp->conn_lock);
11362 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11363 				mutex_exit(&connp->conn_lock);
11364 			}
11365 			break;	/* goto sizeof (int) option return */
11366 		case IPV6_RECVRTHDRDSTOPTS:
11367 			if (!checkonly) {
11368 				mutex_enter(&connp->conn_lock);
11369 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11370 				mutex_exit(&connp->conn_lock);
11371 			}
11372 			break;	/* goto sizeof (int) option return */
11373 		case IPV6_PKTINFO:
11374 			if (inlen == 0)
11375 				return (-EINVAL);	/* clearing option */
11376 			error = ip6_set_pktinfo(cr, connp,
11377 			    (struct in6_pktinfo *)invalp, first_mp);
11378 			if (error != 0)
11379 				*outlenp = 0;
11380 			else
11381 				*outlenp = inlen;
11382 			return (error);
11383 		case IPV6_NEXTHOP: {
11384 			struct sockaddr_in6 *sin6;
11385 
11386 			/* Verify that the nexthop is reachable */
11387 			if (inlen == 0)
11388 				return (-EINVAL);	/* clearing option */
11389 
11390 			sin6 = (struct sockaddr_in6 *)invalp;
11391 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11392 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11393 			    NULL, MATCH_IRE_DEFAULT, ipst);
11394 
11395 			if (ire == NULL) {
11396 				*outlenp = 0;
11397 				return (EHOSTUNREACH);
11398 			}
11399 			ire_refrele(ire);
11400 			return (-EINVAL);
11401 		}
11402 		case IPV6_SEC_OPT:
11403 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11404 			if (error != 0) {
11405 				*outlenp = 0;
11406 				return (error);
11407 			}
11408 			break;
11409 		case IPV6_SRC_PREFERENCES: {
11410 			/*
11411 			 * This is implemented strictly in the ip module
11412 			 * (here and in tcp_opt_*() to accomodate tcp
11413 			 * sockets).  Modules above ip pass this option
11414 			 * down here since ip is the only one that needs to
11415 			 * be aware of source address preferences.
11416 			 *
11417 			 * This socket option only affects connected
11418 			 * sockets that haven't already bound to a specific
11419 			 * IPv6 address.  In other words, sockets that
11420 			 * don't call bind() with an address other than the
11421 			 * unspecified address and that call connect().
11422 			 * ip_bind_connected_v6() passes these preferences
11423 			 * to the ipif_select_source_v6() function.
11424 			 */
11425 			if (inlen != sizeof (uint32_t))
11426 				return (EINVAL);
11427 			error = ip6_set_src_preferences(connp,
11428 			    *(uint32_t *)invalp);
11429 			if (error != 0) {
11430 				*outlenp = 0;
11431 				return (error);
11432 			} else {
11433 				*outlenp = sizeof (uint32_t);
11434 			}
11435 			break;
11436 		}
11437 		case IPV6_V6ONLY:
11438 			if (*i1 < 0 || *i1 > 1) {
11439 				return (EINVAL);
11440 			}
11441 			mutex_enter(&connp->conn_lock);
11442 			connp->conn_ipv6_v6only = *i1;
11443 			mutex_exit(&connp->conn_lock);
11444 			break;
11445 		default:
11446 			return (-EINVAL);
11447 		}
11448 		break;
11449 	default:
11450 		/*
11451 		 * "soft" error (negative)
11452 		 * option not handled at this level
11453 		 * Note: Do not modify *outlenp
11454 		 */
11455 		return (-EINVAL);
11456 	}
11457 	/*
11458 	 * Common case of return from an option that is sizeof (int)
11459 	 */
11460 	*(int *)outvalp = *i1;
11461 	*outlenp = sizeof (int);
11462 	return (0);
11463 }
11464 
11465 /*
11466  * This routine gets default values of certain options whose default
11467  * values are maintained by protocol specific code
11468  */
11469 /* ARGSUSED */
11470 int
11471 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11472 {
11473 	int *i1 = (int *)ptr;
11474 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11475 
11476 	switch (level) {
11477 	case IPPROTO_IP:
11478 		switch (name) {
11479 		case IP_MULTICAST_TTL:
11480 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11481 			return (sizeof (uchar_t));
11482 		case IP_MULTICAST_LOOP:
11483 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11484 			return (sizeof (uchar_t));
11485 		default:
11486 			return (-1);
11487 		}
11488 	case IPPROTO_IPV6:
11489 		switch (name) {
11490 		case IPV6_UNICAST_HOPS:
11491 			*i1 = ipst->ips_ipv6_def_hops;
11492 			return (sizeof (int));
11493 		case IPV6_MULTICAST_HOPS:
11494 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11495 			return (sizeof (int));
11496 		case IPV6_MULTICAST_LOOP:
11497 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11498 			return (sizeof (int));
11499 		case IPV6_V6ONLY:
11500 			*i1 = 1;
11501 			return (sizeof (int));
11502 		default:
11503 			return (-1);
11504 		}
11505 	default:
11506 		return (-1);
11507 	}
11508 	/* NOTREACHED */
11509 }
11510 
11511 /*
11512  * Given a destination address and a pointer to where to put the information
11513  * this routine fills in the mtuinfo.
11514  */
11515 int
11516 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11517     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11518 {
11519 	ire_t *ire;
11520 	ip_stack_t	*ipst = ns->netstack_ip;
11521 
11522 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11523 		return (-1);
11524 
11525 	bzero(mtuinfo, sizeof (*mtuinfo));
11526 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11527 	mtuinfo->ip6m_addr.sin6_port = port;
11528 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11529 
11530 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11531 	if (ire != NULL) {
11532 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11533 		ire_refrele(ire);
11534 	} else {
11535 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11536 	}
11537 	return (sizeof (struct ip6_mtuinfo));
11538 }
11539 
11540 /*
11541  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11542  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11543  * isn't.  This doesn't matter as the error checking is done properly for the
11544  * other MRT options coming in through ip_opt_set.
11545  */
11546 int
11547 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11548 {
11549 	conn_t		*connp = Q_TO_CONN(q);
11550 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11551 
11552 	switch (level) {
11553 	case IPPROTO_IP:
11554 		switch (name) {
11555 		case MRT_VERSION:
11556 		case MRT_ASSERT:
11557 			(void) ip_mrouter_get(name, q, ptr);
11558 			return (sizeof (int));
11559 		case IP_SEC_OPT:
11560 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11561 		case IP_NEXTHOP:
11562 			if (connp->conn_nexthop_set) {
11563 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11564 				return (sizeof (ipaddr_t));
11565 			} else
11566 				return (0);
11567 		case IP_RECVPKTINFO:
11568 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11569 			return (sizeof (int));
11570 		default:
11571 			break;
11572 		}
11573 		break;
11574 	case IPPROTO_IPV6:
11575 		switch (name) {
11576 		case IPV6_SEC_OPT:
11577 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11578 		case IPV6_SRC_PREFERENCES: {
11579 			return (ip6_get_src_preferences(connp,
11580 			    (uint32_t *)ptr));
11581 		}
11582 		case IPV6_V6ONLY:
11583 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11584 			return (sizeof (int));
11585 		case IPV6_PATHMTU:
11586 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11587 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11588 		default:
11589 			break;
11590 		}
11591 		break;
11592 	default:
11593 		break;
11594 	}
11595 	return (-1);
11596 }
11597 
11598 /* Named Dispatch routine to get a current value out of our parameter table. */
11599 /* ARGSUSED */
11600 static int
11601 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11602 {
11603 	ipparam_t *ippa = (ipparam_t *)cp;
11604 
11605 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11606 	return (0);
11607 }
11608 
11609 /* ARGSUSED */
11610 static int
11611 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11612 {
11613 
11614 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11615 	return (0);
11616 }
11617 
11618 /*
11619  * Set ip{,6}_forwarding values.  This means walking through all of the
11620  * ill's and toggling their forwarding values.
11621  */
11622 /* ARGSUSED */
11623 static int
11624 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11625 {
11626 	long new_value;
11627 	int *forwarding_value = (int *)cp;
11628 	ill_t *ill;
11629 	boolean_t isv6;
11630 	ill_walk_context_t ctx;
11631 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11632 
11633 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11634 
11635 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11636 	    new_value < 0 || new_value > 1) {
11637 		return (EINVAL);
11638 	}
11639 
11640 	*forwarding_value = new_value;
11641 
11642 	/*
11643 	 * Regardless of the current value of ip_forwarding, set all per-ill
11644 	 * values of ip_forwarding to the value being set.
11645 	 *
11646 	 * Bring all the ill's up to date with the new global value.
11647 	 */
11648 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11649 
11650 	if (isv6)
11651 		ill = ILL_START_WALK_V6(&ctx, ipst);
11652 	else
11653 		ill = ILL_START_WALK_V4(&ctx, ipst);
11654 
11655 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11656 		(void) ill_forward_set(ill, new_value != 0);
11657 
11658 	rw_exit(&ipst->ips_ill_g_lock);
11659 	return (0);
11660 }
11661 
11662 /*
11663  * Walk through the param array specified registering each element with the
11664  * Named Dispatch handler. This is called only during init. So it is ok
11665  * not to acquire any locks
11666  */
11667 static boolean_t
11668 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11669     ipndp_t *ipnd, size_t ipnd_cnt)
11670 {
11671 	for (; ippa_cnt-- > 0; ippa++) {
11672 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11673 			if (!nd_load(ndp, ippa->ip_param_name,
11674 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11675 				nd_free(ndp);
11676 				return (B_FALSE);
11677 			}
11678 		}
11679 	}
11680 
11681 	for (; ipnd_cnt-- > 0; ipnd++) {
11682 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11683 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11684 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11685 			    ipnd->ip_ndp_data)) {
11686 				nd_free(ndp);
11687 				return (B_FALSE);
11688 			}
11689 		}
11690 	}
11691 
11692 	return (B_TRUE);
11693 }
11694 
11695 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11696 /* ARGSUSED */
11697 static int
11698 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11699 {
11700 	long		new_value;
11701 	ipparam_t	*ippa = (ipparam_t *)cp;
11702 
11703 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11704 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11705 		return (EINVAL);
11706 	}
11707 	ippa->ip_param_value = new_value;
11708 	return (0);
11709 }
11710 
11711 /*
11712  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11713  * When an ipf is passed here for the first time, if
11714  * we already have in-order fragments on the queue, we convert from the fast-
11715  * path reassembly scheme to the hard-case scheme.  From then on, additional
11716  * fragments are reassembled here.  We keep track of the start and end offsets
11717  * of each piece, and the number of holes in the chain.  When the hole count
11718  * goes to zero, we are done!
11719  *
11720  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11721  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11722  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11723  * after the call to ip_reassemble().
11724  */
11725 int
11726 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11727     size_t msg_len)
11728 {
11729 	uint_t	end;
11730 	mblk_t	*next_mp;
11731 	mblk_t	*mp1;
11732 	uint_t	offset;
11733 	boolean_t incr_dups = B_TRUE;
11734 	boolean_t offset_zero_seen = B_FALSE;
11735 	boolean_t pkt_boundary_checked = B_FALSE;
11736 
11737 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11738 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11739 
11740 	/* Add in byte count */
11741 	ipf->ipf_count += msg_len;
11742 	if (ipf->ipf_end) {
11743 		/*
11744 		 * We were part way through in-order reassembly, but now there
11745 		 * is a hole.  We walk through messages already queued, and
11746 		 * mark them for hard case reassembly.  We know that up till
11747 		 * now they were in order starting from offset zero.
11748 		 */
11749 		offset = 0;
11750 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11751 			IP_REASS_SET_START(mp1, offset);
11752 			if (offset == 0) {
11753 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11754 				offset = -ipf->ipf_nf_hdr_len;
11755 			}
11756 			offset += mp1->b_wptr - mp1->b_rptr;
11757 			IP_REASS_SET_END(mp1, offset);
11758 		}
11759 		/* One hole at the end. */
11760 		ipf->ipf_hole_cnt = 1;
11761 		/* Brand it as a hard case, forever. */
11762 		ipf->ipf_end = 0;
11763 	}
11764 	/* Walk through all the new pieces. */
11765 	do {
11766 		end = start + (mp->b_wptr - mp->b_rptr);
11767 		/*
11768 		 * If start is 0, decrease 'end' only for the first mblk of
11769 		 * the fragment. Otherwise 'end' can get wrong value in the
11770 		 * second pass of the loop if first mblk is exactly the
11771 		 * size of ipf_nf_hdr_len.
11772 		 */
11773 		if (start == 0 && !offset_zero_seen) {
11774 			/* First segment */
11775 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11776 			end -= ipf->ipf_nf_hdr_len;
11777 			offset_zero_seen = B_TRUE;
11778 		}
11779 		next_mp = mp->b_cont;
11780 		/*
11781 		 * We are checking to see if there is any interesing data
11782 		 * to process.  If there isn't and the mblk isn't the
11783 		 * one which carries the unfragmentable header then we
11784 		 * drop it.  It's possible to have just the unfragmentable
11785 		 * header come through without any data.  That needs to be
11786 		 * saved.
11787 		 *
11788 		 * If the assert at the top of this function holds then the
11789 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11790 		 * is infrequently traveled enough that the test is left in
11791 		 * to protect against future code changes which break that
11792 		 * invariant.
11793 		 */
11794 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11795 			/* Empty.  Blast it. */
11796 			IP_REASS_SET_START(mp, 0);
11797 			IP_REASS_SET_END(mp, 0);
11798 			/*
11799 			 * If the ipf points to the mblk we are about to free,
11800 			 * update ipf to point to the next mblk (or NULL
11801 			 * if none).
11802 			 */
11803 			if (ipf->ipf_mp->b_cont == mp)
11804 				ipf->ipf_mp->b_cont = next_mp;
11805 			freeb(mp);
11806 			continue;
11807 		}
11808 		mp->b_cont = NULL;
11809 		IP_REASS_SET_START(mp, start);
11810 		IP_REASS_SET_END(mp, end);
11811 		if (!ipf->ipf_tail_mp) {
11812 			ipf->ipf_tail_mp = mp;
11813 			ipf->ipf_mp->b_cont = mp;
11814 			if (start == 0 || !more) {
11815 				ipf->ipf_hole_cnt = 1;
11816 				/*
11817 				 * if the first fragment comes in more than one
11818 				 * mblk, this loop will be executed for each
11819 				 * mblk. Need to adjust hole count so exiting
11820 				 * this routine will leave hole count at 1.
11821 				 */
11822 				if (next_mp)
11823 					ipf->ipf_hole_cnt++;
11824 			} else
11825 				ipf->ipf_hole_cnt = 2;
11826 			continue;
11827 		} else if (ipf->ipf_last_frag_seen && !more &&
11828 		    !pkt_boundary_checked) {
11829 			/*
11830 			 * We check datagram boundary only if this fragment
11831 			 * claims to be the last fragment and we have seen a
11832 			 * last fragment in the past too. We do this only
11833 			 * once for a given fragment.
11834 			 *
11835 			 * start cannot be 0 here as fragments with start=0
11836 			 * and MF=0 gets handled as a complete packet. These
11837 			 * fragments should not reach here.
11838 			 */
11839 
11840 			if (start + msgdsize(mp) !=
11841 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11842 				/*
11843 				 * We have two fragments both of which claim
11844 				 * to be the last fragment but gives conflicting
11845 				 * information about the whole datagram size.
11846 				 * Something fishy is going on. Drop the
11847 				 * fragment and free up the reassembly list.
11848 				 */
11849 				return (IP_REASS_FAILED);
11850 			}
11851 
11852 			/*
11853 			 * We shouldn't come to this code block again for this
11854 			 * particular fragment.
11855 			 */
11856 			pkt_boundary_checked = B_TRUE;
11857 		}
11858 
11859 		/* New stuff at or beyond tail? */
11860 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11861 		if (start >= offset) {
11862 			if (ipf->ipf_last_frag_seen) {
11863 				/* current fragment is beyond last fragment */
11864 				return (IP_REASS_FAILED);
11865 			}
11866 			/* Link it on end. */
11867 			ipf->ipf_tail_mp->b_cont = mp;
11868 			ipf->ipf_tail_mp = mp;
11869 			if (more) {
11870 				if (start != offset)
11871 					ipf->ipf_hole_cnt++;
11872 			} else if (start == offset && next_mp == NULL)
11873 					ipf->ipf_hole_cnt--;
11874 			continue;
11875 		}
11876 		mp1 = ipf->ipf_mp->b_cont;
11877 		offset = IP_REASS_START(mp1);
11878 		/* New stuff at the front? */
11879 		if (start < offset) {
11880 			if (start == 0) {
11881 				if (end >= offset) {
11882 					/* Nailed the hole at the begining. */
11883 					ipf->ipf_hole_cnt--;
11884 				}
11885 			} else if (end < offset) {
11886 				/*
11887 				 * A hole, stuff, and a hole where there used
11888 				 * to be just a hole.
11889 				 */
11890 				ipf->ipf_hole_cnt++;
11891 			}
11892 			mp->b_cont = mp1;
11893 			/* Check for overlap. */
11894 			while (end > offset) {
11895 				if (end < IP_REASS_END(mp1)) {
11896 					mp->b_wptr -= end - offset;
11897 					IP_REASS_SET_END(mp, offset);
11898 					BUMP_MIB(ill->ill_ip_mib,
11899 					    ipIfStatsReasmPartDups);
11900 					break;
11901 				}
11902 				/* Did we cover another hole? */
11903 				if ((mp1->b_cont &&
11904 				    IP_REASS_END(mp1) !=
11905 				    IP_REASS_START(mp1->b_cont) &&
11906 				    end >= IP_REASS_START(mp1->b_cont)) ||
11907 				    (!ipf->ipf_last_frag_seen && !more)) {
11908 					ipf->ipf_hole_cnt--;
11909 				}
11910 				/* Clip out mp1. */
11911 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11912 					/*
11913 					 * After clipping out mp1, this guy
11914 					 * is now hanging off the end.
11915 					 */
11916 					ipf->ipf_tail_mp = mp;
11917 				}
11918 				IP_REASS_SET_START(mp1, 0);
11919 				IP_REASS_SET_END(mp1, 0);
11920 				/* Subtract byte count */
11921 				ipf->ipf_count -= mp1->b_datap->db_lim -
11922 				    mp1->b_datap->db_base;
11923 				freeb(mp1);
11924 				BUMP_MIB(ill->ill_ip_mib,
11925 				    ipIfStatsReasmPartDups);
11926 				mp1 = mp->b_cont;
11927 				if (!mp1)
11928 					break;
11929 				offset = IP_REASS_START(mp1);
11930 			}
11931 			ipf->ipf_mp->b_cont = mp;
11932 			continue;
11933 		}
11934 		/*
11935 		 * The new piece starts somewhere between the start of the head
11936 		 * and before the end of the tail.
11937 		 */
11938 		for (; mp1; mp1 = mp1->b_cont) {
11939 			offset = IP_REASS_END(mp1);
11940 			if (start < offset) {
11941 				if (end <= offset) {
11942 					/* Nothing new. */
11943 					IP_REASS_SET_START(mp, 0);
11944 					IP_REASS_SET_END(mp, 0);
11945 					/* Subtract byte count */
11946 					ipf->ipf_count -= mp->b_datap->db_lim -
11947 					    mp->b_datap->db_base;
11948 					if (incr_dups) {
11949 						ipf->ipf_num_dups++;
11950 						incr_dups = B_FALSE;
11951 					}
11952 					freeb(mp);
11953 					BUMP_MIB(ill->ill_ip_mib,
11954 					    ipIfStatsReasmDuplicates);
11955 					break;
11956 				}
11957 				/*
11958 				 * Trim redundant stuff off beginning of new
11959 				 * piece.
11960 				 */
11961 				IP_REASS_SET_START(mp, offset);
11962 				mp->b_rptr += offset - start;
11963 				BUMP_MIB(ill->ill_ip_mib,
11964 				    ipIfStatsReasmPartDups);
11965 				start = offset;
11966 				if (!mp1->b_cont) {
11967 					/*
11968 					 * After trimming, this guy is now
11969 					 * hanging off the end.
11970 					 */
11971 					mp1->b_cont = mp;
11972 					ipf->ipf_tail_mp = mp;
11973 					if (!more) {
11974 						ipf->ipf_hole_cnt--;
11975 					}
11976 					break;
11977 				}
11978 			}
11979 			if (start >= IP_REASS_START(mp1->b_cont))
11980 				continue;
11981 			/* Fill a hole */
11982 			if (start > offset)
11983 				ipf->ipf_hole_cnt++;
11984 			mp->b_cont = mp1->b_cont;
11985 			mp1->b_cont = mp;
11986 			mp1 = mp->b_cont;
11987 			offset = IP_REASS_START(mp1);
11988 			if (end >= offset) {
11989 				ipf->ipf_hole_cnt--;
11990 				/* Check for overlap. */
11991 				while (end > offset) {
11992 					if (end < IP_REASS_END(mp1)) {
11993 						mp->b_wptr -= end - offset;
11994 						IP_REASS_SET_END(mp, offset);
11995 						/*
11996 						 * TODO we might bump
11997 						 * this up twice if there is
11998 						 * overlap at both ends.
11999 						 */
12000 						BUMP_MIB(ill->ill_ip_mib,
12001 						    ipIfStatsReasmPartDups);
12002 						break;
12003 					}
12004 					/* Did we cover another hole? */
12005 					if ((mp1->b_cont &&
12006 					    IP_REASS_END(mp1)
12007 					    != IP_REASS_START(mp1->b_cont) &&
12008 					    end >=
12009 					    IP_REASS_START(mp1->b_cont)) ||
12010 					    (!ipf->ipf_last_frag_seen &&
12011 					    !more)) {
12012 						ipf->ipf_hole_cnt--;
12013 					}
12014 					/* Clip out mp1. */
12015 					if ((mp->b_cont = mp1->b_cont) ==
12016 					    NULL) {
12017 						/*
12018 						 * After clipping out mp1,
12019 						 * this guy is now hanging
12020 						 * off the end.
12021 						 */
12022 						ipf->ipf_tail_mp = mp;
12023 					}
12024 					IP_REASS_SET_START(mp1, 0);
12025 					IP_REASS_SET_END(mp1, 0);
12026 					/* Subtract byte count */
12027 					ipf->ipf_count -=
12028 					    mp1->b_datap->db_lim -
12029 					    mp1->b_datap->db_base;
12030 					freeb(mp1);
12031 					BUMP_MIB(ill->ill_ip_mib,
12032 					    ipIfStatsReasmPartDups);
12033 					mp1 = mp->b_cont;
12034 					if (!mp1)
12035 						break;
12036 					offset = IP_REASS_START(mp1);
12037 				}
12038 			}
12039 			break;
12040 		}
12041 	} while (start = end, mp = next_mp);
12042 
12043 	/* Fragment just processed could be the last one. Remember this fact */
12044 	if (!more)
12045 		ipf->ipf_last_frag_seen = B_TRUE;
12046 
12047 	/* Still got holes? */
12048 	if (ipf->ipf_hole_cnt)
12049 		return (IP_REASS_PARTIAL);
12050 	/* Clean up overloaded fields to avoid upstream disasters. */
12051 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12052 		IP_REASS_SET_START(mp1, 0);
12053 		IP_REASS_SET_END(mp1, 0);
12054 	}
12055 	return (IP_REASS_COMPLETE);
12056 }
12057 
12058 /*
12059  * ipsec processing for the fast path, used for input UDP Packets
12060  * Returns true if ready for passup to UDP.
12061  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12062  * was an ESP-in-UDP packet, etc.).
12063  */
12064 static boolean_t
12065 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12066     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12067 {
12068 	uint32_t	ill_index;
12069 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12070 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12071 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12072 	udp_t		*udp = connp->conn_udp;
12073 
12074 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12075 	/* The ill_index of the incoming ILL */
12076 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12077 
12078 	/* pass packet up to the transport */
12079 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12080 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12081 		    NULL, mctl_present);
12082 		if (*first_mpp == NULL) {
12083 			return (B_FALSE);
12084 		}
12085 	}
12086 
12087 	/* Initiate IPPF processing for fastpath UDP */
12088 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12089 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12090 		if (*mpp == NULL) {
12091 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12092 			    "deferred/dropped during IPPF processing\n"));
12093 			return (B_FALSE);
12094 		}
12095 	}
12096 	/*
12097 	 * Remove 0-spi if it's 0, or move everything behind
12098 	 * the UDP header over it and forward to ESP via
12099 	 * ip_proto_input().
12100 	 */
12101 	if (udp->udp_nat_t_endpoint) {
12102 		if (mctl_present) {
12103 			/* mctl_present *shouldn't* happen. */
12104 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12105 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12106 			    &ipss->ipsec_dropper);
12107 			*first_mpp = NULL;
12108 			return (B_FALSE);
12109 		}
12110 
12111 		/* "ill" is "recv_ill" in actuality. */
12112 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12113 			return (B_FALSE);
12114 
12115 		/* Else continue like a normal UDP packet. */
12116 	}
12117 
12118 	/*
12119 	 * We make the checks as below since we are in the fast path
12120 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12121 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12122 	 */
12123 	if (connp->conn_recvif || connp->conn_recvslla ||
12124 	    connp->conn_ip_recvpktinfo) {
12125 		if (connp->conn_recvif) {
12126 			in_flags = IPF_RECVIF;
12127 		}
12128 		/*
12129 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12130 		 * so the flag passed to ip_add_info is based on IP version
12131 		 * of connp.
12132 		 */
12133 		if (connp->conn_ip_recvpktinfo) {
12134 			if (connp->conn_af_isv6) {
12135 				/*
12136 				 * V6 only needs index
12137 				 */
12138 				in_flags |= IPF_RECVIF;
12139 			} else {
12140 				/*
12141 				 * V4 needs index + matching address.
12142 				 */
12143 				in_flags |= IPF_RECVADDR;
12144 			}
12145 		}
12146 		if (connp->conn_recvslla) {
12147 			in_flags |= IPF_RECVSLLA;
12148 		}
12149 		/*
12150 		 * since in_flags are being set ill will be
12151 		 * referenced in ip_add_info, so it better not
12152 		 * be NULL.
12153 		 */
12154 		/*
12155 		 * the actual data will be contained in b_cont
12156 		 * upon successful return of the following call.
12157 		 * If the call fails then the original mblk is
12158 		 * returned.
12159 		 */
12160 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12161 		    ipst);
12162 	}
12163 
12164 	return (B_TRUE);
12165 }
12166 
12167 /*
12168  * Fragmentation reassembly.  Each ILL has a hash table for
12169  * queuing packets undergoing reassembly for all IPIFs
12170  * associated with the ILL.  The hash is based on the packet
12171  * IP ident field.  The ILL frag hash table was allocated
12172  * as a timer block at the time the ILL was created.  Whenever
12173  * there is anything on the reassembly queue, the timer will
12174  * be running.  Returns B_TRUE if successful else B_FALSE;
12175  * frees mp on failure.
12176  */
12177 static boolean_t
12178 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12179     uint32_t *cksum_val, uint16_t *cksum_flags)
12180 {
12181 	uint32_t	frag_offset_flags;
12182 	ill_t		*ill = (ill_t *)q->q_ptr;
12183 	mblk_t		*mp = *mpp;
12184 	mblk_t		*t_mp;
12185 	ipaddr_t	dst;
12186 	uint8_t		proto = ipha->ipha_protocol;
12187 	uint32_t	sum_val;
12188 	uint16_t	sum_flags;
12189 	ipf_t		*ipf;
12190 	ipf_t		**ipfp;
12191 	ipfb_t		*ipfb;
12192 	uint16_t	ident;
12193 	uint32_t	offset;
12194 	ipaddr_t	src;
12195 	uint_t		hdr_length;
12196 	uint32_t	end;
12197 	mblk_t		*mp1;
12198 	mblk_t		*tail_mp;
12199 	size_t		count;
12200 	size_t		msg_len;
12201 	uint8_t		ecn_info = 0;
12202 	uint32_t	packet_size;
12203 	boolean_t	pruned = B_FALSE;
12204 	ip_stack_t *ipst = ill->ill_ipst;
12205 
12206 	if (cksum_val != NULL)
12207 		*cksum_val = 0;
12208 	if (cksum_flags != NULL)
12209 		*cksum_flags = 0;
12210 
12211 	/*
12212 	 * Drop the fragmented as early as possible, if
12213 	 * we don't have resource(s) to re-assemble.
12214 	 */
12215 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12216 		freemsg(mp);
12217 		return (B_FALSE);
12218 	}
12219 
12220 	/* Check for fragmentation offset; return if there's none */
12221 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12222 	    (IPH_MF | IPH_OFFSET)) == 0)
12223 		return (B_TRUE);
12224 
12225 	/*
12226 	 * We utilize hardware computed checksum info only for UDP since
12227 	 * IP fragmentation is a normal occurence for the protocol.  In
12228 	 * addition, checksum offload support for IP fragments carrying
12229 	 * UDP payload is commonly implemented across network adapters.
12230 	 */
12231 	ASSERT(ill != NULL);
12232 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12233 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12234 		mblk_t *mp1 = mp->b_cont;
12235 		int32_t len;
12236 
12237 		/* Record checksum information from the packet */
12238 		sum_val = (uint32_t)DB_CKSUM16(mp);
12239 		sum_flags = DB_CKSUMFLAGS(mp);
12240 
12241 		/* IP payload offset from beginning of mblk */
12242 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12243 
12244 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12245 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12246 		    offset >= DB_CKSUMSTART(mp) &&
12247 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12248 			uint32_t adj;
12249 			/*
12250 			 * Partial checksum has been calculated by hardware
12251 			 * and attached to the packet; in addition, any
12252 			 * prepended extraneous data is even byte aligned.
12253 			 * If any such data exists, we adjust the checksum;
12254 			 * this would also handle any postpended data.
12255 			 */
12256 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12257 			    mp, mp1, len, adj);
12258 
12259 			/* One's complement subtract extraneous checksum */
12260 			if (adj >= sum_val)
12261 				sum_val = ~(adj - sum_val) & 0xFFFF;
12262 			else
12263 				sum_val -= adj;
12264 		}
12265 	} else {
12266 		sum_val = 0;
12267 		sum_flags = 0;
12268 	}
12269 
12270 	/* Clear hardware checksumming flag */
12271 	DB_CKSUMFLAGS(mp) = 0;
12272 
12273 	ident = ipha->ipha_ident;
12274 	offset = (frag_offset_flags << 3) & 0xFFFF;
12275 	src = ipha->ipha_src;
12276 	dst = ipha->ipha_dst;
12277 	hdr_length = IPH_HDR_LENGTH(ipha);
12278 	end = ntohs(ipha->ipha_length) - hdr_length;
12279 
12280 	/* If end == 0 then we have a packet with no data, so just free it */
12281 	if (end == 0) {
12282 		freemsg(mp);
12283 		return (B_FALSE);
12284 	}
12285 
12286 	/* Record the ECN field info. */
12287 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12288 	if (offset != 0) {
12289 		/*
12290 		 * If this isn't the first piece, strip the header, and
12291 		 * add the offset to the end value.
12292 		 */
12293 		mp->b_rptr += hdr_length;
12294 		end += offset;
12295 	}
12296 
12297 	msg_len = MBLKSIZE(mp);
12298 	tail_mp = mp;
12299 	while (tail_mp->b_cont != NULL) {
12300 		tail_mp = tail_mp->b_cont;
12301 		msg_len += MBLKSIZE(tail_mp);
12302 	}
12303 
12304 	/* If the reassembly list for this ILL will get too big, prune it */
12305 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12306 	    ipst->ips_ip_reass_queue_bytes) {
12307 		ill_frag_prune(ill,
12308 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12309 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12310 		pruned = B_TRUE;
12311 	}
12312 
12313 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12314 	mutex_enter(&ipfb->ipfb_lock);
12315 
12316 	ipfp = &ipfb->ipfb_ipf;
12317 	/* Try to find an existing fragment queue for this packet. */
12318 	for (;;) {
12319 		ipf = ipfp[0];
12320 		if (ipf != NULL) {
12321 			/*
12322 			 * It has to match on ident and src/dst address.
12323 			 */
12324 			if (ipf->ipf_ident == ident &&
12325 			    ipf->ipf_src == src &&
12326 			    ipf->ipf_dst == dst &&
12327 			    ipf->ipf_protocol == proto) {
12328 				/*
12329 				 * If we have received too many
12330 				 * duplicate fragments for this packet
12331 				 * free it.
12332 				 */
12333 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12334 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12335 					freemsg(mp);
12336 					mutex_exit(&ipfb->ipfb_lock);
12337 					return (B_FALSE);
12338 				}
12339 				/* Found it. */
12340 				break;
12341 			}
12342 			ipfp = &ipf->ipf_hash_next;
12343 			continue;
12344 		}
12345 
12346 		/*
12347 		 * If we pruned the list, do we want to store this new
12348 		 * fragment?. We apply an optimization here based on the
12349 		 * fact that most fragments will be received in order.
12350 		 * So if the offset of this incoming fragment is zero,
12351 		 * it is the first fragment of a new packet. We will
12352 		 * keep it.  Otherwise drop the fragment, as we have
12353 		 * probably pruned the packet already (since the
12354 		 * packet cannot be found).
12355 		 */
12356 		if (pruned && offset != 0) {
12357 			mutex_exit(&ipfb->ipfb_lock);
12358 			freemsg(mp);
12359 			return (B_FALSE);
12360 		}
12361 
12362 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12363 			/*
12364 			 * Too many fragmented packets in this hash
12365 			 * bucket. Free the oldest.
12366 			 */
12367 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12368 		}
12369 
12370 		/* New guy.  Allocate a frag message. */
12371 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12372 		if (mp1 == NULL) {
12373 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12374 			freemsg(mp);
12375 reass_done:
12376 			mutex_exit(&ipfb->ipfb_lock);
12377 			return (B_FALSE);
12378 		}
12379 
12380 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12381 		mp1->b_cont = mp;
12382 
12383 		/* Initialize the fragment header. */
12384 		ipf = (ipf_t *)mp1->b_rptr;
12385 		ipf->ipf_mp = mp1;
12386 		ipf->ipf_ptphn = ipfp;
12387 		ipfp[0] = ipf;
12388 		ipf->ipf_hash_next = NULL;
12389 		ipf->ipf_ident = ident;
12390 		ipf->ipf_protocol = proto;
12391 		ipf->ipf_src = src;
12392 		ipf->ipf_dst = dst;
12393 		ipf->ipf_nf_hdr_len = 0;
12394 		/* Record reassembly start time. */
12395 		ipf->ipf_timestamp = gethrestime_sec();
12396 		/* Record ipf generation and account for frag header */
12397 		ipf->ipf_gen = ill->ill_ipf_gen++;
12398 		ipf->ipf_count = MBLKSIZE(mp1);
12399 		ipf->ipf_last_frag_seen = B_FALSE;
12400 		ipf->ipf_ecn = ecn_info;
12401 		ipf->ipf_num_dups = 0;
12402 		ipfb->ipfb_frag_pkts++;
12403 		ipf->ipf_checksum = 0;
12404 		ipf->ipf_checksum_flags = 0;
12405 
12406 		/* Store checksum value in fragment header */
12407 		if (sum_flags != 0) {
12408 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12409 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12410 			ipf->ipf_checksum = sum_val;
12411 			ipf->ipf_checksum_flags = sum_flags;
12412 		}
12413 
12414 		/*
12415 		 * We handle reassembly two ways.  In the easy case,
12416 		 * where all the fragments show up in order, we do
12417 		 * minimal bookkeeping, and just clip new pieces on
12418 		 * the end.  If we ever see a hole, then we go off
12419 		 * to ip_reassemble which has to mark the pieces and
12420 		 * keep track of the number of holes, etc.  Obviously,
12421 		 * the point of having both mechanisms is so we can
12422 		 * handle the easy case as efficiently as possible.
12423 		 */
12424 		if (offset == 0) {
12425 			/* Easy case, in-order reassembly so far. */
12426 			ipf->ipf_count += msg_len;
12427 			ipf->ipf_tail_mp = tail_mp;
12428 			/*
12429 			 * Keep track of next expected offset in
12430 			 * ipf_end.
12431 			 */
12432 			ipf->ipf_end = end;
12433 			ipf->ipf_nf_hdr_len = hdr_length;
12434 		} else {
12435 			/* Hard case, hole at the beginning. */
12436 			ipf->ipf_tail_mp = NULL;
12437 			/*
12438 			 * ipf_end == 0 means that we have given up
12439 			 * on easy reassembly.
12440 			 */
12441 			ipf->ipf_end = 0;
12442 
12443 			/* Forget checksum offload from now on */
12444 			ipf->ipf_checksum_flags = 0;
12445 
12446 			/*
12447 			 * ipf_hole_cnt is set by ip_reassemble.
12448 			 * ipf_count is updated by ip_reassemble.
12449 			 * No need to check for return value here
12450 			 * as we don't expect reassembly to complete
12451 			 * or fail for the first fragment itself.
12452 			 */
12453 			(void) ip_reassemble(mp, ipf,
12454 			    (frag_offset_flags & IPH_OFFSET) << 3,
12455 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12456 		}
12457 		/* Update per ipfb and ill byte counts */
12458 		ipfb->ipfb_count += ipf->ipf_count;
12459 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12460 		ill->ill_frag_count += ipf->ipf_count;
12461 		/* If the frag timer wasn't already going, start it. */
12462 		mutex_enter(&ill->ill_lock);
12463 		ill_frag_timer_start(ill);
12464 		mutex_exit(&ill->ill_lock);
12465 		goto reass_done;
12466 	}
12467 
12468 	/*
12469 	 * If the packet's flag has changed (it could be coming up
12470 	 * from an interface different than the previous, therefore
12471 	 * possibly different checksum capability), then forget about
12472 	 * any stored checksum states.  Otherwise add the value to
12473 	 * the existing one stored in the fragment header.
12474 	 */
12475 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12476 		sum_val += ipf->ipf_checksum;
12477 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12478 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12479 		ipf->ipf_checksum = sum_val;
12480 	} else if (ipf->ipf_checksum_flags != 0) {
12481 		/* Forget checksum offload from now on */
12482 		ipf->ipf_checksum_flags = 0;
12483 	}
12484 
12485 	/*
12486 	 * We have a new piece of a datagram which is already being
12487 	 * reassembled.  Update the ECN info if all IP fragments
12488 	 * are ECN capable.  If there is one which is not, clear
12489 	 * all the info.  If there is at least one which has CE
12490 	 * code point, IP needs to report that up to transport.
12491 	 */
12492 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12493 		if (ecn_info == IPH_ECN_CE)
12494 			ipf->ipf_ecn = IPH_ECN_CE;
12495 	} else {
12496 		ipf->ipf_ecn = IPH_ECN_NECT;
12497 	}
12498 	if (offset && ipf->ipf_end == offset) {
12499 		/* The new fragment fits at the end */
12500 		ipf->ipf_tail_mp->b_cont = mp;
12501 		/* Update the byte count */
12502 		ipf->ipf_count += msg_len;
12503 		/* Update per ipfb and ill byte counts */
12504 		ipfb->ipfb_count += msg_len;
12505 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12506 		ill->ill_frag_count += msg_len;
12507 		if (frag_offset_flags & IPH_MF) {
12508 			/* More to come. */
12509 			ipf->ipf_end = end;
12510 			ipf->ipf_tail_mp = tail_mp;
12511 			goto reass_done;
12512 		}
12513 	} else {
12514 		/* Go do the hard cases. */
12515 		int ret;
12516 
12517 		if (offset == 0)
12518 			ipf->ipf_nf_hdr_len = hdr_length;
12519 
12520 		/* Save current byte count */
12521 		count = ipf->ipf_count;
12522 		ret = ip_reassemble(mp, ipf,
12523 		    (frag_offset_flags & IPH_OFFSET) << 3,
12524 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12525 		/* Count of bytes added and subtracted (freeb()ed) */
12526 		count = ipf->ipf_count - count;
12527 		if (count) {
12528 			/* Update per ipfb and ill byte counts */
12529 			ipfb->ipfb_count += count;
12530 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12531 			ill->ill_frag_count += count;
12532 		}
12533 		if (ret == IP_REASS_PARTIAL) {
12534 			goto reass_done;
12535 		} else if (ret == IP_REASS_FAILED) {
12536 			/* Reassembly failed. Free up all resources */
12537 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12538 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12539 				IP_REASS_SET_START(t_mp, 0);
12540 				IP_REASS_SET_END(t_mp, 0);
12541 			}
12542 			freemsg(mp);
12543 			goto reass_done;
12544 		}
12545 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12546 	}
12547 	/*
12548 	 * We have completed reassembly.  Unhook the frag header from
12549 	 * the reassembly list.
12550 	 *
12551 	 * Before we free the frag header, record the ECN info
12552 	 * to report back to the transport.
12553 	 */
12554 	ecn_info = ipf->ipf_ecn;
12555 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12556 	ipfp = ipf->ipf_ptphn;
12557 
12558 	/* We need to supply these to caller */
12559 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12560 		sum_val = ipf->ipf_checksum;
12561 	else
12562 		sum_val = 0;
12563 
12564 	mp1 = ipf->ipf_mp;
12565 	count = ipf->ipf_count;
12566 	ipf = ipf->ipf_hash_next;
12567 	if (ipf != NULL)
12568 		ipf->ipf_ptphn = ipfp;
12569 	ipfp[0] = ipf;
12570 	ill->ill_frag_count -= count;
12571 	ASSERT(ipfb->ipfb_count >= count);
12572 	ipfb->ipfb_count -= count;
12573 	ipfb->ipfb_frag_pkts--;
12574 	mutex_exit(&ipfb->ipfb_lock);
12575 	/* Ditch the frag header. */
12576 	mp = mp1->b_cont;
12577 
12578 	freeb(mp1);
12579 
12580 	/* Restore original IP length in header. */
12581 	packet_size = (uint32_t)msgdsize(mp);
12582 	if (packet_size > IP_MAXPACKET) {
12583 		freemsg(mp);
12584 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12585 		return (B_FALSE);
12586 	}
12587 
12588 	if (DB_REF(mp) > 1) {
12589 		mblk_t *mp2 = copymsg(mp);
12590 
12591 		freemsg(mp);
12592 		if (mp2 == NULL) {
12593 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12594 			return (B_FALSE);
12595 		}
12596 		mp = mp2;
12597 	}
12598 	ipha = (ipha_t *)mp->b_rptr;
12599 
12600 	ipha->ipha_length = htons((uint16_t)packet_size);
12601 	/* We're now complete, zip the frag state */
12602 	ipha->ipha_fragment_offset_and_flags = 0;
12603 	/* Record the ECN info. */
12604 	ipha->ipha_type_of_service &= 0xFC;
12605 	ipha->ipha_type_of_service |= ecn_info;
12606 	*mpp = mp;
12607 
12608 	/* Reassembly is successful; return checksum information if needed */
12609 	if (cksum_val != NULL)
12610 		*cksum_val = sum_val;
12611 	if (cksum_flags != NULL)
12612 		*cksum_flags = sum_flags;
12613 
12614 	return (B_TRUE);
12615 }
12616 
12617 /*
12618  * Perform ip header check sum update local options.
12619  * return B_TRUE if all is well, else return B_FALSE and release
12620  * the mp. caller is responsible for decrementing ire ref cnt.
12621  */
12622 static boolean_t
12623 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12624     ip_stack_t *ipst)
12625 {
12626 	mblk_t		*first_mp;
12627 	boolean_t	mctl_present;
12628 	uint16_t	sum;
12629 
12630 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12631 	/*
12632 	 * Don't do the checksum if it has gone through AH/ESP
12633 	 * processing.
12634 	 */
12635 	if (!mctl_present) {
12636 		sum = ip_csum_hdr(ipha);
12637 		if (sum != 0) {
12638 			if (ill != NULL) {
12639 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12640 			} else {
12641 				BUMP_MIB(&ipst->ips_ip_mib,
12642 				    ipIfStatsInCksumErrs);
12643 			}
12644 			freemsg(first_mp);
12645 			return (B_FALSE);
12646 		}
12647 	}
12648 
12649 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12650 		if (mctl_present)
12651 			freeb(first_mp);
12652 		return (B_FALSE);
12653 	}
12654 
12655 	return (B_TRUE);
12656 }
12657 
12658 /*
12659  * All udp packet are delivered to the local host via this routine.
12660  */
12661 void
12662 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12663     ill_t *recv_ill)
12664 {
12665 	uint32_t	sum;
12666 	uint32_t	u1;
12667 	boolean_t	mctl_present;
12668 	conn_t		*connp;
12669 	mblk_t		*first_mp;
12670 	uint16_t	*up;
12671 	ill_t		*ill = (ill_t *)q->q_ptr;
12672 	uint16_t	reass_hck_flags = 0;
12673 	ip_stack_t	*ipst;
12674 
12675 	ASSERT(recv_ill != NULL);
12676 	ipst = recv_ill->ill_ipst;
12677 
12678 #define	rptr    ((uchar_t *)ipha)
12679 
12680 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12681 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12682 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12683 	ASSERT(ill != NULL);
12684 
12685 	/*
12686 	 * FAST PATH for udp packets
12687 	 */
12688 
12689 	/* u1 is # words of IP options */
12690 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12691 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12692 
12693 	/* IP options present */
12694 	if (u1 != 0)
12695 		goto ipoptions;
12696 
12697 	/* Check the IP header checksum.  */
12698 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12699 		/* Clear the IP header h/w cksum flag */
12700 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12701 	} else if (!mctl_present) {
12702 		/*
12703 		 * Don't verify header checksum if this packet is coming
12704 		 * back from AH/ESP as we already did it.
12705 		 */
12706 #define	uph	((uint16_t *)ipha)
12707 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12708 		    uph[6] + uph[7] + uph[8] + uph[9];
12709 #undef	uph
12710 		/* finish doing IP checksum */
12711 		sum = (sum & 0xFFFF) + (sum >> 16);
12712 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12713 		if (sum != 0 && sum != 0xFFFF) {
12714 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12715 			freemsg(first_mp);
12716 			return;
12717 		}
12718 	}
12719 
12720 	/*
12721 	 * Count for SNMP of inbound packets for ire.
12722 	 * if mctl is present this might be a secure packet and
12723 	 * has already been counted for in ip_proto_input().
12724 	 */
12725 	if (!mctl_present) {
12726 		UPDATE_IB_PKT_COUNT(ire);
12727 		ire->ire_last_used_time = lbolt;
12728 	}
12729 
12730 	/* packet part of fragmented IP packet? */
12731 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12732 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12733 		goto fragmented;
12734 	}
12735 
12736 	/* u1 = IP header length (20 bytes) */
12737 	u1 = IP_SIMPLE_HDR_LENGTH;
12738 
12739 	/* packet does not contain complete IP & UDP headers */
12740 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12741 		goto udppullup;
12742 
12743 	/* up points to UDP header */
12744 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12745 #define	iphs    ((uint16_t *)ipha)
12746 
12747 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12748 	if (up[3] != 0) {
12749 		mblk_t *mp1 = mp->b_cont;
12750 		boolean_t cksum_err;
12751 		uint16_t hck_flags = 0;
12752 
12753 		/* Pseudo-header checksum */
12754 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12755 		    iphs[9] + up[2];
12756 
12757 		/*
12758 		 * Revert to software checksum calculation if the interface
12759 		 * isn't capable of checksum offload or if IPsec is present.
12760 		 */
12761 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12762 			hck_flags = DB_CKSUMFLAGS(mp);
12763 
12764 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12765 			IP_STAT(ipst, ip_in_sw_cksum);
12766 
12767 		IP_CKSUM_RECV(hck_flags, u1,
12768 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12769 		    (int32_t)((uchar_t *)up - rptr),
12770 		    mp, mp1, cksum_err);
12771 
12772 		if (cksum_err) {
12773 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12774 			if (hck_flags & HCK_FULLCKSUM)
12775 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12776 			else if (hck_flags & HCK_PARTIALCKSUM)
12777 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12778 			else
12779 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12780 
12781 			freemsg(first_mp);
12782 			return;
12783 		}
12784 	}
12785 
12786 	/* Non-fragmented broadcast or multicast packet? */
12787 	if (ire->ire_type == IRE_BROADCAST)
12788 		goto udpslowpath;
12789 
12790 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12791 	    ire->ire_zoneid, ipst)) != NULL) {
12792 		ASSERT(connp->conn_upq != NULL);
12793 		IP_STAT(ipst, ip_udp_fast_path);
12794 
12795 		if (CONN_UDP_FLOWCTLD(connp)) {
12796 			freemsg(mp);
12797 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12798 		} else {
12799 			if (!mctl_present) {
12800 				BUMP_MIB(ill->ill_ip_mib,
12801 				    ipIfStatsHCInDelivers);
12802 			}
12803 			/*
12804 			 * mp and first_mp can change.
12805 			 */
12806 			if (ip_udp_check(q, connp, recv_ill,
12807 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12808 				/* Send it upstream */
12809 				(connp->conn_recv)(connp, mp, NULL);
12810 			}
12811 		}
12812 		/*
12813 		 * freeb() cannot deal with null mblk being passed
12814 		 * in and first_mp can be set to null in the call
12815 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12816 		 */
12817 		if (mctl_present && first_mp != NULL) {
12818 			freeb(first_mp);
12819 		}
12820 		CONN_DEC_REF(connp);
12821 		return;
12822 	}
12823 
12824 	/*
12825 	 * if we got here we know the packet is not fragmented and
12826 	 * has no options. The classifier could not find a conn_t and
12827 	 * most likely its an icmp packet so send it through slow path.
12828 	 */
12829 
12830 	goto udpslowpath;
12831 
12832 ipoptions:
12833 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12834 		goto slow_done;
12835 	}
12836 
12837 	UPDATE_IB_PKT_COUNT(ire);
12838 	ire->ire_last_used_time = lbolt;
12839 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12840 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12841 fragmented:
12842 		/*
12843 		 * "sum" and "reass_hck_flags" are non-zero if the
12844 		 * reassembled packet has a valid hardware computed
12845 		 * checksum information associated with it.
12846 		 */
12847 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12848 			goto slow_done;
12849 		/*
12850 		 * Make sure that first_mp points back to mp as
12851 		 * the mp we came in with could have changed in
12852 		 * ip_rput_fragment().
12853 		 */
12854 		ASSERT(!mctl_present);
12855 		ipha = (ipha_t *)mp->b_rptr;
12856 		first_mp = mp;
12857 	}
12858 
12859 	/* Now we have a complete datagram, destined for this machine. */
12860 	u1 = IPH_HDR_LENGTH(ipha);
12861 	/* Pull up the UDP header, if necessary. */
12862 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12863 udppullup:
12864 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12865 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12866 			freemsg(first_mp);
12867 			goto slow_done;
12868 		}
12869 		ipha = (ipha_t *)mp->b_rptr;
12870 	}
12871 
12872 	/*
12873 	 * Validate the checksum for the reassembled packet; for the
12874 	 * pullup case we calculate the payload checksum in software.
12875 	 */
12876 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12877 	if (up[3] != 0) {
12878 		boolean_t cksum_err;
12879 
12880 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12881 			IP_STAT(ipst, ip_in_sw_cksum);
12882 
12883 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12884 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12885 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12886 		    iphs[9] + up[2], sum, cksum_err);
12887 
12888 		if (cksum_err) {
12889 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12890 
12891 			if (reass_hck_flags & HCK_FULLCKSUM)
12892 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12893 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12894 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12895 			else
12896 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12897 
12898 			freemsg(first_mp);
12899 			goto slow_done;
12900 		}
12901 	}
12902 udpslowpath:
12903 
12904 	/* Clear hardware checksum flag to be safe */
12905 	DB_CKSUMFLAGS(mp) = 0;
12906 
12907 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12908 	    (ire->ire_type == IRE_BROADCAST),
12909 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12910 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12911 
12912 slow_done:
12913 	IP_STAT(ipst, ip_udp_slow_path);
12914 	return;
12915 
12916 #undef  iphs
12917 #undef  rptr
12918 }
12919 
12920 /* ARGSUSED */
12921 static mblk_t *
12922 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12923     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12924     ill_rx_ring_t *ill_ring)
12925 {
12926 	conn_t		*connp;
12927 	uint32_t	sum;
12928 	uint32_t	u1;
12929 	uint16_t	*up;
12930 	int		offset;
12931 	ssize_t		len;
12932 	mblk_t		*mp1;
12933 	boolean_t	syn_present = B_FALSE;
12934 	tcph_t		*tcph;
12935 	uint_t		ip_hdr_len;
12936 	ill_t		*ill = (ill_t *)q->q_ptr;
12937 	zoneid_t	zoneid = ire->ire_zoneid;
12938 	boolean_t	cksum_err;
12939 	uint16_t	hck_flags = 0;
12940 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12941 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12942 
12943 #define	rptr	((uchar_t *)ipha)
12944 
12945 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12946 	ASSERT(ill != NULL);
12947 
12948 	/*
12949 	 * FAST PATH for tcp packets
12950 	 */
12951 
12952 	/* u1 is # words of IP options */
12953 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12954 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12955 
12956 	/* IP options present */
12957 	if (u1) {
12958 		goto ipoptions;
12959 	} else if (!mctl_present) {
12960 		/* Check the IP header checksum.  */
12961 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12962 			/* Clear the IP header h/w cksum flag */
12963 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12964 		} else if (!mctl_present) {
12965 			/*
12966 			 * Don't verify header checksum if this packet
12967 			 * is coming back from AH/ESP as we already did it.
12968 			 */
12969 #define	uph	((uint16_t *)ipha)
12970 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12971 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12972 #undef	uph
12973 			/* finish doing IP checksum */
12974 			sum = (sum & 0xFFFF) + (sum >> 16);
12975 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12976 			if (sum != 0 && sum != 0xFFFF) {
12977 				BUMP_MIB(ill->ill_ip_mib,
12978 				    ipIfStatsInCksumErrs);
12979 				goto error;
12980 			}
12981 		}
12982 	}
12983 
12984 	if (!mctl_present) {
12985 		UPDATE_IB_PKT_COUNT(ire);
12986 		ire->ire_last_used_time = lbolt;
12987 	}
12988 
12989 	/* packet part of fragmented IP packet? */
12990 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12991 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12992 		goto fragmented;
12993 	}
12994 
12995 	/* u1 = IP header length (20 bytes) */
12996 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12997 
12998 	/* does packet contain IP+TCP headers? */
12999 	len = mp->b_wptr - rptr;
13000 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13001 		IP_STAT(ipst, ip_tcppullup);
13002 		goto tcppullup;
13003 	}
13004 
13005 	/* TCP options present? */
13006 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13007 
13008 	/*
13009 	 * If options need to be pulled up, then goto tcpoptions.
13010 	 * otherwise we are still in the fast path
13011 	 */
13012 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13013 		IP_STAT(ipst, ip_tcpoptions);
13014 		goto tcpoptions;
13015 	}
13016 
13017 	/* multiple mblks of tcp data? */
13018 	if ((mp1 = mp->b_cont) != NULL) {
13019 		/* more then two? */
13020 		if (mp1->b_cont != NULL) {
13021 			IP_STAT(ipst, ip_multipkttcp);
13022 			goto multipkttcp;
13023 		}
13024 		len += mp1->b_wptr - mp1->b_rptr;
13025 	}
13026 
13027 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13028 
13029 	/* part of pseudo checksum */
13030 
13031 	/* TCP datagram length */
13032 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13033 
13034 #define	iphs    ((uint16_t *)ipha)
13035 
13036 #ifdef	_BIG_ENDIAN
13037 	u1 += IPPROTO_TCP;
13038 #else
13039 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13040 #endif
13041 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13042 
13043 	/*
13044 	 * Revert to software checksum calculation if the interface
13045 	 * isn't capable of checksum offload or if IPsec is present.
13046 	 */
13047 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13048 		hck_flags = DB_CKSUMFLAGS(mp);
13049 
13050 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13051 		IP_STAT(ipst, ip_in_sw_cksum);
13052 
13053 	IP_CKSUM_RECV(hck_flags, u1,
13054 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13055 	    (int32_t)((uchar_t *)up - rptr),
13056 	    mp, mp1, cksum_err);
13057 
13058 	if (cksum_err) {
13059 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13060 
13061 		if (hck_flags & HCK_FULLCKSUM)
13062 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13063 		else if (hck_flags & HCK_PARTIALCKSUM)
13064 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13065 		else
13066 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13067 
13068 		goto error;
13069 	}
13070 
13071 try_again:
13072 
13073 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13074 	    zoneid, ipst)) == NULL) {
13075 		/* Send the TH_RST */
13076 		goto no_conn;
13077 	}
13078 
13079 	/*
13080 	 * TCP FAST PATH for AF_INET socket.
13081 	 *
13082 	 * TCP fast path to avoid extra work. An AF_INET socket type
13083 	 * does not have facility to receive extra information via
13084 	 * ip_process or ip_add_info. Also, when the connection was
13085 	 * established, we made a check if this connection is impacted
13086 	 * by any global IPsec policy or per connection policy (a
13087 	 * policy that comes in effect later will not apply to this
13088 	 * connection). Since all this can be determined at the
13089 	 * connection establishment time, a quick check of flags
13090 	 * can avoid extra work.
13091 	 */
13092 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13093 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13094 		ASSERT(first_mp == mp);
13095 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13096 		SET_SQUEUE(mp, tcp_rput_data, connp);
13097 		return (mp);
13098 	}
13099 
13100 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13101 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13102 		if (IPCL_IS_TCP(connp)) {
13103 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13104 			DB_CKSUMSTART(mp) =
13105 			    (intptr_t)ip_squeue_get(ill_ring);
13106 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13107 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13108 				BUMP_MIB(ill->ill_ip_mib,
13109 				    ipIfStatsHCInDelivers);
13110 				SET_SQUEUE(mp, connp->conn_recv, connp);
13111 				return (mp);
13112 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13113 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13114 				BUMP_MIB(ill->ill_ip_mib,
13115 				    ipIfStatsHCInDelivers);
13116 				ip_squeue_enter_unbound++;
13117 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13118 				    connp);
13119 				return (mp);
13120 			}
13121 			syn_present = B_TRUE;
13122 		}
13123 
13124 	}
13125 
13126 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13127 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13128 
13129 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13130 		/* No need to send this packet to TCP */
13131 		if ((flags & TH_RST) || (flags & TH_URG)) {
13132 			CONN_DEC_REF(connp);
13133 			freemsg(first_mp);
13134 			return (NULL);
13135 		}
13136 		if (flags & TH_ACK) {
13137 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13138 			    ipst->ips_netstack->netstack_tcp, connp);
13139 			CONN_DEC_REF(connp);
13140 			return (NULL);
13141 		}
13142 
13143 		CONN_DEC_REF(connp);
13144 		freemsg(first_mp);
13145 		return (NULL);
13146 	}
13147 
13148 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13149 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13150 		    ipha, NULL, mctl_present);
13151 		if (first_mp == NULL) {
13152 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13153 			CONN_DEC_REF(connp);
13154 			return (NULL);
13155 		}
13156 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13157 			ASSERT(syn_present);
13158 			if (mctl_present) {
13159 				ASSERT(first_mp != mp);
13160 				first_mp->b_datap->db_struioflag |=
13161 				    STRUIO_POLICY;
13162 			} else {
13163 				ASSERT(first_mp == mp);
13164 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13165 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13166 			}
13167 		} else {
13168 			/*
13169 			 * Discard first_mp early since we're dealing with a
13170 			 * fully-connected conn_t and tcp doesn't do policy in
13171 			 * this case.
13172 			 */
13173 			if (mctl_present) {
13174 				freeb(first_mp);
13175 				mctl_present = B_FALSE;
13176 			}
13177 			first_mp = mp;
13178 		}
13179 	}
13180 
13181 	/* Initiate IPPF processing for fastpath */
13182 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13183 		uint32_t	ill_index;
13184 
13185 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13186 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13187 		if (mp == NULL) {
13188 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13189 			    "deferred/dropped during IPPF processing\n"));
13190 			CONN_DEC_REF(connp);
13191 			if (mctl_present)
13192 				freeb(first_mp);
13193 			return (NULL);
13194 		} else if (mctl_present) {
13195 			/*
13196 			 * ip_process might return a new mp.
13197 			 */
13198 			ASSERT(first_mp != mp);
13199 			first_mp->b_cont = mp;
13200 		} else {
13201 			first_mp = mp;
13202 		}
13203 
13204 	}
13205 
13206 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13207 		/*
13208 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13209 		 * make sure IPF_RECVIF is passed to ip_add_info.
13210 		 */
13211 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13212 		    IPCL_ZONEID(connp), ipst);
13213 		if (mp == NULL) {
13214 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13215 			CONN_DEC_REF(connp);
13216 			if (mctl_present)
13217 				freeb(first_mp);
13218 			return (NULL);
13219 		} else if (mctl_present) {
13220 			/*
13221 			 * ip_add_info might return a new mp.
13222 			 */
13223 			ASSERT(first_mp != mp);
13224 			first_mp->b_cont = mp;
13225 		} else {
13226 			first_mp = mp;
13227 		}
13228 	}
13229 
13230 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13231 	if (IPCL_IS_TCP(connp)) {
13232 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13233 		return (first_mp);
13234 	} else {
13235 		/* SOCK_RAW, IPPROTO_TCP case */
13236 		(connp->conn_recv)(connp, first_mp, NULL);
13237 		CONN_DEC_REF(connp);
13238 		return (NULL);
13239 	}
13240 
13241 no_conn:
13242 	/* Initiate IPPf processing, if needed. */
13243 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13244 		uint32_t ill_index;
13245 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13246 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13247 		if (first_mp == NULL) {
13248 			return (NULL);
13249 		}
13250 	}
13251 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13252 
13253 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13254 	    ipst->ips_netstack->netstack_tcp, NULL);
13255 	return (NULL);
13256 ipoptions:
13257 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13258 		goto slow_done;
13259 	}
13260 
13261 	UPDATE_IB_PKT_COUNT(ire);
13262 	ire->ire_last_used_time = lbolt;
13263 
13264 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13265 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13266 fragmented:
13267 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13268 			if (mctl_present)
13269 				freeb(first_mp);
13270 			goto slow_done;
13271 		}
13272 		/*
13273 		 * Make sure that first_mp points back to mp as
13274 		 * the mp we came in with could have changed in
13275 		 * ip_rput_fragment().
13276 		 */
13277 		ASSERT(!mctl_present);
13278 		ipha = (ipha_t *)mp->b_rptr;
13279 		first_mp = mp;
13280 	}
13281 
13282 	/* Now we have a complete datagram, destined for this machine. */
13283 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13284 
13285 	len = mp->b_wptr - mp->b_rptr;
13286 	/* Pull up a minimal TCP header, if necessary. */
13287 	if (len < (u1 + 20)) {
13288 tcppullup:
13289 		if (!pullupmsg(mp, u1 + 20)) {
13290 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13291 			goto error;
13292 		}
13293 		ipha = (ipha_t *)mp->b_rptr;
13294 		len = mp->b_wptr - mp->b_rptr;
13295 	}
13296 
13297 	/*
13298 	 * Extract the offset field from the TCP header.  As usual, we
13299 	 * try to help the compiler more than the reader.
13300 	 */
13301 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13302 	if (offset != 5) {
13303 tcpoptions:
13304 		if (offset < 5) {
13305 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13306 			goto error;
13307 		}
13308 		/*
13309 		 * There must be TCP options.
13310 		 * Make sure we can grab them.
13311 		 */
13312 		offset <<= 2;
13313 		offset += u1;
13314 		if (len < offset) {
13315 			if (!pullupmsg(mp, offset)) {
13316 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13317 				goto error;
13318 			}
13319 			ipha = (ipha_t *)mp->b_rptr;
13320 			len = mp->b_wptr - rptr;
13321 		}
13322 	}
13323 
13324 	/* Get the total packet length in len, including headers. */
13325 	if (mp->b_cont) {
13326 multipkttcp:
13327 		len = msgdsize(mp);
13328 	}
13329 
13330 	/*
13331 	 * Check the TCP checksum by pulling together the pseudo-
13332 	 * header checksum, and passing it to ip_csum to be added in
13333 	 * with the TCP datagram.
13334 	 *
13335 	 * Since we are not using the hwcksum if available we must
13336 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13337 	 * If either of these fails along the way the mblk is freed.
13338 	 * If this logic ever changes and mblk is reused to say send
13339 	 * ICMP's back, then this flag may need to be cleared in
13340 	 * other places as well.
13341 	 */
13342 	DB_CKSUMFLAGS(mp) = 0;
13343 
13344 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13345 
13346 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13347 #ifdef	_BIG_ENDIAN
13348 	u1 += IPPROTO_TCP;
13349 #else
13350 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13351 #endif
13352 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13353 	/*
13354 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13355 	 */
13356 	IP_STAT(ipst, ip_in_sw_cksum);
13357 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13358 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13359 		goto error;
13360 	}
13361 
13362 	IP_STAT(ipst, ip_tcp_slow_path);
13363 	goto try_again;
13364 #undef  iphs
13365 #undef  rptr
13366 
13367 error:
13368 	freemsg(first_mp);
13369 slow_done:
13370 	return (NULL);
13371 }
13372 
13373 /* ARGSUSED */
13374 static void
13375 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13376     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13377 {
13378 	conn_t		*connp;
13379 	uint32_t	sum;
13380 	uint32_t	u1;
13381 	ssize_t		len;
13382 	sctp_hdr_t	*sctph;
13383 	zoneid_t	zoneid = ire->ire_zoneid;
13384 	uint32_t	pktsum;
13385 	uint32_t	calcsum;
13386 	uint32_t	ports;
13387 	in6_addr_t	map_src, map_dst;
13388 	ill_t		*ill = (ill_t *)q->q_ptr;
13389 	ip_stack_t	*ipst;
13390 	sctp_stack_t	*sctps;
13391 
13392 	ASSERT(recv_ill != NULL);
13393 	ipst = recv_ill->ill_ipst;
13394 	sctps = ipst->ips_netstack->netstack_sctp;
13395 
13396 #define	rptr	((uchar_t *)ipha)
13397 
13398 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13399 	ASSERT(ill != NULL);
13400 
13401 	/* u1 is # words of IP options */
13402 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13403 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13404 
13405 	/* IP options present */
13406 	if (u1 > 0) {
13407 		goto ipoptions;
13408 	} else {
13409 		/* Check the IP header checksum.  */
13410 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13411 		    !mctl_present) {
13412 #define	uph	((uint16_t *)ipha)
13413 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13414 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13415 #undef	uph
13416 			/* finish doing IP checksum */
13417 			sum = (sum & 0xFFFF) + (sum >> 16);
13418 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13419 			/*
13420 			 * Don't verify header checksum if this packet
13421 			 * is coming back from AH/ESP as we already did it.
13422 			 */
13423 			if (sum != 0 && sum != 0xFFFF) {
13424 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13425 				goto error;
13426 			}
13427 		}
13428 		/*
13429 		 * Since there is no SCTP h/w cksum support yet, just
13430 		 * clear the flag.
13431 		 */
13432 		DB_CKSUMFLAGS(mp) = 0;
13433 	}
13434 
13435 	/*
13436 	 * Don't verify header checksum if this packet is coming
13437 	 * back from AH/ESP as we already did it.
13438 	 */
13439 	if (!mctl_present) {
13440 		UPDATE_IB_PKT_COUNT(ire);
13441 		ire->ire_last_used_time = lbolt;
13442 	}
13443 
13444 	/* packet part of fragmented IP packet? */
13445 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13446 	if (u1 & (IPH_MF | IPH_OFFSET))
13447 		goto fragmented;
13448 
13449 	/* u1 = IP header length (20 bytes) */
13450 	u1 = IP_SIMPLE_HDR_LENGTH;
13451 
13452 find_sctp_client:
13453 	/* Pullup if we don't have the sctp common header. */
13454 	len = MBLKL(mp);
13455 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13456 		if (mp->b_cont == NULL ||
13457 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13458 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13459 			goto error;
13460 		}
13461 		ipha = (ipha_t *)mp->b_rptr;
13462 		len = MBLKL(mp);
13463 	}
13464 
13465 	sctph = (sctp_hdr_t *)(rptr + u1);
13466 #ifdef	DEBUG
13467 	if (!skip_sctp_cksum) {
13468 #endif
13469 		pktsum = sctph->sh_chksum;
13470 		sctph->sh_chksum = 0;
13471 		calcsum = sctp_cksum(mp, u1);
13472 		if (calcsum != pktsum) {
13473 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13474 			goto error;
13475 		}
13476 		sctph->sh_chksum = pktsum;
13477 #ifdef	DEBUG	/* skip_sctp_cksum */
13478 	}
13479 #endif
13480 	/* get the ports */
13481 	ports = *(uint32_t *)&sctph->sh_sport;
13482 
13483 	IRE_REFRELE(ire);
13484 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13485 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13486 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13487 	    sctps)) == NULL) {
13488 		/* Check for raw socket or OOTB handling */
13489 		goto no_conn;
13490 	}
13491 
13492 	/* Found a client; up it goes */
13493 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13494 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13495 	return;
13496 
13497 no_conn:
13498 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13499 	    ports, mctl_present, flags, B_TRUE, zoneid);
13500 	return;
13501 
13502 ipoptions:
13503 	DB_CKSUMFLAGS(mp) = 0;
13504 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13505 		goto slow_done;
13506 
13507 	UPDATE_IB_PKT_COUNT(ire);
13508 	ire->ire_last_used_time = lbolt;
13509 
13510 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13511 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13512 fragmented:
13513 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13514 			goto slow_done;
13515 		/*
13516 		 * Make sure that first_mp points back to mp as
13517 		 * the mp we came in with could have changed in
13518 		 * ip_rput_fragment().
13519 		 */
13520 		ASSERT(!mctl_present);
13521 		ipha = (ipha_t *)mp->b_rptr;
13522 		first_mp = mp;
13523 	}
13524 
13525 	/* Now we have a complete datagram, destined for this machine. */
13526 	u1 = IPH_HDR_LENGTH(ipha);
13527 	goto find_sctp_client;
13528 #undef  iphs
13529 #undef  rptr
13530 
13531 error:
13532 	freemsg(first_mp);
13533 slow_done:
13534 	IRE_REFRELE(ire);
13535 }
13536 
13537 #define	VER_BITS	0xF0
13538 #define	VERSION_6	0x60
13539 
13540 static boolean_t
13541 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13542     ipaddr_t *dstp, ip_stack_t *ipst)
13543 {
13544 	uint_t	opt_len;
13545 	ipha_t *ipha;
13546 	ssize_t len;
13547 	uint_t	pkt_len;
13548 
13549 	ASSERT(ill != NULL);
13550 	IP_STAT(ipst, ip_ipoptions);
13551 	ipha = *iphapp;
13552 
13553 #define	rptr    ((uchar_t *)ipha)
13554 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13555 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13556 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13557 		freemsg(mp);
13558 		return (B_FALSE);
13559 	}
13560 
13561 	/* multiple mblk or too short */
13562 	pkt_len = ntohs(ipha->ipha_length);
13563 
13564 	/* Get the number of words of IP options in the IP header. */
13565 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13566 	if (opt_len) {
13567 		/* IP Options present!  Validate and process. */
13568 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13569 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13570 			goto done;
13571 		}
13572 		/*
13573 		 * Recompute complete header length and make sure we
13574 		 * have access to all of it.
13575 		 */
13576 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13577 		if (len > (mp->b_wptr - rptr)) {
13578 			if (len > pkt_len) {
13579 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13580 				goto done;
13581 			}
13582 			if (!pullupmsg(mp, len)) {
13583 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13584 				goto done;
13585 			}
13586 			ipha = (ipha_t *)mp->b_rptr;
13587 		}
13588 		/*
13589 		 * Go off to ip_rput_options which returns the next hop
13590 		 * destination address, which may have been affected
13591 		 * by source routing.
13592 		 */
13593 		IP_STAT(ipst, ip_opt);
13594 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13595 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13596 			return (B_FALSE);
13597 		}
13598 	}
13599 	*iphapp = ipha;
13600 	return (B_TRUE);
13601 done:
13602 	/* clear b_prev - used by ip_mroute_decap */
13603 	mp->b_prev = NULL;
13604 	freemsg(mp);
13605 	return (B_FALSE);
13606 #undef  rptr
13607 }
13608 
13609 /*
13610  * Deal with the fact that there is no ire for the destination.
13611  */
13612 static ire_t *
13613 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13614 {
13615 	ipha_t	*ipha;
13616 	ill_t	*ill;
13617 	ire_t	*ire;
13618 	boolean_t	check_multirt = B_FALSE;
13619 	ip_stack_t *ipst;
13620 
13621 	ipha = (ipha_t *)mp->b_rptr;
13622 	ill = (ill_t *)q->q_ptr;
13623 
13624 	ASSERT(ill != NULL);
13625 	ipst = ill->ill_ipst;
13626 
13627 	/*
13628 	 * No IRE for this destination, so it can't be for us.
13629 	 * Unless we are forwarding, drop the packet.
13630 	 * We have to let source routed packets through
13631 	 * since we don't yet know if they are 'ping -l'
13632 	 * packets i.e. if they will go out over the
13633 	 * same interface as they came in on.
13634 	 */
13635 	if (ll_multicast) {
13636 		freemsg(mp);
13637 		return (NULL);
13638 	}
13639 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13640 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13641 		freemsg(mp);
13642 		return (NULL);
13643 	}
13644 
13645 	/*
13646 	 * Mark this packet as having originated externally.
13647 	 *
13648 	 * For non-forwarding code path, ire_send later double
13649 	 * checks this interface to see if it is still exists
13650 	 * post-ARP resolution.
13651 	 *
13652 	 * Also, IPQOS uses this to differentiate between
13653 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13654 	 * QOS packet processing in ip_wput_attach_llhdr().
13655 	 * The QoS module can mark the b_band for a fastpath message
13656 	 * or the dl_priority field in a unitdata_req header for
13657 	 * CoS marking. This info can only be found in
13658 	 * ip_wput_attach_llhdr().
13659 	 */
13660 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13661 	/*
13662 	 * Clear the indication that this may have a hardware checksum
13663 	 * as we are not using it
13664 	 */
13665 	DB_CKSUMFLAGS(mp) = 0;
13666 
13667 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13668 	    MBLK_GETLABEL(mp), ipst);
13669 
13670 	if (ire == NULL && check_multirt) {
13671 		/* Let ip_newroute handle CGTP  */
13672 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13673 		return (NULL);
13674 	}
13675 
13676 	if (ire != NULL)
13677 		return (ire);
13678 
13679 	mp->b_prev = mp->b_next = 0;
13680 	/* send icmp unreachable */
13681 	q = WR(q);
13682 	/* Sent by forwarding path, and router is global zone */
13683 	if (ip_source_routed(ipha, ipst)) {
13684 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13685 		    GLOBAL_ZONEID, ipst);
13686 	} else {
13687 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13688 		    ipst);
13689 	}
13690 
13691 	return (NULL);
13692 
13693 }
13694 
13695 /*
13696  * check ip header length and align it.
13697  */
13698 static boolean_t
13699 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13700 {
13701 	ssize_t len;
13702 	ill_t *ill;
13703 	ipha_t	*ipha;
13704 
13705 	len = MBLKL(mp);
13706 
13707 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13708 		ill = (ill_t *)q->q_ptr;
13709 
13710 		if (!OK_32PTR(mp->b_rptr))
13711 			IP_STAT(ipst, ip_notaligned1);
13712 		else
13713 			IP_STAT(ipst, ip_notaligned2);
13714 		/* Guard against bogus device drivers */
13715 		if (len < 0) {
13716 			/* clear b_prev - used by ip_mroute_decap */
13717 			mp->b_prev = NULL;
13718 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13719 			freemsg(mp);
13720 			return (B_FALSE);
13721 		}
13722 
13723 		if (ip_rput_pullups++ == 0) {
13724 			ipha = (ipha_t *)mp->b_rptr;
13725 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13726 			    "ip_check_and_align_header: %s forced us to "
13727 			    " pullup pkt, hdr len %ld, hdr addr %p",
13728 			    ill->ill_name, len, ipha);
13729 		}
13730 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13731 			/* clear b_prev - used by ip_mroute_decap */
13732 			mp->b_prev = NULL;
13733 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13734 			freemsg(mp);
13735 			return (B_FALSE);
13736 		}
13737 	}
13738 	return (B_TRUE);
13739 }
13740 
13741 ire_t *
13742 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13743 {
13744 	ire_t		*new_ire;
13745 	ill_t		*ire_ill;
13746 	uint_t		ifindex;
13747 	ip_stack_t	*ipst = ill->ill_ipst;
13748 	boolean_t	strict_check = B_FALSE;
13749 
13750 	/*
13751 	 * This packet came in on an interface other than the one associated
13752 	 * with the first ire we found for the destination address. We do
13753 	 * another ire lookup here, using the ingress ill, to see if the
13754 	 * interface is in an interface group.
13755 	 * As long as the ills belong to the same group, we don't consider
13756 	 * them to be arriving on the wrong interface. Thus, if the switch
13757 	 * is doing inbound load spreading, we won't drop packets when the
13758 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13759 	 * for 'usesrc groups' where the destination address may belong to
13760 	 * another interface to allow multipathing to happen.
13761 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13762 	 * where the local address may not be unique. In this case we were
13763 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13764 	 * actually returned. The new lookup, which is more specific, should
13765 	 * only find the IRE_LOCAL associated with the ingress ill if one
13766 	 * exists.
13767 	 */
13768 
13769 	if (ire->ire_ipversion == IPV4_VERSION) {
13770 		if (ipst->ips_ip_strict_dst_multihoming)
13771 			strict_check = B_TRUE;
13772 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13773 		    ill->ill_ipif, ALL_ZONES, NULL,
13774 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13775 	} else {
13776 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13777 		if (ipst->ips_ipv6_strict_dst_multihoming)
13778 			strict_check = B_TRUE;
13779 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13780 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13781 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13782 	}
13783 	/*
13784 	 * If the same ire that was returned in ip_input() is found then this
13785 	 * is an indication that interface groups are in use. The packet
13786 	 * arrived on a different ill in the group than the one associated with
13787 	 * the destination address.  If a different ire was found then the same
13788 	 * IP address must be hosted on multiple ills. This is possible with
13789 	 * unnumbered point2point interfaces. We switch to use this new ire in
13790 	 * order to have accurate interface statistics.
13791 	 */
13792 	if (new_ire != NULL) {
13793 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13794 			ire_refrele(ire);
13795 			ire = new_ire;
13796 		} else {
13797 			ire_refrele(new_ire);
13798 		}
13799 		return (ire);
13800 	} else if ((ire->ire_rfq == NULL) &&
13801 	    (ire->ire_ipversion == IPV4_VERSION)) {
13802 		/*
13803 		 * The best match could have been the original ire which
13804 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13805 		 * the strict multihoming checks are irrelevant as we consider
13806 		 * local addresses hosted on lo0 to be interface agnostic. We
13807 		 * only expect a null ire_rfq on IREs which are associated with
13808 		 * lo0 hence we can return now.
13809 		 */
13810 		return (ire);
13811 	}
13812 
13813 	/*
13814 	 * Chase pointers once and store locally.
13815 	 */
13816 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13817 	    (ill_t *)(ire->ire_rfq->q_ptr);
13818 	ifindex = ill->ill_usesrc_ifindex;
13819 
13820 	/*
13821 	 * Check if it's a legal address on the 'usesrc' interface.
13822 	 */
13823 	if ((ifindex != 0) && (ire_ill != NULL) &&
13824 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13825 		return (ire);
13826 	}
13827 
13828 	/*
13829 	 * If the ip*_strict_dst_multihoming switch is on then we can
13830 	 * only accept this packet if the interface is marked as routing.
13831 	 */
13832 	if (!(strict_check))
13833 		return (ire);
13834 
13835 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13836 	    ILLF_ROUTER) != 0) {
13837 		return (ire);
13838 	}
13839 
13840 	ire_refrele(ire);
13841 	return (NULL);
13842 }
13843 
13844 ire_t *
13845 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13846 {
13847 	ipha_t	*ipha;
13848 	ipaddr_t ip_dst, ip_src;
13849 	ire_t	*src_ire = NULL;
13850 	ill_t	*stq_ill;
13851 	uint_t	hlen;
13852 	uint_t	pkt_len;
13853 	uint32_t sum;
13854 	queue_t	*dev_q;
13855 	boolean_t check_multirt = B_FALSE;
13856 	ip_stack_t *ipst = ill->ill_ipst;
13857 
13858 	ipha = (ipha_t *)mp->b_rptr;
13859 
13860 	/*
13861 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13862 	 * The loopback address check for both src and dst has already
13863 	 * been checked in ip_input
13864 	 */
13865 	ip_dst = ntohl(dst);
13866 	ip_src = ntohl(ipha->ipha_src);
13867 
13868 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13869 	    IN_CLASSD(ip_src)) {
13870 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13871 		goto drop;
13872 	}
13873 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13874 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13875 
13876 	if (src_ire != NULL) {
13877 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13878 		goto drop;
13879 	}
13880 
13881 
13882 	/* No ire cache of nexthop. So first create one  */
13883 	if (ire == NULL) {
13884 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13885 		/*
13886 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13887 		 * is not set. So upon return from ire_forward
13888 		 * check_multirt should remain as false.
13889 		 */
13890 		ASSERT(!check_multirt);
13891 		if (ire == NULL) {
13892 			/* An attempt was made to forward the packet */
13893 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13894 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13895 			mp->b_prev = mp->b_next = 0;
13896 			/* send icmp unreachable */
13897 			/* Sent by forwarding path, and router is global zone */
13898 			if (ip_source_routed(ipha, ipst)) {
13899 				icmp_unreachable(ill->ill_wq, mp,
13900 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13901 				    ipst);
13902 			} else {
13903 				icmp_unreachable(ill->ill_wq, mp,
13904 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13905 				    ipst);
13906 			}
13907 			return (ire);
13908 		}
13909 	}
13910 
13911 	/*
13912 	 * Forwarding fastpath exception case:
13913 	 * If either of the follwoing case is true, we take
13914 	 * the slowpath
13915 	 *	o forwarding is not enabled
13916 	 *	o incoming and outgoing interface are the same, or the same
13917 	 *	  IPMP group
13918 	 *	o corresponding ire is in incomplete state
13919 	 *	o packet needs fragmentation
13920 	 *
13921 	 * The codeflow from here on is thus:
13922 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13923 	 */
13924 	pkt_len = ntohs(ipha->ipha_length);
13925 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13926 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13927 	    !(ill->ill_flags & ILLF_ROUTER) ||
13928 	    (ill == stq_ill) ||
13929 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13930 	    (ire->ire_nce == NULL) ||
13931 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13932 	    (pkt_len > ire->ire_max_frag) ||
13933 	    ipha->ipha_ttl <= 1) {
13934 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13935 		    ipha, ill, B_FALSE);
13936 		return (ire);
13937 	}
13938 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13939 
13940 	DTRACE_PROBE4(ip4__forwarding__start,
13941 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13942 
13943 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13944 	    ipst->ips_ipv4firewall_forwarding,
13945 	    ill, stq_ill, ipha, mp, mp, ipst);
13946 
13947 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13948 
13949 	if (mp == NULL)
13950 		goto drop;
13951 
13952 	mp->b_datap->db_struioun.cksum.flags = 0;
13953 	/* Adjust the checksum to reflect the ttl decrement. */
13954 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13955 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13956 	ipha->ipha_ttl--;
13957 
13958 	dev_q = ire->ire_stq->q_next;
13959 	if ((dev_q->q_next != NULL ||
13960 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13961 		goto indiscard;
13962 	}
13963 
13964 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13965 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13966 
13967 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13968 		mblk_t *mpip = mp;
13969 
13970 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13971 		if (mp != NULL) {
13972 			DTRACE_PROBE4(ip4__physical__out__start,
13973 			    ill_t *, NULL, ill_t *, stq_ill,
13974 			    ipha_t *, ipha, mblk_t *, mp);
13975 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
13976 			    ipst->ips_ipv4firewall_physical_out,
13977 			    NULL, stq_ill, ipha, mp, mpip, ipst);
13978 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13979 			    mp);
13980 			if (mp == NULL)
13981 				goto drop;
13982 
13983 			UPDATE_IB_PKT_COUNT(ire);
13984 			ire->ire_last_used_time = lbolt;
13985 			BUMP_MIB(stq_ill->ill_ip_mib,
13986 			    ipIfStatsHCOutForwDatagrams);
13987 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13988 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
13989 			    pkt_len);
13990 			putnext(ire->ire_stq, mp);
13991 			return (ire);
13992 		}
13993 	}
13994 
13995 indiscard:
13996 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13997 drop:
13998 	if (mp != NULL)
13999 		freemsg(mp);
14000 	if (src_ire != NULL)
14001 		ire_refrele(src_ire);
14002 	return (ire);
14003 
14004 }
14005 
14006 /*
14007  * This function is called in the forwarding slowpath, when
14008  * either the ire lacks the link-layer address, or the packet needs
14009  * further processing(eg. fragmentation), before transmission.
14010  */
14011 
14012 static void
14013 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14014     ill_t *ill, boolean_t ll_multicast)
14015 {
14016 	ill_group_t	*ill_group;
14017 	ill_group_t	*ire_group;
14018 	queue_t		*dev_q;
14019 	ire_t		*src_ire;
14020 	ip_stack_t	*ipst = ill->ill_ipst;
14021 
14022 	ASSERT(ire->ire_stq != NULL);
14023 
14024 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14025 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14026 
14027 	if (ll_multicast != 0) {
14028 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14029 		goto drop_pkt;
14030 	}
14031 
14032 	/*
14033 	 * check if ipha_src is a broadcast address. Note that this
14034 	 * check is redundant when we get here from ip_fast_forward()
14035 	 * which has already done this check. However, since we can
14036 	 * also get here from ip_rput_process_broadcast() or, for
14037 	 * for the slow path through ip_fast_forward(), we perform
14038 	 * the check again for code-reusability
14039 	 */
14040 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14041 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14042 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14043 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14044 		if (src_ire != NULL)
14045 			ire_refrele(src_ire);
14046 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14047 		ip2dbg(("ip_rput_process_forward: Received packet with"
14048 		    " bad src/dst address on %s\n", ill->ill_name));
14049 		goto drop_pkt;
14050 	}
14051 
14052 	ill_group = ill->ill_group;
14053 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14054 	/*
14055 	 * Check if we want to forward this one at this time.
14056 	 * We allow source routed packets on a host provided that
14057 	 * they go out the same interface or same interface group
14058 	 * as they came in on.
14059 	 *
14060 	 * XXX To be quicker, we may wish to not chase pointers to
14061 	 * get the ILLF_ROUTER flag and instead store the
14062 	 * forwarding policy in the ire.  An unfortunate
14063 	 * side-effect of that would be requiring an ire flush
14064 	 * whenever the ILLF_ROUTER flag changes.
14065 	 */
14066 	if (((ill->ill_flags &
14067 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14068 	    ILLF_ROUTER) == 0) &&
14069 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14070 	    (ill_group != NULL && ill_group == ire_group)))) {
14071 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14072 		if (ip_source_routed(ipha, ipst)) {
14073 			q = WR(q);
14074 			/*
14075 			 * Clear the indication that this may have
14076 			 * hardware checksum as we are not using it.
14077 			 */
14078 			DB_CKSUMFLAGS(mp) = 0;
14079 			/* Sent by forwarding path, and router is global zone */
14080 			icmp_unreachable(q, mp,
14081 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14082 			return;
14083 		}
14084 		goto drop_pkt;
14085 	}
14086 
14087 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14088 
14089 	/* Packet is being forwarded. Turning off hwcksum flag. */
14090 	DB_CKSUMFLAGS(mp) = 0;
14091 	if (ipst->ips_ip_g_send_redirects) {
14092 		/*
14093 		 * Check whether the incoming interface and outgoing
14094 		 * interface is part of the same group. If so,
14095 		 * send redirects.
14096 		 *
14097 		 * Check the source address to see if it originated
14098 		 * on the same logical subnet it is going back out on.
14099 		 * If so, we should be able to send it a redirect.
14100 		 * Avoid sending a redirect if the destination
14101 		 * is directly connected (i.e., ipha_dst is the same
14102 		 * as ire_gateway_addr or the ire_addr of the
14103 		 * nexthop IRE_CACHE ), or if the packet was source
14104 		 * routed out this interface.
14105 		 */
14106 		ipaddr_t src, nhop;
14107 		mblk_t	*mp1;
14108 		ire_t	*nhop_ire = NULL;
14109 
14110 		/*
14111 		 * Check whether ire_rfq and q are from the same ill
14112 		 * or if they are not same, they at least belong
14113 		 * to the same group. If so, send redirects.
14114 		 */
14115 		if ((ire->ire_rfq == q ||
14116 		    (ill_group != NULL && ill_group == ire_group)) &&
14117 		    !ip_source_routed(ipha, ipst)) {
14118 
14119 			nhop = (ire->ire_gateway_addr != 0 ?
14120 			    ire->ire_gateway_addr : ire->ire_addr);
14121 
14122 			if (ipha->ipha_dst == nhop) {
14123 				/*
14124 				 * We avoid sending a redirect if the
14125 				 * destination is directly connected
14126 				 * because it is possible that multiple
14127 				 * IP subnets may have been configured on
14128 				 * the link, and the source may not
14129 				 * be on the same subnet as ip destination,
14130 				 * even though they are on the same
14131 				 * physical link.
14132 				 */
14133 				goto sendit;
14134 			}
14135 
14136 			src = ipha->ipha_src;
14137 
14138 			/*
14139 			 * We look up the interface ire for the nexthop,
14140 			 * to see if ipha_src is in the same subnet
14141 			 * as the nexthop.
14142 			 *
14143 			 * Note that, if, in the future, IRE_CACHE entries
14144 			 * are obsoleted,  this lookup will not be needed,
14145 			 * as the ire passed to this function will be the
14146 			 * same as the nhop_ire computed below.
14147 			 */
14148 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14149 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14150 			    0, NULL, MATCH_IRE_TYPE, ipst);
14151 
14152 			if (nhop_ire != NULL) {
14153 				if ((src & nhop_ire->ire_mask) ==
14154 				    (nhop & nhop_ire->ire_mask)) {
14155 					/*
14156 					 * The source is directly connected.
14157 					 * Just copy the ip header (which is
14158 					 * in the first mblk)
14159 					 */
14160 					mp1 = copyb(mp);
14161 					if (mp1 != NULL) {
14162 						icmp_send_redirect(WR(q), mp1,
14163 						    nhop, ipst);
14164 					}
14165 				}
14166 				ire_refrele(nhop_ire);
14167 			}
14168 		}
14169 	}
14170 sendit:
14171 	dev_q = ire->ire_stq->q_next;
14172 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14173 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14174 		freemsg(mp);
14175 		return;
14176 	}
14177 
14178 	ip_rput_forward(ire, ipha, mp, ill);
14179 	return;
14180 
14181 drop_pkt:
14182 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14183 	freemsg(mp);
14184 }
14185 
14186 ire_t *
14187 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14188     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14189 {
14190 	queue_t		*q;
14191 	uint16_t	hcksumflags;
14192 	ip_stack_t	*ipst = ill->ill_ipst;
14193 
14194 	q = *qp;
14195 
14196 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14197 
14198 	/*
14199 	 * Clear the indication that this may have hardware
14200 	 * checksum as we are not using it for forwarding.
14201 	 */
14202 	hcksumflags = DB_CKSUMFLAGS(mp);
14203 	DB_CKSUMFLAGS(mp) = 0;
14204 
14205 	/*
14206 	 * Directed broadcast forwarding: if the packet came in over a
14207 	 * different interface then it is routed out over we can forward it.
14208 	 */
14209 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14210 		ire_refrele(ire);
14211 		freemsg(mp);
14212 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14213 		return (NULL);
14214 	}
14215 	/*
14216 	 * For multicast we have set dst to be INADDR_BROADCAST
14217 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14218 	 * only for broadcast packets.
14219 	 */
14220 	if (!CLASSD(ipha->ipha_dst)) {
14221 		ire_t *new_ire;
14222 		ipif_t *ipif;
14223 		/*
14224 		 * For ill groups, as the switch duplicates broadcasts
14225 		 * across all the ports, we need to filter out and
14226 		 * send up only one copy. There is one copy for every
14227 		 * broadcast address on each ill. Thus, we look for a
14228 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14229 		 * later to see whether this ill is eligible to receive
14230 		 * them or not. ill_nominate_bcast_rcv() nominates only
14231 		 * one set of IREs for receiving.
14232 		 */
14233 
14234 		ipif = ipif_get_next_ipif(NULL, ill);
14235 		if (ipif == NULL) {
14236 			ire_refrele(ire);
14237 			freemsg(mp);
14238 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14239 			return (NULL);
14240 		}
14241 		new_ire = ire_ctable_lookup(dst, 0, 0,
14242 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14243 		ipif_refrele(ipif);
14244 
14245 		if (new_ire != NULL) {
14246 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14247 				ire_refrele(ire);
14248 				ire_refrele(new_ire);
14249 				freemsg(mp);
14250 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14251 				return (NULL);
14252 			}
14253 			/*
14254 			 * In the special case of multirouted broadcast
14255 			 * packets, we unconditionally need to "gateway"
14256 			 * them to the appropriate interface here.
14257 			 * In the normal case, this cannot happen, because
14258 			 * there is no broadcast IRE tagged with the
14259 			 * RTF_MULTIRT flag.
14260 			 */
14261 			if (new_ire->ire_flags & RTF_MULTIRT) {
14262 				ire_refrele(new_ire);
14263 				if (ire->ire_rfq != NULL) {
14264 					q = ire->ire_rfq;
14265 					*qp = q;
14266 				}
14267 			} else {
14268 				ire_refrele(ire);
14269 				ire = new_ire;
14270 			}
14271 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14272 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14273 				/*
14274 				 * Free the message if
14275 				 * ip_g_forward_directed_bcast is turned
14276 				 * off for non-local broadcast.
14277 				 */
14278 				ire_refrele(ire);
14279 				freemsg(mp);
14280 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14281 				return (NULL);
14282 			}
14283 		} else {
14284 			/*
14285 			 * This CGTP packet successfully passed the
14286 			 * CGTP filter, but the related CGTP
14287 			 * broadcast IRE has not been found,
14288 			 * meaning that the redundant ipif is
14289 			 * probably down. However, if we discarded
14290 			 * this packet, its duplicate would be
14291 			 * filtered out by the CGTP filter so none
14292 			 * of them would get through. So we keep
14293 			 * going with this one.
14294 			 */
14295 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14296 			if (ire->ire_rfq != NULL) {
14297 				q = ire->ire_rfq;
14298 				*qp = q;
14299 			}
14300 		}
14301 	}
14302 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14303 		/*
14304 		 * Verify that there are not more then one
14305 		 * IRE_BROADCAST with this broadcast address which
14306 		 * has ire_stq set.
14307 		 * TODO: simplify, loop over all IRE's
14308 		 */
14309 		ire_t	*ire1;
14310 		int	num_stq = 0;
14311 		mblk_t	*mp1;
14312 
14313 		/* Find the first one with ire_stq set */
14314 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14315 		for (ire1 = ire; ire1 &&
14316 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14317 		    ire1 = ire1->ire_next)
14318 			;
14319 		if (ire1) {
14320 			ire_refrele(ire);
14321 			ire = ire1;
14322 			IRE_REFHOLD(ire);
14323 		}
14324 
14325 		/* Check if there are additional ones with stq set */
14326 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14327 			if (ire->ire_addr != ire1->ire_addr)
14328 				break;
14329 			if (ire1->ire_stq) {
14330 				num_stq++;
14331 				break;
14332 			}
14333 		}
14334 		rw_exit(&ire->ire_bucket->irb_lock);
14335 		if (num_stq == 1 && ire->ire_stq != NULL) {
14336 			ip1dbg(("ip_rput_process_broadcast: directed "
14337 			    "broadcast to 0x%x\n",
14338 			    ntohl(ire->ire_addr)));
14339 			mp1 = copymsg(mp);
14340 			if (mp1) {
14341 				switch (ipha->ipha_protocol) {
14342 				case IPPROTO_UDP:
14343 					ip_udp_input(q, mp1, ipha, ire, ill);
14344 					break;
14345 				default:
14346 					ip_proto_input(q, mp1, ipha, ire, ill,
14347 					    B_FALSE);
14348 					break;
14349 				}
14350 			}
14351 			/*
14352 			 * Adjust ttl to 2 (1+1 - the forward engine
14353 			 * will decrement it by one.
14354 			 */
14355 			if (ip_csum_hdr(ipha)) {
14356 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14357 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14358 				freemsg(mp);
14359 				ire_refrele(ire);
14360 				return (NULL);
14361 			}
14362 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14363 			ipha->ipha_hdr_checksum = 0;
14364 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14365 			ip_rput_process_forward(q, mp, ire, ipha,
14366 			    ill, ll_multicast);
14367 			ire_refrele(ire);
14368 			return (NULL);
14369 		}
14370 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14371 		    ntohl(ire->ire_addr)));
14372 	}
14373 
14374 
14375 	/* Restore any hardware checksum flags */
14376 	DB_CKSUMFLAGS(mp) = hcksumflags;
14377 	return (ire);
14378 }
14379 
14380 /* ARGSUSED */
14381 static boolean_t
14382 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14383     int *ll_multicast, ipaddr_t *dstp)
14384 {
14385 	ip_stack_t	*ipst = ill->ill_ipst;
14386 
14387 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14388 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14389 	    ntohs(ipha->ipha_length));
14390 
14391 	/*
14392 	 * Forward packets only if we have joined the allmulti
14393 	 * group on this interface.
14394 	 */
14395 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14396 		int retval;
14397 
14398 		/*
14399 		 * Clear the indication that this may have hardware
14400 		 * checksum as we are not using it.
14401 		 */
14402 		DB_CKSUMFLAGS(mp) = 0;
14403 		retval = ip_mforward(ill, ipha, mp);
14404 		/* ip_mforward updates mib variables if needed */
14405 		/* clear b_prev - used by ip_mroute_decap */
14406 		mp->b_prev = NULL;
14407 
14408 		switch (retval) {
14409 		case 0:
14410 			/*
14411 			 * pkt is okay and arrived on phyint.
14412 			 *
14413 			 * If we are running as a multicast router
14414 			 * we need to see all IGMP and/or PIM packets.
14415 			 */
14416 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14417 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14418 				goto done;
14419 			}
14420 			break;
14421 		case -1:
14422 			/* pkt is mal-formed, toss it */
14423 			goto drop_pkt;
14424 		case 1:
14425 			/* pkt is okay and arrived on a tunnel */
14426 			/*
14427 			 * If we are running a multicast router
14428 			 *  we need to see all igmp packets.
14429 			 */
14430 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14431 				*dstp = INADDR_BROADCAST;
14432 				*ll_multicast = 1;
14433 				return (B_FALSE);
14434 			}
14435 
14436 			goto drop_pkt;
14437 		}
14438 	}
14439 
14440 	ILM_WALKER_HOLD(ill);
14441 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14442 		/*
14443 		 * This might just be caused by the fact that
14444 		 * multiple IP Multicast addresses map to the same
14445 		 * link layer multicast - no need to increment counter!
14446 		 */
14447 		ILM_WALKER_RELE(ill);
14448 		freemsg(mp);
14449 		return (B_TRUE);
14450 	}
14451 	ILM_WALKER_RELE(ill);
14452 done:
14453 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14454 	/*
14455 	 * This assumes the we deliver to all streams for multicast
14456 	 * and broadcast packets.
14457 	 */
14458 	*dstp = INADDR_BROADCAST;
14459 	*ll_multicast = 1;
14460 	return (B_FALSE);
14461 drop_pkt:
14462 	ip2dbg(("ip_rput: drop pkt\n"));
14463 	freemsg(mp);
14464 	return (B_TRUE);
14465 }
14466 
14467 static boolean_t
14468 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14469     int *ll_multicast, mblk_t **mpp)
14470 {
14471 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14472 	boolean_t must_copy = B_FALSE;
14473 	struct iocblk   *iocp;
14474 	ipha_t		*ipha;
14475 	ip_stack_t	*ipst = ill->ill_ipst;
14476 
14477 #define	rptr    ((uchar_t *)ipha)
14478 
14479 	first_mp = *first_mpp;
14480 	mp = *mpp;
14481 
14482 	ASSERT(first_mp == mp);
14483 
14484 	/*
14485 	 * if db_ref > 1 then copymsg and free original. Packet may be
14486 	 * changed and do not want other entity who has a reference to this
14487 	 * message to trip over the changes. This is a blind change because
14488 	 * trying to catch all places that might change packet is too
14489 	 * difficult (since it may be a module above this one)
14490 	 *
14491 	 * This corresponds to the non-fast path case. We walk down the full
14492 	 * chain in this case, and check the db_ref count of all the dblks,
14493 	 * and do a copymsg if required. It is possible that the db_ref counts
14494 	 * of the data blocks in the mblk chain can be different.
14495 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14496 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14497 	 * 'snoop' is running.
14498 	 */
14499 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14500 		if (mp1->b_datap->db_ref > 1) {
14501 			must_copy = B_TRUE;
14502 			break;
14503 		}
14504 	}
14505 
14506 	if (must_copy) {
14507 		mp1 = copymsg(mp);
14508 		if (mp1 == NULL) {
14509 			for (mp1 = mp; mp1 != NULL;
14510 			    mp1 = mp1->b_cont) {
14511 				mp1->b_next = NULL;
14512 				mp1->b_prev = NULL;
14513 			}
14514 			freemsg(mp);
14515 			if (ill != NULL) {
14516 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14517 			} else {
14518 				BUMP_MIB(&ipst->ips_ip_mib,
14519 				    ipIfStatsInDiscards);
14520 			}
14521 			return (B_TRUE);
14522 		}
14523 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14524 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14525 			/* Copy b_prev - used by ip_mroute_decap */
14526 			to_mp->b_prev = from_mp->b_prev;
14527 			from_mp->b_prev = NULL;
14528 		}
14529 		*first_mpp = first_mp = mp1;
14530 		freemsg(mp);
14531 		mp = mp1;
14532 		*mpp = mp1;
14533 	}
14534 
14535 	ipha = (ipha_t *)mp->b_rptr;
14536 
14537 	/*
14538 	 * previous code has a case for M_DATA.
14539 	 * We want to check how that happens.
14540 	 */
14541 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14542 	switch (first_mp->b_datap->db_type) {
14543 	case M_PROTO:
14544 	case M_PCPROTO:
14545 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14546 		    DL_UNITDATA_IND) {
14547 			/* Go handle anything other than data elsewhere. */
14548 			ip_rput_dlpi(q, mp);
14549 			return (B_TRUE);
14550 		}
14551 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14552 		/* Ditch the DLPI header. */
14553 		mp1 = mp->b_cont;
14554 		ASSERT(first_mp == mp);
14555 		*first_mpp = mp1;
14556 		freeb(mp);
14557 		*mpp = mp1;
14558 		return (B_FALSE);
14559 	case M_IOCACK:
14560 		ip1dbg(("got iocack "));
14561 		iocp = (struct iocblk *)mp->b_rptr;
14562 		switch (iocp->ioc_cmd) {
14563 		case DL_IOC_HDR_INFO:
14564 			ill = (ill_t *)q->q_ptr;
14565 			ill_fastpath_ack(ill, mp);
14566 			return (B_TRUE);
14567 		case SIOCSTUNPARAM:
14568 		case OSIOCSTUNPARAM:
14569 			/* Go through qwriter_ip */
14570 			break;
14571 		case SIOCGTUNPARAM:
14572 		case OSIOCGTUNPARAM:
14573 			ip_rput_other(NULL, q, mp, NULL);
14574 			return (B_TRUE);
14575 		default:
14576 			putnext(q, mp);
14577 			return (B_TRUE);
14578 		}
14579 		/* FALLTHRU */
14580 	case M_ERROR:
14581 	case M_HANGUP:
14582 		/*
14583 		 * Since this is on the ill stream we unconditionally
14584 		 * bump up the refcount
14585 		 */
14586 		ill_refhold(ill);
14587 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14588 		return (B_TRUE);
14589 	case M_CTL:
14590 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14591 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14592 		    IPHADA_M_CTL)) {
14593 			/*
14594 			 * It's an IPsec accelerated packet.
14595 			 * Make sure that the ill from which we received the
14596 			 * packet has enabled IPsec hardware acceleration.
14597 			 */
14598 			if (!(ill->ill_capabilities &
14599 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14600 				/* IPsec kstats: bean counter */
14601 				freemsg(mp);
14602 				return (B_TRUE);
14603 			}
14604 
14605 			/*
14606 			 * Make mp point to the mblk following the M_CTL,
14607 			 * then process according to type of mp.
14608 			 * After this processing, first_mp will point to
14609 			 * the data-attributes and mp to the pkt following
14610 			 * the M_CTL.
14611 			 */
14612 			mp = first_mp->b_cont;
14613 			if (mp == NULL) {
14614 				freemsg(first_mp);
14615 				return (B_TRUE);
14616 			}
14617 			/*
14618 			 * A Hardware Accelerated packet can only be M_DATA
14619 			 * ESP or AH packet.
14620 			 */
14621 			if (mp->b_datap->db_type != M_DATA) {
14622 				/* non-M_DATA IPsec accelerated packet */
14623 				IPSECHW_DEBUG(IPSECHW_PKT,
14624 				    ("non-M_DATA IPsec accelerated pkt\n"));
14625 				freemsg(first_mp);
14626 				return (B_TRUE);
14627 			}
14628 			ipha = (ipha_t *)mp->b_rptr;
14629 			if (ipha->ipha_protocol != IPPROTO_AH &&
14630 			    ipha->ipha_protocol != IPPROTO_ESP) {
14631 				IPSECHW_DEBUG(IPSECHW_PKT,
14632 				    ("non-M_DATA IPsec accelerated pkt\n"));
14633 				freemsg(first_mp);
14634 				return (B_TRUE);
14635 			}
14636 			*mpp = mp;
14637 			return (B_FALSE);
14638 		}
14639 		putnext(q, mp);
14640 		return (B_TRUE);
14641 	case M_IOCNAK:
14642 		ip1dbg(("got iocnak "));
14643 		iocp = (struct iocblk *)mp->b_rptr;
14644 		switch (iocp->ioc_cmd) {
14645 		case SIOCSTUNPARAM:
14646 		case OSIOCSTUNPARAM:
14647 			/*
14648 			 * Since this is on the ill stream we unconditionally
14649 			 * bump up the refcount
14650 			 */
14651 			ill_refhold(ill);
14652 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14653 			return (B_TRUE);
14654 		case DL_IOC_HDR_INFO:
14655 		case SIOCGTUNPARAM:
14656 		case OSIOCGTUNPARAM:
14657 			ip_rput_other(NULL, q, mp, NULL);
14658 			return (B_TRUE);
14659 		default:
14660 			break;
14661 		}
14662 		/* FALLTHRU */
14663 	default:
14664 		putnext(q, mp);
14665 		return (B_TRUE);
14666 	}
14667 }
14668 
14669 /* Read side put procedure.  Packets coming from the wire arrive here. */
14670 void
14671 ip_rput(queue_t *q, mblk_t *mp)
14672 {
14673 	ill_t	*ill;
14674 	union DL_primitives *dl;
14675 
14676 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14677 
14678 	ill = (ill_t *)q->q_ptr;
14679 
14680 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14681 		/*
14682 		 * If things are opening or closing, only accept high-priority
14683 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14684 		 * created; on close, things hanging off the ill may have been
14685 		 * freed already.)
14686 		 */
14687 		dl = (union DL_primitives *)mp->b_rptr;
14688 		if (DB_TYPE(mp) != M_PCPROTO ||
14689 		    dl->dl_primitive == DL_UNITDATA_IND) {
14690 			/*
14691 			 * SIOC[GS]TUNPARAM ioctls can come here.
14692 			 */
14693 			inet_freemsg(mp);
14694 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14695 			    "ip_rput_end: q %p (%S)", q, "uninit");
14696 			return;
14697 		}
14698 	}
14699 
14700 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14701 	    "ip_rput_end: q %p (%S)", q, "end");
14702 
14703 	ip_input(ill, NULL, mp, NULL);
14704 }
14705 
14706 static mblk_t *
14707 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14708 {
14709 	mblk_t *mp1;
14710 	boolean_t adjusted = B_FALSE;
14711 	ip_stack_t *ipst = ill->ill_ipst;
14712 
14713 	IP_STAT(ipst, ip_db_ref);
14714 	/*
14715 	 * The IP_RECVSLLA option depends on having the
14716 	 * link layer header. First check that:
14717 	 * a> the underlying device is of type ether,
14718 	 * since this option is currently supported only
14719 	 * over ethernet.
14720 	 * b> there is enough room to copy over the link
14721 	 * layer header.
14722 	 *
14723 	 * Once the checks are done, adjust rptr so that
14724 	 * the link layer header will be copied via
14725 	 * copymsg. Note that, IFT_ETHER may be returned
14726 	 * by some non-ethernet drivers but in this case
14727 	 * the second check will fail.
14728 	 */
14729 	if (ill->ill_type == IFT_ETHER &&
14730 	    (mp->b_rptr - mp->b_datap->db_base) >=
14731 	    sizeof (struct ether_header)) {
14732 		mp->b_rptr -= sizeof (struct ether_header);
14733 		adjusted = B_TRUE;
14734 	}
14735 	mp1 = copymsg(mp);
14736 
14737 	if (mp1 == NULL) {
14738 		mp->b_next = NULL;
14739 		/* clear b_prev - used by ip_mroute_decap */
14740 		mp->b_prev = NULL;
14741 		freemsg(mp);
14742 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14743 		return (NULL);
14744 	}
14745 
14746 	if (adjusted) {
14747 		/*
14748 		 * Copy is done. Restore the pointer in
14749 		 * the _new_ mblk
14750 		 */
14751 		mp1->b_rptr += sizeof (struct ether_header);
14752 	}
14753 
14754 	/* Copy b_prev - used by ip_mroute_decap */
14755 	mp1->b_prev = mp->b_prev;
14756 	mp->b_prev = NULL;
14757 
14758 	/* preserve the hardware checksum flags and data, if present */
14759 	if (DB_CKSUMFLAGS(mp) != 0) {
14760 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14761 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14762 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14763 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14764 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14765 	}
14766 
14767 	freemsg(mp);
14768 	return (mp1);
14769 }
14770 
14771 /*
14772  * Direct read side procedure capable of dealing with chains. GLDv3 based
14773  * drivers call this function directly with mblk chains while STREAMS
14774  * read side procedure ip_rput() calls this for single packet with ip_ring
14775  * set to NULL to process one packet at a time.
14776  *
14777  * The ill will always be valid if this function is called directly from
14778  * the driver.
14779  *
14780  * If ip_input() is called from GLDv3:
14781  *
14782  *   - This must be a non-VLAN IP stream.
14783  *   - 'mp' is either an untagged or a special priority-tagged packet.
14784  *   - Any VLAN tag that was in the MAC header has been stripped.
14785  *
14786  * If the IP header in packet is not 32-bit aligned, every message in the
14787  * chain will be aligned before further operations. This is required on SPARC
14788  * platform.
14789  */
14790 /* ARGSUSED */
14791 void
14792 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14793     struct mac_header_info_s *mhip)
14794 {
14795 	ipaddr_t		dst = NULL;
14796 	ipaddr_t		prev_dst;
14797 	ire_t			*ire = NULL;
14798 	ipha_t			*ipha;
14799 	uint_t			pkt_len;
14800 	ssize_t			len;
14801 	uint_t			opt_len;
14802 	int			ll_multicast;
14803 	int			cgtp_flt_pkt;
14804 	queue_t			*q = ill->ill_rq;
14805 	squeue_t		*curr_sqp = NULL;
14806 	mblk_t 			*head = NULL;
14807 	mblk_t			*tail = NULL;
14808 	mblk_t			*first_mp;
14809 	mblk_t 			*mp;
14810 	mblk_t			*dmp;
14811 	int			cnt = 0;
14812 	ip_stack_t		*ipst = ill->ill_ipst;
14813 
14814 	ASSERT(mp_chain != NULL);
14815 	ASSERT(ill != NULL);
14816 
14817 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14818 
14819 #define	rptr	((uchar_t *)ipha)
14820 
14821 	while (mp_chain != NULL) {
14822 		first_mp = mp = mp_chain;
14823 		mp_chain = mp_chain->b_next;
14824 		mp->b_next = NULL;
14825 		ll_multicast = 0;
14826 
14827 		/*
14828 		 * We do ire caching from one iteration to
14829 		 * another. In the event the packet chain contains
14830 		 * all packets from the same dst, this caching saves
14831 		 * an ire_cache_lookup for each of the succeeding
14832 		 * packets in a packet chain.
14833 		 */
14834 		prev_dst = dst;
14835 
14836 		/*
14837 		 * if db_ref > 1 then copymsg and free original. Packet
14838 		 * may be changed and we do not want the other entity
14839 		 * who has a reference to this message to trip over the
14840 		 * changes. This is a blind change because trying to
14841 		 * catch all places that might change the packet is too
14842 		 * difficult.
14843 		 *
14844 		 * This corresponds to the fast path case, where we have
14845 		 * a chain of M_DATA mblks.  We check the db_ref count
14846 		 * of only the 1st data block in the mblk chain. There
14847 		 * doesn't seem to be a reason why a device driver would
14848 		 * send up data with varying db_ref counts in the mblk
14849 		 * chain. In any case the Fast path is a private
14850 		 * interface, and our drivers don't do such a thing.
14851 		 * Given the above assumption, there is no need to walk
14852 		 * down the entire mblk chain (which could have a
14853 		 * potential performance problem)
14854 		 */
14855 
14856 		if (DB_REF(mp) > 1) {
14857 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14858 				continue;
14859 		}
14860 
14861 		/*
14862 		 * Check and align the IP header.
14863 		 */
14864 		first_mp = mp;
14865 		if (DB_TYPE(mp) == M_DATA) {
14866 			dmp = mp;
14867 		} else if (DB_TYPE(mp) == M_PROTO &&
14868 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14869 			dmp = mp->b_cont;
14870 		} else {
14871 			dmp = NULL;
14872 		}
14873 		if (dmp != NULL) {
14874 			/*
14875 			 * IP header ptr not aligned?
14876 			 * OR IP header not complete in first mblk
14877 			 */
14878 			if (!OK_32PTR(dmp->b_rptr) ||
14879 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14880 				if (!ip_check_and_align_header(q, dmp, ipst))
14881 					continue;
14882 			}
14883 		}
14884 
14885 		/*
14886 		 * ip_input fast path
14887 		 */
14888 
14889 		/* mblk type is not M_DATA */
14890 		if (DB_TYPE(mp) != M_DATA) {
14891 			if (ip_rput_process_notdata(q, &first_mp, ill,
14892 			    &ll_multicast, &mp))
14893 				continue;
14894 		}
14895 
14896 		/* Make sure its an M_DATA and that its aligned */
14897 		ASSERT(DB_TYPE(mp) == M_DATA);
14898 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14899 
14900 		ipha = (ipha_t *)mp->b_rptr;
14901 		len = mp->b_wptr - rptr;
14902 		pkt_len = ntohs(ipha->ipha_length);
14903 
14904 		/*
14905 		 * We must count all incoming packets, even if they end
14906 		 * up being dropped later on.
14907 		 */
14908 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14909 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14910 
14911 		/* multiple mblk or too short */
14912 		len -= pkt_len;
14913 		if (len != 0) {
14914 			/*
14915 			 * Make sure we have data length consistent
14916 			 * with the IP header.
14917 			 */
14918 			if (mp->b_cont == NULL) {
14919 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14920 					BUMP_MIB(ill->ill_ip_mib,
14921 					    ipIfStatsInHdrErrors);
14922 					ip2dbg(("ip_input: drop pkt\n"));
14923 					freemsg(mp);
14924 					continue;
14925 				}
14926 				mp->b_wptr = rptr + pkt_len;
14927 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14928 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14929 					BUMP_MIB(ill->ill_ip_mib,
14930 					    ipIfStatsInHdrErrors);
14931 					ip2dbg(("ip_input: drop pkt\n"));
14932 					freemsg(mp);
14933 					continue;
14934 				}
14935 				(void) adjmsg(mp, -len);
14936 				IP_STAT(ipst, ip_multimblk3);
14937 			}
14938 		}
14939 
14940 		/* Obtain the dst of the current packet */
14941 		dst = ipha->ipha_dst;
14942 
14943 		if (IP_LOOPBACK_ADDR(dst) ||
14944 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14945 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14946 			cmn_err(CE_CONT, "dst %X src %X\n",
14947 			    dst, ipha->ipha_src);
14948 			freemsg(mp);
14949 			continue;
14950 		}
14951 
14952 		/*
14953 		 * The event for packets being received from a 'physical'
14954 		 * interface is placed after validation of the source and/or
14955 		 * destination address as being local so that packets can be
14956 		 * redirected to loopback addresses using ipnat.
14957 		 */
14958 		DTRACE_PROBE4(ip4__physical__in__start,
14959 		    ill_t *, ill, ill_t *, NULL,
14960 		    ipha_t *, ipha, mblk_t *, first_mp);
14961 
14962 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14963 		    ipst->ips_ipv4firewall_physical_in,
14964 		    ill, NULL, ipha, first_mp, mp, ipst);
14965 
14966 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14967 
14968 		if (first_mp == NULL) {
14969 			continue;
14970 		}
14971 		dst = ipha->ipha_dst;
14972 
14973 		/*
14974 		 * Attach any necessary label information to
14975 		 * this packet
14976 		 */
14977 		if (is_system_labeled() &&
14978 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14979 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14980 			freemsg(mp);
14981 			continue;
14982 		}
14983 
14984 		/*
14985 		 * Reuse the cached ire only if the ipha_dst of the previous
14986 		 * packet is the same as the current packet AND it is not
14987 		 * INADDR_ANY.
14988 		 */
14989 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14990 		    (ire != NULL)) {
14991 			ire_refrele(ire);
14992 			ire = NULL;
14993 		}
14994 		opt_len = ipha->ipha_version_and_hdr_length -
14995 		    IP_SIMPLE_HDR_VERSION;
14996 
14997 		/*
14998 		 * Check to see if we can take the fastpath.
14999 		 * That is possible if the following conditions are met
15000 		 *	o Tsol disabled
15001 		 *	o CGTP disabled
15002 		 *	o ipp_action_count is 0
15003 		 *	o no options in the packet
15004 		 *	o not a RSVP packet
15005 		 * 	o not a multicast packet
15006 		 */
15007 		if (!is_system_labeled() &&
15008 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15009 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15010 		    !ll_multicast && !CLASSD(dst)) {
15011 			if (ire == NULL)
15012 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15013 				    ipst);
15014 
15015 			/* incoming packet is for forwarding */
15016 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15017 				ire = ip_fast_forward(ire, dst, ill, mp);
15018 				continue;
15019 			}
15020 			/* incoming packet is for local consumption */
15021 			if (ire->ire_type & IRE_LOCAL)
15022 				goto local;
15023 		}
15024 
15025 		/*
15026 		 * Disable ire caching for anything more complex
15027 		 * than the simple fast path case we checked for above.
15028 		 */
15029 		if (ire != NULL) {
15030 			ire_refrele(ire);
15031 			ire = NULL;
15032 		}
15033 
15034 		/* Full-blown slow path */
15035 		if (opt_len != 0) {
15036 			if (len != 0)
15037 				IP_STAT(ipst, ip_multimblk4);
15038 			else
15039 				IP_STAT(ipst, ip_ipoptions);
15040 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15041 			    &dst, ipst))
15042 				continue;
15043 		}
15044 
15045 		/*
15046 		 * Invoke the CGTP (multirouting) filtering module to process
15047 		 * the incoming packet. Packets identified as duplicates
15048 		 * must be discarded. Filtering is active only if the
15049 		 * the ip_cgtp_filter ndd variable is non-zero.
15050 		 */
15051 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15052 		if (ipst->ips_ip_cgtp_filter &&
15053 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15054 			netstackid_t stackid;
15055 
15056 			stackid = ipst->ips_netstack->netstack_stackid;
15057 			cgtp_flt_pkt =
15058 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15059 			    ill->ill_phyint->phyint_ifindex, mp);
15060 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15061 				freemsg(first_mp);
15062 				continue;
15063 			}
15064 		}
15065 
15066 		/*
15067 		 * If rsvpd is running, let RSVP daemon handle its processing
15068 		 * and forwarding of RSVP multicast/unicast packets.
15069 		 * If rsvpd is not running but mrouted is running, RSVP
15070 		 * multicast packets are forwarded as multicast traffic
15071 		 * and RSVP unicast packets are forwarded by unicast router.
15072 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15073 		 * packets are not forwarded, but the unicast packets are
15074 		 * forwarded like unicast traffic.
15075 		 */
15076 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15077 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15078 		    NULL) {
15079 			/* RSVP packet and rsvpd running. Treat as ours */
15080 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15081 			/*
15082 			 * This assumes that we deliver to all streams for
15083 			 * multicast and broadcast packets.
15084 			 * We have to force ll_multicast to 1 to handle the
15085 			 * M_DATA messages passed in from ip_mroute_decap.
15086 			 */
15087 			dst = INADDR_BROADCAST;
15088 			ll_multicast = 1;
15089 		} else if (CLASSD(dst)) {
15090 			/* packet is multicast */
15091 			mp->b_next = NULL;
15092 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15093 			    &ll_multicast, &dst))
15094 				continue;
15095 		}
15096 
15097 		if (ire == NULL) {
15098 			ire = ire_cache_lookup(dst, ALL_ZONES,
15099 			    MBLK_GETLABEL(mp), ipst);
15100 		}
15101 
15102 		if (ire == NULL) {
15103 			/*
15104 			 * No IRE for this destination, so it can't be for us.
15105 			 * Unless we are forwarding, drop the packet.
15106 			 * We have to let source routed packets through
15107 			 * since we don't yet know if they are 'ping -l'
15108 			 * packets i.e. if they will go out over the
15109 			 * same interface as they came in on.
15110 			 */
15111 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15112 			if (ire == NULL)
15113 				continue;
15114 		}
15115 
15116 		/*
15117 		 * Broadcast IRE may indicate either broadcast or
15118 		 * multicast packet
15119 		 */
15120 		if (ire->ire_type == IRE_BROADCAST) {
15121 			/*
15122 			 * Skip broadcast checks if packet is UDP multicast;
15123 			 * we'd rather not enter ip_rput_process_broadcast()
15124 			 * unless the packet is broadcast for real, since
15125 			 * that routine is a no-op for multicast.
15126 			 */
15127 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15128 			    !CLASSD(ipha->ipha_dst)) {
15129 				ire = ip_rput_process_broadcast(&q, mp,
15130 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15131 				    ll_multicast);
15132 				if (ire == NULL)
15133 					continue;
15134 			}
15135 		} else if (ire->ire_stq != NULL) {
15136 			/* fowarding? */
15137 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15138 			    ll_multicast);
15139 			/* ip_rput_process_forward consumed the packet */
15140 			continue;
15141 		}
15142 
15143 local:
15144 		/*
15145 		 * If the queue in the ire is different to the ingress queue
15146 		 * then we need to check to see if we can accept the packet.
15147 		 * Note that for multicast packets and broadcast packets sent
15148 		 * to a broadcast address which is shared between multiple
15149 		 * interfaces we should not do this since we just got a random
15150 		 * broadcast ire.
15151 		 */
15152 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15153 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15154 			    ill)) == NULL) {
15155 				/* Drop packet */
15156 				BUMP_MIB(ill->ill_ip_mib,
15157 				    ipIfStatsForwProhibits);
15158 				freemsg(mp);
15159 				continue;
15160 			}
15161 			if (ire->ire_rfq != NULL)
15162 				q = ire->ire_rfq;
15163 		}
15164 
15165 		switch (ipha->ipha_protocol) {
15166 		case IPPROTO_TCP:
15167 			ASSERT(first_mp == mp);
15168 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15169 			    mp, 0, q, ip_ring)) != NULL) {
15170 				if (curr_sqp == NULL) {
15171 					curr_sqp = GET_SQUEUE(mp);
15172 					ASSERT(cnt == 0);
15173 					cnt++;
15174 					head = tail = mp;
15175 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15176 					ASSERT(tail != NULL);
15177 					cnt++;
15178 					tail->b_next = mp;
15179 					tail = mp;
15180 				} else {
15181 					/*
15182 					 * A different squeue. Send the
15183 					 * chain for the previous squeue on
15184 					 * its way. This shouldn't happen
15185 					 * often unless interrupt binding
15186 					 * changes.
15187 					 */
15188 					IP_STAT(ipst, ip_input_multi_squeue);
15189 					squeue_enter_chain(curr_sqp, head,
15190 					    tail, cnt, SQTAG_IP_INPUT);
15191 					curr_sqp = GET_SQUEUE(mp);
15192 					head = mp;
15193 					tail = mp;
15194 					cnt = 1;
15195 				}
15196 			}
15197 			continue;
15198 		case IPPROTO_UDP:
15199 			ASSERT(first_mp == mp);
15200 			ip_udp_input(q, mp, ipha, ire, ill);
15201 			continue;
15202 		case IPPROTO_SCTP:
15203 			ASSERT(first_mp == mp);
15204 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15205 			    q, dst);
15206 			/* ire has been released by ip_sctp_input */
15207 			ire = NULL;
15208 			continue;
15209 		default:
15210 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15211 			continue;
15212 		}
15213 	}
15214 
15215 	if (ire != NULL)
15216 		ire_refrele(ire);
15217 
15218 	if (head != NULL)
15219 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15220 
15221 	/*
15222 	 * This code is there just to make netperf/ttcp look good.
15223 	 *
15224 	 * Its possible that after being in polling mode (and having cleared
15225 	 * the backlog), squeues have turned the interrupt frequency higher
15226 	 * to improve latency at the expense of more CPU utilization (less
15227 	 * packets per interrupts or more number of interrupts). Workloads
15228 	 * like ttcp/netperf do manage to tickle polling once in a while
15229 	 * but for the remaining time, stay in higher interrupt mode since
15230 	 * their packet arrival rate is pretty uniform and this shows up
15231 	 * as higher CPU utilization. Since people care about CPU utilization
15232 	 * while running netperf/ttcp, turn the interrupt frequency back to
15233 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15234 	 */
15235 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15236 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15237 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15238 			ip_ring->rr_blank(ip_ring->rr_handle,
15239 			    ip_ring->rr_normal_blank_time,
15240 			    ip_ring->rr_normal_pkt_cnt);
15241 		}
15242 		}
15243 
15244 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15245 	    "ip_input_end: q %p (%S)", q, "end");
15246 #undef  rptr
15247 }
15248 
15249 static void
15250 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15251     t_uscalar_t err)
15252 {
15253 	if (dl_err == DL_SYSERR) {
15254 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15255 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15256 		    ill->ill_name, dlpi_prim_str(prim), err);
15257 		return;
15258 	}
15259 
15260 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15261 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15262 	    dlpi_err_str(dl_err));
15263 }
15264 
15265 /*
15266  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15267  * than DL_UNITDATA_IND messages. If we need to process this message
15268  * exclusively, we call qwriter_ip, in which case we also need to call
15269  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15270  */
15271 void
15272 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15273 {
15274 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15275 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15276 	ill_t		*ill = (ill_t *)q->q_ptr;
15277 	boolean_t	pending;
15278 
15279 	ip1dbg(("ip_rput_dlpi"));
15280 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15281 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15282 		    "%s (0x%x), unix %u\n", ill->ill_name,
15283 		    dlpi_prim_str(dlea->dl_error_primitive),
15284 		    dlea->dl_error_primitive,
15285 		    dlpi_err_str(dlea->dl_errno),
15286 		    dlea->dl_errno,
15287 		    dlea->dl_unix_errno));
15288 	}
15289 
15290 	/*
15291 	 * If we received an ACK but didn't send a request for it, then it
15292 	 * can't be part of any pending operation; discard up-front.
15293 	 */
15294 	switch (dloa->dl_primitive) {
15295 	case DL_NOTIFY_IND:
15296 		pending = B_TRUE;
15297 		break;
15298 	case DL_ERROR_ACK:
15299 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15300 		break;
15301 	case DL_OK_ACK:
15302 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15303 		break;
15304 	case DL_INFO_ACK:
15305 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15306 		break;
15307 	case DL_BIND_ACK:
15308 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15309 		break;
15310 	case DL_PHYS_ADDR_ACK:
15311 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15312 		break;
15313 	case DL_NOTIFY_ACK:
15314 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15315 		break;
15316 	case DL_CONTROL_ACK:
15317 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15318 		break;
15319 	case DL_CAPABILITY_ACK:
15320 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15321 		break;
15322 	default:
15323 		/* Not a DLPI message we support or were expecting */
15324 		freemsg(mp);
15325 		return;
15326 	}
15327 
15328 	if (!pending) {
15329 		freemsg(mp);
15330 		return;
15331 	}
15332 
15333 	switch (dloa->dl_primitive) {
15334 	case DL_ERROR_ACK:
15335 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15336 			mutex_enter(&ill->ill_lock);
15337 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15338 			cv_signal(&ill->ill_cv);
15339 			mutex_exit(&ill->ill_lock);
15340 		}
15341 		break;
15342 
15343 	case DL_OK_ACK:
15344 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15345 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15346 		switch (dloa->dl_correct_primitive) {
15347 		case DL_UNBIND_REQ:
15348 			mutex_enter(&ill->ill_lock);
15349 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15350 			cv_signal(&ill->ill_cv);
15351 			mutex_exit(&ill->ill_lock);
15352 			break;
15353 
15354 		case DL_ENABMULTI_REQ:
15355 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15356 				ill->ill_dlpi_multicast_state = IDS_OK;
15357 			break;
15358 		}
15359 		break;
15360 	default:
15361 		break;
15362 	}
15363 
15364 	/*
15365 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15366 	 * and we need to become writer to continue to process it. If it's not
15367 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15368 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15369 	 * some work as part of the current exclusive operation that actually
15370 	 * is not part of it -- which is wrong, but better than the
15371 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15372 	 * should track which DLPI requests have ACKs that we wait on
15373 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15374 	 *
15375 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15376 	 * Since this is on the ill stream we unconditionally bump up the
15377 	 * refcount without doing ILL_CAN_LOOKUP().
15378 	 */
15379 	ill_refhold(ill);
15380 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15381 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15382 	else
15383 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15384 }
15385 
15386 /*
15387  * Handling of DLPI messages that require exclusive access to the ipsq.
15388  *
15389  * Need to do ill_pending_mp_release on ioctl completion, which could
15390  * happen here. (along with mi_copy_done)
15391  */
15392 /* ARGSUSED */
15393 static void
15394 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15395 {
15396 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15397 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15398 	int		err = 0;
15399 	ill_t		*ill;
15400 	ipif_t		*ipif = NULL;
15401 	mblk_t		*mp1 = NULL;
15402 	conn_t		*connp = NULL;
15403 	t_uscalar_t	paddrreq;
15404 	mblk_t		*mp_hw;
15405 	boolean_t	success;
15406 	boolean_t	ioctl_aborted = B_FALSE;
15407 	boolean_t	log = B_TRUE;
15408 	hook_nic_event_t	*info;
15409 	ip_stack_t		*ipst;
15410 
15411 	ip1dbg(("ip_rput_dlpi_writer .."));
15412 	ill = (ill_t *)q->q_ptr;
15413 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15414 
15415 	ASSERT(IAM_WRITER_ILL(ill));
15416 
15417 	ipst = ill->ill_ipst;
15418 
15419 	/*
15420 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15421 	 * both are null or non-null. However we can assert that only
15422 	 * after grabbing the ipsq_lock. So we don't make any assertion
15423 	 * here and in other places in the code.
15424 	 */
15425 	ipif = ipsq->ipsq_pending_ipif;
15426 	/*
15427 	 * The current ioctl could have been aborted by the user and a new
15428 	 * ioctl to bring up another ill could have started. We could still
15429 	 * get a response from the driver later.
15430 	 */
15431 	if (ipif != NULL && ipif->ipif_ill != ill)
15432 		ioctl_aborted = B_TRUE;
15433 
15434 	switch (dloa->dl_primitive) {
15435 	case DL_ERROR_ACK:
15436 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15437 		    dlpi_prim_str(dlea->dl_error_primitive)));
15438 
15439 		switch (dlea->dl_error_primitive) {
15440 		case DL_PROMISCON_REQ:
15441 		case DL_PROMISCOFF_REQ:
15442 		case DL_DISABMULTI_REQ:
15443 		case DL_UNBIND_REQ:
15444 		case DL_ATTACH_REQ:
15445 		case DL_INFO_REQ:
15446 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15447 			break;
15448 		case DL_NOTIFY_REQ:
15449 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15450 			log = B_FALSE;
15451 			break;
15452 		case DL_PHYS_ADDR_REQ:
15453 			/*
15454 			 * For IPv6 only, there are two additional
15455 			 * phys_addr_req's sent to the driver to get the
15456 			 * IPv6 token and lla. This allows IP to acquire
15457 			 * the hardware address format for a given interface
15458 			 * without having built in knowledge of the hardware
15459 			 * address. ill_phys_addr_pend keeps track of the last
15460 			 * DL_PAR sent so we know which response we are
15461 			 * dealing with. ill_dlpi_done will update
15462 			 * ill_phys_addr_pend when it sends the next req.
15463 			 * We don't complete the IOCTL until all three DL_PARs
15464 			 * have been attempted, so set *_len to 0 and break.
15465 			 */
15466 			paddrreq = ill->ill_phys_addr_pend;
15467 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15468 			if (paddrreq == DL_IPV6_TOKEN) {
15469 				ill->ill_token_length = 0;
15470 				log = B_FALSE;
15471 				break;
15472 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15473 				ill->ill_nd_lla_len = 0;
15474 				log = B_FALSE;
15475 				break;
15476 			}
15477 			/*
15478 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15479 			 * We presumably have an IOCTL hanging out waiting
15480 			 * for completion. Find it and complete the IOCTL
15481 			 * with the error noted.
15482 			 * However, ill_dl_phys was called on an ill queue
15483 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15484 			 * set. But the ioctl is known to be pending on ill_wq.
15485 			 */
15486 			if (!ill->ill_ifname_pending)
15487 				break;
15488 			ill->ill_ifname_pending = 0;
15489 			if (!ioctl_aborted)
15490 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15491 			if (mp1 != NULL) {
15492 				/*
15493 				 * This operation (SIOCSLIFNAME) must have
15494 				 * happened on the ill. Assert there is no conn
15495 				 */
15496 				ASSERT(connp == NULL);
15497 				q = ill->ill_wq;
15498 			}
15499 			break;
15500 		case DL_BIND_REQ:
15501 			ill_dlpi_done(ill, DL_BIND_REQ);
15502 			if (ill->ill_ifname_pending)
15503 				break;
15504 			/*
15505 			 * Something went wrong with the bind.  We presumably
15506 			 * have an IOCTL hanging out waiting for completion.
15507 			 * Find it, take down the interface that was coming
15508 			 * up, and complete the IOCTL with the error noted.
15509 			 */
15510 			if (!ioctl_aborted)
15511 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15512 			if (mp1 != NULL) {
15513 				/*
15514 				 * This operation (SIOCSLIFFLAGS) must have
15515 				 * happened from a conn.
15516 				 */
15517 				ASSERT(connp != NULL);
15518 				q = CONNP_TO_WQ(connp);
15519 				if (ill->ill_move_in_progress) {
15520 					ILL_CLEAR_MOVE(ill);
15521 				}
15522 				(void) ipif_down(ipif, NULL, NULL);
15523 				/* error is set below the switch */
15524 			}
15525 			break;
15526 		case DL_ENABMULTI_REQ:
15527 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15528 
15529 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15530 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15531 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15532 				ipif_t *ipif;
15533 
15534 				printf("ip: joining multicasts failed (%d)"
15535 				    " on %s - will use link layer "
15536 				    "broadcasts for multicast\n",
15537 				    dlea->dl_errno, ill->ill_name);
15538 
15539 				/*
15540 				 * Set up the multicast mapping alone.
15541 				 * writer, so ok to access ill->ill_ipif
15542 				 * without any lock.
15543 				 */
15544 				ipif = ill->ill_ipif;
15545 				mutex_enter(&ill->ill_phyint->phyint_lock);
15546 				ill->ill_phyint->phyint_flags |=
15547 				    PHYI_MULTI_BCAST;
15548 				mutex_exit(&ill->ill_phyint->phyint_lock);
15549 
15550 				if (!ill->ill_isv6) {
15551 					(void) ipif_arp_setup_multicast(ipif,
15552 					    NULL);
15553 				} else {
15554 					(void) ipif_ndp_setup_multicast(ipif,
15555 					    NULL);
15556 				}
15557 			}
15558 			freemsg(mp);	/* Don't want to pass this up */
15559 			return;
15560 
15561 		case DL_CAPABILITY_REQ:
15562 		case DL_CONTROL_REQ:
15563 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15564 			ill->ill_dlpi_capab_state = IDS_FAILED;
15565 			freemsg(mp);
15566 			return;
15567 		}
15568 		/*
15569 		 * Note the error for IOCTL completion (mp1 is set when
15570 		 * ready to complete ioctl). If ill_ifname_pending_err is
15571 		 * set, an error occured during plumbing (ill_ifname_pending),
15572 		 * so we want to report that error.
15573 		 *
15574 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15575 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15576 		 * expected to get errack'd if the driver doesn't support
15577 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15578 		 * if these error conditions are encountered.
15579 		 */
15580 		if (mp1 != NULL) {
15581 			if (ill->ill_ifname_pending_err != 0)  {
15582 				err = ill->ill_ifname_pending_err;
15583 				ill->ill_ifname_pending_err = 0;
15584 			} else {
15585 				err = dlea->dl_unix_errno ?
15586 				    dlea->dl_unix_errno : ENXIO;
15587 			}
15588 		/*
15589 		 * If we're plumbing an interface and an error hasn't already
15590 		 * been saved, set ill_ifname_pending_err to the error passed
15591 		 * up. Ignore the error if log is B_FALSE (see comment above).
15592 		 */
15593 		} else if (log && ill->ill_ifname_pending &&
15594 		    ill->ill_ifname_pending_err == 0) {
15595 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15596 			    dlea->dl_unix_errno : ENXIO;
15597 		}
15598 
15599 		if (log)
15600 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15601 			    dlea->dl_errno, dlea->dl_unix_errno);
15602 		break;
15603 	case DL_CAPABILITY_ACK:
15604 		/* Call a routine to handle this one. */
15605 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15606 		ill_capability_ack(ill, mp);
15607 
15608 		/*
15609 		 * If the ack is due to renegotiation, we will need to send
15610 		 * a new CAPABILITY_REQ to start the renegotiation.
15611 		 */
15612 		if (ill->ill_capab_reneg) {
15613 			ill->ill_capab_reneg = B_FALSE;
15614 			ill_capability_probe(ill);
15615 		}
15616 		break;
15617 	case DL_CONTROL_ACK:
15618 		/* We treat all of these as "fire and forget" */
15619 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15620 		break;
15621 	case DL_INFO_ACK:
15622 		/* Call a routine to handle this one. */
15623 		ill_dlpi_done(ill, DL_INFO_REQ);
15624 		ip_ll_subnet_defaults(ill, mp);
15625 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15626 		return;
15627 	case DL_BIND_ACK:
15628 		/*
15629 		 * We should have an IOCTL waiting on this unless
15630 		 * sent by ill_dl_phys, in which case just return
15631 		 */
15632 		ill_dlpi_done(ill, DL_BIND_REQ);
15633 		if (ill->ill_ifname_pending)
15634 			break;
15635 
15636 		if (!ioctl_aborted)
15637 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15638 		if (mp1 == NULL)
15639 			break;
15640 		/*
15641 		 * Because mp1 was added by ill_dl_up(), and it always
15642 		 * passes a valid connp, connp must be valid here.
15643 		 */
15644 		ASSERT(connp != NULL);
15645 		q = CONNP_TO_WQ(connp);
15646 
15647 		/*
15648 		 * We are exclusive. So nothing can change even after
15649 		 * we get the pending mp. If need be we can put it back
15650 		 * and restart, as in calling ipif_arp_up()  below.
15651 		 */
15652 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15653 
15654 		mutex_enter(&ill->ill_lock);
15655 
15656 		ill->ill_dl_up = 1;
15657 
15658 		if ((info = ill->ill_nic_event_info) != NULL) {
15659 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15660 			    "attached for %s\n", info->hne_event,
15661 			    ill->ill_name));
15662 			if (info->hne_data != NULL)
15663 				kmem_free(info->hne_data, info->hne_datalen);
15664 			kmem_free(info, sizeof (hook_nic_event_t));
15665 		}
15666 
15667 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15668 		if (info != NULL) {
15669 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15670 			info->hne_lif = 0;
15671 			info->hne_event = NE_UP;
15672 			info->hne_data = NULL;
15673 			info->hne_datalen = 0;
15674 			info->hne_family = ill->ill_isv6 ?
15675 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15676 		} else
15677 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15678 			    "event information for %s (ENOMEM)\n",
15679 			    ill->ill_name));
15680 
15681 		ill->ill_nic_event_info = info;
15682 
15683 		mutex_exit(&ill->ill_lock);
15684 
15685 		/*
15686 		 * Now bring up the resolver; when that is complete, we'll
15687 		 * create IREs.  Note that we intentionally mirror what
15688 		 * ipif_up() would have done, because we got here by way of
15689 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15690 		 */
15691 		if (ill->ill_isv6) {
15692 			/*
15693 			 * v6 interfaces.
15694 			 * Unlike ARP which has to do another bind
15695 			 * and attach, once we get here we are
15696 			 * done with NDP. Except in the case of
15697 			 * ILLF_XRESOLV, in which case we send an
15698 			 * AR_INTERFACE_UP to the external resolver.
15699 			 * If all goes well, the ioctl will complete
15700 			 * in ip_rput(). If there's an error, we
15701 			 * complete it here.
15702 			 */
15703 			if ((err = ipif_ndp_up(ipif)) == 0) {
15704 				if (ill->ill_flags & ILLF_XRESOLV) {
15705 					mutex_enter(&connp->conn_lock);
15706 					mutex_enter(&ill->ill_lock);
15707 					success = ipsq_pending_mp_add(
15708 					    connp, ipif, q, mp1, 0);
15709 					mutex_exit(&ill->ill_lock);
15710 					mutex_exit(&connp->conn_lock);
15711 					if (success) {
15712 						err = ipif_resolver_up(ipif,
15713 						    Res_act_initial);
15714 						if (err == EINPROGRESS) {
15715 							freemsg(mp);
15716 							return;
15717 						}
15718 						ASSERT(err != 0);
15719 						mp1 = ipsq_pending_mp_get(ipsq,
15720 						    &connp);
15721 						ASSERT(mp1 != NULL);
15722 					} else {
15723 						/* conn has started closing */
15724 						err = EINTR;
15725 					}
15726 				} else { /* Non XRESOLV interface */
15727 					(void) ipif_resolver_up(ipif,
15728 					    Res_act_initial);
15729 					err = ipif_up_done_v6(ipif);
15730 				}
15731 			}
15732 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15733 			/*
15734 			 * ARP and other v4 external resolvers.
15735 			 * Leave the pending mblk intact so that
15736 			 * the ioctl completes in ip_rput().
15737 			 */
15738 			mutex_enter(&connp->conn_lock);
15739 			mutex_enter(&ill->ill_lock);
15740 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15741 			mutex_exit(&ill->ill_lock);
15742 			mutex_exit(&connp->conn_lock);
15743 			if (success) {
15744 				err = ipif_resolver_up(ipif, Res_act_initial);
15745 				if (err == EINPROGRESS) {
15746 					freemsg(mp);
15747 					return;
15748 				}
15749 				ASSERT(err != 0);
15750 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15751 			} else {
15752 				/* The conn has started closing */
15753 				err = EINTR;
15754 			}
15755 		} else {
15756 			/*
15757 			 * This one is complete. Reply to pending ioctl.
15758 			 */
15759 			(void) ipif_resolver_up(ipif, Res_act_initial);
15760 			err = ipif_up_done(ipif);
15761 		}
15762 
15763 		if ((err == 0) && (ill->ill_up_ipifs)) {
15764 			err = ill_up_ipifs(ill, q, mp1);
15765 			if (err == EINPROGRESS) {
15766 				freemsg(mp);
15767 				return;
15768 			}
15769 		}
15770 
15771 		if (ill->ill_up_ipifs) {
15772 			ill_group_cleanup(ill);
15773 		}
15774 
15775 		break;
15776 	case DL_NOTIFY_IND: {
15777 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15778 		ire_t *ire;
15779 		boolean_t need_ire_walk_v4 = B_FALSE;
15780 		boolean_t need_ire_walk_v6 = B_FALSE;
15781 
15782 		switch (notify->dl_notification) {
15783 		case DL_NOTE_PHYS_ADDR:
15784 			err = ill_set_phys_addr(ill, mp);
15785 			break;
15786 
15787 		case DL_NOTE_FASTPATH_FLUSH:
15788 			ill_fastpath_flush(ill);
15789 			break;
15790 
15791 		case DL_NOTE_SDU_SIZE:
15792 			/*
15793 			 * Change the MTU size of the interface, of all
15794 			 * attached ipif's, and of all relevant ire's.  The
15795 			 * new value's a uint32_t at notify->dl_data.
15796 			 * Mtu change Vs. new ire creation - protocol below.
15797 			 *
15798 			 * a Mark the ipif as IPIF_CHANGING.
15799 			 * b Set the new mtu in the ipif.
15800 			 * c Change the ire_max_frag on all affected ires
15801 			 * d Unmark the IPIF_CHANGING
15802 			 *
15803 			 * To see how the protocol works, assume an interface
15804 			 * route is also being added simultaneously by
15805 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15806 			 * the ire. If the ire is created before step a,
15807 			 * it will be cleaned up by step c. If the ire is
15808 			 * created after step d, it will see the new value of
15809 			 * ipif_mtu. Any attempt to create the ire between
15810 			 * steps a to d will fail because of the IPIF_CHANGING
15811 			 * flag. Note that ire_create() is passed a pointer to
15812 			 * the ipif_mtu, and not the value. During ire_add
15813 			 * under the bucket lock, the ire_max_frag of the
15814 			 * new ire being created is set from the ipif/ire from
15815 			 * which it is being derived.
15816 			 */
15817 			mutex_enter(&ill->ill_lock);
15818 			ill->ill_max_frag = (uint_t)notify->dl_data;
15819 
15820 			/*
15821 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15822 			 * leave it alone
15823 			 */
15824 			if (ill->ill_mtu_userspecified) {
15825 				mutex_exit(&ill->ill_lock);
15826 				break;
15827 			}
15828 			ill->ill_max_mtu = ill->ill_max_frag;
15829 			if (ill->ill_isv6) {
15830 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15831 					ill->ill_max_mtu = IPV6_MIN_MTU;
15832 			} else {
15833 				if (ill->ill_max_mtu < IP_MIN_MTU)
15834 					ill->ill_max_mtu = IP_MIN_MTU;
15835 			}
15836 			for (ipif = ill->ill_ipif; ipif != NULL;
15837 			    ipif = ipif->ipif_next) {
15838 				/*
15839 				 * Don't override the mtu if the user
15840 				 * has explicitly set it.
15841 				 */
15842 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15843 					continue;
15844 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15845 				if (ipif->ipif_isv6)
15846 					ire = ipif_to_ire_v6(ipif);
15847 				else
15848 					ire = ipif_to_ire(ipif);
15849 				if (ire != NULL) {
15850 					ire->ire_max_frag = ipif->ipif_mtu;
15851 					ire_refrele(ire);
15852 				}
15853 				if (ipif->ipif_flags & IPIF_UP) {
15854 					if (ill->ill_isv6)
15855 						need_ire_walk_v6 = B_TRUE;
15856 					else
15857 						need_ire_walk_v4 = B_TRUE;
15858 				}
15859 			}
15860 			mutex_exit(&ill->ill_lock);
15861 			if (need_ire_walk_v4)
15862 				ire_walk_v4(ill_mtu_change, (char *)ill,
15863 				    ALL_ZONES, ipst);
15864 			if (need_ire_walk_v6)
15865 				ire_walk_v6(ill_mtu_change, (char *)ill,
15866 				    ALL_ZONES, ipst);
15867 			break;
15868 		case DL_NOTE_LINK_UP:
15869 		case DL_NOTE_LINK_DOWN: {
15870 			/*
15871 			 * We are writer. ill / phyint / ipsq assocs stable.
15872 			 * The RUNNING flag reflects the state of the link.
15873 			 */
15874 			phyint_t *phyint = ill->ill_phyint;
15875 			uint64_t new_phyint_flags;
15876 			boolean_t changed = B_FALSE;
15877 			boolean_t went_up;
15878 
15879 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15880 			mutex_enter(&phyint->phyint_lock);
15881 			new_phyint_flags = went_up ?
15882 			    phyint->phyint_flags | PHYI_RUNNING :
15883 			    phyint->phyint_flags & ~PHYI_RUNNING;
15884 			if (new_phyint_flags != phyint->phyint_flags) {
15885 				phyint->phyint_flags = new_phyint_flags;
15886 				changed = B_TRUE;
15887 			}
15888 			mutex_exit(&phyint->phyint_lock);
15889 			/*
15890 			 * ill_restart_dad handles the DAD restart and routing
15891 			 * socket notification logic.
15892 			 */
15893 			if (changed) {
15894 				ill_restart_dad(phyint->phyint_illv4, went_up);
15895 				ill_restart_dad(phyint->phyint_illv6, went_up);
15896 			}
15897 			break;
15898 		}
15899 		case DL_NOTE_PROMISC_ON_PHYS:
15900 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15901 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15902 			mutex_enter(&ill->ill_lock);
15903 			ill->ill_promisc_on_phys = B_TRUE;
15904 			mutex_exit(&ill->ill_lock);
15905 			break;
15906 		case DL_NOTE_PROMISC_OFF_PHYS:
15907 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15908 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15909 			mutex_enter(&ill->ill_lock);
15910 			ill->ill_promisc_on_phys = B_FALSE;
15911 			mutex_exit(&ill->ill_lock);
15912 			break;
15913 		case DL_NOTE_CAPAB_RENEG:
15914 			/*
15915 			 * Something changed on the driver side.
15916 			 * It wants us to renegotiate the capabilities
15917 			 * on this ill. One possible cause is the aggregation
15918 			 * interface under us where a port got added or
15919 			 * went away.
15920 			 *
15921 			 * If the capability negotiation is already done
15922 			 * or is in progress, reset the capabilities and
15923 			 * mark the ill's ill_capab_reneg to be B_TRUE,
15924 			 * so that when the ack comes back, we can start
15925 			 * the renegotiation process.
15926 			 *
15927 			 * Note that if ill_capab_reneg is already B_TRUE
15928 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
15929 			 * the capability resetting request has been sent
15930 			 * and the renegotiation has not been started yet;
15931 			 * nothing needs to be done in this case.
15932 			 */
15933 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
15934 				ill_capability_reset(ill);
15935 				ill->ill_capab_reneg = B_TRUE;
15936 			}
15937 			break;
15938 		default:
15939 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15940 			    "type 0x%x for DL_NOTIFY_IND\n",
15941 			    notify->dl_notification));
15942 			break;
15943 		}
15944 
15945 		/*
15946 		 * As this is an asynchronous operation, we
15947 		 * should not call ill_dlpi_done
15948 		 */
15949 		break;
15950 	}
15951 	case DL_NOTIFY_ACK: {
15952 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15953 
15954 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15955 			ill->ill_note_link = 1;
15956 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15957 		break;
15958 	}
15959 	case DL_PHYS_ADDR_ACK: {
15960 		/*
15961 		 * As part of plumbing the interface via SIOCSLIFNAME,
15962 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
15963 		 * whose answers we receive here.  As each answer is received,
15964 		 * we call ill_dlpi_done() to dispatch the next request as
15965 		 * we're processing the current one.  Once all answers have
15966 		 * been received, we use ipsq_pending_mp_get() to dequeue the
15967 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
15968 		 * is invoked from an ill queue, conn_oper_pending_ill is not
15969 		 * available, but we know the ioctl is pending on ill_wq.)
15970 		 */
15971 		uint_t paddrlen, paddroff;
15972 
15973 		paddrreq = ill->ill_phys_addr_pend;
15974 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
15975 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
15976 
15977 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15978 		if (paddrreq == DL_IPV6_TOKEN) {
15979 			/*
15980 			 * bcopy to low-order bits of ill_token
15981 			 *
15982 			 * XXX Temporary hack - currently, all known tokens
15983 			 * are 64 bits, so I'll cheat for the moment.
15984 			 */
15985 			bcopy(mp->b_rptr + paddroff,
15986 			    &ill->ill_token.s6_addr32[2], paddrlen);
15987 			ill->ill_token_length = paddrlen;
15988 			break;
15989 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15990 			ASSERT(ill->ill_nd_lla_mp == NULL);
15991 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
15992 			mp = NULL;
15993 			break;
15994 		}
15995 
15996 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
15997 		ASSERT(ill->ill_phys_addr_mp == NULL);
15998 		if (!ill->ill_ifname_pending)
15999 			break;
16000 		ill->ill_ifname_pending = 0;
16001 		if (!ioctl_aborted)
16002 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16003 		if (mp1 != NULL) {
16004 			ASSERT(connp == NULL);
16005 			q = ill->ill_wq;
16006 		}
16007 		/*
16008 		 * If any error acks received during the plumbing sequence,
16009 		 * ill_ifname_pending_err will be set. Break out and send up
16010 		 * the error to the pending ioctl.
16011 		 */
16012 		if (ill->ill_ifname_pending_err != 0) {
16013 			err = ill->ill_ifname_pending_err;
16014 			ill->ill_ifname_pending_err = 0;
16015 			break;
16016 		}
16017 
16018 		ill->ill_phys_addr_mp = mp;
16019 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16020 		mp = NULL;
16021 
16022 		/*
16023 		 * If paddrlen is zero, the DLPI provider doesn't support
16024 		 * physical addresses.  The other two tests were historical
16025 		 * workarounds for bugs in our former PPP implementation, but
16026 		 * now other things have grown dependencies on them -- e.g.,
16027 		 * the tun module specifies a dl_addr_length of zero in its
16028 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16029 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16030 		 * but only after careful testing ensures that all dependent
16031 		 * broken DLPI providers have been fixed.
16032 		 */
16033 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16034 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16035 			ill->ill_phys_addr = NULL;
16036 		} else if (paddrlen != ill->ill_phys_addr_length) {
16037 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16038 			    paddrlen, ill->ill_phys_addr_length));
16039 			err = EINVAL;
16040 			break;
16041 		}
16042 
16043 		if (ill->ill_nd_lla_mp == NULL) {
16044 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16045 				err = ENOMEM;
16046 				break;
16047 			}
16048 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16049 		}
16050 
16051 		/*
16052 		 * Set the interface token.  If the zeroth interface address
16053 		 * is unspecified, then set it to the link local address.
16054 		 */
16055 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16056 			(void) ill_setdefaulttoken(ill);
16057 
16058 		ASSERT(ill->ill_ipif->ipif_id == 0);
16059 		if (ipif != NULL &&
16060 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16061 			(void) ipif_setlinklocal(ipif);
16062 		}
16063 		break;
16064 	}
16065 	case DL_OK_ACK:
16066 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16067 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16068 		    dloa->dl_correct_primitive));
16069 		switch (dloa->dl_correct_primitive) {
16070 		case DL_PROMISCON_REQ:
16071 		case DL_PROMISCOFF_REQ:
16072 		case DL_ENABMULTI_REQ:
16073 		case DL_DISABMULTI_REQ:
16074 		case DL_UNBIND_REQ:
16075 		case DL_ATTACH_REQ:
16076 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16077 			break;
16078 		}
16079 		break;
16080 	default:
16081 		break;
16082 	}
16083 
16084 	freemsg(mp);
16085 	if (mp1 != NULL) {
16086 		/*
16087 		 * The operation must complete without EINPROGRESS
16088 		 * since ipsq_pending_mp_get() has removed the mblk
16089 		 * from ipsq_pending_mp.  Otherwise, the operation
16090 		 * will be stuck forever in the ipsq.
16091 		 */
16092 		ASSERT(err != EINPROGRESS);
16093 
16094 		switch (ipsq->ipsq_current_ioctl) {
16095 		case 0:
16096 			ipsq_current_finish(ipsq);
16097 			break;
16098 
16099 		case SIOCLIFADDIF:
16100 		case SIOCSLIFNAME:
16101 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16102 			break;
16103 
16104 		default:
16105 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16106 			break;
16107 		}
16108 	}
16109 }
16110 
16111 /*
16112  * ip_rput_other is called by ip_rput to handle messages modifying the global
16113  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16114  */
16115 /* ARGSUSED */
16116 void
16117 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16118 {
16119 	ill_t		*ill;
16120 	struct iocblk	*iocp;
16121 	mblk_t		*mp1;
16122 	conn_t		*connp = NULL;
16123 
16124 	ip1dbg(("ip_rput_other "));
16125 	ill = (ill_t *)q->q_ptr;
16126 	/*
16127 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16128 	 * in which case ipsq is NULL.
16129 	 */
16130 	if (ipsq != NULL) {
16131 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16132 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16133 	}
16134 
16135 	switch (mp->b_datap->db_type) {
16136 	case M_ERROR:
16137 	case M_HANGUP:
16138 		/*
16139 		 * The device has a problem.  We force the ILL down.  It can
16140 		 * be brought up again manually using SIOCSIFFLAGS (via
16141 		 * ifconfig or equivalent).
16142 		 */
16143 		ASSERT(ipsq != NULL);
16144 		if (mp->b_rptr < mp->b_wptr)
16145 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16146 		if (ill->ill_error == 0)
16147 			ill->ill_error = ENXIO;
16148 		if (!ill_down_start(q, mp))
16149 			return;
16150 		ipif_all_down_tail(ipsq, q, mp, NULL);
16151 		break;
16152 	case M_IOCACK:
16153 		iocp = (struct iocblk *)mp->b_rptr;
16154 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16155 		switch (iocp->ioc_cmd) {
16156 		case SIOCSTUNPARAM:
16157 		case OSIOCSTUNPARAM:
16158 			ASSERT(ipsq != NULL);
16159 			/*
16160 			 * Finish socket ioctl passed through to tun.
16161 			 * We should have an IOCTL waiting on this.
16162 			 */
16163 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16164 			if (ill->ill_isv6) {
16165 				struct iftun_req *ta;
16166 
16167 				/*
16168 				 * if a source or destination is
16169 				 * being set, try and set the link
16170 				 * local address for the tunnel
16171 				 */
16172 				ta = (struct iftun_req *)mp->b_cont->
16173 				    b_cont->b_rptr;
16174 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16175 					ipif_set_tun_llink(ill, ta);
16176 				}
16177 
16178 			}
16179 			if (mp1 != NULL) {
16180 				/*
16181 				 * Now copy back the b_next/b_prev used by
16182 				 * mi code for the mi_copy* functions.
16183 				 * See ip_sioctl_tunparam() for the reason.
16184 				 * Also protect against missing b_cont.
16185 				 */
16186 				if (mp->b_cont != NULL) {
16187 					mp->b_cont->b_next =
16188 					    mp1->b_cont->b_next;
16189 					mp->b_cont->b_prev =
16190 					    mp1->b_cont->b_prev;
16191 				}
16192 				inet_freemsg(mp1);
16193 				ASSERT(connp != NULL);
16194 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16195 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16196 			} else {
16197 				ASSERT(connp == NULL);
16198 				putnext(q, mp);
16199 			}
16200 			break;
16201 		case SIOCGTUNPARAM:
16202 		case OSIOCGTUNPARAM:
16203 			/*
16204 			 * This is really M_IOCDATA from the tunnel driver.
16205 			 * convert back and complete the ioctl.
16206 			 * We should have an IOCTL waiting on this.
16207 			 */
16208 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16209 			if (mp1) {
16210 				/*
16211 				 * Now copy back the b_next/b_prev used by
16212 				 * mi code for the mi_copy* functions.
16213 				 * See ip_sioctl_tunparam() for the reason.
16214 				 * Also protect against missing b_cont.
16215 				 */
16216 				if (mp->b_cont != NULL) {
16217 					mp->b_cont->b_next =
16218 					    mp1->b_cont->b_next;
16219 					mp->b_cont->b_prev =
16220 					    mp1->b_cont->b_prev;
16221 				}
16222 				inet_freemsg(mp1);
16223 				if (iocp->ioc_error == 0)
16224 					mp->b_datap->db_type = M_IOCDATA;
16225 				ASSERT(connp != NULL);
16226 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16227 				    iocp->ioc_error, COPYOUT, NULL);
16228 			} else {
16229 				ASSERT(connp == NULL);
16230 				putnext(q, mp);
16231 			}
16232 			break;
16233 		default:
16234 			break;
16235 		}
16236 		break;
16237 	case M_IOCNAK:
16238 		iocp = (struct iocblk *)mp->b_rptr;
16239 
16240 		switch (iocp->ioc_cmd) {
16241 		int mode;
16242 
16243 		case DL_IOC_HDR_INFO:
16244 			/*
16245 			 * If this was the first attempt turn of the
16246 			 * fastpath probing.
16247 			 */
16248 			mutex_enter(&ill->ill_lock);
16249 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16250 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16251 				mutex_exit(&ill->ill_lock);
16252 				ill_fastpath_nack(ill);
16253 				ip1dbg(("ip_rput: DLPI fastpath off on "
16254 				    "interface %s\n",
16255 				    ill->ill_name));
16256 			} else {
16257 				mutex_exit(&ill->ill_lock);
16258 			}
16259 			freemsg(mp);
16260 			break;
16261 		case SIOCSTUNPARAM:
16262 		case OSIOCSTUNPARAM:
16263 			ASSERT(ipsq != NULL);
16264 			/*
16265 			 * Finish socket ioctl passed through to tun
16266 			 * We should have an IOCTL waiting on this.
16267 			 */
16268 			/* FALLTHRU */
16269 		case SIOCGTUNPARAM:
16270 		case OSIOCGTUNPARAM:
16271 			/*
16272 			 * This is really M_IOCDATA from the tunnel driver.
16273 			 * convert back and complete the ioctl.
16274 			 * We should have an IOCTL waiting on this.
16275 			 */
16276 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16277 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16278 				mp1 = ill_pending_mp_get(ill, &connp,
16279 				    iocp->ioc_id);
16280 				mode = COPYOUT;
16281 				ipsq = NULL;
16282 			} else {
16283 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16284 				mode = NO_COPYOUT;
16285 			}
16286 			if (mp1 != NULL) {
16287 				/*
16288 				 * Now copy back the b_next/b_prev used by
16289 				 * mi code for the mi_copy* functions.
16290 				 * See ip_sioctl_tunparam() for the reason.
16291 				 * Also protect against missing b_cont.
16292 				 */
16293 				if (mp->b_cont != NULL) {
16294 					mp->b_cont->b_next =
16295 					    mp1->b_cont->b_next;
16296 					mp->b_cont->b_prev =
16297 					    mp1->b_cont->b_prev;
16298 				}
16299 				inet_freemsg(mp1);
16300 				if (iocp->ioc_error == 0)
16301 					iocp->ioc_error = EINVAL;
16302 				ASSERT(connp != NULL);
16303 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16304 				    iocp->ioc_error, mode, ipsq);
16305 			} else {
16306 				ASSERT(connp == NULL);
16307 				putnext(q, mp);
16308 			}
16309 			break;
16310 		default:
16311 			break;
16312 		}
16313 	default:
16314 		break;
16315 	}
16316 }
16317 
16318 /*
16319  * NOTE : This function does not ire_refrele the ire argument passed in.
16320  *
16321  * IPQoS notes
16322  * IP policy is invoked twice for a forwarded packet, once on the read side
16323  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16324  * enabled. An additional parameter, in_ill, has been added for this purpose.
16325  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16326  * because ip_mroute drops this information.
16327  *
16328  */
16329 void
16330 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16331 {
16332 	uint32_t	old_pkt_len;
16333 	uint32_t	pkt_len;
16334 	queue_t	*q;
16335 	uint32_t	sum;
16336 #define	rptr	((uchar_t *)ipha)
16337 	uint32_t	max_frag;
16338 	uint32_t	ill_index;
16339 	ill_t		*out_ill;
16340 	mib2_ipIfStatsEntry_t *mibptr;
16341 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16342 
16343 	/* Get the ill_index of the incoming ILL */
16344 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16345 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16346 
16347 	/* Initiate Read side IPPF processing */
16348 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16349 		ip_process(IPP_FWD_IN, &mp, ill_index);
16350 		if (mp == NULL) {
16351 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16352 			    "during IPPF processing\n"));
16353 			return;
16354 		}
16355 	}
16356 
16357 	/* Adjust the checksum to reflect the ttl decrement. */
16358 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16359 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16360 
16361 	if (ipha->ipha_ttl-- <= 1) {
16362 		if (ip_csum_hdr(ipha)) {
16363 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16364 			goto drop_pkt;
16365 		}
16366 		/*
16367 		 * Note: ire_stq this will be NULL for multicast
16368 		 * datagrams using the long path through arp (the IRE
16369 		 * is not an IRE_CACHE). This should not cause
16370 		 * problems since we don't generate ICMP errors for
16371 		 * multicast packets.
16372 		 */
16373 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16374 		q = ire->ire_stq;
16375 		if (q != NULL) {
16376 			/* Sent by forwarding path, and router is global zone */
16377 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16378 			    GLOBAL_ZONEID, ipst);
16379 		} else
16380 			freemsg(mp);
16381 		return;
16382 	}
16383 
16384 	/*
16385 	 * Don't forward if the interface is down
16386 	 */
16387 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16388 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16389 		ip2dbg(("ip_rput_forward:interface is down\n"));
16390 		goto drop_pkt;
16391 	}
16392 
16393 	/* Get the ill_index of the outgoing ILL */
16394 	out_ill = ire_to_ill(ire);
16395 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16396 
16397 	DTRACE_PROBE4(ip4__forwarding__start,
16398 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16399 
16400 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16401 	    ipst->ips_ipv4firewall_forwarding,
16402 	    in_ill, out_ill, ipha, mp, mp, ipst);
16403 
16404 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16405 
16406 	if (mp == NULL)
16407 		return;
16408 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16409 
16410 	if (is_system_labeled()) {
16411 		mblk_t *mp1;
16412 
16413 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16414 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16415 			goto drop_pkt;
16416 		}
16417 		/* Size may have changed */
16418 		mp = mp1;
16419 		ipha = (ipha_t *)mp->b_rptr;
16420 		pkt_len = ntohs(ipha->ipha_length);
16421 	}
16422 
16423 	/* Check if there are options to update */
16424 	if (!IS_SIMPLE_IPH(ipha)) {
16425 		if (ip_csum_hdr(ipha)) {
16426 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16427 			goto drop_pkt;
16428 		}
16429 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16430 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16431 			return;
16432 		}
16433 
16434 		ipha->ipha_hdr_checksum = 0;
16435 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16436 	}
16437 	max_frag = ire->ire_max_frag;
16438 	if (pkt_len > max_frag) {
16439 		/*
16440 		 * It needs fragging on its way out.  We haven't
16441 		 * verified the header checksum yet.  Since we
16442 		 * are going to put a surely good checksum in the
16443 		 * outgoing header, we have to make sure that it
16444 		 * was good coming in.
16445 		 */
16446 		if (ip_csum_hdr(ipha)) {
16447 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16448 			goto drop_pkt;
16449 		}
16450 		/* Initiate Write side IPPF processing */
16451 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16452 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16453 			if (mp == NULL) {
16454 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16455 				    " during IPPF processing\n"));
16456 				return;
16457 			}
16458 		}
16459 		/*
16460 		 * Handle labeled packet resizing.
16461 		 *
16462 		 * If we have added a label, inform ip_wput_frag() of its
16463 		 * effect on the MTU for ICMP messages.
16464 		 */
16465 		if (pkt_len > old_pkt_len) {
16466 			uint32_t secopt_size;
16467 
16468 			secopt_size = pkt_len - old_pkt_len;
16469 			if (secopt_size < max_frag)
16470 				max_frag -= secopt_size;
16471 		}
16472 
16473 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16474 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16475 		return;
16476 	}
16477 
16478 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16479 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16480 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16481 	    ipst->ips_ipv4firewall_physical_out,
16482 	    NULL, out_ill, ipha, mp, mp, ipst);
16483 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16484 	if (mp == NULL)
16485 		return;
16486 
16487 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16488 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16489 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16490 	/* ip_xmit_v4 always consumes the packet */
16491 	return;
16492 
16493 drop_pkt:;
16494 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16495 	freemsg(mp);
16496 #undef	rptr
16497 }
16498 
16499 void
16500 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16501 {
16502 	ire_t	*ire;
16503 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16504 
16505 	ASSERT(!ipif->ipif_isv6);
16506 	/*
16507 	 * Find an IRE which matches the destination and the outgoing
16508 	 * queue in the cache table. All we need is an IRE_CACHE which
16509 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16510 	 * then it is enough to have some IRE_CACHE in the group.
16511 	 */
16512 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16513 		dst = ipif->ipif_pp_dst_addr;
16514 
16515 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16516 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16517 	if (ire == NULL) {
16518 		/*
16519 		 * Mark this packet to make it be delivered to
16520 		 * ip_rput_forward after the new ire has been
16521 		 * created.
16522 		 */
16523 		mp->b_prev = NULL;
16524 		mp->b_next = mp;
16525 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16526 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16527 	} else {
16528 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16529 		IRE_REFRELE(ire);
16530 	}
16531 }
16532 
16533 /* Update any source route, record route or timestamp options */
16534 static int
16535 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16536 {
16537 	ipoptp_t	opts;
16538 	uchar_t		*opt;
16539 	uint8_t		optval;
16540 	uint8_t		optlen;
16541 	ipaddr_t	dst;
16542 	uint32_t	ts;
16543 	ire_t		*dst_ire = NULL;
16544 	ire_t		*tmp_ire = NULL;
16545 	timestruc_t	now;
16546 
16547 	ip2dbg(("ip_rput_forward_options\n"));
16548 	dst = ipha->ipha_dst;
16549 	for (optval = ipoptp_first(&opts, ipha);
16550 	    optval != IPOPT_EOL;
16551 	    optval = ipoptp_next(&opts)) {
16552 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16553 		opt = opts.ipoptp_cur;
16554 		optlen = opts.ipoptp_len;
16555 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16556 		    optval, opts.ipoptp_len));
16557 		switch (optval) {
16558 			uint32_t off;
16559 		case IPOPT_SSRR:
16560 		case IPOPT_LSRR:
16561 			/* Check if adminstratively disabled */
16562 			if (!ipst->ips_ip_forward_src_routed) {
16563 				if (ire->ire_stq != NULL) {
16564 					/*
16565 					 * Sent by forwarding path, and router
16566 					 * is global zone
16567 					 */
16568 					icmp_unreachable(ire->ire_stq, mp,
16569 					    ICMP_SOURCE_ROUTE_FAILED,
16570 					    GLOBAL_ZONEID, ipst);
16571 				} else {
16572 					ip0dbg(("ip_rput_forward_options: "
16573 					    "unable to send unreach\n"));
16574 					freemsg(mp);
16575 				}
16576 				return (-1);
16577 			}
16578 
16579 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16580 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16581 			if (dst_ire == NULL) {
16582 				/*
16583 				 * Must be partial since ip_rput_options
16584 				 * checked for strict.
16585 				 */
16586 				break;
16587 			}
16588 			off = opt[IPOPT_OFFSET];
16589 			off--;
16590 		redo_srr:
16591 			if (optlen < IP_ADDR_LEN ||
16592 			    off > optlen - IP_ADDR_LEN) {
16593 				/* End of source route */
16594 				ip1dbg((
16595 				    "ip_rput_forward_options: end of SR\n"));
16596 				ire_refrele(dst_ire);
16597 				break;
16598 			}
16599 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16600 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16601 			    IP_ADDR_LEN);
16602 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16603 			    ntohl(dst)));
16604 
16605 			/*
16606 			 * Check if our address is present more than
16607 			 * once as consecutive hops in source route.
16608 			 */
16609 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16610 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16611 			if (tmp_ire != NULL) {
16612 				ire_refrele(tmp_ire);
16613 				off += IP_ADDR_LEN;
16614 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16615 				goto redo_srr;
16616 			}
16617 			ipha->ipha_dst = dst;
16618 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16619 			ire_refrele(dst_ire);
16620 			break;
16621 		case IPOPT_RR:
16622 			off = opt[IPOPT_OFFSET];
16623 			off--;
16624 			if (optlen < IP_ADDR_LEN ||
16625 			    off > optlen - IP_ADDR_LEN) {
16626 				/* No more room - ignore */
16627 				ip1dbg((
16628 				    "ip_rput_forward_options: end of RR\n"));
16629 				break;
16630 			}
16631 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16632 			    IP_ADDR_LEN);
16633 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16634 			break;
16635 		case IPOPT_TS:
16636 			/* Insert timestamp if there is room */
16637 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16638 			case IPOPT_TS_TSONLY:
16639 				off = IPOPT_TS_TIMELEN;
16640 				break;
16641 			case IPOPT_TS_PRESPEC:
16642 			case IPOPT_TS_PRESPEC_RFC791:
16643 				/* Verify that the address matched */
16644 				off = opt[IPOPT_OFFSET] - 1;
16645 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16646 				dst_ire = ire_ctable_lookup(dst, 0,
16647 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16648 				    MATCH_IRE_TYPE, ipst);
16649 				if (dst_ire == NULL) {
16650 					/* Not for us */
16651 					break;
16652 				}
16653 				ire_refrele(dst_ire);
16654 				/* FALLTHRU */
16655 			case IPOPT_TS_TSANDADDR:
16656 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16657 				break;
16658 			default:
16659 				/*
16660 				 * ip_*put_options should have already
16661 				 * dropped this packet.
16662 				 */
16663 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16664 				    "unknown IT - bug in ip_rput_options?\n");
16665 				return (0);	/* Keep "lint" happy */
16666 			}
16667 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16668 				/* Increase overflow counter */
16669 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16670 				opt[IPOPT_POS_OV_FLG] =
16671 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16672 				    (off << 4));
16673 				break;
16674 			}
16675 			off = opt[IPOPT_OFFSET] - 1;
16676 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16677 			case IPOPT_TS_PRESPEC:
16678 			case IPOPT_TS_PRESPEC_RFC791:
16679 			case IPOPT_TS_TSANDADDR:
16680 				bcopy(&ire->ire_src_addr,
16681 				    (char *)opt + off, IP_ADDR_LEN);
16682 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16683 				/* FALLTHRU */
16684 			case IPOPT_TS_TSONLY:
16685 				off = opt[IPOPT_OFFSET] - 1;
16686 				/* Compute # of milliseconds since midnight */
16687 				gethrestime(&now);
16688 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16689 				    now.tv_nsec / (NANOSEC / MILLISEC);
16690 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16691 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16692 				break;
16693 			}
16694 			break;
16695 		}
16696 	}
16697 	return (0);
16698 }
16699 
16700 /*
16701  * This is called after processing at least one of AH/ESP headers.
16702  *
16703  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16704  * the actual, physical interface on which the packet was received,
16705  * but, when ip_strict_dst_multihoming is set to 1, could be the
16706  * interface which had the ipha_dst configured when the packet went
16707  * through ip_rput. The ill_index corresponding to the recv_ill
16708  * is saved in ipsec_in_rill_index
16709  *
16710  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16711  * cannot assume "ire" points to valid data for any IPv6 cases.
16712  */
16713 void
16714 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16715 {
16716 	mblk_t *mp;
16717 	ipaddr_t dst;
16718 	in6_addr_t *v6dstp;
16719 	ipha_t *ipha;
16720 	ip6_t *ip6h;
16721 	ipsec_in_t *ii;
16722 	boolean_t ill_need_rele = B_FALSE;
16723 	boolean_t rill_need_rele = B_FALSE;
16724 	boolean_t ire_need_rele = B_FALSE;
16725 	netstack_t	*ns;
16726 	ip_stack_t	*ipst;
16727 
16728 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16729 	ASSERT(ii->ipsec_in_ill_index != 0);
16730 	ns = ii->ipsec_in_ns;
16731 	ASSERT(ii->ipsec_in_ns != NULL);
16732 	ipst = ns->netstack_ip;
16733 
16734 	mp = ipsec_mp->b_cont;
16735 	ASSERT(mp != NULL);
16736 
16737 
16738 	if (ill == NULL) {
16739 		ASSERT(recv_ill == NULL);
16740 		/*
16741 		 * We need to get the original queue on which ip_rput_local
16742 		 * or ip_rput_data_v6 was called.
16743 		 */
16744 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16745 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16746 		ill_need_rele = B_TRUE;
16747 
16748 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16749 			recv_ill = ill_lookup_on_ifindex(
16750 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16751 			    NULL, NULL, NULL, NULL, ipst);
16752 			rill_need_rele = B_TRUE;
16753 		} else {
16754 			recv_ill = ill;
16755 		}
16756 
16757 		if ((ill == NULL) || (recv_ill == NULL)) {
16758 			ip0dbg(("ip_fanout_proto_again: interface "
16759 			    "disappeared\n"));
16760 			if (ill != NULL)
16761 				ill_refrele(ill);
16762 			if (recv_ill != NULL)
16763 				ill_refrele(recv_ill);
16764 			freemsg(ipsec_mp);
16765 			return;
16766 		}
16767 	}
16768 
16769 	ASSERT(ill != NULL && recv_ill != NULL);
16770 
16771 	if (mp->b_datap->db_type == M_CTL) {
16772 		/*
16773 		 * AH/ESP is returning the ICMP message after
16774 		 * removing their headers. Fanout again till
16775 		 * it gets to the right protocol.
16776 		 */
16777 		if (ii->ipsec_in_v4) {
16778 			icmph_t *icmph;
16779 			int iph_hdr_length;
16780 			int hdr_length;
16781 
16782 			ipha = (ipha_t *)mp->b_rptr;
16783 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16784 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16785 			ipha = (ipha_t *)&icmph[1];
16786 			hdr_length = IPH_HDR_LENGTH(ipha);
16787 			/*
16788 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16789 			 * Reset the type to M_DATA.
16790 			 */
16791 			mp->b_datap->db_type = M_DATA;
16792 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16793 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16794 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16795 		} else {
16796 			icmp6_t *icmp6;
16797 			int hdr_length;
16798 
16799 			ip6h = (ip6_t *)mp->b_rptr;
16800 			/* Don't call hdr_length_v6() unless you have to. */
16801 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16802 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16803 			else
16804 				hdr_length = IPV6_HDR_LEN;
16805 
16806 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16807 			/*
16808 			 * icmp_inbound_error_fanout_v6 may need to do
16809 			 * pullupmsg.  Reset the type to M_DATA.
16810 			 */
16811 			mp->b_datap->db_type = M_DATA;
16812 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16813 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16814 		}
16815 		if (ill_need_rele)
16816 			ill_refrele(ill);
16817 		if (rill_need_rele)
16818 			ill_refrele(recv_ill);
16819 		return;
16820 	}
16821 
16822 	if (ii->ipsec_in_v4) {
16823 		ipha = (ipha_t *)mp->b_rptr;
16824 		dst = ipha->ipha_dst;
16825 		if (CLASSD(dst)) {
16826 			/*
16827 			 * Multicast has to be delivered to all streams.
16828 			 */
16829 			dst = INADDR_BROADCAST;
16830 		}
16831 
16832 		if (ire == NULL) {
16833 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16834 			    MBLK_GETLABEL(mp), ipst);
16835 			if (ire == NULL) {
16836 				if (ill_need_rele)
16837 					ill_refrele(ill);
16838 				if (rill_need_rele)
16839 					ill_refrele(recv_ill);
16840 				ip1dbg(("ip_fanout_proto_again: "
16841 				    "IRE not found"));
16842 				freemsg(ipsec_mp);
16843 				return;
16844 			}
16845 			ire_need_rele = B_TRUE;
16846 		}
16847 
16848 		switch (ipha->ipha_protocol) {
16849 			case IPPROTO_UDP:
16850 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16851 				    recv_ill);
16852 				if (ire_need_rele)
16853 					ire_refrele(ire);
16854 				break;
16855 			case IPPROTO_TCP:
16856 				if (!ire_need_rele)
16857 					IRE_REFHOLD(ire);
16858 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16859 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16860 				IRE_REFRELE(ire);
16861 				if (mp != NULL)
16862 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16863 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16864 				break;
16865 			case IPPROTO_SCTP:
16866 				if (!ire_need_rele)
16867 					IRE_REFHOLD(ire);
16868 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16869 				    ipsec_mp, 0, ill->ill_rq, dst);
16870 				break;
16871 			default:
16872 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16873 				    recv_ill, B_FALSE);
16874 				if (ire_need_rele)
16875 					ire_refrele(ire);
16876 				break;
16877 		}
16878 	} else {
16879 		uint32_t rput_flags = 0;
16880 
16881 		ip6h = (ip6_t *)mp->b_rptr;
16882 		v6dstp = &ip6h->ip6_dst;
16883 		/*
16884 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16885 		 * address.
16886 		 *
16887 		 * Currently, we don't store that state in the IPSEC_IN
16888 		 * message, and we may need to.
16889 		 */
16890 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16891 		    IP6_IN_LLMCAST : 0);
16892 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16893 		    NULL, NULL);
16894 	}
16895 	if (ill_need_rele)
16896 		ill_refrele(ill);
16897 	if (rill_need_rele)
16898 		ill_refrele(recv_ill);
16899 }
16900 
16901 /*
16902  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16903  * returns 'true' if there are still fragments left on the queue, in
16904  * which case we restart the timer.
16905  */
16906 void
16907 ill_frag_timer(void *arg)
16908 {
16909 	ill_t	*ill = (ill_t *)arg;
16910 	boolean_t frag_pending;
16911 	ip_stack_t	*ipst = ill->ill_ipst;
16912 
16913 	mutex_enter(&ill->ill_lock);
16914 	ASSERT(!ill->ill_fragtimer_executing);
16915 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16916 		ill->ill_frag_timer_id = 0;
16917 		mutex_exit(&ill->ill_lock);
16918 		return;
16919 	}
16920 	ill->ill_fragtimer_executing = 1;
16921 	mutex_exit(&ill->ill_lock);
16922 
16923 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16924 
16925 	/*
16926 	 * Restart the timer, if we have fragments pending or if someone
16927 	 * wanted us to be scheduled again.
16928 	 */
16929 	mutex_enter(&ill->ill_lock);
16930 	ill->ill_fragtimer_executing = 0;
16931 	ill->ill_frag_timer_id = 0;
16932 	if (frag_pending || ill->ill_fragtimer_needrestart)
16933 		ill_frag_timer_start(ill);
16934 	mutex_exit(&ill->ill_lock);
16935 }
16936 
16937 void
16938 ill_frag_timer_start(ill_t *ill)
16939 {
16940 	ip_stack_t	*ipst = ill->ill_ipst;
16941 
16942 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16943 
16944 	/* If the ill is closing or opening don't proceed */
16945 	if (ill->ill_state_flags & ILL_CONDEMNED)
16946 		return;
16947 
16948 	if (ill->ill_fragtimer_executing) {
16949 		/*
16950 		 * ill_frag_timer is currently executing. Just record the
16951 		 * the fact that we want the timer to be restarted.
16952 		 * ill_frag_timer will post a timeout before it returns,
16953 		 * ensuring it will be called again.
16954 		 */
16955 		ill->ill_fragtimer_needrestart = 1;
16956 		return;
16957 	}
16958 
16959 	if (ill->ill_frag_timer_id == 0) {
16960 		/*
16961 		 * The timer is neither running nor is the timeout handler
16962 		 * executing. Post a timeout so that ill_frag_timer will be
16963 		 * called
16964 		 */
16965 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16966 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
16967 		ill->ill_fragtimer_needrestart = 0;
16968 	}
16969 }
16970 
16971 /*
16972  * This routine is needed for loopback when forwarding multicasts.
16973  *
16974  * IPQoS Notes:
16975  * IPPF processing is done in fanout routines.
16976  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16977  * processing for IPsec packets is done when it comes back in clear.
16978  * NOTE : The callers of this function need to do the ire_refrele for the
16979  *	  ire that is being passed in.
16980  */
16981 void
16982 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16983     ill_t *recv_ill, boolean_t esp_in_udp_packet)
16984 {
16985 	ill_t	*ill = (ill_t *)q->q_ptr;
16986 	uint32_t	sum;
16987 	uint32_t	u1;
16988 	uint32_t	u2;
16989 	int		hdr_length;
16990 	boolean_t	mctl_present;
16991 	mblk_t		*first_mp = mp;
16992 	mblk_t		*hada_mp = NULL;
16993 	ipha_t		*inner_ipha;
16994 	ip_stack_t	*ipst;
16995 
16996 	ASSERT(recv_ill != NULL);
16997 	ipst = recv_ill->ill_ipst;
16998 
16999 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17000 	    "ip_rput_locl_start: q %p", q);
17001 
17002 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17003 	ASSERT(ill != NULL);
17004 
17005 
17006 #define	rptr	((uchar_t *)ipha)
17007 #define	iphs	((uint16_t *)ipha)
17008 
17009 	/*
17010 	 * no UDP or TCP packet should come here anymore.
17011 	 */
17012 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17013 	    ipha->ipha_protocol != IPPROTO_UDP);
17014 
17015 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17016 	if (mctl_present &&
17017 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17018 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17019 
17020 		/*
17021 		 * It's an IPsec accelerated packet.
17022 		 * Keep a pointer to the data attributes around until
17023 		 * we allocate the ipsec_info_t.
17024 		 */
17025 		IPSECHW_DEBUG(IPSECHW_PKT,
17026 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17027 		hada_mp = first_mp;
17028 		hada_mp->b_cont = NULL;
17029 		/*
17030 		 * Since it is accelerated, it comes directly from
17031 		 * the ill and the data attributes is followed by
17032 		 * the packet data.
17033 		 */
17034 		ASSERT(mp->b_datap->db_type != M_CTL);
17035 		first_mp = mp;
17036 		mctl_present = B_FALSE;
17037 	}
17038 
17039 	/*
17040 	 * IF M_CTL is not present, then ipsec_in_is_secure
17041 	 * should return B_TRUE. There is a case where loopback
17042 	 * packets has an M_CTL in the front with all the
17043 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17044 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17045 	 * packets never comes here, it is safe to ASSERT the
17046 	 * following.
17047 	 */
17048 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17049 
17050 	/*
17051 	 * Also, we should never have an mctl_present if this is an
17052 	 * ESP-in-UDP packet.
17053 	 */
17054 	ASSERT(!mctl_present || !esp_in_udp_packet);
17055 
17056 
17057 	/* u1 is # words of IP options */
17058 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17059 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17060 
17061 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17062 		if (u1) {
17063 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17064 				if (hada_mp != NULL)
17065 					freemsg(hada_mp);
17066 				return;
17067 			}
17068 		} else {
17069 			/* Check the IP header checksum.  */
17070 #define	uph	((uint16_t *)ipha)
17071 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17072 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17073 #undef  uph
17074 			/* finish doing IP checksum */
17075 			sum = (sum & 0xFFFF) + (sum >> 16);
17076 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17077 			if (sum && sum != 0xFFFF) {
17078 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17079 				goto drop_pkt;
17080 			}
17081 		}
17082 	}
17083 
17084 	/*
17085 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17086 	 * might be called more than once for secure packets, count only
17087 	 * the first time.
17088 	 */
17089 	if (!mctl_present) {
17090 		UPDATE_IB_PKT_COUNT(ire);
17091 		ire->ire_last_used_time = lbolt;
17092 	}
17093 
17094 	/* Check for fragmentation offset. */
17095 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17096 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17097 	if (u1) {
17098 		/*
17099 		 * We re-assemble fragments before we do the AH/ESP
17100 		 * processing. Thus, M_CTL should not be present
17101 		 * while we are re-assembling.
17102 		 */
17103 		ASSERT(!mctl_present);
17104 		ASSERT(first_mp == mp);
17105 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17106 			return;
17107 		}
17108 		/*
17109 		 * Make sure that first_mp points back to mp as
17110 		 * the mp we came in with could have changed in
17111 		 * ip_rput_fragment().
17112 		 */
17113 		ipha = (ipha_t *)mp->b_rptr;
17114 		first_mp = mp;
17115 	}
17116 
17117 	/*
17118 	 * Clear hardware checksumming flag as it is currently only
17119 	 * used by TCP and UDP.
17120 	 */
17121 	DB_CKSUMFLAGS(mp) = 0;
17122 
17123 	/* Now we have a complete datagram, destined for this machine. */
17124 	u1 = IPH_HDR_LENGTH(ipha);
17125 	switch (ipha->ipha_protocol) {
17126 	case IPPROTO_ICMP: {
17127 		ire_t		*ire_zone;
17128 		ilm_t		*ilm;
17129 		mblk_t		*mp1;
17130 		zoneid_t	last_zoneid;
17131 
17132 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17133 			ASSERT(ire->ire_type == IRE_BROADCAST);
17134 			/*
17135 			 * In the multicast case, applications may have joined
17136 			 * the group from different zones, so we need to deliver
17137 			 * the packet to each of them. Loop through the
17138 			 * multicast memberships structures (ilm) on the receive
17139 			 * ill and send a copy of the packet up each matching
17140 			 * one. However, we don't do this for multicasts sent on
17141 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17142 			 * they must stay in the sender's zone.
17143 			 *
17144 			 * ilm_add_v6() ensures that ilms in the same zone are
17145 			 * contiguous in the ill_ilm list. We use this property
17146 			 * to avoid sending duplicates needed when two
17147 			 * applications in the same zone join the same group on
17148 			 * different logical interfaces: we ignore the ilm if
17149 			 * its zoneid is the same as the last matching one.
17150 			 * In addition, the sending of the packet for
17151 			 * ire_zoneid is delayed until all of the other ilms
17152 			 * have been exhausted.
17153 			 */
17154 			last_zoneid = -1;
17155 			ILM_WALKER_HOLD(recv_ill);
17156 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17157 			    ilm = ilm->ilm_next) {
17158 				if ((ilm->ilm_flags & ILM_DELETED) ||
17159 				    ipha->ipha_dst != ilm->ilm_addr ||
17160 				    ilm->ilm_zoneid == last_zoneid ||
17161 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17162 				    ilm->ilm_zoneid == ALL_ZONES ||
17163 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17164 					continue;
17165 				mp1 = ip_copymsg(first_mp);
17166 				if (mp1 == NULL)
17167 					continue;
17168 				icmp_inbound(q, mp1, B_TRUE, ill,
17169 				    0, sum, mctl_present, B_TRUE,
17170 				    recv_ill, ilm->ilm_zoneid);
17171 				last_zoneid = ilm->ilm_zoneid;
17172 			}
17173 			ILM_WALKER_RELE(recv_ill);
17174 		} else if (ire->ire_type == IRE_BROADCAST) {
17175 			/*
17176 			 * In the broadcast case, there may be many zones
17177 			 * which need a copy of the packet delivered to them.
17178 			 * There is one IRE_BROADCAST per broadcast address
17179 			 * and per zone; we walk those using a helper function.
17180 			 * In addition, the sending of the packet for ire is
17181 			 * delayed until all of the other ires have been
17182 			 * processed.
17183 			 */
17184 			IRB_REFHOLD(ire->ire_bucket);
17185 			ire_zone = NULL;
17186 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17187 			    ire)) != NULL) {
17188 				mp1 = ip_copymsg(first_mp);
17189 				if (mp1 == NULL)
17190 					continue;
17191 
17192 				UPDATE_IB_PKT_COUNT(ire_zone);
17193 				ire_zone->ire_last_used_time = lbolt;
17194 				icmp_inbound(q, mp1, B_TRUE, ill,
17195 				    0, sum, mctl_present, B_TRUE,
17196 				    recv_ill, ire_zone->ire_zoneid);
17197 			}
17198 			IRB_REFRELE(ire->ire_bucket);
17199 		}
17200 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17201 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17202 		    ire->ire_zoneid);
17203 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17204 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17205 		return;
17206 	}
17207 	case IPPROTO_IGMP:
17208 		/*
17209 		 * If we are not willing to accept IGMP packets in clear,
17210 		 * then check with global policy.
17211 		 */
17212 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17213 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17214 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17215 			if (first_mp == NULL)
17216 				return;
17217 		}
17218 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17219 			freemsg(first_mp);
17220 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17222 			return;
17223 		}
17224 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17225 			/* Bad packet - discarded by igmp_input */
17226 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17227 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17228 			if (mctl_present)
17229 				freeb(first_mp);
17230 			return;
17231 		}
17232 		/*
17233 		 * igmp_input() may have returned the pulled up message.
17234 		 * So first_mp and ipha need to be reinitialized.
17235 		 */
17236 		ipha = (ipha_t *)mp->b_rptr;
17237 		if (mctl_present)
17238 			first_mp->b_cont = mp;
17239 		else
17240 			first_mp = mp;
17241 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17242 		    connf_head != NULL) {
17243 			/* No user-level listener for IGMP packets */
17244 			goto drop_pkt;
17245 		}
17246 		/* deliver to local raw users */
17247 		break;
17248 	case IPPROTO_PIM:
17249 		/*
17250 		 * If we are not willing to accept PIM packets in clear,
17251 		 * then check with global policy.
17252 		 */
17253 		if (ipst->ips_pim_accept_clear_messages == 0) {
17254 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17255 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17256 			if (first_mp == NULL)
17257 				return;
17258 		}
17259 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17260 			freemsg(first_mp);
17261 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17262 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17263 			return;
17264 		}
17265 		if (pim_input(q, mp, ill) != 0) {
17266 			/* Bad packet - discarded by pim_input */
17267 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17268 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17269 			if (mctl_present)
17270 				freeb(first_mp);
17271 			return;
17272 		}
17273 
17274 		/*
17275 		 * pim_input() may have pulled up the message so ipha needs to
17276 		 * be reinitialized.
17277 		 */
17278 		ipha = (ipha_t *)mp->b_rptr;
17279 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17280 		    connf_head != NULL) {
17281 			/* No user-level listener for PIM packets */
17282 			goto drop_pkt;
17283 		}
17284 		/* deliver to local raw users */
17285 		break;
17286 	case IPPROTO_ENCAP:
17287 		/*
17288 		 * Handle self-encapsulated packets (IP-in-IP where
17289 		 * the inner addresses == the outer addresses).
17290 		 */
17291 		hdr_length = IPH_HDR_LENGTH(ipha);
17292 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17293 		    mp->b_wptr) {
17294 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17295 			    sizeof (ipha_t) - mp->b_rptr)) {
17296 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17297 				freemsg(first_mp);
17298 				return;
17299 			}
17300 			ipha = (ipha_t *)mp->b_rptr;
17301 		}
17302 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17303 		/*
17304 		 * Check the sanity of the inner IP header.
17305 		 */
17306 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17307 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17308 			freemsg(first_mp);
17309 			return;
17310 		}
17311 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17312 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17313 			freemsg(first_mp);
17314 			return;
17315 		}
17316 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17317 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17318 			ipsec_in_t *ii;
17319 
17320 			/*
17321 			 * Self-encapsulated tunnel packet. Remove
17322 			 * the outer IP header and fanout again.
17323 			 * We also need to make sure that the inner
17324 			 * header is pulled up until options.
17325 			 */
17326 			mp->b_rptr = (uchar_t *)inner_ipha;
17327 			ipha = inner_ipha;
17328 			hdr_length = IPH_HDR_LENGTH(ipha);
17329 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17330 				if (!pullupmsg(mp, (uchar_t *)ipha +
17331 				    + hdr_length - mp->b_rptr)) {
17332 					freemsg(first_mp);
17333 					return;
17334 				}
17335 				ipha = (ipha_t *)mp->b_rptr;
17336 			}
17337 			if (!mctl_present) {
17338 				ASSERT(first_mp == mp);
17339 				/*
17340 				 * This means that somebody is sending
17341 				 * Self-encapsualted packets without AH/ESP.
17342 				 * If AH/ESP was present, we would have already
17343 				 * allocated the first_mp.
17344 				 */
17345 				first_mp = ipsec_in_alloc(B_TRUE,
17346 				    ipst->ips_netstack);
17347 				if (first_mp == NULL) {
17348 					ip1dbg(("ip_proto_input: IPSEC_IN "
17349 					    "allocation failure.\n"));
17350 					BUMP_MIB(ill->ill_ip_mib,
17351 					    ipIfStatsInDiscards);
17352 					freemsg(mp);
17353 					return;
17354 				}
17355 				first_mp->b_cont = mp;
17356 			}
17357 			/*
17358 			 * We generally store the ill_index if we need to
17359 			 * do IPsec processing as we lose the ill queue when
17360 			 * we come back. But in this case, we never should
17361 			 * have to store the ill_index here as it should have
17362 			 * been stored previously when we processed the
17363 			 * AH/ESP header in this routine or for non-ipsec
17364 			 * cases, we still have the queue. But for some bad
17365 			 * packets from the wire, we can get to IPsec after
17366 			 * this and we better store the index for that case.
17367 			 */
17368 			ill = (ill_t *)q->q_ptr;
17369 			ii = (ipsec_in_t *)first_mp->b_rptr;
17370 			ii->ipsec_in_ill_index =
17371 			    ill->ill_phyint->phyint_ifindex;
17372 			ii->ipsec_in_rill_index =
17373 			    recv_ill->ill_phyint->phyint_ifindex;
17374 			if (ii->ipsec_in_decaps) {
17375 				/*
17376 				 * This packet is self-encapsulated multiple
17377 				 * times. We don't want to recurse infinitely.
17378 				 * To keep it simple, drop the packet.
17379 				 */
17380 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17381 				freemsg(first_mp);
17382 				return;
17383 			}
17384 			ii->ipsec_in_decaps = B_TRUE;
17385 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17386 			    ire);
17387 			return;
17388 		}
17389 		break;
17390 	case IPPROTO_AH:
17391 	case IPPROTO_ESP: {
17392 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17393 
17394 		/*
17395 		 * Fast path for AH/ESP. If this is the first time
17396 		 * we are sending a datagram to AH/ESP, allocate
17397 		 * a IPSEC_IN message and prepend it. Otherwise,
17398 		 * just fanout.
17399 		 */
17400 
17401 		int ipsec_rc;
17402 		ipsec_in_t *ii;
17403 		netstack_t *ns = ipst->ips_netstack;
17404 
17405 		IP_STAT(ipst, ipsec_proto_ahesp);
17406 		if (!mctl_present) {
17407 			ASSERT(first_mp == mp);
17408 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17409 			if (first_mp == NULL) {
17410 				ip1dbg(("ip_proto_input: IPSEC_IN "
17411 				    "allocation failure.\n"));
17412 				freemsg(hada_mp); /* okay ifnull */
17413 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17414 				freemsg(mp);
17415 				return;
17416 			}
17417 			/*
17418 			 * Store the ill_index so that when we come back
17419 			 * from IPsec we ride on the same queue.
17420 			 */
17421 			ill = (ill_t *)q->q_ptr;
17422 			ii = (ipsec_in_t *)first_mp->b_rptr;
17423 			ii->ipsec_in_ill_index =
17424 			    ill->ill_phyint->phyint_ifindex;
17425 			ii->ipsec_in_rill_index =
17426 			    recv_ill->ill_phyint->phyint_ifindex;
17427 			first_mp->b_cont = mp;
17428 			/*
17429 			 * Cache hardware acceleration info.
17430 			 */
17431 			if (hada_mp != NULL) {
17432 				IPSECHW_DEBUG(IPSECHW_PKT,
17433 				    ("ip_rput_local: caching data attr.\n"));
17434 				ii->ipsec_in_accelerated = B_TRUE;
17435 				ii->ipsec_in_da = hada_mp;
17436 				hada_mp = NULL;
17437 			}
17438 		} else {
17439 			ii = (ipsec_in_t *)first_mp->b_rptr;
17440 		}
17441 
17442 		if (!ipsec_loaded(ipss)) {
17443 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17444 			    ire->ire_zoneid, ipst);
17445 			return;
17446 		}
17447 
17448 		ns = ipst->ips_netstack;
17449 		/* select inbound SA and have IPsec process the pkt */
17450 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17451 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17452 			boolean_t esp_in_udp_sa;
17453 			if (esph == NULL)
17454 				return;
17455 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17456 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17457 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17458 			    IPSA_F_NATT) != 0);
17459 			/*
17460 			 * The following is a fancy, but quick, way of saying:
17461 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17462 			 *    OR
17463 			 * ESP SA and ESP-in-UDP packet --> drop
17464 			 */
17465 			if (esp_in_udp_sa != esp_in_udp_packet) {
17466 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17467 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17468 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17469 				    &ns->netstack_ipsec->ipsec_dropper);
17470 				return;
17471 			}
17472 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17473 			    first_mp, esph);
17474 		} else {
17475 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17476 			if (ah == NULL)
17477 				return;
17478 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17479 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17480 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17481 			    first_mp, ah);
17482 		}
17483 
17484 		switch (ipsec_rc) {
17485 		case IPSEC_STATUS_SUCCESS:
17486 			break;
17487 		case IPSEC_STATUS_FAILED:
17488 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17489 			/* FALLTHRU */
17490 		case IPSEC_STATUS_PENDING:
17491 			return;
17492 		}
17493 		/* we're done with IPsec processing, send it up */
17494 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17495 		return;
17496 	}
17497 	default:
17498 		break;
17499 	}
17500 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17501 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17502 		    ire->ire_zoneid));
17503 		goto drop_pkt;
17504 	}
17505 	/*
17506 	 * Handle protocols with which IP is less intimate.  There
17507 	 * can be more than one stream bound to a particular
17508 	 * protocol.  When this is the case, each one gets a copy
17509 	 * of any incoming packets.
17510 	 */
17511 	ip_fanout_proto(q, first_mp, ill, ipha,
17512 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17513 	    B_TRUE, recv_ill, ire->ire_zoneid);
17514 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17515 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17516 	return;
17517 
17518 drop_pkt:
17519 	freemsg(first_mp);
17520 	if (hada_mp != NULL)
17521 		freeb(hada_mp);
17522 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17523 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17524 #undef	rptr
17525 #undef  iphs
17526 
17527 }
17528 
17529 /*
17530  * Update any source route, record route or timestamp options.
17531  * Check that we are at end of strict source route.
17532  * The options have already been checked for sanity in ip_rput_options().
17533  */
17534 static boolean_t
17535 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17536     ip_stack_t *ipst)
17537 {
17538 	ipoptp_t	opts;
17539 	uchar_t		*opt;
17540 	uint8_t		optval;
17541 	uint8_t		optlen;
17542 	ipaddr_t	dst;
17543 	uint32_t	ts;
17544 	ire_t		*dst_ire;
17545 	timestruc_t	now;
17546 	zoneid_t	zoneid;
17547 	ill_t		*ill;
17548 
17549 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17550 
17551 	ip2dbg(("ip_rput_local_options\n"));
17552 
17553 	for (optval = ipoptp_first(&opts, ipha);
17554 	    optval != IPOPT_EOL;
17555 	    optval = ipoptp_next(&opts)) {
17556 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17557 		opt = opts.ipoptp_cur;
17558 		optlen = opts.ipoptp_len;
17559 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17560 		    optval, optlen));
17561 		switch (optval) {
17562 			uint32_t off;
17563 		case IPOPT_SSRR:
17564 		case IPOPT_LSRR:
17565 			off = opt[IPOPT_OFFSET];
17566 			off--;
17567 			if (optlen < IP_ADDR_LEN ||
17568 			    off > optlen - IP_ADDR_LEN) {
17569 				/* End of source route */
17570 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17571 				break;
17572 			}
17573 			/*
17574 			 * This will only happen if two consecutive entries
17575 			 * in the source route contains our address or if
17576 			 * it is a packet with a loose source route which
17577 			 * reaches us before consuming the whole source route
17578 			 */
17579 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17580 			if (optval == IPOPT_SSRR) {
17581 				goto bad_src_route;
17582 			}
17583 			/*
17584 			 * Hack: instead of dropping the packet truncate the
17585 			 * source route to what has been used by filling the
17586 			 * rest with IPOPT_NOP.
17587 			 */
17588 			opt[IPOPT_OLEN] = (uint8_t)off;
17589 			while (off < optlen) {
17590 				opt[off++] = IPOPT_NOP;
17591 			}
17592 			break;
17593 		case IPOPT_RR:
17594 			off = opt[IPOPT_OFFSET];
17595 			off--;
17596 			if (optlen < IP_ADDR_LEN ||
17597 			    off > optlen - IP_ADDR_LEN) {
17598 				/* No more room - ignore */
17599 				ip1dbg((
17600 				    "ip_rput_local_options: end of RR\n"));
17601 				break;
17602 			}
17603 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17604 			    IP_ADDR_LEN);
17605 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17606 			break;
17607 		case IPOPT_TS:
17608 			/* Insert timestamp if there is romm */
17609 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17610 			case IPOPT_TS_TSONLY:
17611 				off = IPOPT_TS_TIMELEN;
17612 				break;
17613 			case IPOPT_TS_PRESPEC:
17614 			case IPOPT_TS_PRESPEC_RFC791:
17615 				/* Verify that the address matched */
17616 				off = opt[IPOPT_OFFSET] - 1;
17617 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17618 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17619 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17620 				    ipst);
17621 				if (dst_ire == NULL) {
17622 					/* Not for us */
17623 					break;
17624 				}
17625 				ire_refrele(dst_ire);
17626 				/* FALLTHRU */
17627 			case IPOPT_TS_TSANDADDR:
17628 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17629 				break;
17630 			default:
17631 				/*
17632 				 * ip_*put_options should have already
17633 				 * dropped this packet.
17634 				 */
17635 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17636 				    "unknown IT - bug in ip_rput_options?\n");
17637 				return (B_TRUE);	/* Keep "lint" happy */
17638 			}
17639 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17640 				/* Increase overflow counter */
17641 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17642 				opt[IPOPT_POS_OV_FLG] =
17643 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17644 				    (off << 4));
17645 				break;
17646 			}
17647 			off = opt[IPOPT_OFFSET] - 1;
17648 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17649 			case IPOPT_TS_PRESPEC:
17650 			case IPOPT_TS_PRESPEC_RFC791:
17651 			case IPOPT_TS_TSANDADDR:
17652 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17653 				    IP_ADDR_LEN);
17654 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17655 				/* FALLTHRU */
17656 			case IPOPT_TS_TSONLY:
17657 				off = opt[IPOPT_OFFSET] - 1;
17658 				/* Compute # of milliseconds since midnight */
17659 				gethrestime(&now);
17660 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17661 				    now.tv_nsec / (NANOSEC / MILLISEC);
17662 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17663 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17664 				break;
17665 			}
17666 			break;
17667 		}
17668 	}
17669 	return (B_TRUE);
17670 
17671 bad_src_route:
17672 	q = WR(q);
17673 	if (q->q_next != NULL)
17674 		ill = q->q_ptr;
17675 	else
17676 		ill = NULL;
17677 
17678 	/* make sure we clear any indication of a hardware checksum */
17679 	DB_CKSUMFLAGS(mp) = 0;
17680 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17681 	if (zoneid == ALL_ZONES)
17682 		freemsg(mp);
17683 	else
17684 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17685 	return (B_FALSE);
17686 
17687 }
17688 
17689 /*
17690  * Process IP options in an inbound packet.  If an option affects the
17691  * effective destination address, return the next hop address via dstp.
17692  * Returns -1 if something fails in which case an ICMP error has been sent
17693  * and mp freed.
17694  */
17695 static int
17696 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17697     ip_stack_t *ipst)
17698 {
17699 	ipoptp_t	opts;
17700 	uchar_t		*opt;
17701 	uint8_t		optval;
17702 	uint8_t		optlen;
17703 	ipaddr_t	dst;
17704 	intptr_t	code = 0;
17705 	ire_t		*ire = NULL;
17706 	zoneid_t	zoneid;
17707 	ill_t		*ill;
17708 
17709 	ip2dbg(("ip_rput_options\n"));
17710 	dst = ipha->ipha_dst;
17711 	for (optval = ipoptp_first(&opts, ipha);
17712 	    optval != IPOPT_EOL;
17713 	    optval = ipoptp_next(&opts)) {
17714 		opt = opts.ipoptp_cur;
17715 		optlen = opts.ipoptp_len;
17716 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17717 		    optval, optlen));
17718 		/*
17719 		 * Note: we need to verify the checksum before we
17720 		 * modify anything thus this routine only extracts the next
17721 		 * hop dst from any source route.
17722 		 */
17723 		switch (optval) {
17724 			uint32_t off;
17725 		case IPOPT_SSRR:
17726 		case IPOPT_LSRR:
17727 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17728 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17729 			if (ire == NULL) {
17730 				if (optval == IPOPT_SSRR) {
17731 					ip1dbg(("ip_rput_options: not next"
17732 					    " strict source route 0x%x\n",
17733 					    ntohl(dst)));
17734 					code = (char *)&ipha->ipha_dst -
17735 					    (char *)ipha;
17736 					goto param_prob; /* RouterReq's */
17737 				}
17738 				ip2dbg(("ip_rput_options: "
17739 				    "not next source route 0x%x\n",
17740 				    ntohl(dst)));
17741 				break;
17742 			}
17743 			ire_refrele(ire);
17744 
17745 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17746 				ip1dbg((
17747 				    "ip_rput_options: bad option offset\n"));
17748 				code = (char *)&opt[IPOPT_OLEN] -
17749 				    (char *)ipha;
17750 				goto param_prob;
17751 			}
17752 			off = opt[IPOPT_OFFSET];
17753 			off--;
17754 		redo_srr:
17755 			if (optlen < IP_ADDR_LEN ||
17756 			    off > optlen - IP_ADDR_LEN) {
17757 				/* End of source route */
17758 				ip1dbg(("ip_rput_options: end of SR\n"));
17759 				break;
17760 			}
17761 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17762 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17763 			    ntohl(dst)));
17764 
17765 			/*
17766 			 * Check if our address is present more than
17767 			 * once as consecutive hops in source route.
17768 			 * XXX verify per-interface ip_forwarding
17769 			 * for source route?
17770 			 */
17771 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17772 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17773 
17774 			if (ire != NULL) {
17775 				ire_refrele(ire);
17776 				off += IP_ADDR_LEN;
17777 				goto redo_srr;
17778 			}
17779 
17780 			if (dst == htonl(INADDR_LOOPBACK)) {
17781 				ip1dbg(("ip_rput_options: loopback addr in "
17782 				    "source route!\n"));
17783 				goto bad_src_route;
17784 			}
17785 			/*
17786 			 * For strict: verify that dst is directly
17787 			 * reachable.
17788 			 */
17789 			if (optval == IPOPT_SSRR) {
17790 				ire = ire_ftable_lookup(dst, 0, 0,
17791 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17792 				    MBLK_GETLABEL(mp),
17793 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17794 				if (ire == NULL) {
17795 					ip1dbg(("ip_rput_options: SSRR not "
17796 					    "directly reachable: 0x%x\n",
17797 					    ntohl(dst)));
17798 					goto bad_src_route;
17799 				}
17800 				ire_refrele(ire);
17801 			}
17802 			/*
17803 			 * Defer update of the offset and the record route
17804 			 * until the packet is forwarded.
17805 			 */
17806 			break;
17807 		case IPOPT_RR:
17808 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17809 				ip1dbg((
17810 				    "ip_rput_options: bad option offset\n"));
17811 				code = (char *)&opt[IPOPT_OLEN] -
17812 				    (char *)ipha;
17813 				goto param_prob;
17814 			}
17815 			break;
17816 		case IPOPT_TS:
17817 			/*
17818 			 * Verify that length >= 5 and that there is either
17819 			 * room for another timestamp or that the overflow
17820 			 * counter is not maxed out.
17821 			 */
17822 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17823 			if (optlen < IPOPT_MINLEN_IT) {
17824 				goto param_prob;
17825 			}
17826 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17827 				ip1dbg((
17828 				    "ip_rput_options: bad option offset\n"));
17829 				code = (char *)&opt[IPOPT_OFFSET] -
17830 				    (char *)ipha;
17831 				goto param_prob;
17832 			}
17833 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17834 			case IPOPT_TS_TSONLY:
17835 				off = IPOPT_TS_TIMELEN;
17836 				break;
17837 			case IPOPT_TS_TSANDADDR:
17838 			case IPOPT_TS_PRESPEC:
17839 			case IPOPT_TS_PRESPEC_RFC791:
17840 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17841 				break;
17842 			default:
17843 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17844 				    (char *)ipha;
17845 				goto param_prob;
17846 			}
17847 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17848 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17849 				/*
17850 				 * No room and the overflow counter is 15
17851 				 * already.
17852 				 */
17853 				goto param_prob;
17854 			}
17855 			break;
17856 		}
17857 	}
17858 
17859 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17860 		*dstp = dst;
17861 		return (0);
17862 	}
17863 
17864 	ip1dbg(("ip_rput_options: error processing IP options."));
17865 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17866 
17867 param_prob:
17868 	q = WR(q);
17869 	if (q->q_next != NULL)
17870 		ill = q->q_ptr;
17871 	else
17872 		ill = NULL;
17873 
17874 	/* make sure we clear any indication of a hardware checksum */
17875 	DB_CKSUMFLAGS(mp) = 0;
17876 	/* Don't know whether this is for non-global or global/forwarding */
17877 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17878 	if (zoneid == ALL_ZONES)
17879 		freemsg(mp);
17880 	else
17881 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17882 	return (-1);
17883 
17884 bad_src_route:
17885 	q = WR(q);
17886 	if (q->q_next != NULL)
17887 		ill = q->q_ptr;
17888 	else
17889 		ill = NULL;
17890 
17891 	/* make sure we clear any indication of a hardware checksum */
17892 	DB_CKSUMFLAGS(mp) = 0;
17893 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17894 	if (zoneid == ALL_ZONES)
17895 		freemsg(mp);
17896 	else
17897 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17898 	return (-1);
17899 }
17900 
17901 /*
17902  * IP & ICMP info in >=14 msg's ...
17903  *  - ip fixed part (mib2_ip_t)
17904  *  - icmp fixed part (mib2_icmp_t)
17905  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17906  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17907  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17908  *  - ipRouteAttributeTable (ip 102)	labeled routes
17909  *  - ip multicast membership (ip_member_t)
17910  *  - ip multicast source filtering (ip_grpsrc_t)
17911  *  - igmp fixed part (struct igmpstat)
17912  *  - multicast routing stats (struct mrtstat)
17913  *  - multicast routing vifs (array of struct vifctl)
17914  *  - multicast routing routes (array of struct mfcctl)
17915  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17916  *					One per ill plus one generic
17917  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17918  *					One per ill plus one generic
17919  *  - ipv6RouteEntry			all IPv6 IREs
17920  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17921  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17922  *  - ipv6AddrEntry			all IPv6 ipifs
17923  *  - ipv6 multicast membership (ipv6_member_t)
17924  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17925  *
17926  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17927  *
17928  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17929  * already filled in by the caller.
17930  * Return value of 0 indicates that no messages were sent and caller
17931  * should free mpctl.
17932  */
17933 int
17934 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
17935 {
17936 	ip_stack_t *ipst;
17937 	sctp_stack_t *sctps;
17938 
17939 	if (q->q_next != NULL) {
17940 		ipst = ILLQ_TO_IPST(q);
17941 	} else {
17942 		ipst = CONNQ_TO_IPST(q);
17943 	}
17944 	ASSERT(ipst != NULL);
17945 	sctps = ipst->ips_netstack->netstack_sctp;
17946 
17947 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17948 		return (0);
17949 	}
17950 
17951 	/*
17952 	 * For the purposes of the (broken) packet shell use
17953 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
17954 	 * to make TCP and UDP appear first in the list of mib items.
17955 	 * TBD: We could expand this and use it in netstat so that
17956 	 * the kernel doesn't have to produce large tables (connections,
17957 	 * routes, etc) when netstat only wants the statistics or a particular
17958 	 * table.
17959 	 */
17960 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
17961 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
17962 			return (1);
17963 		}
17964 	}
17965 
17966 	if (level != MIB2_TCP) {
17967 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
17968 			return (1);
17969 		}
17970 	}
17971 
17972 	if (level != MIB2_UDP) {
17973 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
17974 			return (1);
17975 		}
17976 	}
17977 
17978 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
17979 	    ipst)) == NULL) {
17980 		return (1);
17981 	}
17982 
17983 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
17984 		return (1);
17985 	}
17986 
17987 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
17988 		return (1);
17989 	}
17990 
17991 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
17992 		return (1);
17993 	}
17994 
17995 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
17996 		return (1);
17997 	}
17998 
17999 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18000 		return (1);
18001 	}
18002 
18003 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18004 		return (1);
18005 	}
18006 
18007 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18008 		return (1);
18009 	}
18010 
18011 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18012 		return (1);
18013 	}
18014 
18015 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18016 		return (1);
18017 	}
18018 
18019 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18020 		return (1);
18021 	}
18022 
18023 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18024 		return (1);
18025 	}
18026 
18027 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18028 		return (1);
18029 	}
18030 
18031 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18032 		return (1);
18033 	}
18034 
18035 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18036 		return (1);
18037 	}
18038 
18039 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18040 	if (mpctl == NULL) {
18041 		return (1);
18042 	}
18043 
18044 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18045 		return (1);
18046 	}
18047 	freemsg(mpctl);
18048 	return (1);
18049 }
18050 
18051 
18052 /* Get global (legacy) IPv4 statistics */
18053 static mblk_t *
18054 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18055     ip_stack_t *ipst)
18056 {
18057 	mib2_ip_t		old_ip_mib;
18058 	struct opthdr		*optp;
18059 	mblk_t			*mp2ctl;
18060 
18061 	/*
18062 	 * make a copy of the original message
18063 	 */
18064 	mp2ctl = copymsg(mpctl);
18065 
18066 	/* fixed length IP structure... */
18067 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18068 	optp->level = MIB2_IP;
18069 	optp->name = 0;
18070 	SET_MIB(old_ip_mib.ipForwarding,
18071 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18072 	SET_MIB(old_ip_mib.ipDefaultTTL,
18073 	    (uint32_t)ipst->ips_ip_def_ttl);
18074 	SET_MIB(old_ip_mib.ipReasmTimeout,
18075 	    ipst->ips_ip_g_frag_timeout);
18076 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18077 	    sizeof (mib2_ipAddrEntry_t));
18078 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18079 	    sizeof (mib2_ipRouteEntry_t));
18080 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18081 	    sizeof (mib2_ipNetToMediaEntry_t));
18082 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18083 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18084 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18085 	    sizeof (mib2_ipAttributeEntry_t));
18086 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18087 
18088 	/*
18089 	 * Grab the statistics from the new IP MIB
18090 	 */
18091 	SET_MIB(old_ip_mib.ipInReceives,
18092 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18093 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18094 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18095 	SET_MIB(old_ip_mib.ipForwDatagrams,
18096 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18097 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18098 	    ipmib->ipIfStatsInUnknownProtos);
18099 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18100 	SET_MIB(old_ip_mib.ipInDelivers,
18101 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18102 	SET_MIB(old_ip_mib.ipOutRequests,
18103 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18104 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18105 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18106 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18107 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18108 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18109 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18110 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18111 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18112 
18113 	/* ipRoutingDiscards is not being used */
18114 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18115 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18116 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18117 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18118 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18119 	    ipmib->ipIfStatsReasmDuplicates);
18120 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18121 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18122 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18123 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18124 	SET_MIB(old_ip_mib.rawipInOverflows,
18125 	    ipmib->rawipIfStatsInOverflows);
18126 
18127 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18128 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18129 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18130 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18131 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18132 	    ipmib->ipIfStatsOutSwitchIPVersion);
18133 
18134 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18135 	    (int)sizeof (old_ip_mib))) {
18136 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18137 		    (uint_t)sizeof (old_ip_mib)));
18138 	}
18139 
18140 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18141 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18142 	    (int)optp->level, (int)optp->name, (int)optp->len));
18143 	qreply(q, mpctl);
18144 	return (mp2ctl);
18145 }
18146 
18147 /* Per interface IPv4 statistics */
18148 static mblk_t *
18149 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18150 {
18151 	struct opthdr		*optp;
18152 	mblk_t			*mp2ctl;
18153 	ill_t			*ill;
18154 	ill_walk_context_t	ctx;
18155 	mblk_t			*mp_tail = NULL;
18156 	mib2_ipIfStatsEntry_t	global_ip_mib;
18157 
18158 	/*
18159 	 * Make a copy of the original message
18160 	 */
18161 	mp2ctl = copymsg(mpctl);
18162 
18163 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18164 	optp->level = MIB2_IP;
18165 	optp->name = MIB2_IP_TRAFFIC_STATS;
18166 	/* Include "unknown interface" ip_mib */
18167 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18168 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18169 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18170 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18171 	    (ipst->ips_ip_g_forward ? 1 : 2));
18172 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18173 	    (uint32_t)ipst->ips_ip_def_ttl);
18174 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18175 	    sizeof (mib2_ipIfStatsEntry_t));
18176 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18177 	    sizeof (mib2_ipAddrEntry_t));
18178 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18179 	    sizeof (mib2_ipRouteEntry_t));
18180 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18181 	    sizeof (mib2_ipNetToMediaEntry_t));
18182 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18183 	    sizeof (ip_member_t));
18184 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18185 	    sizeof (ip_grpsrc_t));
18186 
18187 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18188 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18189 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18190 		    "failed to allocate %u bytes\n",
18191 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18192 	}
18193 
18194 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18195 
18196 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18197 	ill = ILL_START_WALK_V4(&ctx, ipst);
18198 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18199 		ill->ill_ip_mib->ipIfStatsIfIndex =
18200 		    ill->ill_phyint->phyint_ifindex;
18201 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18202 		    (ipst->ips_ip_g_forward ? 1 : 2));
18203 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18204 		    (uint32_t)ipst->ips_ip_def_ttl);
18205 
18206 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18207 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18208 		    (char *)ill->ill_ip_mib,
18209 		    (int)sizeof (*ill->ill_ip_mib))) {
18210 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18211 			    "failed to allocate %u bytes\n",
18212 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18213 		}
18214 	}
18215 	rw_exit(&ipst->ips_ill_g_lock);
18216 
18217 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18218 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18219 	    "level %d, name %d, len %d\n",
18220 	    (int)optp->level, (int)optp->name, (int)optp->len));
18221 	qreply(q, mpctl);
18222 
18223 	if (mp2ctl == NULL)
18224 		return (NULL);
18225 
18226 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18227 }
18228 
18229 /* Global IPv4 ICMP statistics */
18230 static mblk_t *
18231 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18232 {
18233 	struct opthdr		*optp;
18234 	mblk_t			*mp2ctl;
18235 
18236 	/*
18237 	 * Make a copy of the original message
18238 	 */
18239 	mp2ctl = copymsg(mpctl);
18240 
18241 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18242 	optp->level = MIB2_ICMP;
18243 	optp->name = 0;
18244 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18245 	    (int)sizeof (ipst->ips_icmp_mib))) {
18246 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18247 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18248 	}
18249 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18250 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18251 	    (int)optp->level, (int)optp->name, (int)optp->len));
18252 	qreply(q, mpctl);
18253 	return (mp2ctl);
18254 }
18255 
18256 /* Global IPv4 IGMP statistics */
18257 static mblk_t *
18258 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18259 {
18260 	struct opthdr		*optp;
18261 	mblk_t			*mp2ctl;
18262 
18263 	/*
18264 	 * make a copy of the original message
18265 	 */
18266 	mp2ctl = copymsg(mpctl);
18267 
18268 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18269 	optp->level = EXPER_IGMP;
18270 	optp->name = 0;
18271 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18272 	    (int)sizeof (ipst->ips_igmpstat))) {
18273 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18274 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18275 	}
18276 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18277 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18278 	    (int)optp->level, (int)optp->name, (int)optp->len));
18279 	qreply(q, mpctl);
18280 	return (mp2ctl);
18281 }
18282 
18283 /* Global IPv4 Multicast Routing statistics */
18284 static mblk_t *
18285 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18286 {
18287 	struct opthdr		*optp;
18288 	mblk_t			*mp2ctl;
18289 
18290 	/*
18291 	 * make a copy of the original message
18292 	 */
18293 	mp2ctl = copymsg(mpctl);
18294 
18295 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18296 	optp->level = EXPER_DVMRP;
18297 	optp->name = 0;
18298 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18299 		ip0dbg(("ip_mroute_stats: failed\n"));
18300 	}
18301 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18302 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18303 	    (int)optp->level, (int)optp->name, (int)optp->len));
18304 	qreply(q, mpctl);
18305 	return (mp2ctl);
18306 }
18307 
18308 /* IPv4 address information */
18309 static mblk_t *
18310 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18311 {
18312 	struct opthdr		*optp;
18313 	mblk_t			*mp2ctl;
18314 	mblk_t			*mp_tail = NULL;
18315 	ill_t			*ill;
18316 	ipif_t			*ipif;
18317 	uint_t			bitval;
18318 	mib2_ipAddrEntry_t	mae;
18319 	zoneid_t		zoneid;
18320 	ill_walk_context_t ctx;
18321 
18322 	/*
18323 	 * make a copy of the original message
18324 	 */
18325 	mp2ctl = copymsg(mpctl);
18326 
18327 	/* ipAddrEntryTable */
18328 
18329 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18330 	optp->level = MIB2_IP;
18331 	optp->name = MIB2_IP_ADDR;
18332 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18333 
18334 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18335 	ill = ILL_START_WALK_V4(&ctx, ipst);
18336 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18337 		for (ipif = ill->ill_ipif; ipif != NULL;
18338 		    ipif = ipif->ipif_next) {
18339 			if (ipif->ipif_zoneid != zoneid &&
18340 			    ipif->ipif_zoneid != ALL_ZONES)
18341 				continue;
18342 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18343 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18344 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18345 
18346 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18347 			    OCTET_LENGTH);
18348 			mae.ipAdEntIfIndex.o_length =
18349 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18350 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18351 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18352 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18353 			mae.ipAdEntInfo.ae_subnet_len =
18354 			    ip_mask_to_plen(ipif->ipif_net_mask);
18355 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18356 			for (bitval = 1;
18357 			    bitval &&
18358 			    !(bitval & ipif->ipif_brd_addr);
18359 			    bitval <<= 1)
18360 				noop;
18361 			mae.ipAdEntBcastAddr = bitval;
18362 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18363 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18364 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18365 			mae.ipAdEntInfo.ae_broadcast_addr =
18366 			    ipif->ipif_brd_addr;
18367 			mae.ipAdEntInfo.ae_pp_dst_addr =
18368 			    ipif->ipif_pp_dst_addr;
18369 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18370 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18371 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18372 
18373 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18374 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18375 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18376 				    "allocate %u bytes\n",
18377 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18378 			}
18379 		}
18380 	}
18381 	rw_exit(&ipst->ips_ill_g_lock);
18382 
18383 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18384 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18385 	    (int)optp->level, (int)optp->name, (int)optp->len));
18386 	qreply(q, mpctl);
18387 	return (mp2ctl);
18388 }
18389 
18390 /* IPv6 address information */
18391 static mblk_t *
18392 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18393 {
18394 	struct opthdr		*optp;
18395 	mblk_t			*mp2ctl;
18396 	mblk_t			*mp_tail = NULL;
18397 	ill_t			*ill;
18398 	ipif_t			*ipif;
18399 	mib2_ipv6AddrEntry_t	mae6;
18400 	zoneid_t		zoneid;
18401 	ill_walk_context_t	ctx;
18402 
18403 	/*
18404 	 * make a copy of the original message
18405 	 */
18406 	mp2ctl = copymsg(mpctl);
18407 
18408 	/* ipv6AddrEntryTable */
18409 
18410 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18411 	optp->level = MIB2_IP6;
18412 	optp->name = MIB2_IP6_ADDR;
18413 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18414 
18415 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18416 	ill = ILL_START_WALK_V6(&ctx, ipst);
18417 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18418 		for (ipif = ill->ill_ipif; ipif != NULL;
18419 		    ipif = ipif->ipif_next) {
18420 			if (ipif->ipif_zoneid != zoneid &&
18421 			    ipif->ipif_zoneid != ALL_ZONES)
18422 				continue;
18423 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18424 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18425 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18426 
18427 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18428 			    OCTET_LENGTH);
18429 			mae6.ipv6AddrIfIndex.o_length =
18430 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18431 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18432 			mae6.ipv6AddrPfxLength =
18433 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18434 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18435 			mae6.ipv6AddrInfo.ae_subnet_len =
18436 			    mae6.ipv6AddrPfxLength;
18437 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18438 
18439 			/* Type: stateless(1), stateful(2), unknown(3) */
18440 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18441 				mae6.ipv6AddrType = 1;
18442 			else
18443 				mae6.ipv6AddrType = 2;
18444 			/* Anycast: true(1), false(2) */
18445 			if (ipif->ipif_flags & IPIF_ANYCAST)
18446 				mae6.ipv6AddrAnycastFlag = 1;
18447 			else
18448 				mae6.ipv6AddrAnycastFlag = 2;
18449 
18450 			/*
18451 			 * Address status: preferred(1), deprecated(2),
18452 			 * invalid(3), inaccessible(4), unknown(5)
18453 			 */
18454 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18455 				mae6.ipv6AddrStatus = 3;
18456 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18457 				mae6.ipv6AddrStatus = 2;
18458 			else
18459 				mae6.ipv6AddrStatus = 1;
18460 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18461 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18462 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18463 			    ipif->ipif_v6pp_dst_addr;
18464 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18465 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18466 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18467 			mae6.ipv6AddrIdentifier = ill->ill_token;
18468 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18469 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18470 			mae6.ipv6AddrRetransmitTime =
18471 			    ill->ill_reachable_retrans_time;
18472 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18473 			    (char *)&mae6,
18474 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18475 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18476 				    "allocate %u bytes\n",
18477 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18478 			}
18479 		}
18480 	}
18481 	rw_exit(&ipst->ips_ill_g_lock);
18482 
18483 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18484 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18485 	    (int)optp->level, (int)optp->name, (int)optp->len));
18486 	qreply(q, mpctl);
18487 	return (mp2ctl);
18488 }
18489 
18490 /* IPv4 multicast group membership. */
18491 static mblk_t *
18492 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18493 {
18494 	struct opthdr		*optp;
18495 	mblk_t			*mp2ctl;
18496 	ill_t			*ill;
18497 	ipif_t			*ipif;
18498 	ilm_t			*ilm;
18499 	ip_member_t		ipm;
18500 	mblk_t			*mp_tail = NULL;
18501 	ill_walk_context_t	ctx;
18502 	zoneid_t		zoneid;
18503 
18504 	/*
18505 	 * make a copy of the original message
18506 	 */
18507 	mp2ctl = copymsg(mpctl);
18508 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18509 
18510 	/* ipGroupMember table */
18511 	optp = (struct opthdr *)&mpctl->b_rptr[
18512 	    sizeof (struct T_optmgmt_ack)];
18513 	optp->level = MIB2_IP;
18514 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18515 
18516 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18517 	ill = ILL_START_WALK_V4(&ctx, ipst);
18518 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18519 		ILM_WALKER_HOLD(ill);
18520 		for (ipif = ill->ill_ipif; ipif != NULL;
18521 		    ipif = ipif->ipif_next) {
18522 			if (ipif->ipif_zoneid != zoneid &&
18523 			    ipif->ipif_zoneid != ALL_ZONES)
18524 				continue;	/* not this zone */
18525 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18526 			    OCTET_LENGTH);
18527 			ipm.ipGroupMemberIfIndex.o_length =
18528 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18529 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18530 				ASSERT(ilm->ilm_ipif != NULL);
18531 				ASSERT(ilm->ilm_ill == NULL);
18532 				if (ilm->ilm_ipif != ipif)
18533 					continue;
18534 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18535 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18536 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18537 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18538 				    (char *)&ipm, (int)sizeof (ipm))) {
18539 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18540 					    "failed to allocate %u bytes\n",
18541 					    (uint_t)sizeof (ipm)));
18542 				}
18543 			}
18544 		}
18545 		ILM_WALKER_RELE(ill);
18546 	}
18547 	rw_exit(&ipst->ips_ill_g_lock);
18548 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18549 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18550 	    (int)optp->level, (int)optp->name, (int)optp->len));
18551 	qreply(q, mpctl);
18552 	return (mp2ctl);
18553 }
18554 
18555 /* IPv6 multicast group membership. */
18556 static mblk_t *
18557 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18558 {
18559 	struct opthdr		*optp;
18560 	mblk_t			*mp2ctl;
18561 	ill_t			*ill;
18562 	ilm_t			*ilm;
18563 	ipv6_member_t		ipm6;
18564 	mblk_t			*mp_tail = NULL;
18565 	ill_walk_context_t	ctx;
18566 	zoneid_t		zoneid;
18567 
18568 	/*
18569 	 * make a copy of the original message
18570 	 */
18571 	mp2ctl = copymsg(mpctl);
18572 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18573 
18574 	/* ip6GroupMember table */
18575 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18576 	optp->level = MIB2_IP6;
18577 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18578 
18579 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18580 	ill = ILL_START_WALK_V6(&ctx, ipst);
18581 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18582 		ILM_WALKER_HOLD(ill);
18583 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18584 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18585 			ASSERT(ilm->ilm_ipif == NULL);
18586 			ASSERT(ilm->ilm_ill != NULL);
18587 			if (ilm->ilm_zoneid != zoneid)
18588 				continue;	/* not this zone */
18589 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18590 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18591 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18592 			if (!snmp_append_data2(mpctl->b_cont,
18593 			    &mp_tail,
18594 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18595 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18596 				    "failed to allocate %u bytes\n",
18597 				    (uint_t)sizeof (ipm6)));
18598 			}
18599 		}
18600 		ILM_WALKER_RELE(ill);
18601 	}
18602 	rw_exit(&ipst->ips_ill_g_lock);
18603 
18604 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18605 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18606 	    (int)optp->level, (int)optp->name, (int)optp->len));
18607 	qreply(q, mpctl);
18608 	return (mp2ctl);
18609 }
18610 
18611 /* IP multicast filtered sources */
18612 static mblk_t *
18613 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18614 {
18615 	struct opthdr		*optp;
18616 	mblk_t			*mp2ctl;
18617 	ill_t			*ill;
18618 	ipif_t			*ipif;
18619 	ilm_t			*ilm;
18620 	ip_grpsrc_t		ips;
18621 	mblk_t			*mp_tail = NULL;
18622 	ill_walk_context_t	ctx;
18623 	zoneid_t		zoneid;
18624 	int			i;
18625 	slist_t			*sl;
18626 
18627 	/*
18628 	 * make a copy of the original message
18629 	 */
18630 	mp2ctl = copymsg(mpctl);
18631 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18632 
18633 	/* ipGroupSource table */
18634 	optp = (struct opthdr *)&mpctl->b_rptr[
18635 	    sizeof (struct T_optmgmt_ack)];
18636 	optp->level = MIB2_IP;
18637 	optp->name = EXPER_IP_GROUP_SOURCES;
18638 
18639 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18640 	ill = ILL_START_WALK_V4(&ctx, ipst);
18641 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18642 		ILM_WALKER_HOLD(ill);
18643 		for (ipif = ill->ill_ipif; ipif != NULL;
18644 		    ipif = ipif->ipif_next) {
18645 			if (ipif->ipif_zoneid != zoneid)
18646 				continue;	/* not this zone */
18647 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18648 			    OCTET_LENGTH);
18649 			ips.ipGroupSourceIfIndex.o_length =
18650 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18651 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18652 				ASSERT(ilm->ilm_ipif != NULL);
18653 				ASSERT(ilm->ilm_ill == NULL);
18654 				sl = ilm->ilm_filter;
18655 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18656 					continue;
18657 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18658 				for (i = 0; i < sl->sl_numsrc; i++) {
18659 					if (!IN6_IS_ADDR_V4MAPPED(
18660 					    &sl->sl_addr[i]))
18661 						continue;
18662 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18663 					    ips.ipGroupSourceAddress);
18664 					if (snmp_append_data2(mpctl->b_cont,
18665 					    &mp_tail, (char *)&ips,
18666 					    (int)sizeof (ips)) == 0) {
18667 						ip1dbg(("ip_snmp_get_mib2_"
18668 						    "ip_group_src: failed to "
18669 						    "allocate %u bytes\n",
18670 						    (uint_t)sizeof (ips)));
18671 					}
18672 				}
18673 			}
18674 		}
18675 		ILM_WALKER_RELE(ill);
18676 	}
18677 	rw_exit(&ipst->ips_ill_g_lock);
18678 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18679 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18680 	    (int)optp->level, (int)optp->name, (int)optp->len));
18681 	qreply(q, mpctl);
18682 	return (mp2ctl);
18683 }
18684 
18685 /* IPv6 multicast filtered sources. */
18686 static mblk_t *
18687 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18688 {
18689 	struct opthdr		*optp;
18690 	mblk_t			*mp2ctl;
18691 	ill_t			*ill;
18692 	ilm_t			*ilm;
18693 	ipv6_grpsrc_t		ips6;
18694 	mblk_t			*mp_tail = NULL;
18695 	ill_walk_context_t	ctx;
18696 	zoneid_t		zoneid;
18697 	int			i;
18698 	slist_t			*sl;
18699 
18700 	/*
18701 	 * make a copy of the original message
18702 	 */
18703 	mp2ctl = copymsg(mpctl);
18704 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18705 
18706 	/* ip6GroupMember table */
18707 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18708 	optp->level = MIB2_IP6;
18709 	optp->name = EXPER_IP6_GROUP_SOURCES;
18710 
18711 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18712 	ill = ILL_START_WALK_V6(&ctx, ipst);
18713 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18714 		ILM_WALKER_HOLD(ill);
18715 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18716 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18717 			ASSERT(ilm->ilm_ipif == NULL);
18718 			ASSERT(ilm->ilm_ill != NULL);
18719 			sl = ilm->ilm_filter;
18720 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18721 				continue;
18722 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18723 			for (i = 0; i < sl->sl_numsrc; i++) {
18724 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18725 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18726 				    (char *)&ips6, (int)sizeof (ips6))) {
18727 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18728 					    "group_src: failed to allocate "
18729 					    "%u bytes\n",
18730 					    (uint_t)sizeof (ips6)));
18731 				}
18732 			}
18733 		}
18734 		ILM_WALKER_RELE(ill);
18735 	}
18736 	rw_exit(&ipst->ips_ill_g_lock);
18737 
18738 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18739 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18740 	    (int)optp->level, (int)optp->name, (int)optp->len));
18741 	qreply(q, mpctl);
18742 	return (mp2ctl);
18743 }
18744 
18745 /* Multicast routing virtual interface table. */
18746 static mblk_t *
18747 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18748 {
18749 	struct opthdr		*optp;
18750 	mblk_t			*mp2ctl;
18751 
18752 	/*
18753 	 * make a copy of the original message
18754 	 */
18755 	mp2ctl = copymsg(mpctl);
18756 
18757 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18758 	optp->level = EXPER_DVMRP;
18759 	optp->name = EXPER_DVMRP_VIF;
18760 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18761 		ip0dbg(("ip_mroute_vif: failed\n"));
18762 	}
18763 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18764 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18765 	    (int)optp->level, (int)optp->name, (int)optp->len));
18766 	qreply(q, mpctl);
18767 	return (mp2ctl);
18768 }
18769 
18770 /* Multicast routing table. */
18771 static mblk_t *
18772 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18773 {
18774 	struct opthdr		*optp;
18775 	mblk_t			*mp2ctl;
18776 
18777 	/*
18778 	 * make a copy of the original message
18779 	 */
18780 	mp2ctl = copymsg(mpctl);
18781 
18782 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18783 	optp->level = EXPER_DVMRP;
18784 	optp->name = EXPER_DVMRP_MRT;
18785 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18786 		ip0dbg(("ip_mroute_mrt: failed\n"));
18787 	}
18788 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18789 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18790 	    (int)optp->level, (int)optp->name, (int)optp->len));
18791 	qreply(q, mpctl);
18792 	return (mp2ctl);
18793 }
18794 
18795 /*
18796  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18797  * in one IRE walk.
18798  */
18799 static mblk_t *
18800 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18801 {
18802 	struct opthdr	*optp;
18803 	mblk_t		*mp2ctl;	/* Returned */
18804 	mblk_t		*mp3ctl;	/* nettomedia */
18805 	mblk_t		*mp4ctl;	/* routeattrs */
18806 	iproutedata_t	ird;
18807 	zoneid_t	zoneid;
18808 
18809 	/*
18810 	 * make copies of the original message
18811 	 *	- mp2ctl is returned unchanged to the caller for his use
18812 	 *	- mpctl is sent upstream as ipRouteEntryTable
18813 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18814 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18815 	 */
18816 	mp2ctl = copymsg(mpctl);
18817 	mp3ctl = copymsg(mpctl);
18818 	mp4ctl = copymsg(mpctl);
18819 	if (mp3ctl == NULL || mp4ctl == NULL) {
18820 		freemsg(mp4ctl);
18821 		freemsg(mp3ctl);
18822 		freemsg(mp2ctl);
18823 		freemsg(mpctl);
18824 		return (NULL);
18825 	}
18826 
18827 	bzero(&ird, sizeof (ird));
18828 
18829 	ird.ird_route.lp_head = mpctl->b_cont;
18830 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18831 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18832 
18833 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18834 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18835 
18836 	/* ipRouteEntryTable in mpctl */
18837 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18838 	optp->level = MIB2_IP;
18839 	optp->name = MIB2_IP_ROUTE;
18840 	optp->len = msgdsize(ird.ird_route.lp_head);
18841 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18842 	    (int)optp->level, (int)optp->name, (int)optp->len));
18843 	qreply(q, mpctl);
18844 
18845 	/* ipNetToMediaEntryTable in mp3ctl */
18846 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18847 	optp->level = MIB2_IP;
18848 	optp->name = MIB2_IP_MEDIA;
18849 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18850 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18851 	    (int)optp->level, (int)optp->name, (int)optp->len));
18852 	qreply(q, mp3ctl);
18853 
18854 	/* ipRouteAttributeTable in mp4ctl */
18855 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18856 	optp->level = MIB2_IP;
18857 	optp->name = EXPER_IP_RTATTR;
18858 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18859 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18860 	    (int)optp->level, (int)optp->name, (int)optp->len));
18861 	if (optp->len == 0)
18862 		freemsg(mp4ctl);
18863 	else
18864 		qreply(q, mp4ctl);
18865 
18866 	return (mp2ctl);
18867 }
18868 
18869 /*
18870  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18871  * ipv6NetToMediaEntryTable in an NDP walk.
18872  */
18873 static mblk_t *
18874 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18875 {
18876 	struct opthdr	*optp;
18877 	mblk_t		*mp2ctl;	/* Returned */
18878 	mblk_t		*mp3ctl;	/* nettomedia */
18879 	mblk_t		*mp4ctl;	/* routeattrs */
18880 	iproutedata_t	ird;
18881 	zoneid_t	zoneid;
18882 
18883 	/*
18884 	 * make copies of the original message
18885 	 *	- mp2ctl is returned unchanged to the caller for his use
18886 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18887 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18888 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18889 	 */
18890 	mp2ctl = copymsg(mpctl);
18891 	mp3ctl = copymsg(mpctl);
18892 	mp4ctl = copymsg(mpctl);
18893 	if (mp3ctl == NULL || mp4ctl == NULL) {
18894 		freemsg(mp4ctl);
18895 		freemsg(mp3ctl);
18896 		freemsg(mp2ctl);
18897 		freemsg(mpctl);
18898 		return (NULL);
18899 	}
18900 
18901 	bzero(&ird, sizeof (ird));
18902 
18903 	ird.ird_route.lp_head = mpctl->b_cont;
18904 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18905 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18906 
18907 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18908 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18909 
18910 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18911 	optp->level = MIB2_IP6;
18912 	optp->name = MIB2_IP6_ROUTE;
18913 	optp->len = msgdsize(ird.ird_route.lp_head);
18914 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18915 	    (int)optp->level, (int)optp->name, (int)optp->len));
18916 	qreply(q, mpctl);
18917 
18918 	/* ipv6NetToMediaEntryTable in mp3ctl */
18919 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18920 
18921 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18922 	optp->level = MIB2_IP6;
18923 	optp->name = MIB2_IP6_MEDIA;
18924 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18925 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18926 	    (int)optp->level, (int)optp->name, (int)optp->len));
18927 	qreply(q, mp3ctl);
18928 
18929 	/* ipv6RouteAttributeTable in mp4ctl */
18930 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18931 	optp->level = MIB2_IP6;
18932 	optp->name = EXPER_IP_RTATTR;
18933 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18934 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18935 	    (int)optp->level, (int)optp->name, (int)optp->len));
18936 	if (optp->len == 0)
18937 		freemsg(mp4ctl);
18938 	else
18939 		qreply(q, mp4ctl);
18940 
18941 	return (mp2ctl);
18942 }
18943 
18944 /*
18945  * IPv6 mib: One per ill
18946  */
18947 static mblk_t *
18948 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18949 {
18950 	struct opthdr		*optp;
18951 	mblk_t			*mp2ctl;
18952 	ill_t			*ill;
18953 	ill_walk_context_t	ctx;
18954 	mblk_t			*mp_tail = NULL;
18955 
18956 	/*
18957 	 * Make a copy of the original message
18958 	 */
18959 	mp2ctl = copymsg(mpctl);
18960 
18961 	/* fixed length IPv6 structure ... */
18962 
18963 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18964 	optp->level = MIB2_IP6;
18965 	optp->name = 0;
18966 	/* Include "unknown interface" ip6_mib */
18967 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18968 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
18969 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18970 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
18971 	    ipst->ips_ipv6_forward ? 1 : 2);
18972 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
18973 	    ipst->ips_ipv6_def_hops);
18974 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
18975 	    sizeof (mib2_ipIfStatsEntry_t));
18976 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
18977 	    sizeof (mib2_ipv6AddrEntry_t));
18978 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
18979 	    sizeof (mib2_ipv6RouteEntry_t));
18980 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
18981 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18982 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
18983 	    sizeof (ipv6_member_t));
18984 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
18985 	    sizeof (ipv6_grpsrc_t));
18986 
18987 	/*
18988 	 * Synchronize 64- and 32-bit counters
18989 	 */
18990 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
18991 	    ipIfStatsHCInReceives);
18992 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
18993 	    ipIfStatsHCInDelivers);
18994 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
18995 	    ipIfStatsHCOutRequests);
18996 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
18997 	    ipIfStatsHCOutForwDatagrams);
18998 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
18999 	    ipIfStatsHCOutMcastPkts);
19000 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19001 	    ipIfStatsHCInMcastPkts);
19002 
19003 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19004 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19005 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19006 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19007 	}
19008 
19009 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19010 	ill = ILL_START_WALK_V6(&ctx, ipst);
19011 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19012 		ill->ill_ip_mib->ipIfStatsIfIndex =
19013 		    ill->ill_phyint->phyint_ifindex;
19014 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19015 		    ipst->ips_ipv6_forward ? 1 : 2);
19016 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19017 		    ill->ill_max_hops);
19018 
19019 		/*
19020 		 * Synchronize 64- and 32-bit counters
19021 		 */
19022 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19023 		    ipIfStatsHCInReceives);
19024 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19025 		    ipIfStatsHCInDelivers);
19026 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19027 		    ipIfStatsHCOutRequests);
19028 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19029 		    ipIfStatsHCOutForwDatagrams);
19030 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19031 		    ipIfStatsHCOutMcastPkts);
19032 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19033 		    ipIfStatsHCInMcastPkts);
19034 
19035 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19036 		    (char *)ill->ill_ip_mib,
19037 		    (int)sizeof (*ill->ill_ip_mib))) {
19038 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19039 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19040 		}
19041 	}
19042 	rw_exit(&ipst->ips_ill_g_lock);
19043 
19044 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19045 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19046 	    (int)optp->level, (int)optp->name, (int)optp->len));
19047 	qreply(q, mpctl);
19048 	return (mp2ctl);
19049 }
19050 
19051 /*
19052  * ICMPv6 mib: One per ill
19053  */
19054 static mblk_t *
19055 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19056 {
19057 	struct opthdr		*optp;
19058 	mblk_t			*mp2ctl;
19059 	ill_t			*ill;
19060 	ill_walk_context_t	ctx;
19061 	mblk_t			*mp_tail = NULL;
19062 	/*
19063 	 * Make a copy of the original message
19064 	 */
19065 	mp2ctl = copymsg(mpctl);
19066 
19067 	/* fixed length ICMPv6 structure ... */
19068 
19069 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19070 	optp->level = MIB2_ICMP6;
19071 	optp->name = 0;
19072 	/* Include "unknown interface" icmp6_mib */
19073 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19074 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19075 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19076 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19077 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19078 	    (char *)&ipst->ips_icmp6_mib,
19079 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19080 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19081 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19082 	}
19083 
19084 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19085 	ill = ILL_START_WALK_V6(&ctx, ipst);
19086 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19087 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19088 		    ill->ill_phyint->phyint_ifindex;
19089 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19090 		    (char *)ill->ill_icmp6_mib,
19091 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19092 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19093 			    "%u bytes\n",
19094 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19095 		}
19096 	}
19097 	rw_exit(&ipst->ips_ill_g_lock);
19098 
19099 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19100 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19101 	    (int)optp->level, (int)optp->name, (int)optp->len));
19102 	qreply(q, mpctl);
19103 	return (mp2ctl);
19104 }
19105 
19106 /*
19107  * ire_walk routine to create both ipRouteEntryTable and
19108  * ipRouteAttributeTable in one IRE walk
19109  */
19110 static void
19111 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19112 {
19113 	ill_t				*ill;
19114 	ipif_t				*ipif;
19115 	mib2_ipRouteEntry_t		*re;
19116 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19117 	ipaddr_t			gw_addr;
19118 	tsol_ire_gw_secattr_t		*attrp;
19119 	tsol_gc_t			*gc = NULL;
19120 	tsol_gcgrp_t			*gcgrp = NULL;
19121 	uint_t				sacnt = 0;
19122 	int				i;
19123 
19124 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19125 
19126 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19127 		return;
19128 
19129 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19130 		mutex_enter(&attrp->igsa_lock);
19131 		if ((gc = attrp->igsa_gc) != NULL) {
19132 			gcgrp = gc->gc_grp;
19133 			ASSERT(gcgrp != NULL);
19134 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19135 			sacnt = 1;
19136 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19137 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19138 			gc = gcgrp->gcgrp_head;
19139 			sacnt = gcgrp->gcgrp_count;
19140 		}
19141 		mutex_exit(&attrp->igsa_lock);
19142 
19143 		/* do nothing if there's no gc to report */
19144 		if (gc == NULL) {
19145 			ASSERT(sacnt == 0);
19146 			if (gcgrp != NULL) {
19147 				/* we might as well drop the lock now */
19148 				rw_exit(&gcgrp->gcgrp_rwlock);
19149 				gcgrp = NULL;
19150 			}
19151 			attrp = NULL;
19152 		}
19153 
19154 		ASSERT(gc == NULL || (gcgrp != NULL &&
19155 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19156 	}
19157 	ASSERT(sacnt == 0 || gc != NULL);
19158 
19159 	if (sacnt != 0 &&
19160 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19161 		kmem_free(re, sizeof (*re));
19162 		rw_exit(&gcgrp->gcgrp_rwlock);
19163 		return;
19164 	}
19165 
19166 	/*
19167 	 * Return all IRE types for route table... let caller pick and choose
19168 	 */
19169 	re->ipRouteDest = ire->ire_addr;
19170 	ipif = ire->ire_ipif;
19171 	re->ipRouteIfIndex.o_length = 0;
19172 	if (ire->ire_type == IRE_CACHE) {
19173 		ill = (ill_t *)ire->ire_stq->q_ptr;
19174 		re->ipRouteIfIndex.o_length =
19175 		    ill->ill_name_length == 0 ? 0 :
19176 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19177 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19178 		    re->ipRouteIfIndex.o_length);
19179 	} else if (ipif != NULL) {
19180 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19181 		re->ipRouteIfIndex.o_length =
19182 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19183 	}
19184 	re->ipRouteMetric1 = -1;
19185 	re->ipRouteMetric2 = -1;
19186 	re->ipRouteMetric3 = -1;
19187 	re->ipRouteMetric4 = -1;
19188 
19189 	gw_addr = ire->ire_gateway_addr;
19190 
19191 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19192 		re->ipRouteNextHop = ire->ire_src_addr;
19193 	else
19194 		re->ipRouteNextHop = gw_addr;
19195 	/* indirect(4), direct(3), or invalid(2) */
19196 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19197 		re->ipRouteType = 2;
19198 	else
19199 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19200 	re->ipRouteProto = -1;
19201 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19202 	re->ipRouteMask = ire->ire_mask;
19203 	re->ipRouteMetric5 = -1;
19204 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19205 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19206 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19207 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19208 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19209 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19210 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19211 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19212 
19213 	if (ire->ire_flags & RTF_DYNAMIC) {
19214 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19215 	} else {
19216 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19217 	}
19218 
19219 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19220 	    (char *)re, (int)sizeof (*re))) {
19221 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19222 		    (uint_t)sizeof (*re)));
19223 	}
19224 
19225 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19226 		iaeptr->iae_routeidx = ird->ird_idx;
19227 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19228 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19229 	}
19230 
19231 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19232 	    (char *)iae, sacnt * sizeof (*iae))) {
19233 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19234 		    (unsigned)(sacnt * sizeof (*iae))));
19235 	}
19236 
19237 	/* bump route index for next pass */
19238 	ird->ird_idx++;
19239 
19240 	kmem_free(re, sizeof (*re));
19241 	if (sacnt != 0)
19242 		kmem_free(iae, sacnt * sizeof (*iae));
19243 
19244 	if (gcgrp != NULL)
19245 		rw_exit(&gcgrp->gcgrp_rwlock);
19246 }
19247 
19248 /*
19249  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19250  */
19251 static void
19252 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19253 {
19254 	ill_t				*ill;
19255 	ipif_t				*ipif;
19256 	mib2_ipv6RouteEntry_t		*re;
19257 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19258 	in6_addr_t			gw_addr_v6;
19259 	tsol_ire_gw_secattr_t		*attrp;
19260 	tsol_gc_t			*gc = NULL;
19261 	tsol_gcgrp_t			*gcgrp = NULL;
19262 	uint_t				sacnt = 0;
19263 	int				i;
19264 
19265 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19266 
19267 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19268 		return;
19269 
19270 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19271 		mutex_enter(&attrp->igsa_lock);
19272 		if ((gc = attrp->igsa_gc) != NULL) {
19273 			gcgrp = gc->gc_grp;
19274 			ASSERT(gcgrp != NULL);
19275 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19276 			sacnt = 1;
19277 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19278 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19279 			gc = gcgrp->gcgrp_head;
19280 			sacnt = gcgrp->gcgrp_count;
19281 		}
19282 		mutex_exit(&attrp->igsa_lock);
19283 
19284 		/* do nothing if there's no gc to report */
19285 		if (gc == NULL) {
19286 			ASSERT(sacnt == 0);
19287 			if (gcgrp != NULL) {
19288 				/* we might as well drop the lock now */
19289 				rw_exit(&gcgrp->gcgrp_rwlock);
19290 				gcgrp = NULL;
19291 			}
19292 			attrp = NULL;
19293 		}
19294 
19295 		ASSERT(gc == NULL || (gcgrp != NULL &&
19296 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19297 	}
19298 	ASSERT(sacnt == 0 || gc != NULL);
19299 
19300 	if (sacnt != 0 &&
19301 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19302 		kmem_free(re, sizeof (*re));
19303 		rw_exit(&gcgrp->gcgrp_rwlock);
19304 		return;
19305 	}
19306 
19307 	/*
19308 	 * Return all IRE types for route table... let caller pick and choose
19309 	 */
19310 	re->ipv6RouteDest = ire->ire_addr_v6;
19311 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19312 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19313 	re->ipv6RouteIfIndex.o_length = 0;
19314 	ipif = ire->ire_ipif;
19315 	if (ire->ire_type == IRE_CACHE) {
19316 		ill = (ill_t *)ire->ire_stq->q_ptr;
19317 		re->ipv6RouteIfIndex.o_length =
19318 		    ill->ill_name_length == 0 ? 0 :
19319 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19320 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19321 		    re->ipv6RouteIfIndex.o_length);
19322 	} else if (ipif != NULL) {
19323 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19324 		re->ipv6RouteIfIndex.o_length =
19325 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19326 	}
19327 
19328 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19329 
19330 	mutex_enter(&ire->ire_lock);
19331 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19332 	mutex_exit(&ire->ire_lock);
19333 
19334 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19335 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19336 	else
19337 		re->ipv6RouteNextHop = gw_addr_v6;
19338 
19339 	/* remote(4), local(3), or discard(2) */
19340 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19341 		re->ipv6RouteType = 2;
19342 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19343 		re->ipv6RouteType = 3;
19344 	else
19345 		re->ipv6RouteType = 4;
19346 
19347 	re->ipv6RouteProtocol	= -1;
19348 	re->ipv6RoutePolicy	= 0;
19349 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19350 	re->ipv6RouteNextHopRDI	= 0;
19351 	re->ipv6RouteWeight	= 0;
19352 	re->ipv6RouteMetric	= 0;
19353 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19354 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19355 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19356 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19357 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19358 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19359 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19360 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19361 
19362 	if (ire->ire_flags & RTF_DYNAMIC) {
19363 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19364 	} else {
19365 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19366 	}
19367 
19368 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19369 	    (char *)re, (int)sizeof (*re))) {
19370 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19371 		    (uint_t)sizeof (*re)));
19372 	}
19373 
19374 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19375 		iaeptr->iae_routeidx = ird->ird_idx;
19376 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19377 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19378 	}
19379 
19380 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19381 	    (char *)iae, sacnt * sizeof (*iae))) {
19382 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19383 		    (unsigned)(sacnt * sizeof (*iae))));
19384 	}
19385 
19386 	/* bump route index for next pass */
19387 	ird->ird_idx++;
19388 
19389 	kmem_free(re, sizeof (*re));
19390 	if (sacnt != 0)
19391 		kmem_free(iae, sacnt * sizeof (*iae));
19392 
19393 	if (gcgrp != NULL)
19394 		rw_exit(&gcgrp->gcgrp_rwlock);
19395 }
19396 
19397 /*
19398  * ndp_walk routine to create ipv6NetToMediaEntryTable
19399  */
19400 static int
19401 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19402 {
19403 	ill_t				*ill;
19404 	mib2_ipv6NetToMediaEntry_t	ntme;
19405 	dl_unitdata_req_t		*dl;
19406 
19407 	ill = nce->nce_ill;
19408 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19409 		return (0);
19410 
19411 	/*
19412 	 * Neighbor cache entry attached to IRE with on-link
19413 	 * destination.
19414 	 */
19415 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19416 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19417 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19418 	    (nce->nce_res_mp != NULL)) {
19419 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19420 		ntme.ipv6NetToMediaPhysAddress.o_length =
19421 		    dl->dl_dest_addr_length;
19422 	} else {
19423 		ntme.ipv6NetToMediaPhysAddress.o_length =
19424 		    ill->ill_phys_addr_length;
19425 	}
19426 	if (nce->nce_res_mp != NULL) {
19427 		bcopy((char *)nce->nce_res_mp->b_rptr +
19428 		    NCE_LL_ADDR_OFFSET(ill),
19429 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19430 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19431 	} else {
19432 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19433 		    ill->ill_phys_addr_length);
19434 	}
19435 	/*
19436 	 * Note: Returns ND_* states. Should be:
19437 	 * reachable(1), stale(2), delay(3), probe(4),
19438 	 * invalid(5), unknown(6)
19439 	 */
19440 	ntme.ipv6NetToMediaState = nce->nce_state;
19441 	ntme.ipv6NetToMediaLastUpdated = 0;
19442 
19443 	/* other(1), dynamic(2), static(3), local(4) */
19444 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19445 		ntme.ipv6NetToMediaType = 4;
19446 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19447 		ntme.ipv6NetToMediaType = 1;
19448 	} else {
19449 		ntme.ipv6NetToMediaType = 2;
19450 	}
19451 
19452 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19453 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19454 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19455 		    (uint_t)sizeof (ntme)));
19456 	}
19457 	return (0);
19458 }
19459 
19460 /*
19461  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19462  */
19463 /* ARGSUSED */
19464 int
19465 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19466 {
19467 	switch (level) {
19468 	case MIB2_IP:
19469 	case MIB2_ICMP:
19470 		switch (name) {
19471 		default:
19472 			break;
19473 		}
19474 		return (1);
19475 	default:
19476 		return (1);
19477 	}
19478 }
19479 
19480 /*
19481  * When there exists both a 64- and 32-bit counter of a particular type
19482  * (i.e., InReceives), only the 64-bit counters are added.
19483  */
19484 void
19485 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19486 {
19487 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19488 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19489 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19490 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19491 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19492 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19493 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19494 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19495 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19496 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19497 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19498 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19499 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19500 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19501 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19502 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19503 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19504 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19505 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19506 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19507 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19508 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19509 	    o2->ipIfStatsInWrongIPVersion);
19510 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19511 	    o2->ipIfStatsInWrongIPVersion);
19512 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19513 	    o2->ipIfStatsOutSwitchIPVersion);
19514 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19515 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19516 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19517 	    o2->ipIfStatsHCInForwDatagrams);
19518 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19519 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19520 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19521 	    o2->ipIfStatsHCOutForwDatagrams);
19522 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19523 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19524 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19525 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19526 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19527 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19528 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19529 	    o2->ipIfStatsHCOutMcastOctets);
19530 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19531 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19532 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19533 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19534 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19535 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19536 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19537 }
19538 
19539 void
19540 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19541 {
19542 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19543 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19544 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19545 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19546 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19547 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19548 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19549 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19550 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19551 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19552 	    o2->ipv6IfIcmpInRouterSolicits);
19553 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19554 	    o2->ipv6IfIcmpInRouterAdvertisements);
19555 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19556 	    o2->ipv6IfIcmpInNeighborSolicits);
19557 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19558 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19559 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19560 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19561 	    o2->ipv6IfIcmpInGroupMembQueries);
19562 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19563 	    o2->ipv6IfIcmpInGroupMembResponses);
19564 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19565 	    o2->ipv6IfIcmpInGroupMembReductions);
19566 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19567 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19568 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19569 	    o2->ipv6IfIcmpOutDestUnreachs);
19570 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19571 	    o2->ipv6IfIcmpOutAdminProhibs);
19572 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19573 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19574 	    o2->ipv6IfIcmpOutParmProblems);
19575 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19576 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19577 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19578 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19579 	    o2->ipv6IfIcmpOutRouterSolicits);
19580 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19581 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19582 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19583 	    o2->ipv6IfIcmpOutNeighborSolicits);
19584 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19585 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19586 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19587 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19588 	    o2->ipv6IfIcmpOutGroupMembQueries);
19589 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19590 	    o2->ipv6IfIcmpOutGroupMembResponses);
19591 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19592 	    o2->ipv6IfIcmpOutGroupMembReductions);
19593 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19594 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19595 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19596 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19597 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19598 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19599 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19600 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19601 	    o2->ipv6IfIcmpInGroupMembTotal);
19602 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19603 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19604 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19605 	    o2->ipv6IfIcmpInGroupMembBadReports);
19606 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19607 	    o2->ipv6IfIcmpInGroupMembOurReports);
19608 }
19609 
19610 /*
19611  * Called before the options are updated to check if this packet will
19612  * be source routed from here.
19613  * This routine assumes that the options are well formed i.e. that they
19614  * have already been checked.
19615  */
19616 static boolean_t
19617 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19618 {
19619 	ipoptp_t	opts;
19620 	uchar_t		*opt;
19621 	uint8_t		optval;
19622 	uint8_t		optlen;
19623 	ipaddr_t	dst;
19624 	ire_t		*ire;
19625 
19626 	if (IS_SIMPLE_IPH(ipha)) {
19627 		ip2dbg(("not source routed\n"));
19628 		return (B_FALSE);
19629 	}
19630 	dst = ipha->ipha_dst;
19631 	for (optval = ipoptp_first(&opts, ipha);
19632 	    optval != IPOPT_EOL;
19633 	    optval = ipoptp_next(&opts)) {
19634 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19635 		opt = opts.ipoptp_cur;
19636 		optlen = opts.ipoptp_len;
19637 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19638 		    optval, optlen));
19639 		switch (optval) {
19640 			uint32_t off;
19641 		case IPOPT_SSRR:
19642 		case IPOPT_LSRR:
19643 			/*
19644 			 * If dst is one of our addresses and there are some
19645 			 * entries left in the source route return (true).
19646 			 */
19647 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19648 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19649 			if (ire == NULL) {
19650 				ip2dbg(("ip_source_routed: not next"
19651 				    " source route 0x%x\n",
19652 				    ntohl(dst)));
19653 				return (B_FALSE);
19654 			}
19655 			ire_refrele(ire);
19656 			off = opt[IPOPT_OFFSET];
19657 			off--;
19658 			if (optlen < IP_ADDR_LEN ||
19659 			    off > optlen - IP_ADDR_LEN) {
19660 				/* End of source route */
19661 				ip1dbg(("ip_source_routed: end of SR\n"));
19662 				return (B_FALSE);
19663 			}
19664 			return (B_TRUE);
19665 		}
19666 	}
19667 	ip2dbg(("not source routed\n"));
19668 	return (B_FALSE);
19669 }
19670 
19671 /*
19672  * Check if the packet contains any source route.
19673  */
19674 static boolean_t
19675 ip_source_route_included(ipha_t *ipha)
19676 {
19677 	ipoptp_t	opts;
19678 	uint8_t		optval;
19679 
19680 	if (IS_SIMPLE_IPH(ipha))
19681 		return (B_FALSE);
19682 	for (optval = ipoptp_first(&opts, ipha);
19683 	    optval != IPOPT_EOL;
19684 	    optval = ipoptp_next(&opts)) {
19685 		switch (optval) {
19686 		case IPOPT_SSRR:
19687 		case IPOPT_LSRR:
19688 			return (B_TRUE);
19689 		}
19690 	}
19691 	return (B_FALSE);
19692 }
19693 
19694 /*
19695  * Called when the IRE expiration timer fires.
19696  */
19697 void
19698 ip_trash_timer_expire(void *args)
19699 {
19700 	int			flush_flag = 0;
19701 	ire_expire_arg_t	iea;
19702 	ip_stack_t		*ipst = (ip_stack_t *)args;
19703 
19704 	iea.iea_ipst = ipst;	/* No netstack_hold */
19705 
19706 	/*
19707 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19708 	 * This lock makes sure that a new invocation of this function
19709 	 * that occurs due to an almost immediate timer firing will not
19710 	 * progress beyond this point until the current invocation is done
19711 	 */
19712 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19713 	ipst->ips_ip_ire_expire_id = 0;
19714 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19715 
19716 	/* Periodic timer */
19717 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19718 	    ipst->ips_ip_ire_arp_interval) {
19719 		/*
19720 		 * Remove all IRE_CACHE entries since they might
19721 		 * contain arp information.
19722 		 */
19723 		flush_flag |= FLUSH_ARP_TIME;
19724 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19725 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19726 	}
19727 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19728 	    ipst->ips_ip_ire_redir_interval) {
19729 		/* Remove all redirects */
19730 		flush_flag |= FLUSH_REDIRECT_TIME;
19731 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19732 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19733 	}
19734 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19735 	    ipst->ips_ip_ire_pathmtu_interval) {
19736 		/* Increase path mtu */
19737 		flush_flag |= FLUSH_MTU_TIME;
19738 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19739 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19740 	}
19741 
19742 	/*
19743 	 * Optimize for the case when there are no redirects in the
19744 	 * ftable, that is, no need to walk the ftable in that case.
19745 	 */
19746 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19747 		iea.iea_flush_flag = flush_flag;
19748 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19749 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19750 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19751 		    NULL, ALL_ZONES, ipst);
19752 	}
19753 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19754 	    ipst->ips_ip_redirect_cnt > 0) {
19755 		iea.iea_flush_flag = flush_flag;
19756 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19757 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19758 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19759 	}
19760 	if (flush_flag & FLUSH_MTU_TIME) {
19761 		/*
19762 		 * Walk all IPv6 IRE's and update them
19763 		 * Note that ARP and redirect timers are not
19764 		 * needed since NUD handles stale entries.
19765 		 */
19766 		flush_flag = FLUSH_MTU_TIME;
19767 		iea.iea_flush_flag = flush_flag;
19768 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19769 		    ALL_ZONES, ipst);
19770 	}
19771 
19772 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19773 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19774 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19775 
19776 	/*
19777 	 * Hold the lock to serialize timeout calls and prevent
19778 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19779 	 * for the timer to fire and a new invocation of this function
19780 	 * to start before the return value of timeout has been stored
19781 	 * in ip_ire_expire_id by the current invocation.
19782 	 */
19783 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19784 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19785 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19786 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19787 }
19788 
19789 /*
19790  * Called by the memory allocator subsystem directly, when the system
19791  * is running low on memory.
19792  */
19793 /* ARGSUSED */
19794 void
19795 ip_trash_ire_reclaim(void *args)
19796 {
19797 	netstack_handle_t nh;
19798 	netstack_t *ns;
19799 
19800 	netstack_next_init(&nh);
19801 	while ((ns = netstack_next(&nh)) != NULL) {
19802 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19803 		netstack_rele(ns);
19804 	}
19805 	netstack_next_fini(&nh);
19806 }
19807 
19808 static void
19809 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19810 {
19811 	ire_cache_count_t icc;
19812 	ire_cache_reclaim_t icr;
19813 	ncc_cache_count_t ncc;
19814 	nce_cache_reclaim_t ncr;
19815 	uint_t delete_cnt;
19816 	/*
19817 	 * Memory reclaim call back.
19818 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19819 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19820 	 * entries, determine what fraction to free for
19821 	 * each category of IRE_CACHE entries giving absolute priority
19822 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19823 	 * entry will be freed unless all offlink entries are freed).
19824 	 */
19825 	icc.icc_total = 0;
19826 	icc.icc_unused = 0;
19827 	icc.icc_offlink = 0;
19828 	icc.icc_pmtu = 0;
19829 	icc.icc_onlink = 0;
19830 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19831 
19832 	/*
19833 	 * Free NCEs for IPv6 like the onlink ires.
19834 	 */
19835 	ncc.ncc_total = 0;
19836 	ncc.ncc_host = 0;
19837 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19838 
19839 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19840 	    icc.icc_pmtu + icc.icc_onlink);
19841 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19842 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19843 	if (delete_cnt == 0)
19844 		return;
19845 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19846 	/* Always delete all unused offlink entries */
19847 	icr.icr_ipst = ipst;
19848 	icr.icr_unused = 1;
19849 	if (delete_cnt <= icc.icc_unused) {
19850 		/*
19851 		 * Only need to free unused entries.  In other words,
19852 		 * there are enough unused entries to free to meet our
19853 		 * target number of freed ire cache entries.
19854 		 */
19855 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19856 		ncr.ncr_host = 0;
19857 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19858 		/*
19859 		 * Only need to free unused entries, plus a fraction of offlink
19860 		 * entries.  It follows from the first if statement that
19861 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19862 		 */
19863 		delete_cnt -= icc.icc_unused;
19864 		/* Round up # deleted by truncating fraction */
19865 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19866 		icr.icr_pmtu = icr.icr_onlink = 0;
19867 		ncr.ncr_host = 0;
19868 	} else if (delete_cnt <=
19869 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19870 		/*
19871 		 * Free all unused and offlink entries, plus a fraction of
19872 		 * pmtu entries.  It follows from the previous if statement
19873 		 * that icc_pmtu is non-zero, and that
19874 		 * delete_cnt != icc_unused + icc_offlink.
19875 		 */
19876 		icr.icr_offlink = 1;
19877 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19878 		/* Round up # deleted by truncating fraction */
19879 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19880 		icr.icr_onlink = 0;
19881 		ncr.ncr_host = 0;
19882 	} else {
19883 		/*
19884 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19885 		 * of onlink entries.  If we're here, then we know that
19886 		 * icc_onlink is non-zero, and that
19887 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19888 		 */
19889 		icr.icr_offlink = icr.icr_pmtu = 1;
19890 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19891 		    icc.icc_pmtu;
19892 		/* Round up # deleted by truncating fraction */
19893 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19894 		/* Using the same delete fraction as for onlink IREs */
19895 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19896 	}
19897 #ifdef DEBUG
19898 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19899 	    "fractions %d/%d/%d/%d\n",
19900 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19901 	    icc.icc_unused, icc.icc_offlink,
19902 	    icc.icc_pmtu, icc.icc_onlink,
19903 	    icr.icr_unused, icr.icr_offlink,
19904 	    icr.icr_pmtu, icr.icr_onlink));
19905 #endif
19906 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19907 	if (ncr.ncr_host != 0)
19908 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19909 		    (uchar_t *)&ncr, ipst);
19910 #ifdef DEBUG
19911 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19912 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19913 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19914 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19915 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19916 	    icc.icc_pmtu, icc.icc_onlink));
19917 #endif
19918 }
19919 
19920 /*
19921  * ip_unbind is called when a copy of an unbind request is received from the
19922  * upper level protocol.  We remove this conn from any fanout hash list it is
19923  * on, and zero out the bind information.  No reply is expected up above.
19924  */
19925 mblk_t *
19926 ip_unbind(queue_t *q, mblk_t *mp)
19927 {
19928 	conn_t	*connp = Q_TO_CONN(q);
19929 
19930 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19931 
19932 	if (is_system_labeled() && connp->conn_anon_port) {
19933 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19934 		    connp->conn_mlp_type, connp->conn_ulp,
19935 		    ntohs(connp->conn_lport), B_FALSE);
19936 		connp->conn_anon_port = 0;
19937 	}
19938 	connp->conn_mlp_type = mlptSingle;
19939 
19940 	ipcl_hash_remove(connp);
19941 
19942 	ASSERT(mp->b_cont == NULL);
19943 	/*
19944 	 * Convert mp into a T_OK_ACK
19945 	 */
19946 	mp = mi_tpi_ok_ack_alloc(mp);
19947 
19948 	/*
19949 	 * should not happen in practice... T_OK_ACK is smaller than the
19950 	 * original message.
19951 	 */
19952 	if (mp == NULL)
19953 		return (NULL);
19954 
19955 	return (mp);
19956 }
19957 
19958 /*
19959  * Write side put procedure.  Outbound data, IOCTLs, responses from
19960  * resolvers, etc, come down through here.
19961  *
19962  * arg2 is always a queue_t *.
19963  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19964  * the zoneid.
19965  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19966  */
19967 void
19968 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19969 {
19970 	ip_output_options(arg, mp, arg2, caller, &zero_info);
19971 }
19972 
19973 void
19974 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
19975     ip_opt_info_t *infop)
19976 {
19977 	conn_t		*connp = NULL;
19978 	queue_t		*q = (queue_t *)arg2;
19979 	ipha_t		*ipha;
19980 #define	rptr	((uchar_t *)ipha)
19981 	ire_t		*ire = NULL;
19982 	ire_t		*sctp_ire = NULL;
19983 	uint32_t	v_hlen_tos_len;
19984 	ipaddr_t	dst;
19985 	mblk_t		*first_mp = NULL;
19986 	boolean_t	mctl_present;
19987 	ipsec_out_t	*io;
19988 	int		match_flags;
19989 	ill_t		*attach_ill = NULL;
19990 					/* Bind to IPIF_NOFAILOVER ill etc. */
19991 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19992 	ipif_t		*dst_ipif;
19993 	boolean_t	multirt_need_resolve = B_FALSE;
19994 	mblk_t		*copy_mp = NULL;
19995 	int		err;
19996 	zoneid_t	zoneid;
19997 	int	adjust;
19998 	uint16_t iplen;
19999 	boolean_t	need_decref = B_FALSE;
20000 	boolean_t	ignore_dontroute = B_FALSE;
20001 	boolean_t	ignore_nexthop = B_FALSE;
20002 	boolean_t	ip_nexthop = B_FALSE;
20003 	ipaddr_t	nexthop_addr;
20004 	ip_stack_t	*ipst;
20005 
20006 #ifdef	_BIG_ENDIAN
20007 #define	V_HLEN	(v_hlen_tos_len >> 24)
20008 #else
20009 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20010 #endif
20011 
20012 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20013 	    "ip_wput_start: q %p", q);
20014 
20015 	/*
20016 	 * ip_wput fast path
20017 	 */
20018 
20019 	/* is packet from ARP ? */
20020 	if (q->q_next != NULL) {
20021 		zoneid = (zoneid_t)(uintptr_t)arg;
20022 		goto qnext;
20023 	}
20024 
20025 	connp = (conn_t *)arg;
20026 	ASSERT(connp != NULL);
20027 	zoneid = connp->conn_zoneid;
20028 	ipst = connp->conn_netstack->netstack_ip;
20029 
20030 	/* is queue flow controlled? */
20031 	if ((q->q_first != NULL || connp->conn_draining) &&
20032 	    (caller == IP_WPUT)) {
20033 		ASSERT(!need_decref);
20034 		(void) putq(q, mp);
20035 		return;
20036 	}
20037 
20038 	/* Multidata transmit? */
20039 	if (DB_TYPE(mp) == M_MULTIDATA) {
20040 		/*
20041 		 * We should never get here, since all Multidata messages
20042 		 * originating from tcp should have been directed over to
20043 		 * tcp_multisend() in the first place.
20044 		 */
20045 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20046 		freemsg(mp);
20047 		return;
20048 	} else if (DB_TYPE(mp) != M_DATA)
20049 		goto notdata;
20050 
20051 	if (mp->b_flag & MSGHASREF) {
20052 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20053 		mp->b_flag &= ~MSGHASREF;
20054 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20055 		need_decref = B_TRUE;
20056 	}
20057 	ipha = (ipha_t *)mp->b_rptr;
20058 
20059 	/* is IP header non-aligned or mblk smaller than basic IP header */
20060 #ifndef SAFETY_BEFORE_SPEED
20061 	if (!OK_32PTR(rptr) ||
20062 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20063 		goto hdrtoosmall;
20064 #endif
20065 
20066 	ASSERT(OK_32PTR(ipha));
20067 
20068 	/*
20069 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20070 	 * wrong version, we'll catch it again in ip_output_v6.
20071 	 *
20072 	 * Note that this is *only* locally-generated output here, and never
20073 	 * forwarded data, and that we need to deal only with transports that
20074 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20075 	 * label.)
20076 	 */
20077 	if (is_system_labeled() &&
20078 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20079 	    !connp->conn_ulp_labeled) {
20080 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20081 		    connp->conn_mac_exempt, ipst);
20082 		ipha = (ipha_t *)mp->b_rptr;
20083 		if (err != 0) {
20084 			first_mp = mp;
20085 			if (err == EINVAL)
20086 				goto icmp_parameter_problem;
20087 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20088 			goto discard_pkt;
20089 		}
20090 		iplen = ntohs(ipha->ipha_length) + adjust;
20091 		ipha->ipha_length = htons(iplen);
20092 	}
20093 
20094 	ASSERT(infop != NULL);
20095 
20096 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20097 		/*
20098 		 * IP_PKTINFO ancillary option is present.
20099 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20100 		 * allows using address of any zone as the source address.
20101 		 */
20102 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20103 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20104 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20105 		if (ire == NULL)
20106 			goto drop_pkt;
20107 		ire_refrele(ire);
20108 		ire = NULL;
20109 	}
20110 
20111 	/*
20112 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20113 	 * ill index passed in IP_PKTINFO.
20114 	 */
20115 	if (infop->ip_opt_ill_index != 0 &&
20116 	    connp->conn_xmit_if_ill == NULL &&
20117 	    connp->conn_nofailover_ill == NULL) {
20118 
20119 		xmit_ill = ill_lookup_on_ifindex(
20120 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20121 		    ipst);
20122 
20123 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20124 			goto drop_pkt;
20125 		/*
20126 		 * check that there is an ipif belonging
20127 		 * to our zone. IPCL_ZONEID is not used because
20128 		 * IP_ALLZONES option is valid only when the ill is
20129 		 * accessible from all zones i.e has a valid ipif in
20130 		 * all zones.
20131 		 */
20132 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20133 			goto drop_pkt;
20134 		}
20135 	}
20136 
20137 	/*
20138 	 * If there is a policy, try to attach an ipsec_out in
20139 	 * the front. At the end, first_mp either points to a
20140 	 * M_DATA message or IPSEC_OUT message linked to a
20141 	 * M_DATA message. We have to do it now as we might
20142 	 * lose the "conn" if we go through ip_newroute.
20143 	 */
20144 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20145 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20146 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20147 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20148 			if (need_decref)
20149 				CONN_DEC_REF(connp);
20150 			return;
20151 		} else {
20152 			ASSERT(mp->b_datap->db_type == M_CTL);
20153 			first_mp = mp;
20154 			mp = mp->b_cont;
20155 			mctl_present = B_TRUE;
20156 		}
20157 	} else {
20158 		first_mp = mp;
20159 		mctl_present = B_FALSE;
20160 	}
20161 
20162 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20163 
20164 	/* is wrong version or IP options present */
20165 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20166 		goto version_hdrlen_check;
20167 	dst = ipha->ipha_dst;
20168 
20169 	if (connp->conn_nofailover_ill != NULL) {
20170 		attach_ill = conn_get_held_ill(connp,
20171 		    &connp->conn_nofailover_ill, &err);
20172 		if (err == ILL_LOOKUP_FAILED) {
20173 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20174 			if (need_decref)
20175 				CONN_DEC_REF(connp);
20176 			freemsg(first_mp);
20177 			return;
20178 		}
20179 	}
20180 
20181 
20182 	/* is packet multicast? */
20183 	if (CLASSD(dst))
20184 		goto multicast;
20185 
20186 	/*
20187 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20188 	 * takes precedence over conn_dontroute and conn_nexthop_set
20189 	 */
20190 	if (xmit_ill != NULL) {
20191 		goto send_from_ill;
20192 	}
20193 
20194 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20195 	    (connp->conn_nexthop_set)) {
20196 		/*
20197 		 * If the destination is a broadcast or a loopback
20198 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20199 		 * through the standard path. But in the case of local
20200 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20201 		 * the standard path not IP_XMIT_IF.
20202 		 */
20203 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20204 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20205 		    (ire->ire_type != IRE_LOOPBACK))) {
20206 			if ((connp->conn_dontroute ||
20207 			    connp->conn_nexthop_set) && (ire != NULL) &&
20208 			    (ire->ire_type == IRE_LOCAL))
20209 				goto standard_path;
20210 
20211 			if (ire != NULL) {
20212 				ire_refrele(ire);
20213 				/* No more access to ire */
20214 				ire = NULL;
20215 			}
20216 			/*
20217 			 * bypass routing checks and go directly to
20218 			 * interface.
20219 			 */
20220 			if (connp->conn_dontroute) {
20221 				goto dontroute;
20222 			} else if (connp->conn_nexthop_set) {
20223 				ip_nexthop = B_TRUE;
20224 				nexthop_addr = connp->conn_nexthop_v4;
20225 				goto send_from_ill;
20226 			}
20227 
20228 			/*
20229 			 * If IP_XMIT_IF socket option is set,
20230 			 * then we allow unicast and multicast
20231 			 * packets to go through the ill. It is
20232 			 * quite possible that the destination
20233 			 * is not in the ire cache table and we
20234 			 * do not want to go to ip_newroute()
20235 			 * instead we call ip_newroute_ipif.
20236 			 */
20237 			xmit_ill = conn_get_held_ill(connp,
20238 			    &connp->conn_xmit_if_ill, &err);
20239 			if (err == ILL_LOOKUP_FAILED) {
20240 				BUMP_MIB(&ipst->ips_ip_mib,
20241 				    ipIfStatsOutDiscards);
20242 				if (attach_ill != NULL)
20243 					ill_refrele(attach_ill);
20244 				if (need_decref)
20245 					CONN_DEC_REF(connp);
20246 				freemsg(first_mp);
20247 				return;
20248 			}
20249 			goto send_from_ill;
20250 		}
20251 standard_path:
20252 		/* Must be a broadcast, a loopback or a local ire */
20253 		if (ire != NULL) {
20254 			ire_refrele(ire);
20255 			/* No more access to ire */
20256 			ire = NULL;
20257 		}
20258 	}
20259 
20260 	if (attach_ill != NULL)
20261 		goto send_from_ill;
20262 
20263 	/*
20264 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20265 	 * this for the tcp global queue and listen end point
20266 	 * as it does not really have a real destination to
20267 	 * talk to.  This is also true for SCTP.
20268 	 */
20269 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20270 	    !connp->conn_fully_bound) {
20271 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20272 		if (ire == NULL)
20273 			goto noirefound;
20274 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20275 		    "ip_wput_end: q %p (%S)", q, "end");
20276 
20277 		/*
20278 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20279 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20280 		 */
20281 		if (ire->ire_flags & RTF_MULTIRT) {
20282 
20283 			/*
20284 			 * Force the TTL of multirouted packets if required.
20285 			 * The TTL of such packets is bounded by the
20286 			 * ip_multirt_ttl ndd variable.
20287 			 */
20288 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20289 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20290 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20291 				    "(was %d), dst 0x%08x\n",
20292 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20293 				    ntohl(ire->ire_addr)));
20294 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20295 			}
20296 			/*
20297 			 * We look at this point if there are pending
20298 			 * unresolved routes. ire_multirt_resolvable()
20299 			 * checks in O(n) that all IRE_OFFSUBNET ire
20300 			 * entries for the packet's destination and
20301 			 * flagged RTF_MULTIRT are currently resolved.
20302 			 * If some remain unresolved, we make a copy
20303 			 * of the current message. It will be used
20304 			 * to initiate additional route resolutions.
20305 			 */
20306 			multirt_need_resolve =
20307 			    ire_multirt_need_resolve(ire->ire_addr,
20308 			    MBLK_GETLABEL(first_mp), ipst);
20309 			ip2dbg(("ip_wput[TCP]: ire %p, "
20310 			    "multirt_need_resolve %d, first_mp %p\n",
20311 			    (void *)ire, multirt_need_resolve,
20312 			    (void *)first_mp));
20313 			if (multirt_need_resolve) {
20314 				copy_mp = copymsg(first_mp);
20315 				if (copy_mp != NULL) {
20316 					MULTIRT_DEBUG_TAG(copy_mp);
20317 				}
20318 			}
20319 		}
20320 
20321 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20322 
20323 		/*
20324 		 * Try to resolve another multiroute if
20325 		 * ire_multirt_need_resolve() deemed it necessary.
20326 		 */
20327 		if (copy_mp != NULL)
20328 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20329 		if (need_decref)
20330 			CONN_DEC_REF(connp);
20331 		return;
20332 	}
20333 
20334 	/*
20335 	 * Access to conn_ire_cache. (protected by conn_lock)
20336 	 *
20337 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20338 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20339 	 * send a packet or two with the IRE_CACHE that is going away.
20340 	 * Access to the ire requires an ire refhold on the ire prior to
20341 	 * its use since an interface unplumb thread may delete the cached
20342 	 * ire and release the refhold at any time.
20343 	 *
20344 	 * Caching an ire in the conn_ire_cache
20345 	 *
20346 	 * o Caching an ire pointer in the conn requires a strict check for
20347 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20348 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20349 	 * in the conn is done after making sure under the bucket lock that the
20350 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20351 	 * caching an ire after the unplumb thread has cleaned up the conn.
20352 	 * If the conn does not send a packet subsequently the unplumb thread
20353 	 * will be hanging waiting for the ire count to drop to zero.
20354 	 *
20355 	 * o We also need to atomically test for a null conn_ire_cache and
20356 	 * set the conn_ire_cache under the the protection of the conn_lock
20357 	 * to avoid races among concurrent threads trying to simultaneously
20358 	 * cache an ire in the conn_ire_cache.
20359 	 */
20360 	mutex_enter(&connp->conn_lock);
20361 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20362 
20363 	if (ire != NULL && ire->ire_addr == dst &&
20364 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20365 
20366 		IRE_REFHOLD(ire);
20367 		mutex_exit(&connp->conn_lock);
20368 
20369 	} else {
20370 		boolean_t cached = B_FALSE;
20371 		connp->conn_ire_cache = NULL;
20372 		mutex_exit(&connp->conn_lock);
20373 		/* Release the old ire */
20374 		if (ire != NULL && sctp_ire == NULL)
20375 			IRE_REFRELE_NOTR(ire);
20376 
20377 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20378 		if (ire == NULL)
20379 			goto noirefound;
20380 		IRE_REFHOLD_NOTR(ire);
20381 
20382 		mutex_enter(&connp->conn_lock);
20383 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20384 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20385 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20386 				if (connp->conn_ulp == IPPROTO_TCP)
20387 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20388 				connp->conn_ire_cache = ire;
20389 				cached = B_TRUE;
20390 			}
20391 			rw_exit(&ire->ire_bucket->irb_lock);
20392 		}
20393 		mutex_exit(&connp->conn_lock);
20394 
20395 		/*
20396 		 * We can continue to use the ire but since it was
20397 		 * not cached, we should drop the extra reference.
20398 		 */
20399 		if (!cached)
20400 			IRE_REFRELE_NOTR(ire);
20401 	}
20402 
20403 
20404 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20405 	    "ip_wput_end: q %p (%S)", q, "end");
20406 
20407 	/*
20408 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20409 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20410 	 */
20411 	if (ire->ire_flags & RTF_MULTIRT) {
20412 
20413 		/*
20414 		 * Force the TTL of multirouted packets if required.
20415 		 * The TTL of such packets is bounded by the
20416 		 * ip_multirt_ttl ndd variable.
20417 		 */
20418 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20419 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20420 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20421 			    "(was %d), dst 0x%08x\n",
20422 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20423 			    ntohl(ire->ire_addr)));
20424 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20425 		}
20426 
20427 		/*
20428 		 * At this point, we check to see if there are any pending
20429 		 * unresolved routes. ire_multirt_resolvable()
20430 		 * checks in O(n) that all IRE_OFFSUBNET ire
20431 		 * entries for the packet's destination and
20432 		 * flagged RTF_MULTIRT are currently resolved.
20433 		 * If some remain unresolved, we make a copy
20434 		 * of the current message. It will be used
20435 		 * to initiate additional route resolutions.
20436 		 */
20437 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20438 		    MBLK_GETLABEL(first_mp), ipst);
20439 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20440 		    "multirt_need_resolve %d, first_mp %p\n",
20441 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20442 		if (multirt_need_resolve) {
20443 			copy_mp = copymsg(first_mp);
20444 			if (copy_mp != NULL) {
20445 				MULTIRT_DEBUG_TAG(copy_mp);
20446 			}
20447 		}
20448 	}
20449 
20450 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20451 
20452 	/*
20453 	 * Try to resolve another multiroute if
20454 	 * ire_multirt_resolvable() deemed it necessary
20455 	 */
20456 	if (copy_mp != NULL)
20457 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20458 	if (need_decref)
20459 		CONN_DEC_REF(connp);
20460 	return;
20461 
20462 qnext:
20463 	/*
20464 	 * Upper Level Protocols pass down complete IP datagrams
20465 	 * as M_DATA messages.	Everything else is a sideshow.
20466 	 *
20467 	 * 1) We could be re-entering ip_wput because of ip_neworute
20468 	 *    in which case we could have a IPSEC_OUT message. We
20469 	 *    need to pass through ip_wput like other datagrams and
20470 	 *    hence cannot branch to ip_wput_nondata.
20471 	 *
20472 	 * 2) ARP, AH, ESP, and other clients who are on the module
20473 	 *    instance of IP stream, give us something to deal with.
20474 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20475 	 *
20476 	 * 3) ICMP replies also could come here.
20477 	 */
20478 	ipst = ILLQ_TO_IPST(q);
20479 
20480 	if (DB_TYPE(mp) != M_DATA) {
20481 notdata:
20482 		if (DB_TYPE(mp) == M_CTL) {
20483 			/*
20484 			 * M_CTL messages are used by ARP, AH and ESP to
20485 			 * communicate with IP. We deal with IPSEC_IN and
20486 			 * IPSEC_OUT here. ip_wput_nondata handles other
20487 			 * cases.
20488 			 */
20489 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20490 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20491 				first_mp = mp->b_cont;
20492 				first_mp->b_flag &= ~MSGHASREF;
20493 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20494 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20495 				CONN_DEC_REF(connp);
20496 				connp = NULL;
20497 			}
20498 			if (ii->ipsec_info_type == IPSEC_IN) {
20499 				/*
20500 				 * Either this message goes back to
20501 				 * IPsec for further processing or to
20502 				 * ULP after policy checks.
20503 				 */
20504 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20505 				return;
20506 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20507 				io = (ipsec_out_t *)ii;
20508 				if (io->ipsec_out_proc_begin) {
20509 					/*
20510 					 * IPsec processing has already started.
20511 					 * Complete it.
20512 					 * IPQoS notes: We don't care what is
20513 					 * in ipsec_out_ill_index since this
20514 					 * won't be processed for IPQoS policies
20515 					 * in ipsec_out_process.
20516 					 */
20517 					ipsec_out_process(q, mp, NULL,
20518 					    io->ipsec_out_ill_index);
20519 					return;
20520 				} else {
20521 					connp = (q->q_next != NULL) ?
20522 					    NULL : Q_TO_CONN(q);
20523 					first_mp = mp;
20524 					mp = mp->b_cont;
20525 					mctl_present = B_TRUE;
20526 				}
20527 				zoneid = io->ipsec_out_zoneid;
20528 				ASSERT(zoneid != ALL_ZONES);
20529 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20530 				/*
20531 				 * It's an IPsec control message requesting
20532 				 * an SADB update to be sent to the IPsec
20533 				 * hardware acceleration capable ills.
20534 				 */
20535 				ipsec_ctl_t *ipsec_ctl =
20536 				    (ipsec_ctl_t *)mp->b_rptr;
20537 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20538 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20539 				mblk_t *cmp = mp->b_cont;
20540 
20541 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20542 				ASSERT(cmp != NULL);
20543 
20544 				freeb(mp);
20545 				ill_ipsec_capab_send_all(satype, cmp, sa,
20546 				    ipst->ips_netstack);
20547 				return;
20548 			} else {
20549 				/*
20550 				 * This must be ARP or special TSOL signaling.
20551 				 */
20552 				ip_wput_nondata(NULL, q, mp, NULL);
20553 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20554 				    "ip_wput_end: q %p (%S)", q, "nondata");
20555 				return;
20556 			}
20557 		} else {
20558 			/*
20559 			 * This must be non-(ARP/AH/ESP) messages.
20560 			 */
20561 			ASSERT(!need_decref);
20562 			ip_wput_nondata(NULL, q, mp, NULL);
20563 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20564 			    "ip_wput_end: q %p (%S)", q, "nondata");
20565 			return;
20566 		}
20567 	} else {
20568 		first_mp = mp;
20569 		mctl_present = B_FALSE;
20570 	}
20571 
20572 	ASSERT(first_mp != NULL);
20573 	/*
20574 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20575 	 * to make sure that this packet goes out on the same interface it
20576 	 * came in. We handle that here.
20577 	 */
20578 	if (mctl_present) {
20579 		uint_t ifindex;
20580 
20581 		io = (ipsec_out_t *)first_mp->b_rptr;
20582 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20583 			/*
20584 			 * We may have lost the conn context if we are
20585 			 * coming here from ip_newroute(). Copy the
20586 			 * nexthop information.
20587 			 */
20588 			if (io->ipsec_out_ip_nexthop) {
20589 				ip_nexthop = B_TRUE;
20590 				nexthop_addr = io->ipsec_out_nexthop_addr;
20591 
20592 				ipha = (ipha_t *)mp->b_rptr;
20593 				dst = ipha->ipha_dst;
20594 				goto send_from_ill;
20595 			} else {
20596 				ASSERT(io->ipsec_out_ill_index != 0);
20597 				ifindex = io->ipsec_out_ill_index;
20598 				attach_ill = ill_lookup_on_ifindex(ifindex,
20599 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20600 				if (attach_ill == NULL) {
20601 					ASSERT(xmit_ill == NULL);
20602 					ip1dbg(("ip_output: bad ifindex for "
20603 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20604 					    ifindex));
20605 					freemsg(first_mp);
20606 					BUMP_MIB(&ipst->ips_ip_mib,
20607 					    ipIfStatsOutDiscards);
20608 					ASSERT(!need_decref);
20609 					return;
20610 				}
20611 			}
20612 		}
20613 	}
20614 
20615 	ASSERT(xmit_ill == NULL);
20616 
20617 	/* We have a complete IP datagram heading outbound. */
20618 	ipha = (ipha_t *)mp->b_rptr;
20619 
20620 #ifndef SPEED_BEFORE_SAFETY
20621 	/*
20622 	 * Make sure we have a full-word aligned message and that at least
20623 	 * a simple IP header is accessible in the first message.  If not,
20624 	 * try a pullup.
20625 	 */
20626 	if (!OK_32PTR(rptr) ||
20627 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20628 hdrtoosmall:
20629 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20630 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20631 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20632 			if (first_mp == NULL)
20633 				first_mp = mp;
20634 			goto discard_pkt;
20635 		}
20636 
20637 		/* This function assumes that mp points to an IPv4 packet. */
20638 		if (is_system_labeled() && q->q_next == NULL &&
20639 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20640 		    !connp->conn_ulp_labeled) {
20641 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20642 			    &adjust, connp->conn_mac_exempt, ipst);
20643 			ipha = (ipha_t *)mp->b_rptr;
20644 			if (first_mp != NULL)
20645 				first_mp->b_cont = mp;
20646 			if (err != 0) {
20647 				if (first_mp == NULL)
20648 					first_mp = mp;
20649 				if (err == EINVAL)
20650 					goto icmp_parameter_problem;
20651 				ip2dbg(("ip_wput: label check failed (%d)\n",
20652 				    err));
20653 				goto discard_pkt;
20654 			}
20655 			iplen = ntohs(ipha->ipha_length) + adjust;
20656 			ipha->ipha_length = htons(iplen);
20657 		}
20658 
20659 		ipha = (ipha_t *)mp->b_rptr;
20660 		if (first_mp == NULL) {
20661 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20662 			/*
20663 			 * If we got here because of "goto hdrtoosmall"
20664 			 * We need to attach a IPSEC_OUT.
20665 			 */
20666 			if (connp->conn_out_enforce_policy) {
20667 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20668 				    NULL, ipha->ipha_protocol,
20669 				    ipst->ips_netstack)) == NULL)) {
20670 					BUMP_MIB(&ipst->ips_ip_mib,
20671 					    ipIfStatsOutDiscards);
20672 					if (need_decref)
20673 						CONN_DEC_REF(connp);
20674 					return;
20675 				} else {
20676 					ASSERT(mp->b_datap->db_type == M_CTL);
20677 					first_mp = mp;
20678 					mp = mp->b_cont;
20679 					mctl_present = B_TRUE;
20680 				}
20681 			} else {
20682 				first_mp = mp;
20683 				mctl_present = B_FALSE;
20684 			}
20685 		}
20686 	}
20687 #endif
20688 
20689 	/* Most of the code below is written for speed, not readability */
20690 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20691 
20692 	/*
20693 	 * If ip_newroute() fails, we're going to need a full
20694 	 * header for the icmp wraparound.
20695 	 */
20696 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20697 		uint_t	v_hlen;
20698 version_hdrlen_check:
20699 		ASSERT(first_mp != NULL);
20700 		v_hlen = V_HLEN;
20701 		/*
20702 		 * siphon off IPv6 packets coming down from transport
20703 		 * layer modules here.
20704 		 * Note: high-order bit carries NUD reachability confirmation
20705 		 */
20706 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20707 			/*
20708 			 * FIXME: assume that callers of ip_output* call
20709 			 * the right version?
20710 			 */
20711 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20712 			ASSERT(xmit_ill == NULL);
20713 			if (attach_ill != NULL)
20714 				ill_refrele(attach_ill);
20715 			if (need_decref)
20716 				mp->b_flag |= MSGHASREF;
20717 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20718 			return;
20719 		}
20720 
20721 		if ((v_hlen >> 4) != IP_VERSION) {
20722 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20723 			    "ip_wput_end: q %p (%S)", q, "badvers");
20724 			goto discard_pkt;
20725 		}
20726 		/*
20727 		 * Is the header length at least 20 bytes?
20728 		 *
20729 		 * Are there enough bytes accessible in the header?  If
20730 		 * not, try a pullup.
20731 		 */
20732 		v_hlen &= 0xF;
20733 		v_hlen <<= 2;
20734 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20735 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20736 			    "ip_wput_end: q %p (%S)", q, "badlen");
20737 			goto discard_pkt;
20738 		}
20739 		if (v_hlen > (mp->b_wptr - rptr)) {
20740 			if (!pullupmsg(mp, v_hlen)) {
20741 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20742 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20743 				goto discard_pkt;
20744 			}
20745 			ipha = (ipha_t *)mp->b_rptr;
20746 		}
20747 		/*
20748 		 * Move first entry from any source route into ipha_dst and
20749 		 * verify the options
20750 		 */
20751 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20752 		    zoneid, ipst)) {
20753 			ASSERT(xmit_ill == NULL);
20754 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20755 			if (attach_ill != NULL)
20756 				ill_refrele(attach_ill);
20757 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20758 			    "ip_wput_end: q %p (%S)", q, "badopts");
20759 			if (need_decref)
20760 				CONN_DEC_REF(connp);
20761 			return;
20762 		}
20763 	}
20764 	dst = ipha->ipha_dst;
20765 
20766 	/*
20767 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20768 	 * we have to run the packet through ip_newroute which will take
20769 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20770 	 * a resolver, or assigning a default gateway, etc.
20771 	 */
20772 	if (CLASSD(dst)) {
20773 		ipif_t	*ipif;
20774 		uint32_t setsrc = 0;
20775 
20776 multicast:
20777 		ASSERT(first_mp != NULL);
20778 		ip2dbg(("ip_wput: CLASSD\n"));
20779 		if (connp == NULL) {
20780 			/*
20781 			 * Use the first good ipif on the ill.
20782 			 * XXX Should this ever happen? (Appears
20783 			 * to show up with just ppp and no ethernet due
20784 			 * to in.rdisc.)
20785 			 * However, ire_send should be able to
20786 			 * call ip_wput_ire directly.
20787 			 *
20788 			 * XXX Also, this can happen for ICMP and other packets
20789 			 * with multicast source addresses.  Perhaps we should
20790 			 * fix things so that we drop the packet in question,
20791 			 * but for now, just run with it.
20792 			 */
20793 			ill_t *ill = (ill_t *)q->q_ptr;
20794 
20795 			/*
20796 			 * Don't honor attach_if for this case. If ill
20797 			 * is part of the group, ipif could belong to
20798 			 * any ill and we cannot maintain attach_ill
20799 			 * and ipif_ill same anymore and the assert
20800 			 * below would fail.
20801 			 */
20802 			if (mctl_present && io->ipsec_out_attach_if) {
20803 				io->ipsec_out_ill_index = 0;
20804 				io->ipsec_out_attach_if = B_FALSE;
20805 				ASSERT(attach_ill != NULL);
20806 				ill_refrele(attach_ill);
20807 				attach_ill = NULL;
20808 			}
20809 
20810 			ASSERT(attach_ill == NULL);
20811 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20812 			if (ipif == NULL) {
20813 				if (need_decref)
20814 					CONN_DEC_REF(connp);
20815 				freemsg(first_mp);
20816 				return;
20817 			}
20818 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20819 			    ntohl(dst), ill->ill_name));
20820 		} else {
20821 			/*
20822 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20823 			 * and IP_MULTICAST_IF.
20824 			 * Block comment above this function explains the
20825 			 * locking mechanism used here
20826 			 */
20827 			if (xmit_ill == NULL) {
20828 				xmit_ill = conn_get_held_ill(connp,
20829 				    &connp->conn_xmit_if_ill, &err);
20830 				if (err == ILL_LOOKUP_FAILED) {
20831 					ip1dbg(("ip_wput: No ill for "
20832 					    "IP_XMIT_IF\n"));
20833 					BUMP_MIB(&ipst->ips_ip_mib,
20834 					    ipIfStatsOutNoRoutes);
20835 					goto drop_pkt;
20836 				}
20837 			}
20838 
20839 			if (xmit_ill == NULL) {
20840 				ipif = conn_get_held_ipif(connp,
20841 				    &connp->conn_multicast_ipif, &err);
20842 				if (err == IPIF_LOOKUP_FAILED) {
20843 					ip1dbg(("ip_wput: No ipif for "
20844 					    "multicast\n"));
20845 					BUMP_MIB(&ipst->ips_ip_mib,
20846 					    ipIfStatsOutNoRoutes);
20847 					goto drop_pkt;
20848 				}
20849 			}
20850 			if (xmit_ill != NULL) {
20851 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20852 				if (ipif == NULL) {
20853 					ip1dbg(("ip_wput: No ipif for "
20854 					    "IP_XMIT_IF\n"));
20855 					BUMP_MIB(&ipst->ips_ip_mib,
20856 					    ipIfStatsOutNoRoutes);
20857 					goto drop_pkt;
20858 				}
20859 			} else if (ipif == NULL || ipif->ipif_isv6) {
20860 				/*
20861 				 * We must do this ipif determination here
20862 				 * else we could pass through ip_newroute
20863 				 * and come back here without the conn context.
20864 				 *
20865 				 * Note: we do late binding i.e. we bind to
20866 				 * the interface when the first packet is sent.
20867 				 * For performance reasons we do not rebind on
20868 				 * each packet but keep the binding until the
20869 				 * next IP_MULTICAST_IF option.
20870 				 *
20871 				 * conn_multicast_{ipif,ill} are shared between
20872 				 * IPv4 and IPv6 and AF_INET6 sockets can
20873 				 * send both IPv4 and IPv6 packets. Hence
20874 				 * we have to check that "isv6" matches above.
20875 				 */
20876 				if (ipif != NULL)
20877 					ipif_refrele(ipif);
20878 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20879 				if (ipif == NULL) {
20880 					ip1dbg(("ip_wput: No ipif for "
20881 					    "multicast\n"));
20882 					BUMP_MIB(&ipst->ips_ip_mib,
20883 					    ipIfStatsOutNoRoutes);
20884 					goto drop_pkt;
20885 				}
20886 				err = conn_set_held_ipif(connp,
20887 				    &connp->conn_multicast_ipif, ipif);
20888 				if (err == IPIF_LOOKUP_FAILED) {
20889 					ipif_refrele(ipif);
20890 					ip1dbg(("ip_wput: No ipif for "
20891 					    "multicast\n"));
20892 					BUMP_MIB(&ipst->ips_ip_mib,
20893 					    ipIfStatsOutNoRoutes);
20894 					goto drop_pkt;
20895 				}
20896 			}
20897 		}
20898 		ASSERT(!ipif->ipif_isv6);
20899 		/*
20900 		 * As we may lose the conn by the time we reach ip_wput_ire,
20901 		 * we copy conn_multicast_loop and conn_dontroute on to an
20902 		 * ipsec_out. In case if this datagram goes out secure,
20903 		 * we need the ill_index also. Copy that also into the
20904 		 * ipsec_out.
20905 		 */
20906 		if (mctl_present) {
20907 			io = (ipsec_out_t *)first_mp->b_rptr;
20908 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20909 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20910 		} else {
20911 			ASSERT(mp == first_mp);
20912 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20913 			    BPRI_HI)) == NULL) {
20914 				ipif_refrele(ipif);
20915 				first_mp = mp;
20916 				goto discard_pkt;
20917 			}
20918 			first_mp->b_datap->db_type = M_CTL;
20919 			first_mp->b_wptr += sizeof (ipsec_info_t);
20920 			/* ipsec_out_secure is B_FALSE now */
20921 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20922 			io = (ipsec_out_t *)first_mp->b_rptr;
20923 			io->ipsec_out_type = IPSEC_OUT;
20924 			io->ipsec_out_len = sizeof (ipsec_out_t);
20925 			io->ipsec_out_use_global_policy = B_TRUE;
20926 			io->ipsec_out_ns = ipst->ips_netstack;
20927 			first_mp->b_cont = mp;
20928 			mctl_present = B_TRUE;
20929 		}
20930 		if (attach_ill != NULL) {
20931 			ASSERT(attach_ill == ipif->ipif_ill);
20932 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20933 
20934 			/*
20935 			 * Check if we need an ire that will not be
20936 			 * looked up by anybody else i.e. HIDDEN.
20937 			 */
20938 			if (ill_is_probeonly(attach_ill)) {
20939 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20940 			}
20941 			io->ipsec_out_ill_index =
20942 			    attach_ill->ill_phyint->phyint_ifindex;
20943 			io->ipsec_out_attach_if = B_TRUE;
20944 		} else {
20945 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20946 			io->ipsec_out_ill_index =
20947 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20948 		}
20949 		if (connp != NULL) {
20950 			io->ipsec_out_multicast_loop =
20951 			    connp->conn_multicast_loop;
20952 			io->ipsec_out_dontroute = connp->conn_dontroute;
20953 			io->ipsec_out_zoneid = connp->conn_zoneid;
20954 		}
20955 		/*
20956 		 * If the application uses IP_MULTICAST_IF with
20957 		 * different logical addresses of the same ILL, we
20958 		 * need to make sure that the soruce address of
20959 		 * the packet matches the logical IP address used
20960 		 * in the option. We do it by initializing ipha_src
20961 		 * here. This should keep IPsec also happy as
20962 		 * when we return from IPsec processing, we don't
20963 		 * have to worry about getting the right address on
20964 		 * the packet. Thus it is sufficient to look for
20965 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20966 		 * MATCH_IRE_IPIF.
20967 		 *
20968 		 * NOTE : We need to do it for non-secure case also as
20969 		 * this might go out secure if there is a global policy
20970 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20971 		 * address, the source should be initialized already and
20972 		 * hence we won't be initializing here.
20973 		 *
20974 		 * As we do not have the ire yet, it is possible that
20975 		 * we set the source address here and then later discover
20976 		 * that the ire implies the source address to be assigned
20977 		 * through the RTF_SETSRC flag.
20978 		 * In that case, the setsrc variable will remind us
20979 		 * that overwritting the source address by the one
20980 		 * of the RTF_SETSRC-flagged ire is allowed.
20981 		 */
20982 		if (ipha->ipha_src == INADDR_ANY &&
20983 		    (connp == NULL || !connp->conn_unspec_src)) {
20984 			ipha->ipha_src = ipif->ipif_src_addr;
20985 			setsrc = RTF_SETSRC;
20986 		}
20987 		/*
20988 		 * Find an IRE which matches the destination and the outgoing
20989 		 * queue (i.e. the outgoing interface.)
20990 		 * For loopback use a unicast IP address for
20991 		 * the ire lookup.
20992 		 */
20993 		if (IS_LOOPBACK(ipif->ipif_ill))
20994 			dst = ipif->ipif_lcl_addr;
20995 
20996 		/*
20997 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20998 		 * We don't need to lookup ire in ctable as the packet
20999 		 * needs to be sent to the destination through the specified
21000 		 * ill irrespective of ires in the cache table.
21001 		 */
21002 		ire = NULL;
21003 		if (xmit_ill == NULL) {
21004 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21005 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21006 		}
21007 
21008 		/*
21009 		 * refrele attach_ill as its not needed anymore.
21010 		 */
21011 		if (attach_ill != NULL) {
21012 			ill_refrele(attach_ill);
21013 			attach_ill = NULL;
21014 		}
21015 
21016 		if (ire == NULL) {
21017 			/*
21018 			 * Multicast loopback and multicast forwarding is
21019 			 * done in ip_wput_ire.
21020 			 *
21021 			 * Mark this packet to make it be delivered to
21022 			 * ip_wput_ire after the new ire has been
21023 			 * created.
21024 			 *
21025 			 * The call to ip_newroute_ipif takes into account
21026 			 * the setsrc reminder. In any case, we take care
21027 			 * of the RTF_MULTIRT flag.
21028 			 */
21029 			mp->b_prev = mp->b_next = NULL;
21030 			if (xmit_ill == NULL ||
21031 			    xmit_ill->ill_ipif_up_count > 0) {
21032 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21033 				    setsrc | RTF_MULTIRT, zoneid, infop);
21034 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21035 				    "ip_wput_end: q %p (%S)", q, "noire");
21036 			} else {
21037 				freemsg(first_mp);
21038 			}
21039 			ipif_refrele(ipif);
21040 			if (xmit_ill != NULL)
21041 				ill_refrele(xmit_ill);
21042 			if (need_decref)
21043 				CONN_DEC_REF(connp);
21044 			return;
21045 		}
21046 
21047 		ipif_refrele(ipif);
21048 		ipif = NULL;
21049 		ASSERT(xmit_ill == NULL);
21050 
21051 		/*
21052 		 * Honor the RTF_SETSRC flag for multicast packets,
21053 		 * if allowed by the setsrc reminder.
21054 		 */
21055 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21056 			ipha->ipha_src = ire->ire_src_addr;
21057 		}
21058 
21059 		/*
21060 		 * Unconditionally force the TTL to 1 for
21061 		 * multirouted multicast packets:
21062 		 * multirouted multicast should not cross
21063 		 * multicast routers.
21064 		 */
21065 		if (ire->ire_flags & RTF_MULTIRT) {
21066 			if (ipha->ipha_ttl > 1) {
21067 				ip2dbg(("ip_wput: forcing multicast "
21068 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21069 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21070 				ipha->ipha_ttl = 1;
21071 			}
21072 		}
21073 	} else {
21074 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21075 		if ((ire != NULL) && (ire->ire_type &
21076 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21077 			ignore_dontroute = B_TRUE;
21078 			ignore_nexthop = B_TRUE;
21079 		}
21080 		if (ire != NULL) {
21081 			ire_refrele(ire);
21082 			ire = NULL;
21083 		}
21084 		/*
21085 		 * Guard against coming in from arp in which case conn is NULL.
21086 		 * Also guard against non M_DATA with dontroute set but
21087 		 * destined to local, loopback or broadcast addresses.
21088 		 */
21089 		if (connp != NULL && connp->conn_dontroute &&
21090 		    !ignore_dontroute) {
21091 dontroute:
21092 			/*
21093 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21094 			 * routing protocols from seeing false direct
21095 			 * connectivity.
21096 			 */
21097 			ipha->ipha_ttl = 1;
21098 			/*
21099 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21100 			 * along with SO_DONTROUTE, higher precedence is
21101 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21102 			 */
21103 			if (connp->conn_xmit_if_ill == NULL) {
21104 				/* If suitable ipif not found, drop packet */
21105 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21106 				    ipst);
21107 				if (dst_ipif == NULL) {
21108 					ip1dbg(("ip_wput: no route for "
21109 					    "dst using SO_DONTROUTE\n"));
21110 					BUMP_MIB(&ipst->ips_ip_mib,
21111 					    ipIfStatsOutNoRoutes);
21112 					mp->b_prev = mp->b_next = NULL;
21113 					if (first_mp == NULL)
21114 						first_mp = mp;
21115 					goto drop_pkt;
21116 				} else {
21117 					/*
21118 					 * If suitable ipif has been found, set
21119 					 * xmit_ill to the corresponding
21120 					 * ipif_ill because we'll be following
21121 					 * the IP_XMIT_IF logic.
21122 					 */
21123 					ASSERT(xmit_ill == NULL);
21124 					xmit_ill = dst_ipif->ipif_ill;
21125 					mutex_enter(&xmit_ill->ill_lock);
21126 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21127 						mutex_exit(&xmit_ill->ill_lock);
21128 						xmit_ill = NULL;
21129 						ipif_refrele(dst_ipif);
21130 						ip1dbg(("ip_wput: no route for"
21131 						    " dst using"
21132 						    " SO_DONTROUTE\n"));
21133 						BUMP_MIB(&ipst->ips_ip_mib,
21134 						    ipIfStatsOutNoRoutes);
21135 						mp->b_prev = mp->b_next = NULL;
21136 						if (first_mp == NULL)
21137 							first_mp = mp;
21138 						goto drop_pkt;
21139 					}
21140 					ill_refhold_locked(xmit_ill);
21141 					mutex_exit(&xmit_ill->ill_lock);
21142 					ipif_refrele(dst_ipif);
21143 				}
21144 			}
21145 
21146 		}
21147 		/*
21148 		 * If we are bound to IPIF_NOFAILOVER address, look for
21149 		 * an IRE_CACHE matching the ill.
21150 		 */
21151 send_from_ill:
21152 		if (attach_ill != NULL) {
21153 			ipif_t	*attach_ipif;
21154 
21155 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21156 
21157 			/*
21158 			 * Check if we need an ire that will not be
21159 			 * looked up by anybody else i.e. HIDDEN.
21160 			 */
21161 			if (ill_is_probeonly(attach_ill)) {
21162 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21163 			}
21164 
21165 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21166 			if (attach_ipif == NULL) {
21167 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21168 				goto discard_pkt;
21169 			}
21170 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21171 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21172 			ipif_refrele(attach_ipif);
21173 		} else if (xmit_ill != NULL || (connp != NULL &&
21174 		    connp->conn_xmit_if_ill != NULL)) {
21175 			/*
21176 			 * Mark this packet as originated locally
21177 			 */
21178 			mp->b_prev = mp->b_next = NULL;
21179 			/*
21180 			 * xmit_ill could be NULL if SO_DONTROUTE
21181 			 * is also set.
21182 			 */
21183 			if (xmit_ill == NULL) {
21184 				xmit_ill = conn_get_held_ill(connp,
21185 				    &connp->conn_xmit_if_ill, &err);
21186 				if (err == ILL_LOOKUP_FAILED) {
21187 					BUMP_MIB(&ipst->ips_ip_mib,
21188 					    ipIfStatsOutDiscards);
21189 					if (need_decref)
21190 						CONN_DEC_REF(connp);
21191 					freemsg(first_mp);
21192 					return;
21193 				}
21194 				if (xmit_ill == NULL) {
21195 					if (connp->conn_dontroute)
21196 						goto dontroute;
21197 					goto send_from_ill;
21198 				}
21199 			}
21200 			/*
21201 			 * Could be SO_DONTROUTE case also.
21202 			 * check at least one interface is UP as
21203 			 * specified by this ILL
21204 			 */
21205 			if (xmit_ill->ill_ipif_up_count > 0) {
21206 				ipif_t *ipif;
21207 
21208 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21209 				if (ipif == NULL) {
21210 					ip1dbg(("ip_output: "
21211 					    "xmit_ill NULL ipif\n"));
21212 					goto drop_pkt;
21213 				}
21214 				/*
21215 				 * Look for a ire that is part of the group,
21216 				 * if found use it else call ip_newroute_ipif.
21217 				 * IPCL_ZONEID is not used for matching because
21218 				 * IP_ALLZONES option is valid only when the
21219 				 * ill is accessible from all zones i.e has a
21220 				 * valid ipif in all zones.
21221 				 */
21222 				match_flags = MATCH_IRE_ILL_GROUP |
21223 				    MATCH_IRE_SECATTR;
21224 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21225 				    MBLK_GETLABEL(mp), match_flags, ipst);
21226 				/*
21227 				 * If an ire exists use it or else create
21228 				 * an ire but don't add it to the cache.
21229 				 * Adding an ire may cause issues with
21230 				 * asymmetric routing.
21231 				 * In case of multiroute always act as if
21232 				 * ire does not exist.
21233 				 */
21234 				if (ire == NULL ||
21235 				    ire->ire_flags & RTF_MULTIRT) {
21236 					if (ire != NULL)
21237 						ire_refrele(ire);
21238 					ip_newroute_ipif(q, first_mp, ipif,
21239 					    dst, connp, 0, zoneid, infop);
21240 					ipif_refrele(ipif);
21241 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21242 					ill_refrele(xmit_ill);
21243 					if (need_decref)
21244 						CONN_DEC_REF(connp);
21245 					return;
21246 				}
21247 				ipif_refrele(ipif);
21248 			} else {
21249 				goto drop_pkt;
21250 			}
21251 		} else if (ip_nexthop || (connp != NULL &&
21252 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21253 			if (!ip_nexthop) {
21254 				ip_nexthop = B_TRUE;
21255 				nexthop_addr = connp->conn_nexthop_v4;
21256 			}
21257 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21258 			    MATCH_IRE_GW;
21259 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21260 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21261 		} else {
21262 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21263 			    ipst);
21264 		}
21265 		if (!ire) {
21266 			/*
21267 			 * Make sure we don't load spread if this
21268 			 * is IPIF_NOFAILOVER case.
21269 			 */
21270 			if ((attach_ill != NULL) ||
21271 			    (ip_nexthop && !ignore_nexthop)) {
21272 				if (mctl_present) {
21273 					io = (ipsec_out_t *)first_mp->b_rptr;
21274 					ASSERT(first_mp->b_datap->db_type ==
21275 					    M_CTL);
21276 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21277 				} else {
21278 					ASSERT(mp == first_mp);
21279 					first_mp = allocb(
21280 					    sizeof (ipsec_info_t), BPRI_HI);
21281 					if (first_mp == NULL) {
21282 						first_mp = mp;
21283 						goto discard_pkt;
21284 					}
21285 					first_mp->b_datap->db_type = M_CTL;
21286 					first_mp->b_wptr +=
21287 					    sizeof (ipsec_info_t);
21288 					/* ipsec_out_secure is B_FALSE now */
21289 					bzero(first_mp->b_rptr,
21290 					    sizeof (ipsec_info_t));
21291 					io = (ipsec_out_t *)first_mp->b_rptr;
21292 					io->ipsec_out_type = IPSEC_OUT;
21293 					io->ipsec_out_len =
21294 					    sizeof (ipsec_out_t);
21295 					io->ipsec_out_use_global_policy =
21296 					    B_TRUE;
21297 					io->ipsec_out_ns = ipst->ips_netstack;
21298 					first_mp->b_cont = mp;
21299 					mctl_present = B_TRUE;
21300 				}
21301 				if (attach_ill != NULL) {
21302 					io->ipsec_out_ill_index = attach_ill->
21303 					    ill_phyint->phyint_ifindex;
21304 					io->ipsec_out_attach_if = B_TRUE;
21305 				} else {
21306 					io->ipsec_out_ip_nexthop = ip_nexthop;
21307 					io->ipsec_out_nexthop_addr =
21308 					    nexthop_addr;
21309 				}
21310 			}
21311 noirefound:
21312 			/*
21313 			 * Mark this packet as having originated on
21314 			 * this machine.  This will be noted in
21315 			 * ire_add_then_send, which needs to know
21316 			 * whether to run it back through ip_wput or
21317 			 * ip_rput following successful resolution.
21318 			 */
21319 			mp->b_prev = NULL;
21320 			mp->b_next = NULL;
21321 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21322 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21323 			    "ip_wput_end: q %p (%S)", q, "newroute");
21324 			if (attach_ill != NULL)
21325 				ill_refrele(attach_ill);
21326 			if (xmit_ill != NULL)
21327 				ill_refrele(xmit_ill);
21328 			if (need_decref)
21329 				CONN_DEC_REF(connp);
21330 			return;
21331 		}
21332 	}
21333 
21334 	/* We now know where we are going with it. */
21335 
21336 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21337 	    "ip_wput_end: q %p (%S)", q, "end");
21338 
21339 	/*
21340 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21341 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21342 	 */
21343 	if (ire->ire_flags & RTF_MULTIRT) {
21344 		/*
21345 		 * Force the TTL of multirouted packets if required.
21346 		 * The TTL of such packets is bounded by the
21347 		 * ip_multirt_ttl ndd variable.
21348 		 */
21349 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21350 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21351 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21352 			    "(was %d), dst 0x%08x\n",
21353 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21354 			    ntohl(ire->ire_addr)));
21355 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21356 		}
21357 		/*
21358 		 * At this point, we check to see if there are any pending
21359 		 * unresolved routes. ire_multirt_resolvable()
21360 		 * checks in O(n) that all IRE_OFFSUBNET ire
21361 		 * entries for the packet's destination and
21362 		 * flagged RTF_MULTIRT are currently resolved.
21363 		 * If some remain unresolved, we make a copy
21364 		 * of the current message. It will be used
21365 		 * to initiate additional route resolutions.
21366 		 */
21367 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21368 		    MBLK_GETLABEL(first_mp), ipst);
21369 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21370 		    "multirt_need_resolve %d, first_mp %p\n",
21371 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21372 		if (multirt_need_resolve) {
21373 			copy_mp = copymsg(first_mp);
21374 			if (copy_mp != NULL) {
21375 				MULTIRT_DEBUG_TAG(copy_mp);
21376 			}
21377 		}
21378 	}
21379 
21380 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21381 	/*
21382 	 * Try to resolve another multiroute if
21383 	 * ire_multirt_resolvable() deemed it necessary.
21384 	 * At this point, we need to distinguish
21385 	 * multicasts from other packets. For multicasts,
21386 	 * we call ip_newroute_ipif() and request that both
21387 	 * multirouting and setsrc flags are checked.
21388 	 */
21389 	if (copy_mp != NULL) {
21390 		if (CLASSD(dst)) {
21391 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21392 			if (ipif) {
21393 				ASSERT(infop->ip_opt_ill_index == 0);
21394 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21395 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21396 				ipif_refrele(ipif);
21397 			} else {
21398 				MULTIRT_DEBUG_UNTAG(copy_mp);
21399 				freemsg(copy_mp);
21400 				copy_mp = NULL;
21401 			}
21402 		} else {
21403 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21404 		}
21405 	}
21406 	if (attach_ill != NULL)
21407 		ill_refrele(attach_ill);
21408 	if (xmit_ill != NULL)
21409 		ill_refrele(xmit_ill);
21410 	if (need_decref)
21411 		CONN_DEC_REF(connp);
21412 	return;
21413 
21414 icmp_parameter_problem:
21415 	/* could not have originated externally */
21416 	ASSERT(mp->b_prev == NULL);
21417 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21418 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21419 		/* it's the IP header length that's in trouble */
21420 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21421 		first_mp = NULL;
21422 	}
21423 
21424 discard_pkt:
21425 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21426 drop_pkt:
21427 	ip1dbg(("ip_wput: dropped packet\n"));
21428 	if (ire != NULL)
21429 		ire_refrele(ire);
21430 	if (need_decref)
21431 		CONN_DEC_REF(connp);
21432 	freemsg(first_mp);
21433 	if (attach_ill != NULL)
21434 		ill_refrele(attach_ill);
21435 	if (xmit_ill != NULL)
21436 		ill_refrele(xmit_ill);
21437 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21438 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21439 }
21440 
21441 /*
21442  * If this is a conn_t queue, then we pass in the conn. This includes the
21443  * zoneid.
21444  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21445  * in which case we use the global zoneid since those are all part of
21446  * the global zone.
21447  */
21448 void
21449 ip_wput(queue_t *q, mblk_t *mp)
21450 {
21451 	if (CONN_Q(q))
21452 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21453 	else
21454 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21455 }
21456 
21457 /*
21458  *
21459  * The following rules must be observed when accessing any ipif or ill
21460  * that has been cached in the conn. Typically conn_nofailover_ill,
21461  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21462  *
21463  * Access: The ipif or ill pointed to from the conn can be accessed under
21464  * the protection of the conn_lock or after it has been refheld under the
21465  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21466  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21467  * The reason for this is that a concurrent unplumb could actually be
21468  * cleaning up these cached pointers by walking the conns and might have
21469  * finished cleaning up the conn in question. The macros check that an
21470  * unplumb has not yet started on the ipif or ill.
21471  *
21472  * Caching: An ipif or ill pointer may be cached in the conn only after
21473  * making sure that an unplumb has not started. So the caching is done
21474  * while holding both the conn_lock and the ill_lock and after using the
21475  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21476  * flag before starting the cleanup of conns.
21477  *
21478  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21479  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21480  * or a reference to the ipif or a reference to an ire that references the
21481  * ipif. An ipif does not change its ill except for failover/failback. Since
21482  * failover/failback happens only after bringing down the ipif and making sure
21483  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21484  * the above holds.
21485  */
21486 ipif_t *
21487 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21488 {
21489 	ipif_t	*ipif;
21490 	ill_t	*ill;
21491 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21492 
21493 	*err = 0;
21494 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21495 	mutex_enter(&connp->conn_lock);
21496 	ipif = *ipifp;
21497 	if (ipif != NULL) {
21498 		ill = ipif->ipif_ill;
21499 		mutex_enter(&ill->ill_lock);
21500 		if (IPIF_CAN_LOOKUP(ipif)) {
21501 			ipif_refhold_locked(ipif);
21502 			mutex_exit(&ill->ill_lock);
21503 			mutex_exit(&connp->conn_lock);
21504 			rw_exit(&ipst->ips_ill_g_lock);
21505 			return (ipif);
21506 		} else {
21507 			*err = IPIF_LOOKUP_FAILED;
21508 		}
21509 		mutex_exit(&ill->ill_lock);
21510 	}
21511 	mutex_exit(&connp->conn_lock);
21512 	rw_exit(&ipst->ips_ill_g_lock);
21513 	return (NULL);
21514 }
21515 
21516 ill_t *
21517 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21518 {
21519 	ill_t	*ill;
21520 
21521 	*err = 0;
21522 	mutex_enter(&connp->conn_lock);
21523 	ill = *illp;
21524 	if (ill != NULL) {
21525 		mutex_enter(&ill->ill_lock);
21526 		if (ILL_CAN_LOOKUP(ill)) {
21527 			ill_refhold_locked(ill);
21528 			mutex_exit(&ill->ill_lock);
21529 			mutex_exit(&connp->conn_lock);
21530 			return (ill);
21531 		} else {
21532 			*err = ILL_LOOKUP_FAILED;
21533 		}
21534 		mutex_exit(&ill->ill_lock);
21535 	}
21536 	mutex_exit(&connp->conn_lock);
21537 	return (NULL);
21538 }
21539 
21540 static int
21541 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21542 {
21543 	ill_t	*ill;
21544 
21545 	ill = ipif->ipif_ill;
21546 	mutex_enter(&connp->conn_lock);
21547 	mutex_enter(&ill->ill_lock);
21548 	if (IPIF_CAN_LOOKUP(ipif)) {
21549 		*ipifp = ipif;
21550 		mutex_exit(&ill->ill_lock);
21551 		mutex_exit(&connp->conn_lock);
21552 		return (0);
21553 	}
21554 	mutex_exit(&ill->ill_lock);
21555 	mutex_exit(&connp->conn_lock);
21556 	return (IPIF_LOOKUP_FAILED);
21557 }
21558 
21559 /*
21560  * This is called if the outbound datagram needs fragmentation.
21561  *
21562  * NOTE : This function does not ire_refrele the ire argument passed in.
21563  */
21564 static void
21565 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21566     ip_stack_t *ipst)
21567 {
21568 	ipha_t		*ipha;
21569 	mblk_t		*mp;
21570 	uint32_t	v_hlen_tos_len;
21571 	uint32_t	max_frag;
21572 	uint32_t	frag_flag;
21573 	boolean_t	dont_use;
21574 
21575 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21576 		mp = ipsec_mp->b_cont;
21577 	} else {
21578 		mp = ipsec_mp;
21579 	}
21580 
21581 	ipha = (ipha_t *)mp->b_rptr;
21582 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21583 
21584 #ifdef	_BIG_ENDIAN
21585 #define	V_HLEN	(v_hlen_tos_len >> 24)
21586 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21587 #else
21588 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21589 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21590 #endif
21591 
21592 #ifndef SPEED_BEFORE_SAFETY
21593 	/*
21594 	 * Check that ipha_length is consistent with
21595 	 * the mblk length
21596 	 */
21597 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21598 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21599 		    LENGTH, msgdsize(mp)));
21600 		freemsg(ipsec_mp);
21601 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21602 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21603 		    "packet length mismatch");
21604 		return;
21605 	}
21606 #endif
21607 	/*
21608 	 * Don't use frag_flag if pre-built packet or source
21609 	 * routed or if multicast (since multicast packets do not solicit
21610 	 * ICMP "packet too big" messages). Get the values of
21611 	 * max_frag and frag_flag atomically by acquiring the
21612 	 * ire_lock.
21613 	 */
21614 	mutex_enter(&ire->ire_lock);
21615 	max_frag = ire->ire_max_frag;
21616 	frag_flag = ire->ire_frag_flag;
21617 	mutex_exit(&ire->ire_lock);
21618 
21619 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21620 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21621 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21622 
21623 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21624 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21625 }
21626 
21627 /*
21628  * Used for deciding the MSS size for the upper layer. Thus
21629  * we need to check the outbound policy values in the conn.
21630  */
21631 int
21632 conn_ipsec_length(conn_t *connp)
21633 {
21634 	ipsec_latch_t *ipl;
21635 
21636 	ipl = connp->conn_latch;
21637 	if (ipl == NULL)
21638 		return (0);
21639 
21640 	if (ipl->ipl_out_policy == NULL)
21641 		return (0);
21642 
21643 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21644 }
21645 
21646 /*
21647  * Returns an estimate of the IPsec headers size. This is used if
21648  * we don't want to call into IPsec to get the exact size.
21649  */
21650 int
21651 ipsec_out_extra_length(mblk_t *ipsec_mp)
21652 {
21653 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21654 	ipsec_action_t *a;
21655 
21656 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21657 	if (!io->ipsec_out_secure)
21658 		return (0);
21659 
21660 	a = io->ipsec_out_act;
21661 
21662 	if (a == NULL) {
21663 		ASSERT(io->ipsec_out_policy != NULL);
21664 		a = io->ipsec_out_policy->ipsp_act;
21665 	}
21666 	ASSERT(a != NULL);
21667 
21668 	return (a->ipa_ovhd);
21669 }
21670 
21671 /*
21672  * Returns an estimate of the IPsec headers size. This is used if
21673  * we don't want to call into IPsec to get the exact size.
21674  */
21675 int
21676 ipsec_in_extra_length(mblk_t *ipsec_mp)
21677 {
21678 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21679 	ipsec_action_t *a;
21680 
21681 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21682 
21683 	a = ii->ipsec_in_action;
21684 	return (a == NULL ? 0 : a->ipa_ovhd);
21685 }
21686 
21687 /*
21688  * If there are any source route options, return the true final
21689  * destination. Otherwise, return the destination.
21690  */
21691 ipaddr_t
21692 ip_get_dst(ipha_t *ipha)
21693 {
21694 	ipoptp_t	opts;
21695 	uchar_t		*opt;
21696 	uint8_t		optval;
21697 	uint8_t		optlen;
21698 	ipaddr_t	dst;
21699 	uint32_t off;
21700 
21701 	dst = ipha->ipha_dst;
21702 
21703 	if (IS_SIMPLE_IPH(ipha))
21704 		return (dst);
21705 
21706 	for (optval = ipoptp_first(&opts, ipha);
21707 	    optval != IPOPT_EOL;
21708 	    optval = ipoptp_next(&opts)) {
21709 		opt = opts.ipoptp_cur;
21710 		optlen = opts.ipoptp_len;
21711 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21712 		switch (optval) {
21713 		case IPOPT_SSRR:
21714 		case IPOPT_LSRR:
21715 			off = opt[IPOPT_OFFSET];
21716 			/*
21717 			 * If one of the conditions is true, it means
21718 			 * end of options and dst already has the right
21719 			 * value.
21720 			 */
21721 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21722 				off = optlen - IP_ADDR_LEN;
21723 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21724 			}
21725 			return (dst);
21726 		default:
21727 			break;
21728 		}
21729 	}
21730 
21731 	return (dst);
21732 }
21733 
21734 mblk_t *
21735 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21736     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21737 {
21738 	ipsec_out_t	*io;
21739 	mblk_t		*first_mp;
21740 	boolean_t policy_present;
21741 	ip_stack_t	*ipst;
21742 	ipsec_stack_t	*ipss;
21743 
21744 	ASSERT(ire != NULL);
21745 	ipst = ire->ire_ipst;
21746 	ipss = ipst->ips_netstack->netstack_ipsec;
21747 
21748 	first_mp = mp;
21749 	if (mp->b_datap->db_type == M_CTL) {
21750 		io = (ipsec_out_t *)first_mp->b_rptr;
21751 		/*
21752 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21753 		 *
21754 		 * 1) There is per-socket policy (including cached global
21755 		 *    policy) or a policy on the IP-in-IP tunnel.
21756 		 * 2) There is no per-socket policy, but it is
21757 		 *    a multicast packet that needs to go out
21758 		 *    on a specific interface. This is the case
21759 		 *    where (ip_wput and ip_wput_multicast) attaches
21760 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21761 		 *
21762 		 * In case (2) we check with global policy to
21763 		 * see if there is a match and set the ill_index
21764 		 * appropriately so that we can lookup the ire
21765 		 * properly in ip_wput_ipsec_out.
21766 		 */
21767 
21768 		/*
21769 		 * ipsec_out_use_global_policy is set to B_FALSE
21770 		 * in ipsec_in_to_out(). Refer to that function for
21771 		 * details.
21772 		 */
21773 		if ((io->ipsec_out_latch == NULL) &&
21774 		    (io->ipsec_out_use_global_policy)) {
21775 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21776 			    ire, connp, unspec_src, zoneid));
21777 		}
21778 		if (!io->ipsec_out_secure) {
21779 			/*
21780 			 * If this is not a secure packet, drop
21781 			 * the IPSEC_OUT mp and treat it as a clear
21782 			 * packet. This happens when we are sending
21783 			 * a ICMP reply back to a clear packet. See
21784 			 * ipsec_in_to_out() for details.
21785 			 */
21786 			mp = first_mp->b_cont;
21787 			freeb(first_mp);
21788 		}
21789 		return (mp);
21790 	}
21791 	/*
21792 	 * See whether we need to attach a global policy here. We
21793 	 * don't depend on the conn (as it could be null) for deciding
21794 	 * what policy this datagram should go through because it
21795 	 * should have happened in ip_wput if there was some
21796 	 * policy. This normally happens for connections which are not
21797 	 * fully bound preventing us from caching policies in
21798 	 * ip_bind. Packets coming from the TCP listener/global queue
21799 	 * - which are non-hard_bound - could also be affected by
21800 	 * applying policy here.
21801 	 *
21802 	 * If this packet is coming from tcp global queue or listener,
21803 	 * we will be applying policy here.  This may not be *right*
21804 	 * if these packets are coming from the detached connection as
21805 	 * it could have gone in clear before. This happens only if a
21806 	 * TCP connection started when there is no policy and somebody
21807 	 * added policy before it became detached. Thus packets of the
21808 	 * detached connection could go out secure and the other end
21809 	 * would drop it because it will be expecting in clear. The
21810 	 * converse is not true i.e if somebody starts a TCP
21811 	 * connection and deletes the policy, all the packets will
21812 	 * still go out with the policy that existed before deleting
21813 	 * because ip_unbind sends up policy information which is used
21814 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21815 	 * TCP to attach a dummy IPSEC_OUT and set
21816 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21817 	 * affect performance for normal cases, we are not doing it.
21818 	 * Thus, set policy before starting any TCP connections.
21819 	 *
21820 	 * NOTE - We might apply policy even for a hard bound connection
21821 	 * - for which we cached policy in ip_bind - if somebody added
21822 	 * global policy after we inherited the policy in ip_bind.
21823 	 * This means that the packets that were going out in clear
21824 	 * previously would start going secure and hence get dropped
21825 	 * on the other side. To fix this, TCP attaches a dummy
21826 	 * ipsec_out and make sure that we don't apply global policy.
21827 	 */
21828 	if (ipha != NULL)
21829 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21830 	else
21831 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21832 	if (!policy_present)
21833 		return (mp);
21834 
21835 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21836 	    zoneid));
21837 }
21838 
21839 ire_t *
21840 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21841 {
21842 	ipaddr_t addr;
21843 	ire_t *save_ire;
21844 	irb_t *irb;
21845 	ill_group_t *illgrp;
21846 	int	err;
21847 
21848 	save_ire = ire;
21849 	addr = ire->ire_addr;
21850 
21851 	ASSERT(ire->ire_type == IRE_BROADCAST);
21852 
21853 	illgrp = connp->conn_outgoing_ill->ill_group;
21854 	if (illgrp == NULL) {
21855 		*conn_outgoing_ill = conn_get_held_ill(connp,
21856 		    &connp->conn_outgoing_ill, &err);
21857 		if (err == ILL_LOOKUP_FAILED) {
21858 			ire_refrele(save_ire);
21859 			return (NULL);
21860 		}
21861 		return (save_ire);
21862 	}
21863 	/*
21864 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21865 	 * If it is part of the group, we need to send on the ire
21866 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21867 	 * to this group. This is okay as IP_BOUND_IF really means
21868 	 * any ill in the group. We depend on the fact that the
21869 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21870 	 * if such an ire exists. This is possible only if you have
21871 	 * at least one ill in the group that has not failed.
21872 	 *
21873 	 * First get to the ire that matches the address and group.
21874 	 *
21875 	 * We don't look for an ire with a matching zoneid because a given zone
21876 	 * won't always have broadcast ires on all ills in the group.
21877 	 */
21878 	irb = ire->ire_bucket;
21879 	rw_enter(&irb->irb_lock, RW_READER);
21880 	if (ire->ire_marks & IRE_MARK_NORECV) {
21881 		/*
21882 		 * If the current zone only has an ire broadcast for this
21883 		 * address marked NORECV, the ire we want is ahead in the
21884 		 * bucket, so we look it up deliberately ignoring the zoneid.
21885 		 */
21886 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21887 			if (ire->ire_addr != addr)
21888 				continue;
21889 			/* skip over deleted ires */
21890 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21891 				continue;
21892 		}
21893 	}
21894 	while (ire != NULL) {
21895 		/*
21896 		 * If a new interface is coming up, we could end up
21897 		 * seeing the loopback ire and the non-loopback ire
21898 		 * may not have been added yet. So check for ire_stq
21899 		 */
21900 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21901 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21902 			break;
21903 		}
21904 		ire = ire->ire_next;
21905 	}
21906 	if (ire != NULL && ire->ire_addr == addr &&
21907 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21908 		IRE_REFHOLD(ire);
21909 		rw_exit(&irb->irb_lock);
21910 		ire_refrele(save_ire);
21911 		*conn_outgoing_ill = ire_to_ill(ire);
21912 		/*
21913 		 * Refhold the ill to make the conn_outgoing_ill
21914 		 * independent of the ire. ip_wput_ire goes in a loop
21915 		 * and may refrele the ire. Since we have an ire at this
21916 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21917 		 */
21918 		ill_refhold(*conn_outgoing_ill);
21919 		return (ire);
21920 	}
21921 	rw_exit(&irb->irb_lock);
21922 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21923 	/*
21924 	 * If we can't find a suitable ire, return the original ire.
21925 	 */
21926 	return (save_ire);
21927 }
21928 
21929 /*
21930  * This function does the ire_refrele of the ire passed in as the
21931  * argument. As this function looks up more ires i.e broadcast ires,
21932  * it needs to REFRELE them. Currently, for simplicity we don't
21933  * differentiate the one passed in and looked up here. We always
21934  * REFRELE.
21935  * IPQoS Notes:
21936  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21937  * IPsec packets are done in ipsec_out_process.
21938  *
21939  */
21940 void
21941 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21942     zoneid_t zoneid)
21943 {
21944 	ipha_t		*ipha;
21945 #define	rptr	((uchar_t *)ipha)
21946 	queue_t		*stq;
21947 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21948 	uint32_t	v_hlen_tos_len;
21949 	uint32_t	ttl_protocol;
21950 	ipaddr_t	src;
21951 	ipaddr_t	dst;
21952 	uint32_t	cksum;
21953 	ipaddr_t	orig_src;
21954 	ire_t		*ire1;
21955 	mblk_t		*next_mp;
21956 	uint_t		hlen;
21957 	uint16_t	*up;
21958 	uint32_t	max_frag = ire->ire_max_frag;
21959 	ill_t		*ill = ire_to_ill(ire);
21960 	int		clusterwide;
21961 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21962 	int		ipsec_len;
21963 	mblk_t		*first_mp;
21964 	ipsec_out_t	*io;
21965 	boolean_t	conn_dontroute;		/* conn value for multicast */
21966 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21967 	boolean_t	multicast_forward;	/* Should we forward ? */
21968 	boolean_t	unspec_src;
21969 	ill_t		*conn_outgoing_ill = NULL;
21970 	ill_t		*ire_ill;
21971 	ill_t		*ire1_ill;
21972 	ill_t		*out_ill;
21973 	uint32_t 	ill_index = 0;
21974 	boolean_t	multirt_send = B_FALSE;
21975 	int		err;
21976 	ipxmit_state_t	pktxmit_state;
21977 	ip_stack_t	*ipst = ire->ire_ipst;
21978 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21979 
21980 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21981 	    "ip_wput_ire_start: q %p", q);
21982 
21983 	multicast_forward = B_FALSE;
21984 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21985 
21986 	if (ire->ire_flags & RTF_MULTIRT) {
21987 		/*
21988 		 * Multirouting case. The bucket where ire is stored
21989 		 * probably holds other RTF_MULTIRT flagged ire
21990 		 * to the destination. In this call to ip_wput_ire,
21991 		 * we attempt to send the packet through all
21992 		 * those ires. Thus, we first ensure that ire is the
21993 		 * first RTF_MULTIRT ire in the bucket,
21994 		 * before walking the ire list.
21995 		 */
21996 		ire_t *first_ire;
21997 		irb_t *irb = ire->ire_bucket;
21998 		ASSERT(irb != NULL);
21999 
22000 		/* Make sure we do not omit any multiroute ire. */
22001 		IRB_REFHOLD(irb);
22002 		for (first_ire = irb->irb_ire;
22003 		    first_ire != NULL;
22004 		    first_ire = first_ire->ire_next) {
22005 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22006 			    (first_ire->ire_addr == ire->ire_addr) &&
22007 			    !(first_ire->ire_marks &
22008 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22009 				break;
22010 			}
22011 		}
22012 
22013 		if ((first_ire != NULL) && (first_ire != ire)) {
22014 			IRE_REFHOLD(first_ire);
22015 			ire_refrele(ire);
22016 			ire = first_ire;
22017 			ill = ire_to_ill(ire);
22018 		}
22019 		IRB_REFRELE(irb);
22020 	}
22021 
22022 	/*
22023 	 * conn_outgoing_ill is used only in the broadcast loop.
22024 	 * for performance we don't grab the mutexs in the fastpath
22025 	 */
22026 	if ((connp != NULL) &&
22027 	    (connp->conn_xmit_if_ill == NULL) &&
22028 	    (ire->ire_type == IRE_BROADCAST) &&
22029 	    ((connp->conn_nofailover_ill != NULL) ||
22030 	    (connp->conn_outgoing_ill != NULL))) {
22031 		/*
22032 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22033 		 * option. So, see if this endpoint is bound to a
22034 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22035 		 * that if the interface is failed, we will still send
22036 		 * the packet on the same ill which is what we want.
22037 		 */
22038 		conn_outgoing_ill = conn_get_held_ill(connp,
22039 		    &connp->conn_nofailover_ill, &err);
22040 		if (err == ILL_LOOKUP_FAILED) {
22041 			ire_refrele(ire);
22042 			freemsg(mp);
22043 			return;
22044 		}
22045 		if (conn_outgoing_ill == NULL) {
22046 			/*
22047 			 * Choose a good ill in the group to send the
22048 			 * packets on.
22049 			 */
22050 			ire = conn_set_outgoing_ill(connp, ire,
22051 			    &conn_outgoing_ill);
22052 			if (ire == NULL) {
22053 				freemsg(mp);
22054 				return;
22055 			}
22056 		}
22057 	}
22058 
22059 	if (mp->b_datap->db_type != M_CTL) {
22060 		ipha = (ipha_t *)mp->b_rptr;
22061 	} else {
22062 		io = (ipsec_out_t *)mp->b_rptr;
22063 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22064 		ASSERT(zoneid == io->ipsec_out_zoneid);
22065 		ASSERT(zoneid != ALL_ZONES);
22066 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22067 		dst = ipha->ipha_dst;
22068 		/*
22069 		 * For the multicast case, ipsec_out carries conn_dontroute and
22070 		 * conn_multicast_loop as conn may not be available here. We
22071 		 * need this for multicast loopback and forwarding which is done
22072 		 * later in the code.
22073 		 */
22074 		if (CLASSD(dst)) {
22075 			conn_dontroute = io->ipsec_out_dontroute;
22076 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22077 			/*
22078 			 * If conn_dontroute is not set or conn_multicast_loop
22079 			 * is set, we need to do forwarding/loopback. For
22080 			 * datagrams from ip_wput_multicast, conn_dontroute is
22081 			 * set to B_TRUE and conn_multicast_loop is set to
22082 			 * B_FALSE so that we neither do forwarding nor
22083 			 * loopback.
22084 			 */
22085 			if (!conn_dontroute || conn_multicast_loop)
22086 				multicast_forward = B_TRUE;
22087 		}
22088 	}
22089 
22090 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22091 	    ire->ire_zoneid != ALL_ZONES) {
22092 		/*
22093 		 * When a zone sends a packet to another zone, we try to deliver
22094 		 * the packet under the same conditions as if the destination
22095 		 * was a real node on the network. To do so, we look for a
22096 		 * matching route in the forwarding table.
22097 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22098 		 * ip_newroute() does.
22099 		 * Note that IRE_LOCAL are special, since they are used
22100 		 * when the zoneid doesn't match in some cases. This means that
22101 		 * we need to handle ipha_src differently since ire_src_addr
22102 		 * belongs to the receiving zone instead of the sending zone.
22103 		 * When ip_restrict_interzone_loopback is set, then
22104 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22105 		 * for loopback between zones when the logical "Ethernet" would
22106 		 * have looped them back.
22107 		 */
22108 		ire_t *src_ire;
22109 
22110 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22111 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22112 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22113 		if (src_ire != NULL &&
22114 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22115 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22116 		    ire_local_same_ill_group(ire, src_ire))) {
22117 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22118 				ipha->ipha_src = src_ire->ire_src_addr;
22119 			ire_refrele(src_ire);
22120 		} else {
22121 			ire_refrele(ire);
22122 			if (conn_outgoing_ill != NULL)
22123 				ill_refrele(conn_outgoing_ill);
22124 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22125 			if (src_ire != NULL) {
22126 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22127 					ire_refrele(src_ire);
22128 					freemsg(mp);
22129 					return;
22130 				}
22131 				ire_refrele(src_ire);
22132 			}
22133 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22134 				/* Failed */
22135 				freemsg(mp);
22136 				return;
22137 			}
22138 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22139 			    ipst);
22140 			return;
22141 		}
22142 	}
22143 
22144 	if (mp->b_datap->db_type == M_CTL ||
22145 	    ipss->ipsec_outbound_v4_policy_present) {
22146 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22147 		    unspec_src, zoneid);
22148 		if (mp == NULL) {
22149 			ire_refrele(ire);
22150 			if (conn_outgoing_ill != NULL)
22151 				ill_refrele(conn_outgoing_ill);
22152 			return;
22153 		}
22154 	}
22155 
22156 	first_mp = mp;
22157 	ipsec_len = 0;
22158 
22159 	if (first_mp->b_datap->db_type == M_CTL) {
22160 		io = (ipsec_out_t *)first_mp->b_rptr;
22161 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22162 		mp = first_mp->b_cont;
22163 		ipsec_len = ipsec_out_extra_length(first_mp);
22164 		ASSERT(ipsec_len >= 0);
22165 		/* We already picked up the zoneid from the M_CTL above */
22166 		ASSERT(zoneid == io->ipsec_out_zoneid);
22167 		ASSERT(zoneid != ALL_ZONES);
22168 
22169 		/*
22170 		 * Drop M_CTL here if IPsec processing is not needed.
22171 		 * (Non-IPsec use of M_CTL extracted any information it
22172 		 * needed above).
22173 		 */
22174 		if (ipsec_len == 0) {
22175 			freeb(first_mp);
22176 			first_mp = mp;
22177 		}
22178 	}
22179 
22180 	/*
22181 	 * Fast path for ip_wput_ire
22182 	 */
22183 
22184 	ipha = (ipha_t *)mp->b_rptr;
22185 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22186 	dst = ipha->ipha_dst;
22187 
22188 	/*
22189 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22190 	 * if the socket is a SOCK_RAW type. The transport checksum should
22191 	 * be provided in the pre-built packet, so we don't need to compute it.
22192 	 * Also, other application set flags, like DF, should not be altered.
22193 	 * Other transport MUST pass down zero.
22194 	 */
22195 	ip_hdr_included = ipha->ipha_ident;
22196 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22197 
22198 	if (CLASSD(dst)) {
22199 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22200 		    ntohl(dst),
22201 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22202 		    ntohl(ire->ire_addr)));
22203 	}
22204 
22205 /* Macros to extract header fields from data already in registers */
22206 #ifdef	_BIG_ENDIAN
22207 #define	V_HLEN	(v_hlen_tos_len >> 24)
22208 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22209 #define	PROTO	(ttl_protocol & 0xFF)
22210 #else
22211 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22212 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22213 #define	PROTO	(ttl_protocol >> 8)
22214 #endif
22215 
22216 
22217 	orig_src = src = ipha->ipha_src;
22218 	/* (The loop back to "another" is explained down below.) */
22219 another:;
22220 	/*
22221 	 * Assign an ident value for this packet.  We assign idents on
22222 	 * a per destination basis out of the IRE.  There could be
22223 	 * other threads targeting the same destination, so we have to
22224 	 * arrange for a atomic increment.  Note that we use a 32-bit
22225 	 * atomic add because it has better performance than its
22226 	 * 16-bit sibling.
22227 	 *
22228 	 * If running in cluster mode and if the source address
22229 	 * belongs to a replicated service then vector through
22230 	 * cl_inet_ipident vector to allocate ip identifier
22231 	 * NOTE: This is a contract private interface with the
22232 	 * clustering group.
22233 	 */
22234 	clusterwide = 0;
22235 	if (cl_inet_ipident) {
22236 		ASSERT(cl_inet_isclusterwide);
22237 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22238 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22239 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22240 			    AF_INET, (uint8_t *)(uintptr_t)src,
22241 			    (uint8_t *)(uintptr_t)dst);
22242 			clusterwide = 1;
22243 		}
22244 	}
22245 	if (!clusterwide) {
22246 		ipha->ipha_ident =
22247 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22248 	}
22249 
22250 #ifndef _BIG_ENDIAN
22251 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22252 #endif
22253 
22254 	/*
22255 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22256 	 * This is needed to obey conn_unspec_src when packets go through
22257 	 * ip_newroute + arp.
22258 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22259 	 */
22260 	if (src == INADDR_ANY && !unspec_src) {
22261 		/*
22262 		 * Assign the appropriate source address from the IRE if none
22263 		 * was specified.
22264 		 */
22265 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22266 
22267 		/*
22268 		 * With IP multipathing, broadcast packets are sent on the ire
22269 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22270 		 * the group. However, this ire might not be in the same zone so
22271 		 * we can't always use its source address. We look for a
22272 		 * broadcast ire in the same group and in the right zone.
22273 		 */
22274 		if (ire->ire_type == IRE_BROADCAST &&
22275 		    ire->ire_zoneid != zoneid) {
22276 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22277 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22278 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22279 			if (src_ire != NULL) {
22280 				src = src_ire->ire_src_addr;
22281 				ire_refrele(src_ire);
22282 			} else {
22283 				ire_refrele(ire);
22284 				if (conn_outgoing_ill != NULL)
22285 					ill_refrele(conn_outgoing_ill);
22286 				freemsg(first_mp);
22287 				if (ill != NULL) {
22288 					BUMP_MIB(ill->ill_ip_mib,
22289 					    ipIfStatsOutDiscards);
22290 				} else {
22291 					BUMP_MIB(&ipst->ips_ip_mib,
22292 					    ipIfStatsOutDiscards);
22293 				}
22294 				return;
22295 			}
22296 		} else {
22297 			src = ire->ire_src_addr;
22298 		}
22299 
22300 		if (connp == NULL) {
22301 			ip1dbg(("ip_wput_ire: no connp and no src "
22302 			    "address for dst 0x%x, using src 0x%x\n",
22303 			    ntohl(dst),
22304 			    ntohl(src)));
22305 		}
22306 		ipha->ipha_src = src;
22307 	}
22308 	stq = ire->ire_stq;
22309 
22310 	/*
22311 	 * We only allow ire chains for broadcasts since there will
22312 	 * be multiple IRE_CACHE entries for the same multicast
22313 	 * address (one per ipif).
22314 	 */
22315 	next_mp = NULL;
22316 
22317 	/* broadcast packet */
22318 	if (ire->ire_type == IRE_BROADCAST)
22319 		goto broadcast;
22320 
22321 	/* loopback ? */
22322 	if (stq == NULL)
22323 		goto nullstq;
22324 
22325 	/* The ill_index for outbound ILL */
22326 	ill_index = Q_TO_INDEX(stq);
22327 
22328 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22329 	ttl_protocol = ((uint16_t *)ipha)[4];
22330 
22331 	/* pseudo checksum (do it in parts for IP header checksum) */
22332 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22333 
22334 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22335 		queue_t *dev_q = stq->q_next;
22336 
22337 		/* flow controlled */
22338 		if ((dev_q->q_next || dev_q->q_first) &&
22339 		    !canput(dev_q))
22340 			goto blocked;
22341 		if ((PROTO == IPPROTO_UDP) &&
22342 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22343 			hlen = (V_HLEN & 0xF) << 2;
22344 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22345 			if (*up != 0) {
22346 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22347 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22348 				/* Software checksum? */
22349 				if (DB_CKSUMFLAGS(mp) == 0) {
22350 					IP_STAT(ipst, ip_out_sw_cksum);
22351 					IP_STAT_UPDATE(ipst,
22352 					    ip_udp_out_sw_cksum_bytes,
22353 					    LENGTH - hlen);
22354 				}
22355 			}
22356 		}
22357 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22358 		hlen = (V_HLEN & 0xF) << 2;
22359 		if (PROTO == IPPROTO_TCP) {
22360 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22361 			/*
22362 			 * The packet header is processed once and for all, even
22363 			 * in the multirouting case. We disable hardware
22364 			 * checksum if the packet is multirouted, as it will be
22365 			 * replicated via several interfaces, and not all of
22366 			 * them may have this capability.
22367 			 */
22368 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22369 			    LENGTH, max_frag, ipsec_len, cksum);
22370 			/* Software checksum? */
22371 			if (DB_CKSUMFLAGS(mp) == 0) {
22372 				IP_STAT(ipst, ip_out_sw_cksum);
22373 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22374 				    LENGTH - hlen);
22375 			}
22376 		} else {
22377 			sctp_hdr_t	*sctph;
22378 
22379 			ASSERT(PROTO == IPPROTO_SCTP);
22380 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22381 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22382 			/*
22383 			 * Zero out the checksum field to ensure proper
22384 			 * checksum calculation.
22385 			 */
22386 			sctph->sh_chksum = 0;
22387 #ifdef	DEBUG
22388 			if (!skip_sctp_cksum)
22389 #endif
22390 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22391 		}
22392 	}
22393 
22394 	/*
22395 	 * If this is a multicast packet and originated from ip_wput
22396 	 * we need to do loopback and forwarding checks. If it comes
22397 	 * from ip_wput_multicast, we SHOULD not do this.
22398 	 */
22399 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22400 
22401 	/* checksum */
22402 	cksum += ttl_protocol;
22403 
22404 	/* fragment the packet */
22405 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22406 		goto fragmentit;
22407 	/*
22408 	 * Don't use frag_flag if packet is pre-built or source
22409 	 * routed or if multicast (since multicast packets do
22410 	 * not solicit ICMP "packet too big" messages).
22411 	 */
22412 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22413 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22414 	    !ip_source_route_included(ipha)) &&
22415 	    !CLASSD(ipha->ipha_dst))
22416 		ipha->ipha_fragment_offset_and_flags |=
22417 		    htons(ire->ire_frag_flag);
22418 
22419 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22420 		/* calculate IP header checksum */
22421 		cksum += ipha->ipha_ident;
22422 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22423 		cksum += ipha->ipha_fragment_offset_and_flags;
22424 
22425 		/* IP options present */
22426 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22427 		if (hlen)
22428 			goto checksumoptions;
22429 
22430 		/* calculate hdr checksum */
22431 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22432 		cksum = ~(cksum + (cksum >> 16));
22433 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22434 	}
22435 	if (ipsec_len != 0) {
22436 		/*
22437 		 * We will do the rest of the processing after
22438 		 * we come back from IPsec in ip_wput_ipsec_out().
22439 		 */
22440 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22441 
22442 		io = (ipsec_out_t *)first_mp->b_rptr;
22443 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22444 		    ill_phyint->phyint_ifindex;
22445 
22446 		ipsec_out_process(q, first_mp, ire, ill_index);
22447 		ire_refrele(ire);
22448 		if (conn_outgoing_ill != NULL)
22449 			ill_refrele(conn_outgoing_ill);
22450 		return;
22451 	}
22452 
22453 	/*
22454 	 * In most cases, the emission loop below is entered only
22455 	 * once. Only in the case where the ire holds the
22456 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22457 	 * flagged ires in the bucket, and send the packet
22458 	 * through all crossed RTF_MULTIRT routes.
22459 	 */
22460 	if (ire->ire_flags & RTF_MULTIRT) {
22461 		multirt_send = B_TRUE;
22462 	}
22463 	do {
22464 		if (multirt_send) {
22465 			irb_t *irb;
22466 			/*
22467 			 * We are in a multiple send case, need to get
22468 			 * the next ire and make a duplicate of the packet.
22469 			 * ire1 holds here the next ire to process in the
22470 			 * bucket. If multirouting is expected,
22471 			 * any non-RTF_MULTIRT ire that has the
22472 			 * right destination address is ignored.
22473 			 */
22474 			irb = ire->ire_bucket;
22475 			ASSERT(irb != NULL);
22476 
22477 			IRB_REFHOLD(irb);
22478 			for (ire1 = ire->ire_next;
22479 			    ire1 != NULL;
22480 			    ire1 = ire1->ire_next) {
22481 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22482 					continue;
22483 				if (ire1->ire_addr != ire->ire_addr)
22484 					continue;
22485 				if (ire1->ire_marks &
22486 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22487 					continue;
22488 
22489 				/* Got one */
22490 				IRE_REFHOLD(ire1);
22491 				break;
22492 			}
22493 			IRB_REFRELE(irb);
22494 
22495 			if (ire1 != NULL) {
22496 				next_mp = copyb(mp);
22497 				if ((next_mp == NULL) ||
22498 				    ((mp->b_cont != NULL) &&
22499 				    ((next_mp->b_cont =
22500 				    dupmsg(mp->b_cont)) == NULL))) {
22501 					freemsg(next_mp);
22502 					next_mp = NULL;
22503 					ire_refrele(ire1);
22504 					ire1 = NULL;
22505 				}
22506 			}
22507 
22508 			/* Last multiroute ire; don't loop anymore. */
22509 			if (ire1 == NULL) {
22510 				multirt_send = B_FALSE;
22511 			}
22512 		}
22513 
22514 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22515 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22516 		    mblk_t *, mp);
22517 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22518 		    ipst->ips_ipv4firewall_physical_out,
22519 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22520 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22521 		if (mp == NULL)
22522 			goto release_ire_and_ill;
22523 
22524 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22525 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22526 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22527 		if ((pktxmit_state == SEND_FAILED) ||
22528 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22529 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22530 			    "- packet dropped\n"));
22531 release_ire_and_ill:
22532 			ire_refrele(ire);
22533 			if (next_mp != NULL) {
22534 				freemsg(next_mp);
22535 				ire_refrele(ire1);
22536 			}
22537 			if (conn_outgoing_ill != NULL)
22538 				ill_refrele(conn_outgoing_ill);
22539 			return;
22540 		}
22541 
22542 		if (CLASSD(dst)) {
22543 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22544 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22545 			    LENGTH);
22546 		}
22547 
22548 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22549 		    "ip_wput_ire_end: q %p (%S)",
22550 		    q, "last copy out");
22551 		IRE_REFRELE(ire);
22552 
22553 		if (multirt_send) {
22554 			ASSERT(ire1);
22555 			/*
22556 			 * Proceed with the next RTF_MULTIRT ire,
22557 			 * Also set up the send-to queue accordingly.
22558 			 */
22559 			ire = ire1;
22560 			ire1 = NULL;
22561 			stq = ire->ire_stq;
22562 			mp = next_mp;
22563 			next_mp = NULL;
22564 			ipha = (ipha_t *)mp->b_rptr;
22565 			ill_index = Q_TO_INDEX(stq);
22566 			ill = (ill_t *)stq->q_ptr;
22567 		}
22568 	} while (multirt_send);
22569 	if (conn_outgoing_ill != NULL)
22570 		ill_refrele(conn_outgoing_ill);
22571 	return;
22572 
22573 	/*
22574 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22575 	 */
22576 broadcast:
22577 	{
22578 		/*
22579 		 * Avoid broadcast storms by setting the ttl to 1
22580 		 * for broadcasts. This parameter can be set
22581 		 * via ndd, so make sure that for the SO_DONTROUTE
22582 		 * case that ipha_ttl is always set to 1.
22583 		 * In the event that we are replying to incoming
22584 		 * ICMP packets, conn could be NULL.
22585 		 */
22586 		if ((connp != NULL) && connp->conn_dontroute)
22587 			ipha->ipha_ttl = 1;
22588 		else
22589 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22590 
22591 		/*
22592 		 * Note that we are not doing a IRB_REFHOLD here.
22593 		 * Actually we don't care if the list changes i.e
22594 		 * if somebody deletes an IRE from the list while
22595 		 * we drop the lock, the next time we come around
22596 		 * ire_next will be NULL and hence we won't send
22597 		 * out multiple copies which is fine.
22598 		 */
22599 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22600 		ire1 = ire->ire_next;
22601 		if (conn_outgoing_ill != NULL) {
22602 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22603 				ASSERT(ire1 == ire->ire_next);
22604 				if (ire1 != NULL && ire1->ire_addr == dst) {
22605 					ire_refrele(ire);
22606 					ire = ire1;
22607 					IRE_REFHOLD(ire);
22608 					ire1 = ire->ire_next;
22609 					continue;
22610 				}
22611 				rw_exit(&ire->ire_bucket->irb_lock);
22612 				/* Did not find a matching ill */
22613 				ip1dbg(("ip_wput_ire: broadcast with no "
22614 				    "matching IP_BOUND_IF ill %s\n",
22615 				    conn_outgoing_ill->ill_name));
22616 				freemsg(first_mp);
22617 				if (ire != NULL)
22618 					ire_refrele(ire);
22619 				ill_refrele(conn_outgoing_ill);
22620 				return;
22621 			}
22622 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22623 			/*
22624 			 * If the next IRE has the same address and is not one
22625 			 * of the two copies that we need to send, try to see
22626 			 * whether this copy should be sent at all. This
22627 			 * assumes that we insert loopbacks first and then
22628 			 * non-loopbacks. This is acheived by inserting the
22629 			 * loopback always before non-loopback.
22630 			 * This is used to send a single copy of a broadcast
22631 			 * packet out all physical interfaces that have an
22632 			 * matching IRE_BROADCAST while also looping
22633 			 * back one copy (to ip_wput_local) for each
22634 			 * matching physical interface. However, we avoid
22635 			 * sending packets out different logical that match by
22636 			 * having ipif_up/ipif_down supress duplicate
22637 			 * IRE_BROADCASTS.
22638 			 *
22639 			 * This feature is currently used to get broadcasts
22640 			 * sent to multiple interfaces, when the broadcast
22641 			 * address being used applies to multiple interfaces.
22642 			 * For example, a whole net broadcast will be
22643 			 * replicated on every connected subnet of
22644 			 * the target net.
22645 			 *
22646 			 * Each zone has its own set of IRE_BROADCASTs, so that
22647 			 * we're able to distribute inbound packets to multiple
22648 			 * zones who share a broadcast address. We avoid looping
22649 			 * back outbound packets in different zones but on the
22650 			 * same ill, as the application would see duplicates.
22651 			 *
22652 			 * If the interfaces are part of the same group,
22653 			 * we would want to send only one copy out for
22654 			 * whole group.
22655 			 *
22656 			 * This logic assumes that ire_add_v4() groups the
22657 			 * IRE_BROADCAST entries so that those with the same
22658 			 * ire_addr and ill_group are kept together.
22659 			 */
22660 			ire_ill = ire->ire_ipif->ipif_ill;
22661 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22662 				if (ire_ill->ill_group != NULL &&
22663 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22664 					/*
22665 					 * If the current zone only has an ire
22666 					 * broadcast for this address marked
22667 					 * NORECV, the ire we want is ahead in
22668 					 * the bucket, so we look it up
22669 					 * deliberately ignoring the zoneid.
22670 					 */
22671 					for (ire1 = ire->ire_bucket->irb_ire;
22672 					    ire1 != NULL;
22673 					    ire1 = ire1->ire_next) {
22674 						ire1_ill =
22675 						    ire1->ire_ipif->ipif_ill;
22676 						if (ire1->ire_addr != dst)
22677 							continue;
22678 						/* skip over the current ire */
22679 						if (ire1 == ire)
22680 							continue;
22681 						/* skip over deleted ires */
22682 						if (ire1->ire_marks &
22683 						    IRE_MARK_CONDEMNED)
22684 							continue;
22685 						/*
22686 						 * non-loopback ire in our
22687 						 * group: use it for the next
22688 						 * pass in the loop
22689 						 */
22690 						if (ire1->ire_stq != NULL &&
22691 						    ire1_ill->ill_group ==
22692 						    ire_ill->ill_group)
22693 							break;
22694 					}
22695 				}
22696 			} else {
22697 				while (ire1 != NULL && ire1->ire_addr == dst) {
22698 					ire1_ill = ire1->ire_ipif->ipif_ill;
22699 					/*
22700 					 * We can have two broadcast ires on the
22701 					 * same ill in different zones; here
22702 					 * we'll send a copy of the packet on
22703 					 * each ill and the fanout code will
22704 					 * call conn_wantpacket() to check that
22705 					 * the zone has the broadcast address
22706 					 * configured on the ill. If the two
22707 					 * ires are in the same group we only
22708 					 * send one copy up.
22709 					 */
22710 					if (ire1_ill != ire_ill &&
22711 					    (ire1_ill->ill_group == NULL ||
22712 					    ire_ill->ill_group == NULL ||
22713 					    ire1_ill->ill_group !=
22714 					    ire_ill->ill_group)) {
22715 						break;
22716 					}
22717 					ire1 = ire1->ire_next;
22718 				}
22719 			}
22720 		}
22721 		ASSERT(multirt_send == B_FALSE);
22722 		if (ire1 != NULL && ire1->ire_addr == dst) {
22723 			if ((ire->ire_flags & RTF_MULTIRT) &&
22724 			    (ire1->ire_flags & RTF_MULTIRT)) {
22725 				/*
22726 				 * We are in the multirouting case.
22727 				 * The message must be sent at least
22728 				 * on both ires. These ires have been
22729 				 * inserted AFTER the standard ones
22730 				 * in ip_rt_add(). There are thus no
22731 				 * other ire entries for the destination
22732 				 * address in the rest of the bucket
22733 				 * that do not have the RTF_MULTIRT
22734 				 * flag. We don't process a copy
22735 				 * of the message here. This will be
22736 				 * done in the final sending loop.
22737 				 */
22738 				multirt_send = B_TRUE;
22739 			} else {
22740 				next_mp = ip_copymsg(first_mp);
22741 				if (next_mp != NULL)
22742 					IRE_REFHOLD(ire1);
22743 			}
22744 		}
22745 		rw_exit(&ire->ire_bucket->irb_lock);
22746 	}
22747 
22748 	if (stq) {
22749 		/*
22750 		 * A non-NULL send-to queue means this packet is going
22751 		 * out of this machine.
22752 		 */
22753 		out_ill = (ill_t *)stq->q_ptr;
22754 
22755 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22756 		ttl_protocol = ((uint16_t *)ipha)[4];
22757 		/*
22758 		 * We accumulate the pseudo header checksum in cksum.
22759 		 * This is pretty hairy code, so watch close.  One
22760 		 * thing to keep in mind is that UDP and TCP have
22761 		 * stored their respective datagram lengths in their
22762 		 * checksum fields.  This lines things up real nice.
22763 		 */
22764 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22765 		    (src >> 16) + (src & 0xFFFF);
22766 		/*
22767 		 * We assume the udp checksum field contains the
22768 		 * length, so to compute the pseudo header checksum,
22769 		 * all we need is the protocol number and src/dst.
22770 		 */
22771 		/* Provide the checksums for UDP and TCP. */
22772 		if ((PROTO == IPPROTO_TCP) &&
22773 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22774 			/* hlen gets the number of uchar_ts in the IP header */
22775 			hlen = (V_HLEN & 0xF) << 2;
22776 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22777 			IP_STAT(ipst, ip_out_sw_cksum);
22778 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22779 			    LENGTH - hlen);
22780 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22781 		} else if (PROTO == IPPROTO_SCTP &&
22782 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22783 			sctp_hdr_t	*sctph;
22784 
22785 			hlen = (V_HLEN & 0xF) << 2;
22786 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22787 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22788 			sctph->sh_chksum = 0;
22789 #ifdef	DEBUG
22790 			if (!skip_sctp_cksum)
22791 #endif
22792 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22793 		} else {
22794 			queue_t *dev_q = stq->q_next;
22795 
22796 			if ((dev_q->q_next || dev_q->q_first) &&
22797 			    !canput(dev_q)) {
22798 blocked:
22799 				ipha->ipha_ident = ip_hdr_included;
22800 				/*
22801 				 * If we don't have a conn to apply
22802 				 * backpressure, free the message.
22803 				 * In the ire_send path, we don't know
22804 				 * the position to requeue the packet. Rather
22805 				 * than reorder packets, we just drop this
22806 				 * packet.
22807 				 */
22808 				if (ipst->ips_ip_output_queue &&
22809 				    connp != NULL &&
22810 				    caller != IRE_SEND) {
22811 					if (caller == IP_WSRV) {
22812 						connp->conn_did_putbq = 1;
22813 						(void) putbq(connp->conn_wq,
22814 						    first_mp);
22815 						conn_drain_insert(connp);
22816 						/*
22817 						 * This is the service thread,
22818 						 * and the queue is already
22819 						 * noenabled. The check for
22820 						 * canput and the putbq is not
22821 						 * atomic. So we need to check
22822 						 * again.
22823 						 */
22824 						if (canput(stq->q_next))
22825 							connp->conn_did_putbq
22826 							    = 0;
22827 						IP_STAT(ipst, ip_conn_flputbq);
22828 					} else {
22829 						/*
22830 						 * We are not the service proc.
22831 						 * ip_wsrv will be scheduled or
22832 						 * is already running.
22833 						 */
22834 						(void) putq(connp->conn_wq,
22835 						    first_mp);
22836 					}
22837 				} else {
22838 					out_ill = (ill_t *)stq->q_ptr;
22839 					BUMP_MIB(out_ill->ill_ip_mib,
22840 					    ipIfStatsOutDiscards);
22841 					freemsg(first_mp);
22842 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22843 					    "ip_wput_ire_end: q %p (%S)",
22844 					    q, "discard");
22845 				}
22846 				ire_refrele(ire);
22847 				if (next_mp) {
22848 					ire_refrele(ire1);
22849 					freemsg(next_mp);
22850 				}
22851 				if (conn_outgoing_ill != NULL)
22852 					ill_refrele(conn_outgoing_ill);
22853 				return;
22854 			}
22855 			if ((PROTO == IPPROTO_UDP) &&
22856 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22857 				/*
22858 				 * hlen gets the number of uchar_ts in the
22859 				 * IP header
22860 				 */
22861 				hlen = (V_HLEN & 0xF) << 2;
22862 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22863 				max_frag = ire->ire_max_frag;
22864 				if (*up != 0) {
22865 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22866 					    up, PROTO, hlen, LENGTH, max_frag,
22867 					    ipsec_len, cksum);
22868 					/* Software checksum? */
22869 					if (DB_CKSUMFLAGS(mp) == 0) {
22870 						IP_STAT(ipst, ip_out_sw_cksum);
22871 						IP_STAT_UPDATE(ipst,
22872 						    ip_udp_out_sw_cksum_bytes,
22873 						    LENGTH - hlen);
22874 					}
22875 				}
22876 			}
22877 		}
22878 		/*
22879 		 * Need to do this even when fragmenting. The local
22880 		 * loopback can be done without computing checksums
22881 		 * but forwarding out other interface must be done
22882 		 * after the IP checksum (and ULP checksums) have been
22883 		 * computed.
22884 		 *
22885 		 * NOTE : multicast_forward is set only if this packet
22886 		 * originated from ip_wput. For packets originating from
22887 		 * ip_wput_multicast, it is not set.
22888 		 */
22889 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22890 multi_loopback:
22891 			ip2dbg(("ip_wput: multicast, loop %d\n",
22892 			    conn_multicast_loop));
22893 
22894 			/*  Forget header checksum offload */
22895 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22896 
22897 			/*
22898 			 * Local loopback of multicasts?  Check the
22899 			 * ill.
22900 			 *
22901 			 * Note that the loopback function will not come
22902 			 * in through ip_rput - it will only do the
22903 			 * client fanout thus we need to do an mforward
22904 			 * as well.  The is different from the BSD
22905 			 * logic.
22906 			 */
22907 			if (ill != NULL) {
22908 				ilm_t	*ilm;
22909 
22910 				ILM_WALKER_HOLD(ill);
22911 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22912 				    ALL_ZONES);
22913 				ILM_WALKER_RELE(ill);
22914 				if (ilm != NULL) {
22915 					/*
22916 					 * Pass along the virtual output q.
22917 					 * ip_wput_local() will distribute the
22918 					 * packet to all the matching zones,
22919 					 * except the sending zone when
22920 					 * IP_MULTICAST_LOOP is false.
22921 					 */
22922 					ip_multicast_loopback(q, ill, first_mp,
22923 					    conn_multicast_loop ? 0 :
22924 					    IP_FF_NO_MCAST_LOOP, zoneid);
22925 				}
22926 			}
22927 			if (ipha->ipha_ttl == 0) {
22928 				/*
22929 				 * 0 => only to this host i.e. we are
22930 				 * done. We are also done if this was the
22931 				 * loopback interface since it is sufficient
22932 				 * to loopback one copy of a multicast packet.
22933 				 */
22934 				freemsg(first_mp);
22935 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22936 				    "ip_wput_ire_end: q %p (%S)",
22937 				    q, "loopback");
22938 				ire_refrele(ire);
22939 				if (conn_outgoing_ill != NULL)
22940 					ill_refrele(conn_outgoing_ill);
22941 				return;
22942 			}
22943 			/*
22944 			 * ILLF_MULTICAST is checked in ip_newroute
22945 			 * i.e. we don't need to check it here since
22946 			 * all IRE_CACHEs come from ip_newroute.
22947 			 * For multicast traffic, SO_DONTROUTE is interpreted
22948 			 * to mean only send the packet out the interface
22949 			 * (optionally specified with IP_MULTICAST_IF)
22950 			 * and do not forward it out additional interfaces.
22951 			 * RSVP and the rsvp daemon is an example of a
22952 			 * protocol and user level process that
22953 			 * handles it's own routing. Hence, it uses the
22954 			 * SO_DONTROUTE option to accomplish this.
22955 			 */
22956 
22957 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22958 			    ill != NULL) {
22959 				/* Unconditionally redo the checksum */
22960 				ipha->ipha_hdr_checksum = 0;
22961 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22962 
22963 				/*
22964 				 * If this needs to go out secure, we need
22965 				 * to wait till we finish the IPsec
22966 				 * processing.
22967 				 */
22968 				if (ipsec_len == 0 &&
22969 				    ip_mforward(ill, ipha, mp)) {
22970 					freemsg(first_mp);
22971 					ip1dbg(("ip_wput: mforward failed\n"));
22972 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22973 					    "ip_wput_ire_end: q %p (%S)",
22974 					    q, "mforward failed");
22975 					ire_refrele(ire);
22976 					if (conn_outgoing_ill != NULL)
22977 						ill_refrele(conn_outgoing_ill);
22978 					return;
22979 				}
22980 			}
22981 		}
22982 		max_frag = ire->ire_max_frag;
22983 		cksum += ttl_protocol;
22984 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22985 			/* No fragmentation required for this one. */
22986 			/*
22987 			 * Don't use frag_flag if packet is pre-built or source
22988 			 * routed or if multicast (since multicast packets do
22989 			 * not solicit ICMP "packet too big" messages).
22990 			 */
22991 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22992 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22993 			    !ip_source_route_included(ipha)) &&
22994 			    !CLASSD(ipha->ipha_dst))
22995 				ipha->ipha_fragment_offset_and_flags |=
22996 				    htons(ire->ire_frag_flag);
22997 
22998 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22999 				/* Complete the IP header checksum. */
23000 				cksum += ipha->ipha_ident;
23001 				cksum += (v_hlen_tos_len >> 16)+
23002 				    (v_hlen_tos_len & 0xFFFF);
23003 				cksum += ipha->ipha_fragment_offset_and_flags;
23004 				hlen = (V_HLEN & 0xF) -
23005 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23006 				if (hlen) {
23007 checksumoptions:
23008 					/*
23009 					 * Account for the IP Options in the IP
23010 					 * header checksum.
23011 					 */
23012 					up = (uint16_t *)(rptr+
23013 					    IP_SIMPLE_HDR_LENGTH);
23014 					do {
23015 						cksum += up[0];
23016 						cksum += up[1];
23017 						up += 2;
23018 					} while (--hlen);
23019 				}
23020 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23021 				cksum = ~(cksum + (cksum >> 16));
23022 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23023 			}
23024 			if (ipsec_len != 0) {
23025 				ipsec_out_process(q, first_mp, ire, ill_index);
23026 				if (!next_mp) {
23027 					ire_refrele(ire);
23028 					if (conn_outgoing_ill != NULL)
23029 						ill_refrele(conn_outgoing_ill);
23030 					return;
23031 				}
23032 				goto next;
23033 			}
23034 
23035 			/*
23036 			 * multirt_send has already been handled
23037 			 * for broadcast, but not yet for multicast
23038 			 * or IP options.
23039 			 */
23040 			if (next_mp == NULL) {
23041 				if (ire->ire_flags & RTF_MULTIRT) {
23042 					multirt_send = B_TRUE;
23043 				}
23044 			}
23045 
23046 			/*
23047 			 * In most cases, the emission loop below is
23048 			 * entered only once. Only in the case where
23049 			 * the ire holds the RTF_MULTIRT flag, do we loop
23050 			 * to process all RTF_MULTIRT ires in the bucket,
23051 			 * and send the packet through all crossed
23052 			 * RTF_MULTIRT routes.
23053 			 */
23054 			do {
23055 				if (multirt_send) {
23056 					irb_t *irb;
23057 
23058 					irb = ire->ire_bucket;
23059 					ASSERT(irb != NULL);
23060 					/*
23061 					 * We are in a multiple send case,
23062 					 * need to get the next IRE and make
23063 					 * a duplicate of the packet.
23064 					 */
23065 					IRB_REFHOLD(irb);
23066 					for (ire1 = ire->ire_next;
23067 					    ire1 != NULL;
23068 					    ire1 = ire1->ire_next) {
23069 						if (!(ire1->ire_flags &
23070 						    RTF_MULTIRT)) {
23071 							continue;
23072 						}
23073 						if (ire1->ire_addr !=
23074 						    ire->ire_addr) {
23075 							continue;
23076 						}
23077 						if (ire1->ire_marks &
23078 						    (IRE_MARK_CONDEMNED|
23079 						    IRE_MARK_HIDDEN)) {
23080 							continue;
23081 						}
23082 
23083 						/* Got one */
23084 						IRE_REFHOLD(ire1);
23085 						break;
23086 					}
23087 					IRB_REFRELE(irb);
23088 
23089 					if (ire1 != NULL) {
23090 						next_mp = copyb(mp);
23091 						if ((next_mp == NULL) ||
23092 						    ((mp->b_cont != NULL) &&
23093 						    ((next_mp->b_cont =
23094 						    dupmsg(mp->b_cont))
23095 						    == NULL))) {
23096 							freemsg(next_mp);
23097 							next_mp = NULL;
23098 							ire_refrele(ire1);
23099 							ire1 = NULL;
23100 						}
23101 					}
23102 
23103 					/*
23104 					 * Last multiroute ire; don't loop
23105 					 * anymore. The emission is over
23106 					 * and next_mp is NULL.
23107 					 */
23108 					if (ire1 == NULL) {
23109 						multirt_send = B_FALSE;
23110 					}
23111 				}
23112 
23113 				out_ill = ire_to_ill(ire);
23114 				DTRACE_PROBE4(ip4__physical__out__start,
23115 				    ill_t *, NULL,
23116 				    ill_t *, out_ill,
23117 				    ipha_t *, ipha, mblk_t *, mp);
23118 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23119 				    ipst->ips_ipv4firewall_physical_out,
23120 				    NULL, out_ill, ipha, mp, mp, ipst);
23121 				DTRACE_PROBE1(ip4__physical__out__end,
23122 				    mblk_t *, mp);
23123 				if (mp == NULL)
23124 					goto release_ire_and_ill_2;
23125 
23126 				ASSERT(ipsec_len == 0);
23127 				mp->b_prev =
23128 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23129 				DTRACE_PROBE2(ip__xmit__2,
23130 				    mblk_t *, mp, ire_t *, ire);
23131 				pktxmit_state = ip_xmit_v4(mp, ire,
23132 				    NULL, B_TRUE);
23133 				if ((pktxmit_state == SEND_FAILED) ||
23134 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23135 release_ire_and_ill_2:
23136 					if (next_mp) {
23137 						freemsg(next_mp);
23138 						ire_refrele(ire1);
23139 					}
23140 					ire_refrele(ire);
23141 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23142 					    "ip_wput_ire_end: q %p (%S)",
23143 					    q, "discard MDATA");
23144 					if (conn_outgoing_ill != NULL)
23145 						ill_refrele(conn_outgoing_ill);
23146 					return;
23147 				}
23148 
23149 				if (CLASSD(dst)) {
23150 					BUMP_MIB(out_ill->ill_ip_mib,
23151 					    ipIfStatsHCOutMcastPkts);
23152 					UPDATE_MIB(out_ill->ill_ip_mib,
23153 					    ipIfStatsHCOutMcastOctets,
23154 					    LENGTH);
23155 				} else if (ire->ire_type == IRE_BROADCAST) {
23156 					BUMP_MIB(out_ill->ill_ip_mib,
23157 					    ipIfStatsHCOutBcastPkts);
23158 				}
23159 
23160 				if (multirt_send) {
23161 					/*
23162 					 * We are in a multiple send case,
23163 					 * need to re-enter the sending loop
23164 					 * using the next ire.
23165 					 */
23166 					ire_refrele(ire);
23167 					ire = ire1;
23168 					stq = ire->ire_stq;
23169 					mp = next_mp;
23170 					next_mp = NULL;
23171 					ipha = (ipha_t *)mp->b_rptr;
23172 					ill_index = Q_TO_INDEX(stq);
23173 				}
23174 			} while (multirt_send);
23175 
23176 			if (!next_mp) {
23177 				/*
23178 				 * Last copy going out (the ultra-common
23179 				 * case).  Note that we intentionally replicate
23180 				 * the putnext rather than calling it before
23181 				 * the next_mp check in hopes of a little
23182 				 * tail-call action out of the compiler.
23183 				 */
23184 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23185 				    "ip_wput_ire_end: q %p (%S)",
23186 				    q, "last copy out(1)");
23187 				ire_refrele(ire);
23188 				if (conn_outgoing_ill != NULL)
23189 					ill_refrele(conn_outgoing_ill);
23190 				return;
23191 			}
23192 			/* More copies going out below. */
23193 		} else {
23194 			int offset;
23195 fragmentit:
23196 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23197 			/*
23198 			 * If this would generate a icmp_frag_needed message,
23199 			 * we need to handle it before we do the IPsec
23200 			 * processing. Otherwise, we need to strip the IPsec
23201 			 * headers before we send up the message to the ULPs
23202 			 * which becomes messy and difficult.
23203 			 */
23204 			if (ipsec_len != 0) {
23205 				if ((max_frag < (unsigned int)(LENGTH +
23206 				    ipsec_len)) && (offset & IPH_DF)) {
23207 					out_ill = (ill_t *)stq->q_ptr;
23208 					BUMP_MIB(out_ill->ill_ip_mib,
23209 					    ipIfStatsOutFragFails);
23210 					BUMP_MIB(out_ill->ill_ip_mib,
23211 					    ipIfStatsOutFragReqds);
23212 					ipha->ipha_hdr_checksum = 0;
23213 					ipha->ipha_hdr_checksum =
23214 					    (uint16_t)ip_csum_hdr(ipha);
23215 					icmp_frag_needed(ire->ire_stq, first_mp,
23216 					    max_frag, zoneid, ipst);
23217 					if (!next_mp) {
23218 						ire_refrele(ire);
23219 						if (conn_outgoing_ill != NULL) {
23220 							ill_refrele(
23221 							    conn_outgoing_ill);
23222 						}
23223 						return;
23224 					}
23225 				} else {
23226 					/*
23227 					 * This won't cause a icmp_frag_needed
23228 					 * message. to be generated. Send it on
23229 					 * the wire. Note that this could still
23230 					 * cause fragmentation and all we
23231 					 * do is the generation of the message
23232 					 * to the ULP if needed before IPsec.
23233 					 */
23234 					if (!next_mp) {
23235 						ipsec_out_process(q, first_mp,
23236 						    ire, ill_index);
23237 						TRACE_2(TR_FAC_IP,
23238 						    TR_IP_WPUT_IRE_END,
23239 						    "ip_wput_ire_end: q %p "
23240 						    "(%S)", q,
23241 						    "last ipsec_out_process");
23242 						ire_refrele(ire);
23243 						if (conn_outgoing_ill != NULL) {
23244 							ill_refrele(
23245 							    conn_outgoing_ill);
23246 						}
23247 						return;
23248 					}
23249 					ipsec_out_process(q, first_mp,
23250 					    ire, ill_index);
23251 				}
23252 			} else {
23253 				/*
23254 				 * Initiate IPPF processing. For
23255 				 * fragmentable packets we finish
23256 				 * all QOS packet processing before
23257 				 * calling:
23258 				 * ip_wput_ire_fragmentit->ip_wput_frag
23259 				 */
23260 
23261 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23262 					ip_process(IPP_LOCAL_OUT, &mp,
23263 					    ill_index);
23264 					if (mp == NULL) {
23265 						out_ill = (ill_t *)stq->q_ptr;
23266 						BUMP_MIB(out_ill->ill_ip_mib,
23267 						    ipIfStatsOutDiscards);
23268 						if (next_mp != NULL) {
23269 							freemsg(next_mp);
23270 							ire_refrele(ire1);
23271 						}
23272 						ire_refrele(ire);
23273 						TRACE_2(TR_FAC_IP,
23274 						    TR_IP_WPUT_IRE_END,
23275 						    "ip_wput_ire: q %p (%S)",
23276 						    q, "discard MDATA");
23277 						if (conn_outgoing_ill != NULL) {
23278 							ill_refrele(
23279 							    conn_outgoing_ill);
23280 						}
23281 						return;
23282 					}
23283 				}
23284 				if (!next_mp) {
23285 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23286 					    "ip_wput_ire_end: q %p (%S)",
23287 					    q, "last fragmentation");
23288 					ip_wput_ire_fragmentit(mp, ire,
23289 					    zoneid, ipst);
23290 					ire_refrele(ire);
23291 					if (conn_outgoing_ill != NULL)
23292 						ill_refrele(conn_outgoing_ill);
23293 					return;
23294 				}
23295 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23296 			}
23297 		}
23298 	} else {
23299 nullstq:
23300 		/* A NULL stq means the destination address is local. */
23301 		UPDATE_OB_PKT_COUNT(ire);
23302 		ire->ire_last_used_time = lbolt;
23303 		ASSERT(ire->ire_ipif != NULL);
23304 		if (!next_mp) {
23305 			/*
23306 			 * Is there an "in" and "out" for traffic local
23307 			 * to a host (loopback)?  The code in Solaris doesn't
23308 			 * explicitly draw a line in its code for in vs out,
23309 			 * so we've had to draw a line in the sand: ip_wput_ire
23310 			 * is considered to be the "output" side and
23311 			 * ip_wput_local to be the "input" side.
23312 			 */
23313 			out_ill = ire_to_ill(ire);
23314 
23315 			DTRACE_PROBE4(ip4__loopback__out__start,
23316 			    ill_t *, NULL, ill_t *, out_ill,
23317 			    ipha_t *, ipha, mblk_t *, first_mp);
23318 
23319 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23320 			    ipst->ips_ipv4firewall_loopback_out,
23321 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23322 
23323 			DTRACE_PROBE1(ip4__loopback__out_end,
23324 			    mblk_t *, first_mp);
23325 
23326 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23327 			    "ip_wput_ire_end: q %p (%S)",
23328 			    q, "local address");
23329 
23330 			if (first_mp != NULL)
23331 				ip_wput_local(q, out_ill, ipha,
23332 				    first_mp, ire, 0, ire->ire_zoneid);
23333 			ire_refrele(ire);
23334 			if (conn_outgoing_ill != NULL)
23335 				ill_refrele(conn_outgoing_ill);
23336 			return;
23337 		}
23338 
23339 		out_ill = ire_to_ill(ire);
23340 
23341 		DTRACE_PROBE4(ip4__loopback__out__start,
23342 		    ill_t *, NULL, ill_t *, out_ill,
23343 		    ipha_t *, ipha, mblk_t *, first_mp);
23344 
23345 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23346 		    ipst->ips_ipv4firewall_loopback_out,
23347 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23348 
23349 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23350 
23351 		if (first_mp != NULL)
23352 			ip_wput_local(q, out_ill, ipha,
23353 			    first_mp, ire, 0, ire->ire_zoneid);
23354 	}
23355 next:
23356 	/*
23357 	 * More copies going out to additional interfaces.
23358 	 * ire1 has already been held. We don't need the
23359 	 * "ire" anymore.
23360 	 */
23361 	ire_refrele(ire);
23362 	ire = ire1;
23363 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23364 	mp = next_mp;
23365 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23366 	ill = ire_to_ill(ire);
23367 	first_mp = mp;
23368 	if (ipsec_len != 0) {
23369 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23370 		mp = mp->b_cont;
23371 	}
23372 	dst = ire->ire_addr;
23373 	ipha = (ipha_t *)mp->b_rptr;
23374 	/*
23375 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23376 	 * Restore ipha_ident "no checksum" flag.
23377 	 */
23378 	src = orig_src;
23379 	ipha->ipha_ident = ip_hdr_included;
23380 	goto another;
23381 
23382 #undef	rptr
23383 #undef	Q_TO_INDEX
23384 }
23385 
23386 /*
23387  * Routine to allocate a message that is used to notify the ULP about MDT.
23388  * The caller may provide a pointer to the link-layer MDT capabilities,
23389  * or NULL if MDT is to be disabled on the stream.
23390  */
23391 mblk_t *
23392 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23393 {
23394 	mblk_t *mp;
23395 	ip_mdt_info_t *mdti;
23396 	ill_mdt_capab_t *idst;
23397 
23398 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23399 		DB_TYPE(mp) = M_CTL;
23400 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23401 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23402 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23403 		idst = &(mdti->mdt_capab);
23404 
23405 		/*
23406 		 * If the caller provides us with the capability, copy
23407 		 * it over into our notification message; otherwise
23408 		 * we zero out the capability portion.
23409 		 */
23410 		if (isrc != NULL)
23411 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23412 		else
23413 			bzero((caddr_t)idst, sizeof (*idst));
23414 	}
23415 	return (mp);
23416 }
23417 
23418 /*
23419  * Routine which determines whether MDT can be enabled on the destination
23420  * IRE and IPC combination, and if so, allocates and returns the MDT
23421  * notification mblk that may be used by ULP.  We also check if we need to
23422  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23423  * MDT usage in the past have been lifted.  This gets called during IP
23424  * and ULP binding.
23425  */
23426 mblk_t *
23427 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23428     ill_mdt_capab_t *mdt_cap)
23429 {
23430 	mblk_t *mp;
23431 	boolean_t rc = B_FALSE;
23432 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23433 
23434 	ASSERT(dst_ire != NULL);
23435 	ASSERT(connp != NULL);
23436 	ASSERT(mdt_cap != NULL);
23437 
23438 	/*
23439 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23440 	 * Multidata, which is handled in tcp_multisend().  This
23441 	 * is the reason why we do all these checks here, to ensure
23442 	 * that we don't enable Multidata for the cases which we
23443 	 * can't handle at the moment.
23444 	 */
23445 	do {
23446 		/* Only do TCP at the moment */
23447 		if (connp->conn_ulp != IPPROTO_TCP)
23448 			break;
23449 
23450 		/*
23451 		 * IPsec outbound policy present?  Note that we get here
23452 		 * after calling ipsec_conn_cache_policy() where the global
23453 		 * policy checking is performed.  conn_latch will be
23454 		 * non-NULL as long as there's a policy defined,
23455 		 * i.e. conn_out_enforce_policy may be NULL in such case
23456 		 * when the connection is non-secure, and hence we check
23457 		 * further if the latch refers to an outbound policy.
23458 		 */
23459 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23460 			break;
23461 
23462 		/* CGTP (multiroute) is enabled? */
23463 		if (dst_ire->ire_flags & RTF_MULTIRT)
23464 			break;
23465 
23466 		/* Outbound IPQoS enabled? */
23467 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23468 			/*
23469 			 * In this case, we disable MDT for this and all
23470 			 * future connections going over the interface.
23471 			 */
23472 			mdt_cap->ill_mdt_on = 0;
23473 			break;
23474 		}
23475 
23476 		/* socket option(s) present? */
23477 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23478 			break;
23479 
23480 		rc = B_TRUE;
23481 	/* CONSTCOND */
23482 	} while (0);
23483 
23484 	/* Remember the result */
23485 	connp->conn_mdt_ok = rc;
23486 
23487 	if (!rc)
23488 		return (NULL);
23489 	else if (!mdt_cap->ill_mdt_on) {
23490 		/*
23491 		 * If MDT has been previously turned off in the past, and we
23492 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23493 		 * then enable it for this interface.
23494 		 */
23495 		mdt_cap->ill_mdt_on = 1;
23496 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23497 		    "interface %s\n", ill_name));
23498 	}
23499 
23500 	/* Allocate the MDT info mblk */
23501 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23502 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23503 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23504 		return (NULL);
23505 	}
23506 	return (mp);
23507 }
23508 
23509 /*
23510  * Routine to allocate a message that is used to notify the ULP about LSO.
23511  * The caller may provide a pointer to the link-layer LSO capabilities,
23512  * or NULL if LSO is to be disabled on the stream.
23513  */
23514 mblk_t *
23515 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23516 {
23517 	mblk_t *mp;
23518 	ip_lso_info_t *lsoi;
23519 	ill_lso_capab_t *idst;
23520 
23521 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23522 		DB_TYPE(mp) = M_CTL;
23523 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23524 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23525 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23526 		idst = &(lsoi->lso_capab);
23527 
23528 		/*
23529 		 * If the caller provides us with the capability, copy
23530 		 * it over into our notification message; otherwise
23531 		 * we zero out the capability portion.
23532 		 */
23533 		if (isrc != NULL)
23534 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23535 		else
23536 			bzero((caddr_t)idst, sizeof (*idst));
23537 	}
23538 	return (mp);
23539 }
23540 
23541 /*
23542  * Routine which determines whether LSO can be enabled on the destination
23543  * IRE and IPC combination, and if so, allocates and returns the LSO
23544  * notification mblk that may be used by ULP.  We also check if we need to
23545  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23546  * LSO usage in the past have been lifted.  This gets called during IP
23547  * and ULP binding.
23548  */
23549 mblk_t *
23550 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23551     ill_lso_capab_t *lso_cap)
23552 {
23553 	mblk_t *mp;
23554 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23555 
23556 	ASSERT(dst_ire != NULL);
23557 	ASSERT(connp != NULL);
23558 	ASSERT(lso_cap != NULL);
23559 
23560 	connp->conn_lso_ok = B_TRUE;
23561 
23562 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23563 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23564 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23565 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23566 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23567 		connp->conn_lso_ok = B_FALSE;
23568 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23569 			/*
23570 			 * Disable LSO for this and all future connections going
23571 			 * over the interface.
23572 			 */
23573 			lso_cap->ill_lso_on = 0;
23574 		}
23575 	}
23576 
23577 	if (!connp->conn_lso_ok)
23578 		return (NULL);
23579 	else if (!lso_cap->ill_lso_on) {
23580 		/*
23581 		 * If LSO has been previously turned off in the past, and we
23582 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23583 		 * then enable it for this interface.
23584 		 */
23585 		lso_cap->ill_lso_on = 1;
23586 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23587 		    ill_name));
23588 	}
23589 
23590 	/* Allocate the LSO info mblk */
23591 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23592 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23593 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23594 
23595 	return (mp);
23596 }
23597 
23598 /*
23599  * Create destination address attribute, and fill it with the physical
23600  * destination address and SAP taken from the template DL_UNITDATA_REQ
23601  * message block.
23602  */
23603 boolean_t
23604 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23605 {
23606 	dl_unitdata_req_t *dlurp;
23607 	pattr_t *pa;
23608 	pattrinfo_t pa_info;
23609 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23610 	uint_t das_len, das_off;
23611 
23612 	ASSERT(dlmp != NULL);
23613 
23614 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23615 	das_len = dlurp->dl_dest_addr_length;
23616 	das_off = dlurp->dl_dest_addr_offset;
23617 
23618 	pa_info.type = PATTR_DSTADDRSAP;
23619 	pa_info.len = sizeof (**das) + das_len - 1;
23620 
23621 	/* create and associate the attribute */
23622 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23623 	if (pa != NULL) {
23624 		ASSERT(*das != NULL);
23625 		(*das)->addr_is_group = 0;
23626 		(*das)->addr_len = (uint8_t)das_len;
23627 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23628 	}
23629 
23630 	return (pa != NULL);
23631 }
23632 
23633 /*
23634  * Create hardware checksum attribute and fill it with the values passed.
23635  */
23636 boolean_t
23637 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23638     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23639 {
23640 	pattr_t *pa;
23641 	pattrinfo_t pa_info;
23642 
23643 	ASSERT(mmd != NULL);
23644 
23645 	pa_info.type = PATTR_HCKSUM;
23646 	pa_info.len = sizeof (pattr_hcksum_t);
23647 
23648 	/* create and associate the attribute */
23649 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23650 	if (pa != NULL) {
23651 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23652 
23653 		hck->hcksum_start_offset = start_offset;
23654 		hck->hcksum_stuff_offset = stuff_offset;
23655 		hck->hcksum_end_offset = end_offset;
23656 		hck->hcksum_flags = flags;
23657 	}
23658 	return (pa != NULL);
23659 }
23660 
23661 /*
23662  * Create zerocopy attribute and fill it with the specified flags
23663  */
23664 boolean_t
23665 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23666 {
23667 	pattr_t *pa;
23668 	pattrinfo_t pa_info;
23669 
23670 	ASSERT(mmd != NULL);
23671 	pa_info.type = PATTR_ZCOPY;
23672 	pa_info.len = sizeof (pattr_zcopy_t);
23673 
23674 	/* create and associate the attribute */
23675 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23676 	if (pa != NULL) {
23677 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23678 
23679 		zcopy->zcopy_flags = flags;
23680 	}
23681 	return (pa != NULL);
23682 }
23683 
23684 /*
23685  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23686  * block chain. We could rewrite to handle arbitrary message block chains but
23687  * that would make the code complicated and slow. Right now there three
23688  * restrictions:
23689  *
23690  *   1. The first message block must contain the complete IP header and
23691  *	at least 1 byte of payload data.
23692  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23693  *	so that we can use a single Multidata message.
23694  *   3. No frag must be distributed over two or more message blocks so
23695  *	that we don't need more than two packet descriptors per frag.
23696  *
23697  * The above restrictions allow us to support userland applications (which
23698  * will send down a single message block) and NFS over UDP (which will
23699  * send down a chain of at most three message blocks).
23700  *
23701  * We also don't use MDT for payloads with less than or equal to
23702  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23703  */
23704 boolean_t
23705 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23706 {
23707 	int	blocks;
23708 	ssize_t	total, missing, size;
23709 
23710 	ASSERT(mp != NULL);
23711 	ASSERT(hdr_len > 0);
23712 
23713 	size = MBLKL(mp) - hdr_len;
23714 	if (size <= 0)
23715 		return (B_FALSE);
23716 
23717 	/* The first mblk contains the header and some payload. */
23718 	blocks = 1;
23719 	total = size;
23720 	size %= len;
23721 	missing = (size == 0) ? 0 : (len - size);
23722 	mp = mp->b_cont;
23723 
23724 	while (mp != NULL) {
23725 		/*
23726 		 * Give up if we encounter a zero length message block.
23727 		 * In practice, this should rarely happen and therefore
23728 		 * not worth the trouble of freeing and re-linking the
23729 		 * mblk from the chain to handle such case.
23730 		 */
23731 		if ((size = MBLKL(mp)) == 0)
23732 			return (B_FALSE);
23733 
23734 		/* Too many payload buffers for a single Multidata message? */
23735 		if (++blocks > MULTIDATA_MAX_PBUFS)
23736 			return (B_FALSE);
23737 
23738 		total += size;
23739 		/* Is a frag distributed over two or more message blocks? */
23740 		if (missing > size)
23741 			return (B_FALSE);
23742 		size -= missing;
23743 
23744 		size %= len;
23745 		missing = (size == 0) ? 0 : (len - size);
23746 
23747 		mp = mp->b_cont;
23748 	}
23749 
23750 	return (total > ip_wput_frag_mdt_min);
23751 }
23752 
23753 /*
23754  * Outbound IPv4 fragmentation routine using MDT.
23755  */
23756 static void
23757 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23758     uint32_t frag_flag, int offset)
23759 {
23760 	ipha_t		*ipha_orig;
23761 	int		i1, ip_data_end;
23762 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23763 	mblk_t		*hdr_mp, *md_mp = NULL;
23764 	unsigned char	*hdr_ptr, *pld_ptr;
23765 	multidata_t	*mmd;
23766 	ip_pdescinfo_t	pdi;
23767 	ill_t		*ill;
23768 	ip_stack_t	*ipst = ire->ire_ipst;
23769 
23770 	ASSERT(DB_TYPE(mp) == M_DATA);
23771 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23772 
23773 	ill = ire_to_ill(ire);
23774 	ASSERT(ill != NULL);
23775 
23776 	ipha_orig = (ipha_t *)mp->b_rptr;
23777 	mp->b_rptr += sizeof (ipha_t);
23778 
23779 	/* Calculate how many packets we will send out */
23780 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23781 	pkts = (i1 + len - 1) / len;
23782 	ASSERT(pkts > 1);
23783 
23784 	/* Allocate a message block which will hold all the IP Headers. */
23785 	wroff = ipst->ips_ip_wroff_extra;
23786 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23787 
23788 	i1 = pkts * hdr_chunk_len;
23789 	/*
23790 	 * Create the header buffer, Multidata and destination address
23791 	 * and SAP attribute that should be associated with it.
23792 	 */
23793 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23794 	    ((hdr_mp->b_wptr += i1),
23795 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23796 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23797 		freemsg(mp);
23798 		if (md_mp == NULL) {
23799 			freemsg(hdr_mp);
23800 		} else {
23801 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23802 			freemsg(md_mp);
23803 		}
23804 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23805 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23806 		return;
23807 	}
23808 	IP_STAT(ipst, ip_frag_mdt_allocd);
23809 
23810 	/*
23811 	 * Add a payload buffer to the Multidata; this operation must not
23812 	 * fail, or otherwise our logic in this routine is broken.  There
23813 	 * is no memory allocation done by the routine, so any returned
23814 	 * failure simply tells us that we've done something wrong.
23815 	 *
23816 	 * A failure tells us that either we're adding the same payload
23817 	 * buffer more than once, or we're trying to add more buffers than
23818 	 * allowed.  None of the above cases should happen, and we panic
23819 	 * because either there's horrible heap corruption, and/or
23820 	 * programming mistake.
23821 	 */
23822 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23823 		goto pbuf_panic;
23824 
23825 	hdr_ptr = hdr_mp->b_rptr;
23826 	pld_ptr = mp->b_rptr;
23827 
23828 	/* Establish the ending byte offset, based on the starting offset. */
23829 	offset <<= 3;
23830 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23831 	    IP_SIMPLE_HDR_LENGTH;
23832 
23833 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23834 
23835 	while (pld_ptr < mp->b_wptr) {
23836 		ipha_t		*ipha;
23837 		uint16_t	offset_and_flags;
23838 		uint16_t	ip_len;
23839 		int		error;
23840 
23841 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23842 		ipha = (ipha_t *)(hdr_ptr + wroff);
23843 		ASSERT(OK_32PTR(ipha));
23844 		*ipha = *ipha_orig;
23845 
23846 		if (ip_data_end - offset > len) {
23847 			offset_and_flags = IPH_MF;
23848 		} else {
23849 			/*
23850 			 * Last frag. Set len to the length of this last piece.
23851 			 */
23852 			len = ip_data_end - offset;
23853 			/* A frag of a frag might have IPH_MF non-zero */
23854 			offset_and_flags =
23855 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23856 			    IPH_MF;
23857 		}
23858 		offset_and_flags |= (uint16_t)(offset >> 3);
23859 		offset_and_flags |= (uint16_t)frag_flag;
23860 		/* Store the offset and flags in the IP header. */
23861 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23862 
23863 		/* Store the length in the IP header. */
23864 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23865 		ipha->ipha_length = htons(ip_len);
23866 
23867 		/*
23868 		 * Set the IP header checksum.  Note that mp is just
23869 		 * the header, so this is easy to pass to ip_csum.
23870 		 */
23871 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23872 
23873 		/*
23874 		 * Record offset and size of header and data of the next packet
23875 		 * in the multidata message.
23876 		 */
23877 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23878 		PDESC_PLD_INIT(&pdi);
23879 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23880 		ASSERT(i1 > 0);
23881 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23882 		if (i1 == len) {
23883 			pld_ptr += len;
23884 		} else {
23885 			i1 = len - i1;
23886 			mp = mp->b_cont;
23887 			ASSERT(mp != NULL);
23888 			ASSERT(MBLKL(mp) >= i1);
23889 			/*
23890 			 * Attach the next payload message block to the
23891 			 * multidata message.
23892 			 */
23893 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23894 				goto pbuf_panic;
23895 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23896 			pld_ptr = mp->b_rptr + i1;
23897 		}
23898 
23899 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23900 		    KM_NOSLEEP)) == NULL) {
23901 			/*
23902 			 * Any failure other than ENOMEM indicates that we
23903 			 * have passed in invalid pdesc info or parameters
23904 			 * to mmd_addpdesc, which must not happen.
23905 			 *
23906 			 * EINVAL is a result of failure on boundary checks
23907 			 * against the pdesc info contents.  It should not
23908 			 * happen, and we panic because either there's
23909 			 * horrible heap corruption, and/or programming
23910 			 * mistake.
23911 			 */
23912 			if (error != ENOMEM) {
23913 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23914 				    "pdesc logic error detected for "
23915 				    "mmd %p pinfo %p (%d)\n",
23916 				    (void *)mmd, (void *)&pdi, error);
23917 				/* NOTREACHED */
23918 			}
23919 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23920 			/* Free unattached payload message blocks as well */
23921 			md_mp->b_cont = mp->b_cont;
23922 			goto free_mmd;
23923 		}
23924 
23925 		/* Advance fragment offset. */
23926 		offset += len;
23927 
23928 		/* Advance to location for next header in the buffer. */
23929 		hdr_ptr += hdr_chunk_len;
23930 
23931 		/* Did we reach the next payload message block? */
23932 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23933 			mp = mp->b_cont;
23934 			/*
23935 			 * Attach the next message block with payload
23936 			 * data to the multidata message.
23937 			 */
23938 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23939 				goto pbuf_panic;
23940 			pld_ptr = mp->b_rptr;
23941 		}
23942 	}
23943 
23944 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23945 	ASSERT(mp->b_wptr == pld_ptr);
23946 
23947 	/* Update IP statistics */
23948 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23949 
23950 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23951 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23952 
23953 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23954 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23955 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23956 
23957 	if (pkt_type == OB_PKT) {
23958 		ire->ire_ob_pkt_count += pkts;
23959 		if (ire->ire_ipif != NULL)
23960 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23961 	} else {
23962 		/* The type is IB_PKT in the forwarding path. */
23963 		ire->ire_ib_pkt_count += pkts;
23964 		ASSERT(!IRE_IS_LOCAL(ire));
23965 		if (ire->ire_type & IRE_BROADCAST) {
23966 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23967 		} else {
23968 			UPDATE_MIB(ill->ill_ip_mib,
23969 			    ipIfStatsHCOutForwDatagrams, pkts);
23970 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23971 		}
23972 	}
23973 	ire->ire_last_used_time = lbolt;
23974 	/* Send it down */
23975 	putnext(ire->ire_stq, md_mp);
23976 	return;
23977 
23978 pbuf_panic:
23979 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23980 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23981 	    pbuf_idx);
23982 	/* NOTREACHED */
23983 }
23984 
23985 /*
23986  * Outbound IP fragmentation routine.
23987  *
23988  * NOTE : This routine does not ire_refrele the ire that is passed in
23989  * as the argument.
23990  */
23991 static void
23992 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23993     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23994 {
23995 	int		i1;
23996 	mblk_t		*ll_hdr_mp;
23997 	int 		ll_hdr_len;
23998 	int		hdr_len;
23999 	mblk_t		*hdr_mp;
24000 	ipha_t		*ipha;
24001 	int		ip_data_end;
24002 	int		len;
24003 	mblk_t		*mp = mp_orig, *mp1;
24004 	int		offset;
24005 	queue_t		*q;
24006 	uint32_t	v_hlen_tos_len;
24007 	mblk_t		*first_mp;
24008 	boolean_t	mctl_present;
24009 	ill_t		*ill;
24010 	ill_t		*out_ill;
24011 	mblk_t		*xmit_mp;
24012 	mblk_t		*carve_mp;
24013 	ire_t		*ire1 = NULL;
24014 	ire_t		*save_ire = NULL;
24015 	mblk_t  	*next_mp = NULL;
24016 	boolean_t	last_frag = B_FALSE;
24017 	boolean_t	multirt_send = B_FALSE;
24018 	ire_t		*first_ire = NULL;
24019 	irb_t		*irb = NULL;
24020 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24021 
24022 	ill = ire_to_ill(ire);
24023 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24024 
24025 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24026 
24027 	if (max_frag == 0) {
24028 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24029 		    " -  dropping packet\n"));
24030 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24031 		freemsg(mp);
24032 		return;
24033 	}
24034 
24035 	/*
24036 	 * IPsec does not allow hw accelerated packets to be fragmented
24037 	 * This check is made in ip_wput_ipsec_out prior to coming here
24038 	 * via ip_wput_ire_fragmentit.
24039 	 *
24040 	 * If at this point we have an ire whose ARP request has not
24041 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24042 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24043 	 * This packet and all fragmentable packets for this ire will
24044 	 * continue to get dropped while ire_nce->nce_state remains in
24045 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24046 	 * ND_REACHABLE, all subsquent large packets for this ire will
24047 	 * get fragemented and sent out by this function.
24048 	 */
24049 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24050 		/* If nce_state is ND_INITIAL, trigger ARP query */
24051 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24052 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24053 		    " -  dropping packet\n"));
24054 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24055 		freemsg(mp);
24056 		return;
24057 	}
24058 
24059 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24060 	    "ip_wput_frag_start:");
24061 
24062 	if (mp->b_datap->db_type == M_CTL) {
24063 		first_mp = mp;
24064 		mp_orig = mp = mp->b_cont;
24065 		mctl_present = B_TRUE;
24066 	} else {
24067 		first_mp = mp;
24068 		mctl_present = B_FALSE;
24069 	}
24070 
24071 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24072 	ipha = (ipha_t *)mp->b_rptr;
24073 
24074 	/*
24075 	 * If the Don't Fragment flag is on, generate an ICMP destination
24076 	 * unreachable, fragmentation needed.
24077 	 */
24078 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24079 	if (offset & IPH_DF) {
24080 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24081 		if (is_system_labeled()) {
24082 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24083 			    ire->ire_max_frag - max_frag, AF_INET);
24084 		}
24085 		/*
24086 		 * Need to compute hdr checksum if called from ip_wput_ire.
24087 		 * Note that ip_rput_forward verifies the checksum before
24088 		 * calling this routine so in that case this is a noop.
24089 		 */
24090 		ipha->ipha_hdr_checksum = 0;
24091 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24092 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24093 		    ipst);
24094 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24095 		    "ip_wput_frag_end:(%S)",
24096 		    "don't fragment");
24097 		return;
24098 	}
24099 	/*
24100 	 * Labeled systems adjust max_frag if they add a label
24101 	 * to send the correct path mtu.  We need the real mtu since we
24102 	 * are fragmenting the packet after label adjustment.
24103 	 */
24104 	if (is_system_labeled())
24105 		max_frag = ire->ire_max_frag;
24106 	if (mctl_present)
24107 		freeb(first_mp);
24108 	/*
24109 	 * Establish the starting offset.  May not be zero if we are fragging
24110 	 * a fragment that is being forwarded.
24111 	 */
24112 	offset = offset & IPH_OFFSET;
24113 
24114 	/* TODO why is this test needed? */
24115 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24116 	if (((max_frag - LENGTH) & ~7) < 8) {
24117 		/* TODO: notify ulp somehow */
24118 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24119 		freemsg(mp);
24120 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24121 		    "ip_wput_frag_end:(%S)",
24122 		    "len < 8");
24123 		return;
24124 	}
24125 
24126 	hdr_len = (V_HLEN & 0xF) << 2;
24127 
24128 	ipha->ipha_hdr_checksum = 0;
24129 
24130 	/*
24131 	 * Establish the number of bytes maximum per frag, after putting
24132 	 * in the header.
24133 	 */
24134 	len = (max_frag - hdr_len) & ~7;
24135 
24136 	/* Check if we can use MDT to send out the frags. */
24137 	ASSERT(!IRE_IS_LOCAL(ire));
24138 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24139 	    ipst->ips_ip_multidata_outbound &&
24140 	    !(ire->ire_flags & RTF_MULTIRT) &&
24141 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24142 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24143 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24144 		ASSERT(ill->ill_mdt_capab != NULL);
24145 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24146 			/*
24147 			 * If MDT has been previously turned off in the past,
24148 			 * and we currently can do MDT (due to IPQoS policy
24149 			 * removal, etc.) then enable it for this interface.
24150 			 */
24151 			ill->ill_mdt_capab->ill_mdt_on = 1;
24152 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24153 			    ill->ill_name));
24154 		}
24155 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24156 		    offset);
24157 		return;
24158 	}
24159 
24160 	/* Get a copy of the header for the trailing frags */
24161 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24162 	if (!hdr_mp) {
24163 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24164 		freemsg(mp);
24165 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24166 		    "ip_wput_frag_end:(%S)",
24167 		    "couldn't copy hdr");
24168 		return;
24169 	}
24170 	if (DB_CRED(mp) != NULL)
24171 		mblk_setcred(hdr_mp, DB_CRED(mp));
24172 
24173 	/* Store the starting offset, with the MoreFrags flag. */
24174 	i1 = offset | IPH_MF | frag_flag;
24175 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24176 
24177 	/* Establish the ending byte offset, based on the starting offset. */
24178 	offset <<= 3;
24179 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24180 
24181 	/* Store the length of the first fragment in the IP header. */
24182 	i1 = len + hdr_len;
24183 	ASSERT(i1 <= IP_MAXPACKET);
24184 	ipha->ipha_length = htons((uint16_t)i1);
24185 
24186 	/*
24187 	 * Compute the IP header checksum for the first frag.  We have to
24188 	 * watch out that we stop at the end of the header.
24189 	 */
24190 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24191 
24192 	/*
24193 	 * Now carve off the first frag.  Note that this will include the
24194 	 * original IP header.
24195 	 */
24196 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24197 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24198 		freeb(hdr_mp);
24199 		freemsg(mp_orig);
24200 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24201 		    "ip_wput_frag_end:(%S)",
24202 		    "couldn't carve first");
24203 		return;
24204 	}
24205 
24206 	/*
24207 	 * Multirouting case. Each fragment is replicated
24208 	 * via all non-condemned RTF_MULTIRT routes
24209 	 * currently resolved.
24210 	 * We ensure that first_ire is the first RTF_MULTIRT
24211 	 * ire in the bucket.
24212 	 */
24213 	if (ire->ire_flags & RTF_MULTIRT) {
24214 		irb = ire->ire_bucket;
24215 		ASSERT(irb != NULL);
24216 
24217 		multirt_send = B_TRUE;
24218 
24219 		/* Make sure we do not omit any multiroute ire. */
24220 		IRB_REFHOLD(irb);
24221 		for (first_ire = irb->irb_ire;
24222 		    first_ire != NULL;
24223 		    first_ire = first_ire->ire_next) {
24224 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24225 			    (first_ire->ire_addr == ire->ire_addr) &&
24226 			    !(first_ire->ire_marks &
24227 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24228 				break;
24229 			}
24230 		}
24231 
24232 		if (first_ire != NULL) {
24233 			if (first_ire != ire) {
24234 				IRE_REFHOLD(first_ire);
24235 				/*
24236 				 * Do not release the ire passed in
24237 				 * as the argument.
24238 				 */
24239 				ire = first_ire;
24240 			} else {
24241 				first_ire = NULL;
24242 			}
24243 		}
24244 		IRB_REFRELE(irb);
24245 
24246 		/*
24247 		 * Save the first ire; we will need to restore it
24248 		 * for the trailing frags.
24249 		 * We REFHOLD save_ire, as each iterated ire will be
24250 		 * REFRELEd.
24251 		 */
24252 		save_ire = ire;
24253 		IRE_REFHOLD(save_ire);
24254 	}
24255 
24256 	/*
24257 	 * First fragment emission loop.
24258 	 * In most cases, the emission loop below is entered only
24259 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24260 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24261 	 * bucket, and send the fragment through all crossed
24262 	 * RTF_MULTIRT routes.
24263 	 */
24264 	do {
24265 		if (ire->ire_flags & RTF_MULTIRT) {
24266 			/*
24267 			 * We are in a multiple send case, need to get
24268 			 * the next ire and make a copy of the packet.
24269 			 * ire1 holds here the next ire to process in the
24270 			 * bucket. If multirouting is expected,
24271 			 * any non-RTF_MULTIRT ire that has the
24272 			 * right destination address is ignored.
24273 			 *
24274 			 * We have to take into account the MTU of
24275 			 * each walked ire. max_frag is set by the
24276 			 * the caller and generally refers to
24277 			 * the primary ire entry. Here we ensure that
24278 			 * no route with a lower MTU will be used, as
24279 			 * fragments are carved once for all ires,
24280 			 * then replicated.
24281 			 */
24282 			ASSERT(irb != NULL);
24283 			IRB_REFHOLD(irb);
24284 			for (ire1 = ire->ire_next;
24285 			    ire1 != NULL;
24286 			    ire1 = ire1->ire_next) {
24287 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24288 					continue;
24289 				if (ire1->ire_addr != ire->ire_addr)
24290 					continue;
24291 				if (ire1->ire_marks &
24292 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24293 					continue;
24294 				/*
24295 				 * Ensure we do not exceed the MTU
24296 				 * of the next route.
24297 				 */
24298 				if (ire1->ire_max_frag < max_frag) {
24299 					ip_multirt_bad_mtu(ire1, max_frag);
24300 					continue;
24301 				}
24302 
24303 				/* Got one. */
24304 				IRE_REFHOLD(ire1);
24305 				break;
24306 			}
24307 			IRB_REFRELE(irb);
24308 
24309 			if (ire1 != NULL) {
24310 				next_mp = copyb(mp);
24311 				if ((next_mp == NULL) ||
24312 				    ((mp->b_cont != NULL) &&
24313 				    ((next_mp->b_cont =
24314 				    dupmsg(mp->b_cont)) == NULL))) {
24315 					freemsg(next_mp);
24316 					next_mp = NULL;
24317 					ire_refrele(ire1);
24318 					ire1 = NULL;
24319 				}
24320 			}
24321 
24322 			/* Last multiroute ire; don't loop anymore. */
24323 			if (ire1 == NULL) {
24324 				multirt_send = B_FALSE;
24325 			}
24326 		}
24327 
24328 		ll_hdr_len = 0;
24329 		LOCK_IRE_FP_MP(ire);
24330 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24331 		if (ll_hdr_mp != NULL) {
24332 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24333 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24334 		} else {
24335 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24336 		}
24337 
24338 		/* If there is a transmit header, get a copy for this frag. */
24339 		/*
24340 		 * TODO: should check db_ref before calling ip_carve_mp since
24341 		 * it might give us a dup.
24342 		 */
24343 		if (!ll_hdr_mp) {
24344 			/* No xmit header. */
24345 			xmit_mp = mp;
24346 
24347 		/* We have a link-layer header that can fit in our mblk. */
24348 		} else if (mp->b_datap->db_ref == 1 &&
24349 		    ll_hdr_len != 0 &&
24350 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24351 			/* M_DATA fastpath */
24352 			mp->b_rptr -= ll_hdr_len;
24353 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24354 			xmit_mp = mp;
24355 
24356 		/* Corner case if copyb has failed */
24357 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24358 			UNLOCK_IRE_FP_MP(ire);
24359 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24360 			freeb(hdr_mp);
24361 			freemsg(mp);
24362 			freemsg(mp_orig);
24363 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24364 			    "ip_wput_frag_end:(%S)",
24365 			    "discard");
24366 
24367 			if (multirt_send) {
24368 				ASSERT(ire1);
24369 				ASSERT(next_mp);
24370 
24371 				freemsg(next_mp);
24372 				ire_refrele(ire1);
24373 			}
24374 			if (save_ire != NULL)
24375 				IRE_REFRELE(save_ire);
24376 
24377 			if (first_ire != NULL)
24378 				ire_refrele(first_ire);
24379 			return;
24380 
24381 		/*
24382 		 * Case of res_mp OR the fastpath mp can't fit
24383 		 * in the mblk
24384 		 */
24385 		} else {
24386 			xmit_mp->b_cont = mp;
24387 			if (DB_CRED(mp) != NULL)
24388 				mblk_setcred(xmit_mp, DB_CRED(mp));
24389 			/*
24390 			 * Get priority marking, if any.
24391 			 * We propagate the CoS marking from the
24392 			 * original packet that went to QoS processing
24393 			 * in ip_wput_ire to the newly carved mp.
24394 			 */
24395 			if (DB_TYPE(xmit_mp) == M_DATA)
24396 				xmit_mp->b_band = mp->b_band;
24397 		}
24398 		UNLOCK_IRE_FP_MP(ire);
24399 
24400 		q = ire->ire_stq;
24401 		out_ill = (ill_t *)q->q_ptr;
24402 
24403 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24404 
24405 		DTRACE_PROBE4(ip4__physical__out__start,
24406 		    ill_t *, NULL, ill_t *, out_ill,
24407 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24408 
24409 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24410 		    ipst->ips_ipv4firewall_physical_out,
24411 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24412 
24413 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24414 
24415 		if (xmit_mp != NULL) {
24416 			putnext(q, xmit_mp);
24417 
24418 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24419 			UPDATE_MIB(out_ill->ill_ip_mib,
24420 			    ipIfStatsHCOutOctets, i1);
24421 
24422 			if (pkt_type != OB_PKT) {
24423 				/*
24424 				 * Update the packet count and MIB stats
24425 				 * of trailing RTF_MULTIRT ires.
24426 				 */
24427 				UPDATE_OB_PKT_COUNT(ire);
24428 				BUMP_MIB(out_ill->ill_ip_mib,
24429 				    ipIfStatsOutFragReqds);
24430 			}
24431 		}
24432 
24433 		if (multirt_send) {
24434 			/*
24435 			 * We are in a multiple send case; look for
24436 			 * the next ire and re-enter the loop.
24437 			 */
24438 			ASSERT(ire1);
24439 			ASSERT(next_mp);
24440 			/* REFRELE the current ire before looping */
24441 			ire_refrele(ire);
24442 			ire = ire1;
24443 			ire1 = NULL;
24444 			mp = next_mp;
24445 			next_mp = NULL;
24446 		}
24447 	} while (multirt_send);
24448 
24449 	ASSERT(ire1 == NULL);
24450 
24451 	/* Restore the original ire; we need it for the trailing frags */
24452 	if (save_ire != NULL) {
24453 		/* REFRELE the last iterated ire */
24454 		ire_refrele(ire);
24455 		/* save_ire has been REFHOLDed */
24456 		ire = save_ire;
24457 		save_ire = NULL;
24458 		q = ire->ire_stq;
24459 	}
24460 
24461 	if (pkt_type == OB_PKT) {
24462 		UPDATE_OB_PKT_COUNT(ire);
24463 	} else {
24464 		out_ill = (ill_t *)q->q_ptr;
24465 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24466 		UPDATE_IB_PKT_COUNT(ire);
24467 	}
24468 
24469 	/* Advance the offset to the second frag starting point. */
24470 	offset += len;
24471 	/*
24472 	 * Update hdr_len from the copied header - there might be less options
24473 	 * in the later fragments.
24474 	 */
24475 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24476 	/* Loop until done. */
24477 	for (;;) {
24478 		uint16_t	offset_and_flags;
24479 		uint16_t	ip_len;
24480 
24481 		if (ip_data_end - offset > len) {
24482 			/*
24483 			 * Carve off the appropriate amount from the original
24484 			 * datagram.
24485 			 */
24486 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24487 				mp = NULL;
24488 				break;
24489 			}
24490 			/*
24491 			 * More frags after this one.  Get another copy
24492 			 * of the header.
24493 			 */
24494 			if (carve_mp->b_datap->db_ref == 1 &&
24495 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24496 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24497 				/* Inline IP header */
24498 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24499 				    hdr_mp->b_rptr;
24500 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24501 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24502 				mp = carve_mp;
24503 			} else {
24504 				if (!(mp = copyb(hdr_mp))) {
24505 					freemsg(carve_mp);
24506 					break;
24507 				}
24508 				/* Get priority marking, if any. */
24509 				mp->b_band = carve_mp->b_band;
24510 				mp->b_cont = carve_mp;
24511 			}
24512 			ipha = (ipha_t *)mp->b_rptr;
24513 			offset_and_flags = IPH_MF;
24514 		} else {
24515 			/*
24516 			 * Last frag.  Consume the header. Set len to
24517 			 * the length of this last piece.
24518 			 */
24519 			len = ip_data_end - offset;
24520 
24521 			/*
24522 			 * Carve off the appropriate amount from the original
24523 			 * datagram.
24524 			 */
24525 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24526 				mp = NULL;
24527 				break;
24528 			}
24529 			if (carve_mp->b_datap->db_ref == 1 &&
24530 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24531 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24532 				/* Inline IP header */
24533 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24534 				    hdr_mp->b_rptr;
24535 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24536 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24537 				mp = carve_mp;
24538 				freeb(hdr_mp);
24539 				hdr_mp = mp;
24540 			} else {
24541 				mp = hdr_mp;
24542 				/* Get priority marking, if any. */
24543 				mp->b_band = carve_mp->b_band;
24544 				mp->b_cont = carve_mp;
24545 			}
24546 			ipha = (ipha_t *)mp->b_rptr;
24547 			/* A frag of a frag might have IPH_MF non-zero */
24548 			offset_and_flags =
24549 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24550 			    IPH_MF;
24551 		}
24552 		offset_and_flags |= (uint16_t)(offset >> 3);
24553 		offset_and_flags |= (uint16_t)frag_flag;
24554 		/* Store the offset and flags in the IP header. */
24555 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24556 
24557 		/* Store the length in the IP header. */
24558 		ip_len = (uint16_t)(len + hdr_len);
24559 		ipha->ipha_length = htons(ip_len);
24560 
24561 		/*
24562 		 * Set the IP header checksum.	Note that mp is just
24563 		 * the header, so this is easy to pass to ip_csum.
24564 		 */
24565 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24566 
24567 		/* Attach a transmit header, if any, and ship it. */
24568 		if (pkt_type == OB_PKT) {
24569 			UPDATE_OB_PKT_COUNT(ire);
24570 		} else {
24571 			out_ill = (ill_t *)q->q_ptr;
24572 			BUMP_MIB(out_ill->ill_ip_mib,
24573 			    ipIfStatsHCOutForwDatagrams);
24574 			UPDATE_IB_PKT_COUNT(ire);
24575 		}
24576 
24577 		if (ire->ire_flags & RTF_MULTIRT) {
24578 			irb = ire->ire_bucket;
24579 			ASSERT(irb != NULL);
24580 
24581 			multirt_send = B_TRUE;
24582 
24583 			/*
24584 			 * Save the original ire; we will need to restore it
24585 			 * for the tailing frags.
24586 			 */
24587 			save_ire = ire;
24588 			IRE_REFHOLD(save_ire);
24589 		}
24590 		/*
24591 		 * Emission loop for this fragment, similar
24592 		 * to what is done for the first fragment.
24593 		 */
24594 		do {
24595 			if (multirt_send) {
24596 				/*
24597 				 * We are in a multiple send case, need to get
24598 				 * the next ire and make a copy of the packet.
24599 				 */
24600 				ASSERT(irb != NULL);
24601 				IRB_REFHOLD(irb);
24602 				for (ire1 = ire->ire_next;
24603 				    ire1 != NULL;
24604 				    ire1 = ire1->ire_next) {
24605 					if (!(ire1->ire_flags & RTF_MULTIRT))
24606 						continue;
24607 					if (ire1->ire_addr != ire->ire_addr)
24608 						continue;
24609 					if (ire1->ire_marks &
24610 					    (IRE_MARK_CONDEMNED|
24611 					    IRE_MARK_HIDDEN)) {
24612 						continue;
24613 					}
24614 					/*
24615 					 * Ensure we do not exceed the MTU
24616 					 * of the next route.
24617 					 */
24618 					if (ire1->ire_max_frag < max_frag) {
24619 						ip_multirt_bad_mtu(ire1,
24620 						    max_frag);
24621 						continue;
24622 					}
24623 
24624 					/* Got one. */
24625 					IRE_REFHOLD(ire1);
24626 					break;
24627 				}
24628 				IRB_REFRELE(irb);
24629 
24630 				if (ire1 != NULL) {
24631 					next_mp = copyb(mp);
24632 					if ((next_mp == NULL) ||
24633 					    ((mp->b_cont != NULL) &&
24634 					    ((next_mp->b_cont =
24635 					    dupmsg(mp->b_cont)) == NULL))) {
24636 						freemsg(next_mp);
24637 						next_mp = NULL;
24638 						ire_refrele(ire1);
24639 						ire1 = NULL;
24640 					}
24641 				}
24642 
24643 				/* Last multiroute ire; don't loop anymore. */
24644 				if (ire1 == NULL) {
24645 					multirt_send = B_FALSE;
24646 				}
24647 			}
24648 
24649 			/* Update transmit header */
24650 			ll_hdr_len = 0;
24651 			LOCK_IRE_FP_MP(ire);
24652 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24653 			if (ll_hdr_mp != NULL) {
24654 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24655 				ll_hdr_len = MBLKL(ll_hdr_mp);
24656 			} else {
24657 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24658 			}
24659 
24660 			if (!ll_hdr_mp) {
24661 				xmit_mp = mp;
24662 
24663 			/*
24664 			 * We have link-layer header that can fit in
24665 			 * our mblk.
24666 			 */
24667 			} else if (mp->b_datap->db_ref == 1 &&
24668 			    ll_hdr_len != 0 &&
24669 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24670 				/* M_DATA fastpath */
24671 				mp->b_rptr -= ll_hdr_len;
24672 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24673 				    ll_hdr_len);
24674 				xmit_mp = mp;
24675 
24676 			/*
24677 			 * Case of res_mp OR the fastpath mp can't fit
24678 			 * in the mblk
24679 			 */
24680 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24681 				xmit_mp->b_cont = mp;
24682 				if (DB_CRED(mp) != NULL)
24683 					mblk_setcred(xmit_mp, DB_CRED(mp));
24684 				/* Get priority marking, if any. */
24685 				if (DB_TYPE(xmit_mp) == M_DATA)
24686 					xmit_mp->b_band = mp->b_band;
24687 
24688 			/* Corner case if copyb failed */
24689 			} else {
24690 				/*
24691 				 * Exit both the replication and
24692 				 * fragmentation loops.
24693 				 */
24694 				UNLOCK_IRE_FP_MP(ire);
24695 				goto drop_pkt;
24696 			}
24697 			UNLOCK_IRE_FP_MP(ire);
24698 
24699 			mp1 = mp;
24700 			out_ill = (ill_t *)q->q_ptr;
24701 
24702 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24703 
24704 			DTRACE_PROBE4(ip4__physical__out__start,
24705 			    ill_t *, NULL, ill_t *, out_ill,
24706 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24707 
24708 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24709 			    ipst->ips_ipv4firewall_physical_out,
24710 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24711 
24712 			DTRACE_PROBE1(ip4__physical__out__end,
24713 			    mblk_t *, xmit_mp);
24714 
24715 			if (mp != mp1 && hdr_mp == mp1)
24716 				hdr_mp = mp;
24717 			if (mp != mp1 && mp_orig == mp1)
24718 				mp_orig = mp;
24719 
24720 			if (xmit_mp != NULL) {
24721 				putnext(q, xmit_mp);
24722 
24723 				BUMP_MIB(out_ill->ill_ip_mib,
24724 				    ipIfStatsHCOutTransmits);
24725 				UPDATE_MIB(out_ill->ill_ip_mib,
24726 				    ipIfStatsHCOutOctets, ip_len);
24727 
24728 				if (pkt_type != OB_PKT) {
24729 					/*
24730 					 * Update the packet count of trailing
24731 					 * RTF_MULTIRT ires.
24732 					 */
24733 					UPDATE_OB_PKT_COUNT(ire);
24734 				}
24735 			}
24736 
24737 			/* All done if we just consumed the hdr_mp. */
24738 			if (mp == hdr_mp) {
24739 				last_frag = B_TRUE;
24740 				BUMP_MIB(out_ill->ill_ip_mib,
24741 				    ipIfStatsOutFragOKs);
24742 			}
24743 
24744 			if (multirt_send) {
24745 				/*
24746 				 * We are in a multiple send case; look for
24747 				 * the next ire and re-enter the loop.
24748 				 */
24749 				ASSERT(ire1);
24750 				ASSERT(next_mp);
24751 				/* REFRELE the current ire before looping */
24752 				ire_refrele(ire);
24753 				ire = ire1;
24754 				ire1 = NULL;
24755 				q = ire->ire_stq;
24756 				mp = next_mp;
24757 				next_mp = NULL;
24758 			}
24759 		} while (multirt_send);
24760 		/*
24761 		 * Restore the original ire; we need it for the
24762 		 * trailing frags
24763 		 */
24764 		if (save_ire != NULL) {
24765 			ASSERT(ire1 == NULL);
24766 			/* REFRELE the last iterated ire */
24767 			ire_refrele(ire);
24768 			/* save_ire has been REFHOLDed */
24769 			ire = save_ire;
24770 			q = ire->ire_stq;
24771 			save_ire = NULL;
24772 		}
24773 
24774 		if (last_frag) {
24775 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24776 			    "ip_wput_frag_end:(%S)",
24777 			    "consumed hdr_mp");
24778 
24779 			if (first_ire != NULL)
24780 				ire_refrele(first_ire);
24781 			return;
24782 		}
24783 		/* Otherwise, advance and loop. */
24784 		offset += len;
24785 	}
24786 
24787 drop_pkt:
24788 	/* Clean up following allocation failure. */
24789 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24790 	freemsg(mp);
24791 	if (mp != hdr_mp)
24792 		freeb(hdr_mp);
24793 	if (mp != mp_orig)
24794 		freemsg(mp_orig);
24795 
24796 	if (save_ire != NULL)
24797 		IRE_REFRELE(save_ire);
24798 	if (first_ire != NULL)
24799 		ire_refrele(first_ire);
24800 
24801 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24802 	    "ip_wput_frag_end:(%S)",
24803 	    "end--alloc failure");
24804 }
24805 
24806 /*
24807  * Copy the header plus those options which have the copy bit set
24808  */
24809 static mblk_t *
24810 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24811 {
24812 	mblk_t	*mp;
24813 	uchar_t	*up;
24814 
24815 	/*
24816 	 * Quick check if we need to look for options without the copy bit
24817 	 * set
24818 	 */
24819 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24820 	if (!mp)
24821 		return (mp);
24822 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24823 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24824 		bcopy(rptr, mp->b_rptr, hdr_len);
24825 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24826 		return (mp);
24827 	}
24828 	up  = mp->b_rptr;
24829 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24830 	up += IP_SIMPLE_HDR_LENGTH;
24831 	rptr += IP_SIMPLE_HDR_LENGTH;
24832 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24833 	while (hdr_len > 0) {
24834 		uint32_t optval;
24835 		uint32_t optlen;
24836 
24837 		optval = *rptr;
24838 		if (optval == IPOPT_EOL)
24839 			break;
24840 		if (optval == IPOPT_NOP)
24841 			optlen = 1;
24842 		else
24843 			optlen = rptr[1];
24844 		if (optval & IPOPT_COPY) {
24845 			bcopy(rptr, up, optlen);
24846 			up += optlen;
24847 		}
24848 		rptr += optlen;
24849 		hdr_len -= optlen;
24850 	}
24851 	/*
24852 	 * Make sure that we drop an even number of words by filling
24853 	 * with EOL to the next word boundary.
24854 	 */
24855 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24856 	    hdr_len & 0x3; hdr_len++)
24857 		*up++ = IPOPT_EOL;
24858 	mp->b_wptr = up;
24859 	/* Update header length */
24860 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24861 	return (mp);
24862 }
24863 
24864 /*
24865  * Delivery to local recipients including fanout to multiple recipients.
24866  * Does not do checksumming of UDP/TCP.
24867  * Note: q should be the read side queue for either the ill or conn.
24868  * Note: rq should be the read side q for the lower (ill) stream.
24869  * We don't send packets to IPPF processing, thus the last argument
24870  * to all the fanout calls are B_FALSE.
24871  */
24872 void
24873 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24874     int fanout_flags, zoneid_t zoneid)
24875 {
24876 	uint32_t	protocol;
24877 	mblk_t		*first_mp;
24878 	boolean_t	mctl_present;
24879 	int		ire_type;
24880 #define	rptr	((uchar_t *)ipha)
24881 	ip_stack_t	*ipst = ill->ill_ipst;
24882 
24883 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24884 	    "ip_wput_local_start: q %p", q);
24885 
24886 	if (ire != NULL) {
24887 		ire_type = ire->ire_type;
24888 	} else {
24889 		/*
24890 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24891 		 * packet is not multicast, we can't tell the ire type.
24892 		 */
24893 		ASSERT(CLASSD(ipha->ipha_dst));
24894 		ire_type = IRE_BROADCAST;
24895 	}
24896 
24897 	first_mp = mp;
24898 	if (first_mp->b_datap->db_type == M_CTL) {
24899 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24900 		if (!io->ipsec_out_secure) {
24901 			/*
24902 			 * This ipsec_out_t was allocated in ip_wput
24903 			 * for multicast packets to store the ill_index.
24904 			 * As this is being delivered locally, we don't
24905 			 * need this anymore.
24906 			 */
24907 			mp = first_mp->b_cont;
24908 			freeb(first_mp);
24909 			first_mp = mp;
24910 			mctl_present = B_FALSE;
24911 		} else {
24912 			/*
24913 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24914 			 * security properties for the looped-back packet.
24915 			 */
24916 			mctl_present = B_TRUE;
24917 			mp = first_mp->b_cont;
24918 			ASSERT(mp != NULL);
24919 			ipsec_out_to_in(first_mp);
24920 		}
24921 	} else {
24922 		mctl_present = B_FALSE;
24923 	}
24924 
24925 	DTRACE_PROBE4(ip4__loopback__in__start,
24926 	    ill_t *, ill, ill_t *, NULL,
24927 	    ipha_t *, ipha, mblk_t *, first_mp);
24928 
24929 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24930 	    ipst->ips_ipv4firewall_loopback_in,
24931 	    ill, NULL, ipha, first_mp, mp, ipst);
24932 
24933 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24934 
24935 	if (first_mp == NULL)
24936 		return;
24937 
24938 	ipst->ips_loopback_packets++;
24939 
24940 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24941 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24942 	if (!IS_SIMPLE_IPH(ipha)) {
24943 		ip_wput_local_options(ipha, ipst);
24944 	}
24945 
24946 	protocol = ipha->ipha_protocol;
24947 	switch (protocol) {
24948 	case IPPROTO_ICMP: {
24949 		ire_t		*ire_zone;
24950 		ilm_t		*ilm;
24951 		mblk_t		*mp1;
24952 		zoneid_t	last_zoneid;
24953 
24954 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24955 			ASSERT(ire_type == IRE_BROADCAST);
24956 			/*
24957 			 * In the multicast case, applications may have joined
24958 			 * the group from different zones, so we need to deliver
24959 			 * the packet to each of them. Loop through the
24960 			 * multicast memberships structures (ilm) on the receive
24961 			 * ill and send a copy of the packet up each matching
24962 			 * one. However, we don't do this for multicasts sent on
24963 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24964 			 * they must stay in the sender's zone.
24965 			 *
24966 			 * ilm_add_v6() ensures that ilms in the same zone are
24967 			 * contiguous in the ill_ilm list. We use this property
24968 			 * to avoid sending duplicates needed when two
24969 			 * applications in the same zone join the same group on
24970 			 * different logical interfaces: we ignore the ilm if
24971 			 * it's zoneid is the same as the last matching one.
24972 			 * In addition, the sending of the packet for
24973 			 * ire_zoneid is delayed until all of the other ilms
24974 			 * have been exhausted.
24975 			 */
24976 			last_zoneid = -1;
24977 			ILM_WALKER_HOLD(ill);
24978 			for (ilm = ill->ill_ilm; ilm != NULL;
24979 			    ilm = ilm->ilm_next) {
24980 				if ((ilm->ilm_flags & ILM_DELETED) ||
24981 				    ipha->ipha_dst != ilm->ilm_addr ||
24982 				    ilm->ilm_zoneid == last_zoneid ||
24983 				    ilm->ilm_zoneid == zoneid ||
24984 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24985 					continue;
24986 				mp1 = ip_copymsg(first_mp);
24987 				if (mp1 == NULL)
24988 					continue;
24989 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24990 				    mctl_present, B_FALSE, ill,
24991 				    ilm->ilm_zoneid);
24992 				last_zoneid = ilm->ilm_zoneid;
24993 			}
24994 			ILM_WALKER_RELE(ill);
24995 			/*
24996 			 * Loopback case: the sending endpoint has
24997 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24998 			 * dispatch the multicast packet to the sending zone.
24999 			 */
25000 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25001 				freemsg(first_mp);
25002 				return;
25003 			}
25004 		} else if (ire_type == IRE_BROADCAST) {
25005 			/*
25006 			 * In the broadcast case, there may be many zones
25007 			 * which need a copy of the packet delivered to them.
25008 			 * There is one IRE_BROADCAST per broadcast address
25009 			 * and per zone; we walk those using a helper function.
25010 			 * In addition, the sending of the packet for zoneid is
25011 			 * delayed until all of the other ires have been
25012 			 * processed.
25013 			 */
25014 			IRB_REFHOLD(ire->ire_bucket);
25015 			ire_zone = NULL;
25016 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25017 			    ire)) != NULL) {
25018 				mp1 = ip_copymsg(first_mp);
25019 				if (mp1 == NULL)
25020 					continue;
25021 
25022 				UPDATE_IB_PKT_COUNT(ire_zone);
25023 				ire_zone->ire_last_used_time = lbolt;
25024 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25025 				    mctl_present, B_FALSE, ill,
25026 				    ire_zone->ire_zoneid);
25027 			}
25028 			IRB_REFRELE(ire->ire_bucket);
25029 		}
25030 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25031 		    0, mctl_present, B_FALSE, ill, zoneid);
25032 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25033 		    "ip_wput_local_end: q %p (%S)",
25034 		    q, "icmp");
25035 		return;
25036 	}
25037 	case IPPROTO_IGMP:
25038 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25039 			/* Bad packet - discarded by igmp_input */
25040 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25041 			    "ip_wput_local_end: q %p (%S)",
25042 			    q, "igmp_input--bad packet");
25043 			if (mctl_present)
25044 				freeb(first_mp);
25045 			return;
25046 		}
25047 		/*
25048 		 * igmp_input() may have returned the pulled up message.
25049 		 * So first_mp and ipha need to be reinitialized.
25050 		 */
25051 		ipha = (ipha_t *)mp->b_rptr;
25052 		if (mctl_present)
25053 			first_mp->b_cont = mp;
25054 		else
25055 			first_mp = mp;
25056 		/* deliver to local raw users */
25057 		break;
25058 	case IPPROTO_ENCAP:
25059 		/*
25060 		 * This case is covered by either ip_fanout_proto, or by
25061 		 * the above security processing for self-tunneled packets.
25062 		 */
25063 		break;
25064 	case IPPROTO_UDP: {
25065 		uint16_t	*up;
25066 		uint32_t	ports;
25067 
25068 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25069 		    UDP_PORTS_OFFSET);
25070 		/* Force a 'valid' checksum. */
25071 		up[3] = 0;
25072 
25073 		ports = *(uint32_t *)up;
25074 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25075 		    (ire_type == IRE_BROADCAST),
25076 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25077 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25078 		    ill, zoneid);
25079 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25080 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25081 		return;
25082 	}
25083 	case IPPROTO_TCP: {
25084 
25085 		/*
25086 		 * For TCP, discard broadcast packets.
25087 		 */
25088 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25089 			freemsg(first_mp);
25090 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25091 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25092 			return;
25093 		}
25094 
25095 		if (mp->b_datap->db_type == M_DATA) {
25096 			/*
25097 			 * M_DATA mblk, so init mblk (chain) for no struio().
25098 			 */
25099 			mblk_t	*mp1 = mp;
25100 
25101 			do {
25102 				mp1->b_datap->db_struioflag = 0;
25103 			} while ((mp1 = mp1->b_cont) != NULL);
25104 		}
25105 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25106 		    <= mp->b_wptr);
25107 		ip_fanout_tcp(q, first_mp, ill, ipha,
25108 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25109 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25110 		    mctl_present, B_FALSE, zoneid);
25111 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25112 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25113 		return;
25114 	}
25115 	case IPPROTO_SCTP:
25116 	{
25117 		uint32_t	ports;
25118 
25119 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25120 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25121 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25122 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25123 		return;
25124 	}
25125 
25126 	default:
25127 		break;
25128 	}
25129 	/*
25130 	 * Find a client for some other protocol.  We give
25131 	 * copies to multiple clients, if more than one is
25132 	 * bound.
25133 	 */
25134 	ip_fanout_proto(q, first_mp, ill, ipha,
25135 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25136 	    mctl_present, B_FALSE, ill, zoneid);
25137 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25138 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25139 #undef	rptr
25140 }
25141 
25142 /*
25143  * Update any source route, record route, or timestamp options.
25144  * Check that we are at end of strict source route.
25145  * The options have been sanity checked by ip_wput_options().
25146  */
25147 static void
25148 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25149 {
25150 	ipoptp_t	opts;
25151 	uchar_t		*opt;
25152 	uint8_t		optval;
25153 	uint8_t		optlen;
25154 	ipaddr_t	dst;
25155 	uint32_t	ts;
25156 	ire_t		*ire;
25157 	timestruc_t	now;
25158 
25159 	ip2dbg(("ip_wput_local_options\n"));
25160 	for (optval = ipoptp_first(&opts, ipha);
25161 	    optval != IPOPT_EOL;
25162 	    optval = ipoptp_next(&opts)) {
25163 		opt = opts.ipoptp_cur;
25164 		optlen = opts.ipoptp_len;
25165 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25166 		switch (optval) {
25167 			uint32_t off;
25168 		case IPOPT_SSRR:
25169 		case IPOPT_LSRR:
25170 			off = opt[IPOPT_OFFSET];
25171 			off--;
25172 			if (optlen < IP_ADDR_LEN ||
25173 			    off > optlen - IP_ADDR_LEN) {
25174 				/* End of source route */
25175 				break;
25176 			}
25177 			/*
25178 			 * This will only happen if two consecutive entries
25179 			 * in the source route contains our address or if
25180 			 * it is a packet with a loose source route which
25181 			 * reaches us before consuming the whole source route
25182 			 */
25183 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25184 			if (optval == IPOPT_SSRR) {
25185 				return;
25186 			}
25187 			/*
25188 			 * Hack: instead of dropping the packet truncate the
25189 			 * source route to what has been used by filling the
25190 			 * rest with IPOPT_NOP.
25191 			 */
25192 			opt[IPOPT_OLEN] = (uint8_t)off;
25193 			while (off < optlen) {
25194 				opt[off++] = IPOPT_NOP;
25195 			}
25196 			break;
25197 		case IPOPT_RR:
25198 			off = opt[IPOPT_OFFSET];
25199 			off--;
25200 			if (optlen < IP_ADDR_LEN ||
25201 			    off > optlen - IP_ADDR_LEN) {
25202 				/* No more room - ignore */
25203 				ip1dbg((
25204 				    "ip_wput_forward_options: end of RR\n"));
25205 				break;
25206 			}
25207 			dst = htonl(INADDR_LOOPBACK);
25208 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25209 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25210 			break;
25211 		case IPOPT_TS:
25212 			/* Insert timestamp if there is romm */
25213 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25214 			case IPOPT_TS_TSONLY:
25215 				off = IPOPT_TS_TIMELEN;
25216 				break;
25217 			case IPOPT_TS_PRESPEC:
25218 			case IPOPT_TS_PRESPEC_RFC791:
25219 				/* Verify that the address matched */
25220 				off = opt[IPOPT_OFFSET] - 1;
25221 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25222 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25223 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25224 				    ipst);
25225 				if (ire == NULL) {
25226 					/* Not for us */
25227 					break;
25228 				}
25229 				ire_refrele(ire);
25230 				/* FALLTHRU */
25231 			case IPOPT_TS_TSANDADDR:
25232 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25233 				break;
25234 			default:
25235 				/*
25236 				 * ip_*put_options should have already
25237 				 * dropped this packet.
25238 				 */
25239 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25240 				    "unknown IT - bug in ip_wput_options?\n");
25241 				return;	/* Keep "lint" happy */
25242 			}
25243 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25244 				/* Increase overflow counter */
25245 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25246 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25247 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25248 				    (off << 4);
25249 				break;
25250 			}
25251 			off = opt[IPOPT_OFFSET] - 1;
25252 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25253 			case IPOPT_TS_PRESPEC:
25254 			case IPOPT_TS_PRESPEC_RFC791:
25255 			case IPOPT_TS_TSANDADDR:
25256 				dst = htonl(INADDR_LOOPBACK);
25257 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25258 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25259 				/* FALLTHRU */
25260 			case IPOPT_TS_TSONLY:
25261 				off = opt[IPOPT_OFFSET] - 1;
25262 				/* Compute # of milliseconds since midnight */
25263 				gethrestime(&now);
25264 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25265 				    now.tv_nsec / (NANOSEC / MILLISEC);
25266 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25267 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25268 				break;
25269 			}
25270 			break;
25271 		}
25272 	}
25273 }
25274 
25275 /*
25276  * Send out a multicast packet on interface ipif.
25277  * The sender does not have an conn.
25278  * Caller verifies that this isn't a PHYI_LOOPBACK.
25279  */
25280 void
25281 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25282 {
25283 	ipha_t	*ipha;
25284 	ire_t	*ire;
25285 	ipaddr_t	dst;
25286 	mblk_t		*first_mp;
25287 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25288 
25289 	/* igmp_sendpkt always allocates a ipsec_out_t */
25290 	ASSERT(mp->b_datap->db_type == M_CTL);
25291 	ASSERT(!ipif->ipif_isv6);
25292 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25293 
25294 	first_mp = mp;
25295 	mp = first_mp->b_cont;
25296 	ASSERT(mp->b_datap->db_type == M_DATA);
25297 	ipha = (ipha_t *)mp->b_rptr;
25298 
25299 	/*
25300 	 * Find an IRE which matches the destination and the outgoing
25301 	 * queue (i.e. the outgoing interface.)
25302 	 */
25303 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25304 		dst = ipif->ipif_pp_dst_addr;
25305 	else
25306 		dst = ipha->ipha_dst;
25307 	/*
25308 	 * The source address has already been initialized by the
25309 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25310 	 * be sufficient rather than MATCH_IRE_IPIF.
25311 	 *
25312 	 * This function is used for sending IGMP packets. We need
25313 	 * to make sure that we send the packet out of the interface
25314 	 * (ipif->ipif_ill) where we joined the group. This is to
25315 	 * prevent from switches doing IGMP snooping to send us multicast
25316 	 * packets for a given group on the interface we have joined.
25317 	 * If we can't find an ire, igmp_sendpkt has already initialized
25318 	 * ipsec_out_attach_if so that this will not be load spread in
25319 	 * ip_newroute_ipif.
25320 	 */
25321 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25322 	    MATCH_IRE_ILL, ipst);
25323 	if (!ire) {
25324 		/*
25325 		 * Mark this packet to make it be delivered to
25326 		 * ip_wput_ire after the new ire has been
25327 		 * created.
25328 		 */
25329 		mp->b_prev = NULL;
25330 		mp->b_next = NULL;
25331 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25332 		    zoneid, &zero_info);
25333 		return;
25334 	}
25335 
25336 	/*
25337 	 * Honor the RTF_SETSRC flag; this is the only case
25338 	 * where we force this addr whatever the current src addr is,
25339 	 * because this address is set by igmp_sendpkt(), and
25340 	 * cannot be specified by any user.
25341 	 */
25342 	if (ire->ire_flags & RTF_SETSRC) {
25343 		ipha->ipha_src = ire->ire_src_addr;
25344 	}
25345 
25346 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25347 }
25348 
25349 /*
25350  * NOTE : This function does not ire_refrele the ire argument passed in.
25351  *
25352  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25353  * failure. The nce_fp_mp can vanish any time in the case of
25354  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25355  * the ire_lock to access the nce_fp_mp in this case.
25356  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25357  * prepending a fastpath message IPQoS processing must precede it, we also set
25358  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25359  * (IPQoS might have set the b_band for CoS marking).
25360  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25361  * must follow it so that IPQoS can mark the dl_priority field for CoS
25362  * marking, if needed.
25363  */
25364 static mblk_t *
25365 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25366 {
25367 	uint_t	hlen;
25368 	ipha_t *ipha;
25369 	mblk_t *mp1;
25370 	boolean_t qos_done = B_FALSE;
25371 	uchar_t	*ll_hdr;
25372 	ip_stack_t	*ipst = ire->ire_ipst;
25373 
25374 #define	rptr	((uchar_t *)ipha)
25375 
25376 	ipha = (ipha_t *)mp->b_rptr;
25377 	hlen = 0;
25378 	LOCK_IRE_FP_MP(ire);
25379 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25380 		ASSERT(DB_TYPE(mp1) == M_DATA);
25381 		/* Initiate IPPF processing */
25382 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25383 			UNLOCK_IRE_FP_MP(ire);
25384 			ip_process(proc, &mp, ill_index);
25385 			if (mp == NULL)
25386 				return (NULL);
25387 
25388 			ipha = (ipha_t *)mp->b_rptr;
25389 			LOCK_IRE_FP_MP(ire);
25390 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25391 				qos_done = B_TRUE;
25392 				goto no_fp_mp;
25393 			}
25394 			ASSERT(DB_TYPE(mp1) == M_DATA);
25395 		}
25396 		hlen = MBLKL(mp1);
25397 		/*
25398 		 * Check if we have enough room to prepend fastpath
25399 		 * header
25400 		 */
25401 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25402 			ll_hdr = rptr - hlen;
25403 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25404 			/*
25405 			 * Set the b_rptr to the start of the link layer
25406 			 * header
25407 			 */
25408 			mp->b_rptr = ll_hdr;
25409 			mp1 = mp;
25410 		} else {
25411 			mp1 = copyb(mp1);
25412 			if (mp1 == NULL)
25413 				goto unlock_err;
25414 			mp1->b_band = mp->b_band;
25415 			mp1->b_cont = mp;
25416 			/*
25417 			 * certain system generated traffic may not
25418 			 * have cred/label in ip header block. This
25419 			 * is true even for a labeled system. But for
25420 			 * labeled traffic, inherit the label in the
25421 			 * new header.
25422 			 */
25423 			if (DB_CRED(mp) != NULL)
25424 				mblk_setcred(mp1, DB_CRED(mp));
25425 			/*
25426 			 * XXX disable ICK_VALID and compute checksum
25427 			 * here; can happen if nce_fp_mp changes and
25428 			 * it can't be copied now due to insufficient
25429 			 * space. (unlikely, fp mp can change, but it
25430 			 * does not increase in length)
25431 			 */
25432 		}
25433 		UNLOCK_IRE_FP_MP(ire);
25434 	} else {
25435 no_fp_mp:
25436 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25437 		if (mp1 == NULL) {
25438 unlock_err:
25439 			UNLOCK_IRE_FP_MP(ire);
25440 			freemsg(mp);
25441 			return (NULL);
25442 		}
25443 		UNLOCK_IRE_FP_MP(ire);
25444 		mp1->b_cont = mp;
25445 		/*
25446 		 * certain system generated traffic may not
25447 		 * have cred/label in ip header block. This
25448 		 * is true even for a labeled system. But for
25449 		 * labeled traffic, inherit the label in the
25450 		 * new header.
25451 		 */
25452 		if (DB_CRED(mp) != NULL)
25453 			mblk_setcred(mp1, DB_CRED(mp));
25454 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25455 			ip_process(proc, &mp1, ill_index);
25456 			if (mp1 == NULL)
25457 				return (NULL);
25458 		}
25459 	}
25460 	return (mp1);
25461 #undef rptr
25462 }
25463 
25464 /*
25465  * Finish the outbound IPsec processing for an IPv6 packet. This function
25466  * is called from ipsec_out_process() if the IPsec packet was processed
25467  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25468  * asynchronously.
25469  */
25470 void
25471 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25472     ire_t *ire_arg)
25473 {
25474 	in6_addr_t *v6dstp;
25475 	ire_t *ire;
25476 	mblk_t *mp;
25477 	ip6_t *ip6h1;
25478 	uint_t	ill_index;
25479 	ipsec_out_t *io;
25480 	boolean_t attach_if, hwaccel;
25481 	uint32_t flags = IP6_NO_IPPOLICY;
25482 	int match_flags;
25483 	zoneid_t zoneid;
25484 	boolean_t ill_need_rele = B_FALSE;
25485 	boolean_t ire_need_rele = B_FALSE;
25486 	ip_stack_t	*ipst;
25487 
25488 	mp = ipsec_mp->b_cont;
25489 	ip6h1 = (ip6_t *)mp->b_rptr;
25490 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25491 	ASSERT(io->ipsec_out_ns != NULL);
25492 	ipst = io->ipsec_out_ns->netstack_ip;
25493 	ill_index = io->ipsec_out_ill_index;
25494 	if (io->ipsec_out_reachable) {
25495 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25496 	}
25497 	attach_if = io->ipsec_out_attach_if;
25498 	hwaccel = io->ipsec_out_accelerated;
25499 	zoneid = io->ipsec_out_zoneid;
25500 	ASSERT(zoneid != ALL_ZONES);
25501 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25502 	/* Multicast addresses should have non-zero ill_index. */
25503 	v6dstp = &ip6h->ip6_dst;
25504 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25505 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25506 	ASSERT(!attach_if || ill_index != 0);
25507 	if (ill_index != 0) {
25508 		if (ill == NULL) {
25509 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25510 			    B_TRUE, ipst);
25511 
25512 			/* Failure case frees things for us. */
25513 			if (ill == NULL)
25514 				return;
25515 
25516 			ill_need_rele = B_TRUE;
25517 		}
25518 		/*
25519 		 * If this packet needs to go out on a particular interface
25520 		 * honor it.
25521 		 */
25522 		if (attach_if) {
25523 			match_flags = MATCH_IRE_ILL;
25524 
25525 			/*
25526 			 * Check if we need an ire that will not be
25527 			 * looked up by anybody else i.e. HIDDEN.
25528 			 */
25529 			if (ill_is_probeonly(ill)) {
25530 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25531 			}
25532 		}
25533 	}
25534 	ASSERT(mp != NULL);
25535 
25536 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25537 		boolean_t unspec_src;
25538 		ipif_t	*ipif;
25539 
25540 		/*
25541 		 * Use the ill_index to get the right ill.
25542 		 */
25543 		unspec_src = io->ipsec_out_unspec_src;
25544 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25545 		if (ipif == NULL) {
25546 			if (ill_need_rele)
25547 				ill_refrele(ill);
25548 			freemsg(ipsec_mp);
25549 			return;
25550 		}
25551 
25552 		if (ire_arg != NULL) {
25553 			ire = ire_arg;
25554 		} else {
25555 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25556 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25557 			ire_need_rele = B_TRUE;
25558 		}
25559 		if (ire != NULL) {
25560 			ipif_refrele(ipif);
25561 			/*
25562 			 * XXX Do the multicast forwarding now, as the IPsec
25563 			 * processing has been done.
25564 			 */
25565 			goto send;
25566 		}
25567 
25568 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25569 		mp->b_prev = NULL;
25570 		mp->b_next = NULL;
25571 
25572 		/*
25573 		 * If the IPsec packet was processed asynchronously,
25574 		 * drop it now.
25575 		 */
25576 		if (q == NULL) {
25577 			if (ill_need_rele)
25578 				ill_refrele(ill);
25579 			freemsg(ipsec_mp);
25580 			return;
25581 		}
25582 
25583 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25584 		    unspec_src, zoneid);
25585 		ipif_refrele(ipif);
25586 	} else {
25587 		if (attach_if) {
25588 			ipif_t	*ipif;
25589 
25590 			ipif = ipif_get_next_ipif(NULL, ill);
25591 			if (ipif == NULL) {
25592 				if (ill_need_rele)
25593 					ill_refrele(ill);
25594 				freemsg(ipsec_mp);
25595 				return;
25596 			}
25597 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25598 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25599 			ire_need_rele = B_TRUE;
25600 			ipif_refrele(ipif);
25601 		} else {
25602 			if (ire_arg != NULL) {
25603 				ire = ire_arg;
25604 			} else {
25605 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25606 				    ipst);
25607 				ire_need_rele = B_TRUE;
25608 			}
25609 		}
25610 		if (ire != NULL)
25611 			goto send;
25612 		/*
25613 		 * ire disappeared underneath.
25614 		 *
25615 		 * What we need to do here is the ip_newroute
25616 		 * logic to get the ire without doing the IPsec
25617 		 * processing. Follow the same old path. But this
25618 		 * time, ip_wput or ire_add_then_send will call us
25619 		 * directly as all the IPsec operations are done.
25620 		 */
25621 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25622 		mp->b_prev = NULL;
25623 		mp->b_next = NULL;
25624 
25625 		/*
25626 		 * If the IPsec packet was processed asynchronously,
25627 		 * drop it now.
25628 		 */
25629 		if (q == NULL) {
25630 			if (ill_need_rele)
25631 				ill_refrele(ill);
25632 			freemsg(ipsec_mp);
25633 			return;
25634 		}
25635 
25636 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25637 		    zoneid, ipst);
25638 	}
25639 	if (ill != NULL && ill_need_rele)
25640 		ill_refrele(ill);
25641 	return;
25642 send:
25643 	if (ill != NULL && ill_need_rele)
25644 		ill_refrele(ill);
25645 
25646 	/* Local delivery */
25647 	if (ire->ire_stq == NULL) {
25648 		ill_t	*out_ill;
25649 		ASSERT(q != NULL);
25650 
25651 		/* PFHooks: LOOPBACK_OUT */
25652 		out_ill = ire_to_ill(ire);
25653 
25654 		DTRACE_PROBE4(ip6__loopback__out__start,
25655 		    ill_t *, NULL, ill_t *, out_ill,
25656 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25657 
25658 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25659 		    ipst->ips_ipv6firewall_loopback_out,
25660 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25661 
25662 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25663 
25664 		if (ipsec_mp != NULL)
25665 			ip_wput_local_v6(RD(q), out_ill,
25666 			    ip6h, ipsec_mp, ire, 0);
25667 		if (ire_need_rele)
25668 			ire_refrele(ire);
25669 		return;
25670 	}
25671 	/*
25672 	 * Everything is done. Send it out on the wire.
25673 	 * We force the insertion of a fragment header using the
25674 	 * IPH_FRAG_HDR flag in two cases:
25675 	 * - after reception of an ICMPv6 "packet too big" message
25676 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25677 	 * - for multirouted IPv6 packets, so that the receiver can
25678 	 *   discard duplicates according to their fragment identifier
25679 	 */
25680 	/* XXX fix flow control problems. */
25681 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25682 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25683 		if (hwaccel) {
25684 			/*
25685 			 * hardware acceleration does not handle these
25686 			 * "slow path" cases.
25687 			 */
25688 			/* IPsec KSTATS: should bump bean counter here. */
25689 			if (ire_need_rele)
25690 				ire_refrele(ire);
25691 			freemsg(ipsec_mp);
25692 			return;
25693 		}
25694 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25695 		    (mp->b_cont ? msgdsize(mp) :
25696 		    mp->b_wptr - (uchar_t *)ip6h)) {
25697 			/* IPsec KSTATS: should bump bean counter here. */
25698 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25699 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25700 			    msgdsize(mp)));
25701 			if (ire_need_rele)
25702 				ire_refrele(ire);
25703 			freemsg(ipsec_mp);
25704 			return;
25705 		}
25706 		ASSERT(mp->b_prev == NULL);
25707 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25708 		    ntohs(ip6h->ip6_plen) +
25709 		    IPV6_HDR_LEN, ire->ire_max_frag));
25710 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25711 		    ire->ire_max_frag);
25712 	} else {
25713 		UPDATE_OB_PKT_COUNT(ire);
25714 		ire->ire_last_used_time = lbolt;
25715 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25716 	}
25717 	if (ire_need_rele)
25718 		ire_refrele(ire);
25719 	freeb(ipsec_mp);
25720 }
25721 
25722 void
25723 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25724 {
25725 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25726 	da_ipsec_t *hada;	/* data attributes */
25727 	ill_t *ill = (ill_t *)q->q_ptr;
25728 
25729 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25730 
25731 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25732 		/* IPsec KSTATS: Bump lose counter here! */
25733 		freemsg(mp);
25734 		return;
25735 	}
25736 
25737 	/*
25738 	 * It's an IPsec packet that must be
25739 	 * accelerated by the Provider, and the
25740 	 * outbound ill is IPsec acceleration capable.
25741 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25742 	 * to the ill.
25743 	 * IPsec KSTATS: should bump packet counter here.
25744 	 */
25745 
25746 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25747 	if (hada_mp == NULL) {
25748 		/* IPsec KSTATS: should bump packet counter here. */
25749 		freemsg(mp);
25750 		return;
25751 	}
25752 
25753 	hada_mp->b_datap->db_type = M_CTL;
25754 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25755 	hada_mp->b_cont = mp;
25756 
25757 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25758 	bzero(hada, sizeof (da_ipsec_t));
25759 	hada->da_type = IPHADA_M_CTL;
25760 
25761 	putnext(q, hada_mp);
25762 }
25763 
25764 /*
25765  * Finish the outbound IPsec processing. This function is called from
25766  * ipsec_out_process() if the IPsec packet was processed
25767  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25768  * asynchronously.
25769  */
25770 void
25771 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25772     ire_t *ire_arg)
25773 {
25774 	uint32_t v_hlen_tos_len;
25775 	ipaddr_t	dst;
25776 	ipif_t	*ipif = NULL;
25777 	ire_t *ire;
25778 	ire_t *ire1 = NULL;
25779 	mblk_t *next_mp = NULL;
25780 	uint32_t max_frag;
25781 	boolean_t multirt_send = B_FALSE;
25782 	mblk_t *mp;
25783 	ipha_t *ipha1;
25784 	uint_t	ill_index;
25785 	ipsec_out_t *io;
25786 	boolean_t attach_if;
25787 	int match_flags;
25788 	irb_t *irb = NULL;
25789 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25790 	zoneid_t zoneid;
25791 	ipxmit_state_t	pktxmit_state;
25792 	ip_stack_t	*ipst;
25793 
25794 #ifdef	_BIG_ENDIAN
25795 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25796 #else
25797 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25798 #endif
25799 
25800 	mp = ipsec_mp->b_cont;
25801 	ipha1 = (ipha_t *)mp->b_rptr;
25802 	ASSERT(mp != NULL);
25803 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25804 	dst = ipha->ipha_dst;
25805 
25806 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25807 	ill_index = io->ipsec_out_ill_index;
25808 	attach_if = io->ipsec_out_attach_if;
25809 	zoneid = io->ipsec_out_zoneid;
25810 	ASSERT(zoneid != ALL_ZONES);
25811 	ipst = io->ipsec_out_ns->netstack_ip;
25812 	ASSERT(io->ipsec_out_ns != NULL);
25813 
25814 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25815 	if (ill_index != 0) {
25816 		if (ill == NULL) {
25817 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25818 			    ill_index, B_FALSE, ipst);
25819 
25820 			/* Failure case frees things for us. */
25821 			if (ill == NULL)
25822 				return;
25823 
25824 			ill_need_rele = B_TRUE;
25825 		}
25826 		/*
25827 		 * If this packet needs to go out on a particular interface
25828 		 * honor it.
25829 		 */
25830 		if (attach_if) {
25831 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25832 
25833 			/*
25834 			 * Check if we need an ire that will not be
25835 			 * looked up by anybody else i.e. HIDDEN.
25836 			 */
25837 			if (ill_is_probeonly(ill)) {
25838 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25839 			}
25840 		}
25841 	}
25842 
25843 	if (CLASSD(dst)) {
25844 		boolean_t conn_dontroute;
25845 		/*
25846 		 * Use the ill_index to get the right ipif.
25847 		 */
25848 		conn_dontroute = io->ipsec_out_dontroute;
25849 		if (ill_index == 0)
25850 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25851 		else
25852 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25853 		if (ipif == NULL) {
25854 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25855 			    " multicast\n"));
25856 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25857 			freemsg(ipsec_mp);
25858 			goto done;
25859 		}
25860 		/*
25861 		 * ipha_src has already been intialized with the
25862 		 * value of the ipif in ip_wput. All we need now is
25863 		 * an ire to send this downstream.
25864 		 */
25865 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25866 		    MBLK_GETLABEL(mp), match_flags, ipst);
25867 		if (ire != NULL) {
25868 			ill_t *ill1;
25869 			/*
25870 			 * Do the multicast forwarding now, as the IPsec
25871 			 * processing has been done.
25872 			 */
25873 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25874 			    (ill1 = ire_to_ill(ire))) {
25875 				if (ip_mforward(ill1, ipha, mp)) {
25876 					freemsg(ipsec_mp);
25877 					ip1dbg(("ip_wput_ipsec_out: mforward "
25878 					    "failed\n"));
25879 					ire_refrele(ire);
25880 					goto done;
25881 				}
25882 			}
25883 			goto send;
25884 		}
25885 
25886 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25887 		mp->b_prev = NULL;
25888 		mp->b_next = NULL;
25889 
25890 		/*
25891 		 * If the IPsec packet was processed asynchronously,
25892 		 * drop it now.
25893 		 */
25894 		if (q == NULL) {
25895 			freemsg(ipsec_mp);
25896 			goto done;
25897 		}
25898 
25899 		/*
25900 		 * We may be using a wrong ipif to create the ire.
25901 		 * But it is okay as the source address is assigned
25902 		 * for the packet already. Next outbound packet would
25903 		 * create the IRE with the right IPIF in ip_wput.
25904 		 *
25905 		 * Also handle RTF_MULTIRT routes.
25906 		 */
25907 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25908 		    zoneid, &zero_info);
25909 	} else {
25910 		if (attach_if) {
25911 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25912 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25913 		} else {
25914 			if (ire_arg != NULL) {
25915 				ire = ire_arg;
25916 				ire_need_rele = B_FALSE;
25917 			} else {
25918 				ire = ire_cache_lookup(dst, zoneid,
25919 				    MBLK_GETLABEL(mp), ipst);
25920 			}
25921 		}
25922 		if (ire != NULL) {
25923 			goto send;
25924 		}
25925 
25926 		/*
25927 		 * ire disappeared underneath.
25928 		 *
25929 		 * What we need to do here is the ip_newroute
25930 		 * logic to get the ire without doing the IPsec
25931 		 * processing. Follow the same old path. But this
25932 		 * time, ip_wput or ire_add_then_put will call us
25933 		 * directly as all the IPsec operations are done.
25934 		 */
25935 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25936 		mp->b_prev = NULL;
25937 		mp->b_next = NULL;
25938 
25939 		/*
25940 		 * If the IPsec packet was processed asynchronously,
25941 		 * drop it now.
25942 		 */
25943 		if (q == NULL) {
25944 			freemsg(ipsec_mp);
25945 			goto done;
25946 		}
25947 
25948 		/*
25949 		 * Since we're going through ip_newroute() again, we
25950 		 * need to make sure we don't:
25951 		 *
25952 		 *	1.) Trigger the ASSERT() with the ipha_ident
25953 		 *	    overloading.
25954 		 *	2.) Redo transport-layer checksumming, since we've
25955 		 *	    already done all that to get this far.
25956 		 *
25957 		 * The easiest way not do either of the above is to set
25958 		 * the ipha_ident field to IP_HDR_INCLUDED.
25959 		 */
25960 		ipha->ipha_ident = IP_HDR_INCLUDED;
25961 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25962 		    zoneid, ipst);
25963 	}
25964 	goto done;
25965 send:
25966 	if (ire->ire_stq == NULL) {
25967 		ill_t	*out_ill;
25968 		/*
25969 		 * Loopbacks go through ip_wput_local except for one case.
25970 		 * We come here if we generate a icmp_frag_needed message
25971 		 * after IPsec processing is over. When this function calls
25972 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25973 		 * icmp_frag_needed. The message generated comes back here
25974 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25975 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25976 		 * source address as it is usually set in ip_wput_ire. As
25977 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25978 		 * and we end up here. We can't enter ip_wput_ire once the
25979 		 * IPsec processing is over and hence we need to do it here.
25980 		 */
25981 		ASSERT(q != NULL);
25982 		UPDATE_OB_PKT_COUNT(ire);
25983 		ire->ire_last_used_time = lbolt;
25984 		if (ipha->ipha_src == 0)
25985 			ipha->ipha_src = ire->ire_src_addr;
25986 
25987 		/* PFHooks: LOOPBACK_OUT */
25988 		out_ill = ire_to_ill(ire);
25989 
25990 		DTRACE_PROBE4(ip4__loopback__out__start,
25991 		    ill_t *, NULL, ill_t *, out_ill,
25992 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25993 
25994 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25995 		    ipst->ips_ipv4firewall_loopback_out,
25996 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25997 
25998 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25999 
26000 		if (ipsec_mp != NULL)
26001 			ip_wput_local(RD(q), out_ill,
26002 			    ipha, ipsec_mp, ire, 0, zoneid);
26003 		if (ire_need_rele)
26004 			ire_refrele(ire);
26005 		goto done;
26006 	}
26007 
26008 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26009 		/*
26010 		 * We are through with IPsec processing.
26011 		 * Fragment this and send it on the wire.
26012 		 */
26013 		if (io->ipsec_out_accelerated) {
26014 			/*
26015 			 * The packet has been accelerated but must
26016 			 * be fragmented. This should not happen
26017 			 * since AH and ESP must not accelerate
26018 			 * packets that need fragmentation, however
26019 			 * the configuration could have changed
26020 			 * since the AH or ESP processing.
26021 			 * Drop packet.
26022 			 * IPsec KSTATS: bump bean counter here.
26023 			 */
26024 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26025 			    "fragmented accelerated packet!\n"));
26026 			freemsg(ipsec_mp);
26027 		} else {
26028 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26029 		}
26030 		if (ire_need_rele)
26031 			ire_refrele(ire);
26032 		goto done;
26033 	}
26034 
26035 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26036 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26037 	    (void *)ire->ire_ipif, (void *)ipif));
26038 
26039 	/*
26040 	 * Multiroute the secured packet, unless IPsec really
26041 	 * requires the packet to go out only through a particular
26042 	 * interface.
26043 	 */
26044 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26045 		ire_t *first_ire;
26046 		irb = ire->ire_bucket;
26047 		ASSERT(irb != NULL);
26048 		/*
26049 		 * This ire has been looked up as the one that
26050 		 * goes through the given ipif;
26051 		 * make sure we do not omit any other multiroute ire
26052 		 * that may be present in the bucket before this one.
26053 		 */
26054 		IRB_REFHOLD(irb);
26055 		for (first_ire = irb->irb_ire;
26056 		    first_ire != NULL;
26057 		    first_ire = first_ire->ire_next) {
26058 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26059 			    (first_ire->ire_addr == ire->ire_addr) &&
26060 			    !(first_ire->ire_marks &
26061 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26062 				break;
26063 			}
26064 		}
26065 
26066 		if ((first_ire != NULL) && (first_ire != ire)) {
26067 			/*
26068 			 * Don't change the ire if the packet must
26069 			 * be fragmented if sent via this new one.
26070 			 */
26071 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26072 				IRE_REFHOLD(first_ire);
26073 				if (ire_need_rele)
26074 					ire_refrele(ire);
26075 				else
26076 					ire_need_rele = B_TRUE;
26077 				ire = first_ire;
26078 			}
26079 		}
26080 		IRB_REFRELE(irb);
26081 
26082 		multirt_send = B_TRUE;
26083 		max_frag = ire->ire_max_frag;
26084 	} else {
26085 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26086 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26087 			    "flag, attach_if %d\n", attach_if));
26088 		}
26089 	}
26090 
26091 	/*
26092 	 * In most cases, the emission loop below is entered only once.
26093 	 * Only in the case where the ire holds the RTF_MULTIRT
26094 	 * flag, we loop to process all RTF_MULTIRT ires in the
26095 	 * bucket, and send the packet through all crossed
26096 	 * RTF_MULTIRT routes.
26097 	 */
26098 	do {
26099 		if (multirt_send) {
26100 			/*
26101 			 * ire1 holds here the next ire to process in the
26102 			 * bucket. If multirouting is expected,
26103 			 * any non-RTF_MULTIRT ire that has the
26104 			 * right destination address is ignored.
26105 			 */
26106 			ASSERT(irb != NULL);
26107 			IRB_REFHOLD(irb);
26108 			for (ire1 = ire->ire_next;
26109 			    ire1 != NULL;
26110 			    ire1 = ire1->ire_next) {
26111 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26112 					continue;
26113 				if (ire1->ire_addr != ire->ire_addr)
26114 					continue;
26115 				if (ire1->ire_marks &
26116 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26117 					continue;
26118 				/* No loopback here */
26119 				if (ire1->ire_stq == NULL)
26120 					continue;
26121 				/*
26122 				 * Ensure we do not exceed the MTU
26123 				 * of the next route.
26124 				 */
26125 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26126 					ip_multirt_bad_mtu(ire1, max_frag);
26127 					continue;
26128 				}
26129 
26130 				IRE_REFHOLD(ire1);
26131 				break;
26132 			}
26133 			IRB_REFRELE(irb);
26134 			if (ire1 != NULL) {
26135 				/*
26136 				 * We are in a multiple send case, need to
26137 				 * make a copy of the packet.
26138 				 */
26139 				next_mp = copymsg(ipsec_mp);
26140 				if (next_mp == NULL) {
26141 					ire_refrele(ire1);
26142 					ire1 = NULL;
26143 				}
26144 			}
26145 		}
26146 		/*
26147 		 * Everything is done. Send it out on the wire
26148 		 *
26149 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26150 		 * either send it on the wire or, in the case of
26151 		 * HW acceleration, call ipsec_hw_putnext.
26152 		 */
26153 		if (ire->ire_nce &&
26154 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26155 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26156 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26157 			/*
26158 			 * If ire's link-layer is unresolved (this
26159 			 * would only happen if the incomplete ire
26160 			 * was added to cachetable via forwarding path)
26161 			 * don't bother going to ip_xmit_v4. Just drop the
26162 			 * packet.
26163 			 * There is a slight risk here, in that, if we
26164 			 * have the forwarding path create an incomplete
26165 			 * IRE, then until the IRE is completed, any
26166 			 * transmitted IPsec packets will be dropped
26167 			 * instead of being queued waiting for resolution.
26168 			 *
26169 			 * But the likelihood of a forwarding packet and a wput
26170 			 * packet sending to the same dst at the same time
26171 			 * and there not yet be an ARP entry for it is small.
26172 			 * Furthermore, if this actually happens, it might
26173 			 * be likely that wput would generate multiple
26174 			 * packets (and forwarding would also have a train
26175 			 * of packets) for that destination. If this is
26176 			 * the case, some of them would have been dropped
26177 			 * anyway, since ARP only queues a few packets while
26178 			 * waiting for resolution
26179 			 *
26180 			 * NOTE: We should really call ip_xmit_v4,
26181 			 * and let it queue the packet and send the
26182 			 * ARP query and have ARP come back thus:
26183 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26184 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26185 			 * hw accel work. But it's too complex to get
26186 			 * the IPsec hw  acceleration approach to fit
26187 			 * well with ip_xmit_v4 doing ARP without
26188 			 * doing IPsec simplification. For now, we just
26189 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26190 			 * that we can continue with the send on the next
26191 			 * attempt.
26192 			 *
26193 			 * XXX THis should be revisited, when
26194 			 * the IPsec/IP interaction is cleaned up
26195 			 */
26196 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26197 			    " - dropping packet\n"));
26198 			freemsg(ipsec_mp);
26199 			/*
26200 			 * Call ip_xmit_v4() to trigger ARP query
26201 			 * in case the nce_state is ND_INITIAL
26202 			 */
26203 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26204 			goto drop_pkt;
26205 		}
26206 
26207 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26208 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26209 		    mblk_t *, ipsec_mp);
26210 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26211 		    ipst->ips_ipv4firewall_physical_out,
26212 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26213 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26214 		if (ipsec_mp == NULL)
26215 			goto drop_pkt;
26216 
26217 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26218 		pktxmit_state = ip_xmit_v4(mp, ire,
26219 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26220 
26221 		if ((pktxmit_state ==  SEND_FAILED) ||
26222 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26223 
26224 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26225 drop_pkt:
26226 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26227 			    ipIfStatsOutDiscards);
26228 			if (ire_need_rele)
26229 				ire_refrele(ire);
26230 			if (ire1 != NULL) {
26231 				ire_refrele(ire1);
26232 				freemsg(next_mp);
26233 			}
26234 			goto done;
26235 		}
26236 
26237 		freeb(ipsec_mp);
26238 		if (ire_need_rele)
26239 			ire_refrele(ire);
26240 
26241 		if (ire1 != NULL) {
26242 			ire = ire1;
26243 			ire_need_rele = B_TRUE;
26244 			ASSERT(next_mp);
26245 			ipsec_mp = next_mp;
26246 			mp = ipsec_mp->b_cont;
26247 			ire1 = NULL;
26248 			next_mp = NULL;
26249 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26250 		} else {
26251 			multirt_send = B_FALSE;
26252 		}
26253 	} while (multirt_send);
26254 done:
26255 	if (ill != NULL && ill_need_rele)
26256 		ill_refrele(ill);
26257 	if (ipif != NULL)
26258 		ipif_refrele(ipif);
26259 }
26260 
26261 /*
26262  * Get the ill corresponding to the specified ire, and compare its
26263  * capabilities with the protocol and algorithms specified by the
26264  * the SA obtained from ipsec_out. If they match, annotate the
26265  * ipsec_out structure to indicate that the packet needs acceleration.
26266  *
26267  *
26268  * A packet is eligible for outbound hardware acceleration if the
26269  * following conditions are satisfied:
26270  *
26271  * 1. the packet will not be fragmented
26272  * 2. the provider supports the algorithm
26273  * 3. there is no pending control message being exchanged
26274  * 4. snoop is not attached
26275  * 5. the destination address is not a broadcast or multicast address.
26276  *
26277  * Rationale:
26278  *	- Hardware drivers do not support fragmentation with
26279  *	  the current interface.
26280  *	- snoop, multicast, and broadcast may result in exposure of
26281  *	  a cleartext datagram.
26282  * We check all five of these conditions here.
26283  *
26284  * XXX would like to nuke "ire_t *" parameter here; problem is that
26285  * IRE is only way to figure out if a v4 address is a broadcast and
26286  * thus ineligible for acceleration...
26287  */
26288 static void
26289 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26290 {
26291 	ipsec_out_t *io;
26292 	mblk_t *data_mp;
26293 	uint_t plen, overhead;
26294 	ip_stack_t	*ipst;
26295 
26296 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26297 		return;
26298 
26299 	if (ill == NULL)
26300 		return;
26301 	ipst = ill->ill_ipst;
26302 	/*
26303 	 * Destination address is a broadcast or multicast.  Punt.
26304 	 */
26305 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26306 	    IRE_LOCAL)))
26307 		return;
26308 
26309 	data_mp = ipsec_mp->b_cont;
26310 
26311 	if (ill->ill_isv6) {
26312 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26313 
26314 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26315 			return;
26316 
26317 		plen = ip6h->ip6_plen;
26318 	} else {
26319 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26320 
26321 		if (CLASSD(ipha->ipha_dst))
26322 			return;
26323 
26324 		plen = ipha->ipha_length;
26325 	}
26326 	/*
26327 	 * Is there a pending DLPI control message being exchanged
26328 	 * between IP/IPsec and the DLS Provider? If there is, it
26329 	 * could be a SADB update, and the state of the DLS Provider
26330 	 * SADB might not be in sync with the SADB maintained by
26331 	 * IPsec. To avoid dropping packets or using the wrong keying
26332 	 * material, we do not accelerate this packet.
26333 	 */
26334 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26335 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26336 		    "ill_dlpi_pending! don't accelerate packet\n"));
26337 		return;
26338 	}
26339 
26340 	/*
26341 	 * Is the Provider in promiscous mode? If it does, we don't
26342 	 * accelerate the packet since it will bounce back up to the
26343 	 * listeners in the clear.
26344 	 */
26345 	if (ill->ill_promisc_on_phys) {
26346 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26347 		    "ill in promiscous mode, don't accelerate packet\n"));
26348 		return;
26349 	}
26350 
26351 	/*
26352 	 * Will the packet require fragmentation?
26353 	 */
26354 
26355 	/*
26356 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26357 	 * as is used elsewhere.
26358 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26359 	 *	+ 2-byte trailer
26360 	 */
26361 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26362 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26363 
26364 	if ((plen + overhead) > ill->ill_max_mtu)
26365 		return;
26366 
26367 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26368 
26369 	/*
26370 	 * Can the ill accelerate this IPsec protocol and algorithm
26371 	 * specified by the SA?
26372 	 */
26373 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26374 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26375 		return;
26376 	}
26377 
26378 	/*
26379 	 * Tell AH or ESP that the outbound ill is capable of
26380 	 * accelerating this packet.
26381 	 */
26382 	io->ipsec_out_is_capab_ill = B_TRUE;
26383 }
26384 
26385 /*
26386  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26387  *
26388  * If this function returns B_TRUE, the requested SA's have been filled
26389  * into the ipsec_out_*_sa pointers.
26390  *
26391  * If the function returns B_FALSE, the packet has been "consumed", most
26392  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26393  *
26394  * The SA references created by the protocol-specific "select"
26395  * function will be released when the ipsec_mp is freed, thanks to the
26396  * ipsec_out_free destructor -- see spd.c.
26397  */
26398 static boolean_t
26399 ipsec_out_select_sa(mblk_t *ipsec_mp)
26400 {
26401 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26402 	ipsec_out_t *io;
26403 	ipsec_policy_t *pp;
26404 	ipsec_action_t *ap;
26405 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26406 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26407 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26408 
26409 	if (!io->ipsec_out_secure) {
26410 		/*
26411 		 * We came here by mistake.
26412 		 * Don't bother with ipsec processing
26413 		 * We should "discourage" this path in the future.
26414 		 */
26415 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26416 		return (B_FALSE);
26417 	}
26418 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26419 	ASSERT((io->ipsec_out_policy != NULL) ||
26420 	    (io->ipsec_out_act != NULL));
26421 
26422 	ASSERT(io->ipsec_out_failed == B_FALSE);
26423 
26424 	/*
26425 	 * IPsec processing has started.
26426 	 */
26427 	io->ipsec_out_proc_begin = B_TRUE;
26428 	ap = io->ipsec_out_act;
26429 	if (ap == NULL) {
26430 		pp = io->ipsec_out_policy;
26431 		ASSERT(pp != NULL);
26432 		ap = pp->ipsp_act;
26433 		ASSERT(ap != NULL);
26434 	}
26435 
26436 	/*
26437 	 * We have an action.  now, let's select SA's.
26438 	 * (In the future, we can cache this in the conn_t..)
26439 	 */
26440 	if (ap->ipa_want_esp) {
26441 		if (io->ipsec_out_esp_sa == NULL) {
26442 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26443 			    IPPROTO_ESP);
26444 		}
26445 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26446 	}
26447 
26448 	if (ap->ipa_want_ah) {
26449 		if (io->ipsec_out_ah_sa == NULL) {
26450 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26451 			    IPPROTO_AH);
26452 		}
26453 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26454 		/*
26455 		 * The ESP and AH processing order needs to be preserved
26456 		 * when both protocols are required (ESP should be applied
26457 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26458 		 * when both ESP and AH are required, and an AH ACQUIRE
26459 		 * is needed.
26460 		 */
26461 		if (ap->ipa_want_esp && need_ah_acquire)
26462 			need_esp_acquire = B_TRUE;
26463 	}
26464 
26465 	/*
26466 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26467 	 * Release SAs that got referenced, but will not be used until we
26468 	 * acquire _all_ of the SAs we need.
26469 	 */
26470 	if (need_ah_acquire || need_esp_acquire) {
26471 		if (io->ipsec_out_ah_sa != NULL) {
26472 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26473 			io->ipsec_out_ah_sa = NULL;
26474 		}
26475 		if (io->ipsec_out_esp_sa != NULL) {
26476 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26477 			io->ipsec_out_esp_sa = NULL;
26478 		}
26479 
26480 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26481 		return (B_FALSE);
26482 	}
26483 
26484 	return (B_TRUE);
26485 }
26486 
26487 /*
26488  * Process an IPSEC_OUT message and see what you can
26489  * do with it.
26490  * IPQoS Notes:
26491  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26492  * IPsec.
26493  * XXX would like to nuke ire_t.
26494  * XXX ill_index better be "real"
26495  */
26496 void
26497 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26498 {
26499 	ipsec_out_t *io;
26500 	ipsec_policy_t *pp;
26501 	ipsec_action_t *ap;
26502 	ipha_t *ipha;
26503 	ip6_t *ip6h;
26504 	mblk_t *mp;
26505 	ill_t *ill;
26506 	zoneid_t zoneid;
26507 	ipsec_status_t ipsec_rc;
26508 	boolean_t ill_need_rele = B_FALSE;
26509 	ip_stack_t	*ipst;
26510 	ipsec_stack_t	*ipss;
26511 
26512 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26513 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26514 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26515 	ipst = io->ipsec_out_ns->netstack_ip;
26516 	mp = ipsec_mp->b_cont;
26517 
26518 	/*
26519 	 * Initiate IPPF processing. We do it here to account for packets
26520 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26521 	 * We can check for ipsec_out_proc_begin even for such packets, as
26522 	 * they will always be false (asserted below).
26523 	 */
26524 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26525 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26526 		    io->ipsec_out_ill_index : ill_index);
26527 		if (mp == NULL) {
26528 			ip2dbg(("ipsec_out_process: packet dropped "\
26529 			    "during IPPF processing\n"));
26530 			freeb(ipsec_mp);
26531 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26532 			return;
26533 		}
26534 	}
26535 
26536 	if (!io->ipsec_out_secure) {
26537 		/*
26538 		 * We came here by mistake.
26539 		 * Don't bother with ipsec processing
26540 		 * Should "discourage" this path in the future.
26541 		 */
26542 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26543 		goto done;
26544 	}
26545 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26546 	ASSERT((io->ipsec_out_policy != NULL) ||
26547 	    (io->ipsec_out_act != NULL));
26548 	ASSERT(io->ipsec_out_failed == B_FALSE);
26549 
26550 	ipss = ipst->ips_netstack->netstack_ipsec;
26551 	if (!ipsec_loaded(ipss)) {
26552 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26553 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26554 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26555 		} else {
26556 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26557 		}
26558 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26559 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26560 		    &ipss->ipsec_dropper);
26561 		return;
26562 	}
26563 
26564 	/*
26565 	 * IPsec processing has started.
26566 	 */
26567 	io->ipsec_out_proc_begin = B_TRUE;
26568 	ap = io->ipsec_out_act;
26569 	if (ap == NULL) {
26570 		pp = io->ipsec_out_policy;
26571 		ASSERT(pp != NULL);
26572 		ap = pp->ipsp_act;
26573 		ASSERT(ap != NULL);
26574 	}
26575 
26576 	/*
26577 	 * Save the outbound ill index. When the packet comes back
26578 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26579 	 * before sending it the accelerated packet.
26580 	 */
26581 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26582 		int ifindex;
26583 		ill = ire_to_ill(ire);
26584 		ifindex = ill->ill_phyint->phyint_ifindex;
26585 		io->ipsec_out_capab_ill_index = ifindex;
26586 	}
26587 
26588 	/*
26589 	 * The order of processing is first insert a IP header if needed.
26590 	 * Then insert the ESP header and then the AH header.
26591 	 */
26592 	if ((io->ipsec_out_se_done == B_FALSE) &&
26593 	    (ap->ipa_want_se)) {
26594 		/*
26595 		 * First get the outer IP header before sending
26596 		 * it to ESP.
26597 		 */
26598 		ipha_t *oipha, *iipha;
26599 		mblk_t *outer_mp, *inner_mp;
26600 
26601 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26602 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26603 			    "ipsec_out_process: "
26604 			    "Self-Encapsulation failed: Out of memory\n");
26605 			freemsg(ipsec_mp);
26606 			if (ill != NULL) {
26607 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26608 			} else {
26609 				BUMP_MIB(&ipst->ips_ip_mib,
26610 				    ipIfStatsOutDiscards);
26611 			}
26612 			return;
26613 		}
26614 		inner_mp = ipsec_mp->b_cont;
26615 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26616 		oipha = (ipha_t *)outer_mp->b_rptr;
26617 		iipha = (ipha_t *)inner_mp->b_rptr;
26618 		*oipha = *iipha;
26619 		outer_mp->b_wptr += sizeof (ipha_t);
26620 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26621 		    sizeof (ipha_t));
26622 		oipha->ipha_protocol = IPPROTO_ENCAP;
26623 		oipha->ipha_version_and_hdr_length =
26624 		    IP_SIMPLE_HDR_VERSION;
26625 		oipha->ipha_hdr_checksum = 0;
26626 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26627 		outer_mp->b_cont = inner_mp;
26628 		ipsec_mp->b_cont = outer_mp;
26629 
26630 		io->ipsec_out_se_done = B_TRUE;
26631 		io->ipsec_out_tunnel = B_TRUE;
26632 	}
26633 
26634 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26635 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26636 	    !ipsec_out_select_sa(ipsec_mp))
26637 		return;
26638 
26639 	/*
26640 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26641 	 * to do the heavy lifting.
26642 	 */
26643 	zoneid = io->ipsec_out_zoneid;
26644 	ASSERT(zoneid != ALL_ZONES);
26645 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26646 		ASSERT(io->ipsec_out_esp_sa != NULL);
26647 		io->ipsec_out_esp_done = B_TRUE;
26648 		/*
26649 		 * Note that since hw accel can only apply one transform,
26650 		 * not two, we skip hw accel for ESP if we also have AH
26651 		 * This is an design limitation of the interface
26652 		 * which should be revisited.
26653 		 */
26654 		ASSERT(ire != NULL);
26655 		if (io->ipsec_out_ah_sa == NULL) {
26656 			ill = (ill_t *)ire->ire_stq->q_ptr;
26657 			ipsec_out_is_accelerated(ipsec_mp,
26658 			    io->ipsec_out_esp_sa, ill, ire);
26659 		}
26660 
26661 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26662 		switch (ipsec_rc) {
26663 		case IPSEC_STATUS_SUCCESS:
26664 			break;
26665 		case IPSEC_STATUS_FAILED:
26666 			if (ill != NULL) {
26667 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26668 			} else {
26669 				BUMP_MIB(&ipst->ips_ip_mib,
26670 				    ipIfStatsOutDiscards);
26671 			}
26672 			/* FALLTHRU */
26673 		case IPSEC_STATUS_PENDING:
26674 			return;
26675 		}
26676 	}
26677 
26678 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26679 		ASSERT(io->ipsec_out_ah_sa != NULL);
26680 		io->ipsec_out_ah_done = B_TRUE;
26681 		if (ire == NULL) {
26682 			int idx = io->ipsec_out_capab_ill_index;
26683 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26684 			    NULL, NULL, NULL, NULL, ipst);
26685 			ill_need_rele = B_TRUE;
26686 		} else {
26687 			ill = (ill_t *)ire->ire_stq->q_ptr;
26688 		}
26689 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26690 		    ire);
26691 
26692 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26693 		switch (ipsec_rc) {
26694 		case IPSEC_STATUS_SUCCESS:
26695 			break;
26696 		case IPSEC_STATUS_FAILED:
26697 			if (ill != NULL) {
26698 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26699 			} else {
26700 				BUMP_MIB(&ipst->ips_ip_mib,
26701 				    ipIfStatsOutDiscards);
26702 			}
26703 			/* FALLTHRU */
26704 		case IPSEC_STATUS_PENDING:
26705 			if (ill != NULL && ill_need_rele)
26706 				ill_refrele(ill);
26707 			return;
26708 		}
26709 	}
26710 	/*
26711 	 * We are done with IPsec processing. Send it over
26712 	 * the wire.
26713 	 */
26714 done:
26715 	mp = ipsec_mp->b_cont;
26716 	ipha = (ipha_t *)mp->b_rptr;
26717 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26718 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26719 	} else {
26720 		ip6h = (ip6_t *)ipha;
26721 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26722 	}
26723 	if (ill != NULL && ill_need_rele)
26724 		ill_refrele(ill);
26725 }
26726 
26727 /* ARGSUSED */
26728 void
26729 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26730 {
26731 	opt_restart_t	*or;
26732 	int	err;
26733 	conn_t	*connp;
26734 
26735 	ASSERT(CONN_Q(q));
26736 	connp = Q_TO_CONN(q);
26737 
26738 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26739 	or = (opt_restart_t *)first_mp->b_rptr;
26740 	/*
26741 	 * We don't need to pass any credentials here since this is just
26742 	 * a restart. The credentials are passed in when svr4_optcom_req
26743 	 * is called the first time (from ip_wput_nondata).
26744 	 */
26745 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26746 		err = svr4_optcom_req(q, first_mp, NULL,
26747 		    &ip_opt_obj, B_FALSE);
26748 	} else {
26749 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26750 		err = tpi_optcom_req(q, first_mp, NULL,
26751 		    &ip_opt_obj, B_FALSE);
26752 	}
26753 	if (err != EINPROGRESS) {
26754 		/* operation is done */
26755 		CONN_OPER_PENDING_DONE(connp);
26756 	}
26757 }
26758 
26759 /*
26760  * ioctls that go through a down/up sequence may need to wait for the down
26761  * to complete. This involves waiting for the ire and ipif refcnts to go down
26762  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26763  */
26764 /* ARGSUSED */
26765 void
26766 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26767 {
26768 	struct iocblk *iocp;
26769 	mblk_t *mp1;
26770 	ip_ioctl_cmd_t *ipip;
26771 	int err;
26772 	sin_t	*sin;
26773 	struct lifreq *lifr;
26774 	struct ifreq *ifr;
26775 
26776 	iocp = (struct iocblk *)mp->b_rptr;
26777 	ASSERT(ipsq != NULL);
26778 	/* Existence of mp1 verified in ip_wput_nondata */
26779 	mp1 = mp->b_cont->b_cont;
26780 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26781 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26782 		/*
26783 		 * Special case where ipsq_current_ipif is not set:
26784 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26785 		 * ill could also have become part of a ipmp group in the
26786 		 * process, we are here as were not able to complete the
26787 		 * operation in ipif_set_values because we could not become
26788 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26789 		 * will not be set so we need to set it.
26790 		 */
26791 		ill_t *ill = q->q_ptr;
26792 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26793 	}
26794 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26795 
26796 	if (ipip->ipi_cmd_type == IF_CMD) {
26797 		/* This a old style SIOC[GS]IF* command */
26798 		ifr = (struct ifreq *)mp1->b_rptr;
26799 		sin = (sin_t *)&ifr->ifr_addr;
26800 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26801 		/* This a new style SIOC[GS]LIF* command */
26802 		lifr = (struct lifreq *)mp1->b_rptr;
26803 		sin = (sin_t *)&lifr->lifr_addr;
26804 	} else {
26805 		sin = NULL;
26806 	}
26807 
26808 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26809 	    ipip, mp1->b_rptr);
26810 
26811 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26812 }
26813 
26814 /*
26815  * ioctl processing
26816  *
26817  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26818  * the ioctl command in the ioctl tables, determines the copyin data size
26819  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26820  *
26821  * ioctl processing then continues when the M_IOCDATA makes its way down to
26822  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26823  * associated 'conn' is refheld till the end of the ioctl and the general
26824  * ioctl processing function ip_process_ioctl() is called to extract the
26825  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26826  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26827  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26828  * is used to extract the ioctl's arguments.
26829  *
26830  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26831  * so goes thru the serialization primitive ipsq_try_enter. Then the
26832  * appropriate function to handle the ioctl is called based on the entry in
26833  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26834  * which also refreleases the 'conn' that was refheld at the start of the
26835  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26836  *
26837  * Many exclusive ioctls go thru an internal down up sequence as part of
26838  * the operation. For example an attempt to change the IP address of an
26839  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26840  * does all the cleanup such as deleting all ires that use this address.
26841  * Then we need to wait till all references to the interface go away.
26842  */
26843 void
26844 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26845 {
26846 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26847 	ip_ioctl_cmd_t *ipip = arg;
26848 	ip_extract_func_t *extract_funcp;
26849 	cmd_info_t ci;
26850 	int err;
26851 	boolean_t entered_ipsq = B_FALSE;
26852 
26853 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26854 
26855 	if (ipip == NULL)
26856 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26857 
26858 	/*
26859 	 * SIOCLIFADDIF needs to go thru a special path since the
26860 	 * ill may not exist yet. This happens in the case of lo0
26861 	 * which is created using this ioctl.
26862 	 */
26863 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26864 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26865 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26866 		return;
26867 	}
26868 
26869 	ci.ci_ipif = NULL;
26870 	if (ipip->ipi_cmd_type == MISC_CMD) {
26871 		/*
26872 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26873 		 */
26874 		if (ipip->ipi_cmd == IF_UNITSEL) {
26875 			/* ioctl comes down the ill */
26876 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26877 			ipif_refhold(ci.ci_ipif);
26878 		}
26879 		err = 0;
26880 		ci.ci_sin = NULL;
26881 		ci.ci_sin6 = NULL;
26882 		ci.ci_lifr = NULL;
26883 	} else {
26884 		switch (ipip->ipi_cmd_type) {
26885 		case IF_CMD:
26886 		case LIF_CMD:
26887 			extract_funcp = ip_extract_lifreq;
26888 			break;
26889 
26890 		case ARP_CMD:
26891 		case XARP_CMD:
26892 			extract_funcp = ip_extract_arpreq;
26893 			break;
26894 
26895 		case TUN_CMD:
26896 			extract_funcp = ip_extract_tunreq;
26897 			break;
26898 
26899 		case MSFILT_CMD:
26900 			extract_funcp = ip_extract_msfilter;
26901 			break;
26902 
26903 		default:
26904 			ASSERT(0);
26905 		}
26906 
26907 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26908 		if (err != 0) {
26909 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26910 			return;
26911 		}
26912 
26913 		/*
26914 		 * All of the extraction functions return a refheld ipif.
26915 		 */
26916 		ASSERT(ci.ci_ipif != NULL);
26917 	}
26918 
26919 	/*
26920 	 * If ipsq is non-null, we are already being called exclusively
26921 	 */
26922 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26923 	if (!(ipip->ipi_flags & IPI_WR)) {
26924 		/*
26925 		 * A return value of EINPROGRESS means the ioctl is
26926 		 * either queued and waiting for some reason or has
26927 		 * already completed.
26928 		 */
26929 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26930 		    ci.ci_lifr);
26931 		if (ci.ci_ipif != NULL)
26932 			ipif_refrele(ci.ci_ipif);
26933 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26934 		return;
26935 	}
26936 
26937 	ASSERT(ci.ci_ipif != NULL);
26938 
26939 	if (ipsq == NULL) {
26940 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26941 		    ip_process_ioctl, NEW_OP, B_TRUE);
26942 		entered_ipsq = B_TRUE;
26943 	}
26944 	/*
26945 	 * Release the ipif so that ipif_down and friends that wait for
26946 	 * references to go away are not misled about the current ipif_refcnt
26947 	 * values. We are writer so we can access the ipif even after releasing
26948 	 * the ipif.
26949 	 */
26950 	ipif_refrele(ci.ci_ipif);
26951 	if (ipsq == NULL)
26952 		return;
26953 
26954 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26955 
26956 	/*
26957 	 * For most set ioctls that come here, this serves as a single point
26958 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26959 	 * be any new references to the ipif. This helps functions that go
26960 	 * through this path and end up trying to wait for the refcnts
26961 	 * associated with the ipif to go down to zero. Some exceptions are
26962 	 * Failover, Failback, and Groupname commands that operate on more than
26963 	 * just the ci.ci_ipif. These commands internally determine the
26964 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26965 	 * flags on that set. Another exception is the Removeif command that
26966 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26967 	 * ipif to operate on.
26968 	 */
26969 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26970 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26971 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26972 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26973 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26974 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26975 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26976 
26977 	/*
26978 	 * A return value of EINPROGRESS means the ioctl is
26979 	 * either queued and waiting for some reason or has
26980 	 * already completed.
26981 	 */
26982 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26983 
26984 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26985 
26986 	if (entered_ipsq)
26987 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26988 }
26989 
26990 /*
26991  * Complete the ioctl. Typically ioctls use the mi package and need to
26992  * do mi_copyout/mi_copy_done.
26993  */
26994 void
26995 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26996 {
26997 	conn_t	*connp = NULL;
26998 
26999 	if (err == EINPROGRESS)
27000 		return;
27001 
27002 	if (CONN_Q(q)) {
27003 		connp = Q_TO_CONN(q);
27004 		ASSERT(connp->conn_ref >= 2);
27005 	}
27006 
27007 	switch (mode) {
27008 	case COPYOUT:
27009 		if (err == 0)
27010 			mi_copyout(q, mp);
27011 		else
27012 			mi_copy_done(q, mp, err);
27013 		break;
27014 
27015 	case NO_COPYOUT:
27016 		mi_copy_done(q, mp, err);
27017 		break;
27018 
27019 	default:
27020 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27021 		break;
27022 	}
27023 
27024 	/*
27025 	 * The refhold placed at the start of the ioctl is released here.
27026 	 */
27027 	if (connp != NULL)
27028 		CONN_OPER_PENDING_DONE(connp);
27029 
27030 	if (ipsq != NULL)
27031 		ipsq_current_finish(ipsq);
27032 }
27033 
27034 /*
27035  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27036  */
27037 /* ARGSUSED */
27038 void
27039 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27040 {
27041 	conn_t *connp = arg;
27042 	tcp_t	*tcp;
27043 
27044 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27045 	tcp = connp->conn_tcp;
27046 
27047 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27048 		freemsg(mp);
27049 	else
27050 		tcp_rput_other(tcp, mp);
27051 	CONN_OPER_PENDING_DONE(connp);
27052 }
27053 
27054 /* Called from ip_wput for all non data messages */
27055 /* ARGSUSED */
27056 void
27057 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27058 {
27059 	mblk_t		*mp1;
27060 	ire_t		*ire, *fake_ire;
27061 	ill_t		*ill;
27062 	struct iocblk	*iocp;
27063 	ip_ioctl_cmd_t	*ipip;
27064 	cred_t		*cr;
27065 	conn_t		*connp;
27066 	int		err;
27067 	nce_t		*nce;
27068 	ipif_t		*ipif;
27069 	ip_stack_t	*ipst;
27070 	char		*proto_str;
27071 
27072 	if (CONN_Q(q)) {
27073 		connp = Q_TO_CONN(q);
27074 		ipst = connp->conn_netstack->netstack_ip;
27075 	} else {
27076 		connp = NULL;
27077 		ipst = ILLQ_TO_IPST(q);
27078 	}
27079 
27080 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27081 
27082 	switch (DB_TYPE(mp)) {
27083 	case M_IOCTL:
27084 		/*
27085 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27086 		 * will arrange to copy in associated control structures.
27087 		 */
27088 		ip_sioctl_copyin_setup(q, mp);
27089 		return;
27090 	case M_IOCDATA:
27091 		/*
27092 		 * Ensure that this is associated with one of our trans-
27093 		 * parent ioctls.  If it's not ours, discard it if we're
27094 		 * running as a driver, or pass it on if we're a module.
27095 		 */
27096 		iocp = (struct iocblk *)mp->b_rptr;
27097 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27098 		if (ipip == NULL) {
27099 			if (q->q_next == NULL) {
27100 				goto nak;
27101 			} else {
27102 				putnext(q, mp);
27103 			}
27104 			return;
27105 		}
27106 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27107 			/*
27108 			 * the ioctl is one we recognise, but is not
27109 			 * consumed by IP as a module, pass M_IOCDATA
27110 			 * for processing downstream, but only for
27111 			 * common Streams ioctls.
27112 			 */
27113 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27114 				putnext(q, mp);
27115 				return;
27116 			} else {
27117 				goto nak;
27118 			}
27119 		}
27120 
27121 		/* IOCTL continuation following copyin or copyout. */
27122 		if (mi_copy_state(q, mp, NULL) == -1) {
27123 			/*
27124 			 * The copy operation failed.  mi_copy_state already
27125 			 * cleaned up, so we're out of here.
27126 			 */
27127 			return;
27128 		}
27129 		/*
27130 		 * If we just completed a copy in, we become writer and
27131 		 * continue processing in ip_sioctl_copyin_done.  If it
27132 		 * was a copy out, we call mi_copyout again.  If there is
27133 		 * nothing more to copy out, it will complete the IOCTL.
27134 		 */
27135 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27136 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27137 				mi_copy_done(q, mp, EPROTO);
27138 				return;
27139 			}
27140 			/*
27141 			 * Check for cases that need more copying.  A return
27142 			 * value of 0 means a second copyin has been started,
27143 			 * so we return; a return value of 1 means no more
27144 			 * copying is needed, so we continue.
27145 			 */
27146 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27147 			    MI_COPY_COUNT(mp) == 1) {
27148 				if (ip_copyin_msfilter(q, mp) == 0)
27149 					return;
27150 			}
27151 			/*
27152 			 * Refhold the conn, till the ioctl completes. This is
27153 			 * needed in case the ioctl ends up in the pending mp
27154 			 * list. Every mp in the ill_pending_mp list and
27155 			 * the ipsq_pending_mp must have a refhold on the conn
27156 			 * to resume processing. The refhold is released when
27157 			 * the ioctl completes. (normally or abnormally)
27158 			 * In all cases ip_ioctl_finish is called to finish
27159 			 * the ioctl.
27160 			 */
27161 			if (connp != NULL) {
27162 				/* This is not a reentry */
27163 				ASSERT(ipsq == NULL);
27164 				CONN_INC_REF(connp);
27165 			} else {
27166 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27167 					mi_copy_done(q, mp, EINVAL);
27168 					return;
27169 				}
27170 			}
27171 
27172 			ip_process_ioctl(ipsq, q, mp, ipip);
27173 
27174 		} else {
27175 			mi_copyout(q, mp);
27176 		}
27177 		return;
27178 nak:
27179 		iocp->ioc_error = EINVAL;
27180 		mp->b_datap->db_type = M_IOCNAK;
27181 		iocp->ioc_count = 0;
27182 		qreply(q, mp);
27183 		return;
27184 
27185 	case M_IOCNAK:
27186 		/*
27187 		 * The only way we could get here is if a resolver didn't like
27188 		 * an IOCTL we sent it.	 This shouldn't happen.
27189 		 */
27190 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27191 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27192 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27193 		freemsg(mp);
27194 		return;
27195 	case M_IOCACK:
27196 		/* /dev/ip shouldn't see this */
27197 		if (CONN_Q(q))
27198 			goto nak;
27199 
27200 		/* Finish socket ioctls passed through to ARP. */
27201 		ip_sioctl_iocack(q, mp);
27202 		return;
27203 	case M_FLUSH:
27204 		if (*mp->b_rptr & FLUSHW)
27205 			flushq(q, FLUSHALL);
27206 		if (q->q_next) {
27207 			putnext(q, mp);
27208 			return;
27209 		}
27210 		if (*mp->b_rptr & FLUSHR) {
27211 			*mp->b_rptr &= ~FLUSHW;
27212 			qreply(q, mp);
27213 			return;
27214 		}
27215 		freemsg(mp);
27216 		return;
27217 	case IRE_DB_REQ_TYPE:
27218 		if (connp == NULL) {
27219 			proto_str = "IRE_DB_REQ_TYPE";
27220 			goto protonak;
27221 		}
27222 		/* An Upper Level Protocol wants a copy of an IRE. */
27223 		ip_ire_req(q, mp);
27224 		return;
27225 	case M_CTL:
27226 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27227 			break;
27228 
27229 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27230 		    TUN_HELLO) {
27231 			ASSERT(connp != NULL);
27232 			connp->conn_flags |= IPCL_IPTUN;
27233 			freeb(mp);
27234 			return;
27235 		}
27236 
27237 		/* M_CTL messages are used by ARP to tell us things. */
27238 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27239 			break;
27240 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27241 		case AR_ENTRY_SQUERY:
27242 			ip_wput_ctl(q, mp);
27243 			return;
27244 		case AR_CLIENT_NOTIFY:
27245 			ip_arp_news(q, mp);
27246 			return;
27247 		case AR_DLPIOP_DONE:
27248 			ASSERT(q->q_next != NULL);
27249 			ill = (ill_t *)q->q_ptr;
27250 			/* qwriter_ip releases the refhold */
27251 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27252 			ill_refhold(ill);
27253 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27254 			return;
27255 		case AR_ARP_CLOSING:
27256 			/*
27257 			 * ARP (above us) is closing. If no ARP bringup is
27258 			 * currently pending, ack the message so that ARP
27259 			 * can complete its close. Also mark ill_arp_closing
27260 			 * so that new ARP bringups will fail. If any
27261 			 * ARP bringup is currently in progress, we will
27262 			 * ack this when the current ARP bringup completes.
27263 			 */
27264 			ASSERT(q->q_next != NULL);
27265 			ill = (ill_t *)q->q_ptr;
27266 			mutex_enter(&ill->ill_lock);
27267 			ill->ill_arp_closing = 1;
27268 			if (!ill->ill_arp_bringup_pending) {
27269 				mutex_exit(&ill->ill_lock);
27270 				qreply(q, mp);
27271 			} else {
27272 				mutex_exit(&ill->ill_lock);
27273 				freemsg(mp);
27274 			}
27275 			return;
27276 		case AR_ARP_EXTEND:
27277 			/*
27278 			 * The ARP module above us is capable of duplicate
27279 			 * address detection.  Old ATM drivers will not send
27280 			 * this message.
27281 			 */
27282 			ASSERT(q->q_next != NULL);
27283 			ill = (ill_t *)q->q_ptr;
27284 			ill->ill_arp_extend = B_TRUE;
27285 			freemsg(mp);
27286 			return;
27287 		default:
27288 			break;
27289 		}
27290 		break;
27291 	case M_PROTO:
27292 	case M_PCPROTO:
27293 		/*
27294 		 * The only PROTO messages we expect are ULP binds and
27295 		 * copies of option negotiation acknowledgements.
27296 		 */
27297 		switch (((union T_primitives *)mp->b_rptr)->type) {
27298 		case O_T_BIND_REQ:
27299 		case T_BIND_REQ: {
27300 			/* Request can get queued in bind */
27301 			if (connp == NULL) {
27302 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27303 				goto protonak;
27304 			}
27305 			/*
27306 			 * The transports except SCTP call ip_bind_{v4,v6}()
27307 			 * directly instead of a a putnext. SCTP doesn't
27308 			 * generate any T_BIND_REQ since it has its own
27309 			 * fanout data structures. However, ESP and AH
27310 			 * come in for regular binds; all other cases are
27311 			 * bind retries.
27312 			 */
27313 			ASSERT(!IPCL_IS_SCTP(connp));
27314 
27315 			/* Don't increment refcnt if this is a re-entry */
27316 			if (ipsq == NULL)
27317 				CONN_INC_REF(connp);
27318 
27319 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27320 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27321 			if (mp == NULL)
27322 				return;
27323 			if (IPCL_IS_TCP(connp)) {
27324 				/*
27325 				 * In the case of TCP endpoint we
27326 				 * come here only for bind retries
27327 				 */
27328 				ASSERT(ipsq != NULL);
27329 				CONN_INC_REF(connp);
27330 				squeue_fill(connp->conn_sqp, mp,
27331 				    ip_resume_tcp_bind, connp,
27332 				    SQTAG_BIND_RETRY);
27333 			} else if (IPCL_IS_UDP(connp)) {
27334 				/*
27335 				 * In the case of UDP endpoint we
27336 				 * come here only for bind retries
27337 				 */
27338 				ASSERT(ipsq != NULL);
27339 				udp_resume_bind(connp, mp);
27340 			} else if (IPCL_IS_RAWIP(connp)) {
27341 				/*
27342 				 * In the case of RAWIP endpoint we
27343 				 * come here only for bind retries
27344 				 */
27345 				ASSERT(ipsq != NULL);
27346 				rawip_resume_bind(connp, mp);
27347 			} else {
27348 				/* The case of AH and ESP */
27349 				qreply(q, mp);
27350 				CONN_OPER_PENDING_DONE(connp);
27351 			}
27352 			return;
27353 		}
27354 		case T_SVR4_OPTMGMT_REQ:
27355 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27356 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27357 
27358 			if (connp == NULL) {
27359 				proto_str = "T_SVR4_OPTMGMT_REQ";
27360 				goto protonak;
27361 			}
27362 
27363 			if (!snmpcom_req(q, mp, ip_snmp_set,
27364 			    ip_snmp_get, cr)) {
27365 				/*
27366 				 * Call svr4_optcom_req so that it can
27367 				 * generate the ack. We don't come here
27368 				 * if this operation is being restarted.
27369 				 * ip_restart_optmgmt will drop the conn ref.
27370 				 * In the case of ipsec option after the ipsec
27371 				 * load is complete conn_restart_ipsec_waiter
27372 				 * drops the conn ref.
27373 				 */
27374 				ASSERT(ipsq == NULL);
27375 				CONN_INC_REF(connp);
27376 				if (ip_check_for_ipsec_opt(q, mp))
27377 					return;
27378 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27379 				    B_FALSE);
27380 				if (err != EINPROGRESS) {
27381 					/* Operation is done */
27382 					CONN_OPER_PENDING_DONE(connp);
27383 				}
27384 			}
27385 			return;
27386 		case T_OPTMGMT_REQ:
27387 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27388 			/*
27389 			 * Note: No snmpcom_req support through new
27390 			 * T_OPTMGMT_REQ.
27391 			 * Call tpi_optcom_req so that it can
27392 			 * generate the ack.
27393 			 */
27394 			if (connp == NULL) {
27395 				proto_str = "T_OPTMGMT_REQ";
27396 				goto protonak;
27397 			}
27398 
27399 			ASSERT(ipsq == NULL);
27400 			/*
27401 			 * We don't come here for restart. ip_restart_optmgmt
27402 			 * will drop the conn ref. In the case of ipsec option
27403 			 * after the ipsec load is complete
27404 			 * conn_restart_ipsec_waiter drops the conn ref.
27405 			 */
27406 			CONN_INC_REF(connp);
27407 			if (ip_check_for_ipsec_opt(q, mp))
27408 				return;
27409 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27410 			if (err != EINPROGRESS) {
27411 				/* Operation is done */
27412 				CONN_OPER_PENDING_DONE(connp);
27413 			}
27414 			return;
27415 		case T_UNBIND_REQ:
27416 			if (connp == NULL) {
27417 				proto_str = "T_UNBIND_REQ";
27418 				goto protonak;
27419 			}
27420 			mp = ip_unbind(q, mp);
27421 			qreply(q, mp);
27422 			return;
27423 		default:
27424 			/*
27425 			 * Have to drop any DLPI messages coming down from
27426 			 * arp (such as an info_req which would cause ip
27427 			 * to receive an extra info_ack if it was passed
27428 			 * through.
27429 			 */
27430 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27431 			    (int)*(uint_t *)mp->b_rptr));
27432 			freemsg(mp);
27433 			return;
27434 		}
27435 		/* NOTREACHED */
27436 	case IRE_DB_TYPE: {
27437 		nce_t		*nce;
27438 		ill_t		*ill;
27439 		in6_addr_t	gw_addr_v6;
27440 
27441 
27442 		/*
27443 		 * This is a response back from a resolver.  It
27444 		 * consists of a message chain containing:
27445 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27446 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27447 		 * The LL_HDR_MBLK is the DLPI header to use to get
27448 		 * the attached packet, and subsequent ones for the
27449 		 * same destination, transmitted.
27450 		 */
27451 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27452 			break;
27453 		/*
27454 		 * First, check to make sure the resolution succeeded.
27455 		 * If it failed, the second mblk will be empty.
27456 		 * If it is, free the chain, dropping the packet.
27457 		 * (We must ire_delete the ire; that frees the ire mblk)
27458 		 * We're doing this now to support PVCs for ATM; it's
27459 		 * a partial xresolv implementation. When we fully implement
27460 		 * xresolv interfaces, instead of freeing everything here
27461 		 * we'll initiate neighbor discovery.
27462 		 *
27463 		 * For v4 (ARP and other external resolvers) the resolver
27464 		 * frees the message, so no check is needed. This check
27465 		 * is required, though, for a full xresolve implementation.
27466 		 * Including this code here now both shows how external
27467 		 * resolvers can NACK a resolution request using an
27468 		 * existing design that has no specific provisions for NACKs,
27469 		 * and also takes into account that the current non-ARP
27470 		 * external resolver has been coded to use this method of
27471 		 * NACKing for all IPv6 (xresolv) cases,
27472 		 * whether our xresolv implementation is complete or not.
27473 		 *
27474 		 */
27475 		ire = (ire_t *)mp->b_rptr;
27476 		ill = ire_to_ill(ire);
27477 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27478 		if (mp1->b_rptr == mp1->b_wptr) {
27479 			if (ire->ire_ipversion == IPV6_VERSION) {
27480 				/*
27481 				 * XRESOLV interface.
27482 				 */
27483 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27484 				mutex_enter(&ire->ire_lock);
27485 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27486 				mutex_exit(&ire->ire_lock);
27487 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27488 					nce = ndp_lookup_v6(ill,
27489 					    &ire->ire_addr_v6, B_FALSE);
27490 				} else {
27491 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27492 					    B_FALSE);
27493 				}
27494 				if (nce != NULL) {
27495 					nce_resolv_failed(nce);
27496 					ndp_delete(nce);
27497 					NCE_REFRELE(nce);
27498 				}
27499 			}
27500 			mp->b_cont = NULL;
27501 			freemsg(mp1);		/* frees the pkt as well */
27502 			ASSERT(ire->ire_nce == NULL);
27503 			ire_delete((ire_t *)mp->b_rptr);
27504 			return;
27505 		}
27506 
27507 		/*
27508 		 * Split them into IRE_MBLK and pkt and feed it into
27509 		 * ire_add_then_send. Then in ire_add_then_send
27510 		 * the IRE will be added, and then the packet will be
27511 		 * run back through ip_wput. This time it will make
27512 		 * it to the wire.
27513 		 */
27514 		mp->b_cont = NULL;
27515 		mp = mp1->b_cont;		/* now, mp points to pkt */
27516 		mp1->b_cont = NULL;
27517 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27518 		if (ire->ire_ipversion == IPV6_VERSION) {
27519 			/*
27520 			 * XRESOLV interface. Find the nce and put a copy
27521 			 * of the dl_unitdata_req in nce_res_mp
27522 			 */
27523 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27524 			mutex_enter(&ire->ire_lock);
27525 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27526 			mutex_exit(&ire->ire_lock);
27527 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27528 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27529 				    B_FALSE);
27530 			} else {
27531 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27532 			}
27533 			if (nce != NULL) {
27534 				/*
27535 				 * We have to protect nce_res_mp here
27536 				 * from being accessed by other threads
27537 				 * while we change the mblk pointer.
27538 				 * Other functions will also lock the nce when
27539 				 * accessing nce_res_mp.
27540 				 *
27541 				 * The reason we change the mblk pointer
27542 				 * here rather than copying the resolved address
27543 				 * into the template is that, unlike with
27544 				 * ethernet, we have no guarantee that the
27545 				 * resolved address length will be
27546 				 * smaller than or equal to the lla length
27547 				 * with which the template was allocated,
27548 				 * (for ethernet, they're equal)
27549 				 * so we have to use the actual resolved
27550 				 * address mblk - which holds the real
27551 				 * dl_unitdata_req with the resolved address.
27552 				 *
27553 				 * Doing this is the same behavior as was
27554 				 * previously used in the v4 ARP case.
27555 				 */
27556 				mutex_enter(&nce->nce_lock);
27557 				if (nce->nce_res_mp != NULL)
27558 					freemsg(nce->nce_res_mp);
27559 				nce->nce_res_mp = mp1;
27560 				mutex_exit(&nce->nce_lock);
27561 				/*
27562 				 * We do a fastpath probe here because
27563 				 * we have resolved the address without
27564 				 * using Neighbor Discovery.
27565 				 * In the non-XRESOLV v6 case, the fastpath
27566 				 * probe is done right after neighbor
27567 				 * discovery completes.
27568 				 */
27569 				if (nce->nce_res_mp != NULL) {
27570 					int res;
27571 					nce_fastpath_list_add(nce);
27572 					res = ill_fastpath_probe(ill,
27573 					    nce->nce_res_mp);
27574 					if (res != 0 && res != EAGAIN)
27575 						nce_fastpath_list_delete(nce);
27576 				}
27577 
27578 				ire_add_then_send(q, ire, mp);
27579 				/*
27580 				 * Now we have to clean out any packets
27581 				 * that may have been queued on the nce
27582 				 * while it was waiting for address resolution
27583 				 * to complete.
27584 				 */
27585 				mutex_enter(&nce->nce_lock);
27586 				mp1 = nce->nce_qd_mp;
27587 				nce->nce_qd_mp = NULL;
27588 				mutex_exit(&nce->nce_lock);
27589 				while (mp1 != NULL) {
27590 					mblk_t *nxt_mp;
27591 					queue_t *fwdq = NULL;
27592 					ill_t   *inbound_ill;
27593 					uint_t ifindex;
27594 
27595 					nxt_mp = mp1->b_next;
27596 					mp1->b_next = NULL;
27597 					/*
27598 					 * Retrieve ifindex stored in
27599 					 * ip_rput_data_v6()
27600 					 */
27601 					ifindex =
27602 					    (uint_t)(uintptr_t)mp1->b_prev;
27603 					inbound_ill =
27604 					    ill_lookup_on_ifindex(ifindex,
27605 					    B_TRUE, NULL, NULL, NULL,
27606 					    NULL, ipst);
27607 					mp1->b_prev = NULL;
27608 					if (inbound_ill != NULL)
27609 						fwdq = inbound_ill->ill_rq;
27610 
27611 					if (fwdq != NULL) {
27612 						put(fwdq, mp1);
27613 						ill_refrele(inbound_ill);
27614 					} else
27615 						put(WR(ill->ill_rq), mp1);
27616 					mp1 = nxt_mp;
27617 				}
27618 				NCE_REFRELE(nce);
27619 			} else {	/* nce is NULL; clean up */
27620 				ire_delete(ire);
27621 				freemsg(mp);
27622 				freemsg(mp1);
27623 				return;
27624 			}
27625 		} else {
27626 			nce_t *arpce;
27627 			/*
27628 			 * Link layer resolution succeeded. Recompute the
27629 			 * ire_nce.
27630 			 */
27631 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27632 			if ((arpce = ndp_lookup_v4(ill,
27633 			    (ire->ire_gateway_addr != INADDR_ANY ?
27634 			    &ire->ire_gateway_addr : &ire->ire_addr),
27635 			    B_FALSE)) == NULL) {
27636 				freeb(ire->ire_mp);
27637 				freeb(mp1);
27638 				freemsg(mp);
27639 				return;
27640 			}
27641 			mutex_enter(&arpce->nce_lock);
27642 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27643 			if (arpce->nce_state == ND_REACHABLE) {
27644 				/*
27645 				 * Someone resolved this before us;
27646 				 * cleanup the res_mp. Since ire has
27647 				 * not been added yet, the call to ire_add_v4
27648 				 * from ire_add_then_send (when a dup is
27649 				 * detected) will clean up the ire.
27650 				 */
27651 				freeb(mp1);
27652 			} else {
27653 				ASSERT(arpce->nce_res_mp == NULL);
27654 				arpce->nce_res_mp = mp1;
27655 				arpce->nce_state = ND_REACHABLE;
27656 			}
27657 			mutex_exit(&arpce->nce_lock);
27658 			if (ire->ire_marks & IRE_MARK_NOADD) {
27659 				/*
27660 				 * this ire will not be added to the ire
27661 				 * cache table, so we can set the ire_nce
27662 				 * here, as there are no atomicity constraints.
27663 				 */
27664 				ire->ire_nce = arpce;
27665 				/*
27666 				 * We are associating this nce with the ire
27667 				 * so change the nce ref taken in
27668 				 * ndp_lookup_v4() from
27669 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27670 				 */
27671 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27672 			} else {
27673 				NCE_REFRELE(arpce);
27674 			}
27675 			ire_add_then_send(q, ire, mp);
27676 		}
27677 		return;	/* All is well, the packet has been sent. */
27678 	}
27679 	case IRE_ARPRESOLVE_TYPE: {
27680 
27681 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27682 			break;
27683 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27684 		mp->b_cont = NULL;
27685 		/*
27686 		 * First, check to make sure the resolution succeeded.
27687 		 * If it failed, the second mblk will be empty.
27688 		 */
27689 		if (mp1->b_rptr == mp1->b_wptr) {
27690 			/* cleanup  the incomplete ire, free queued packets */
27691 			freemsg(mp); /* fake ire */
27692 			freeb(mp1);  /* dl_unitdata response */
27693 			return;
27694 		}
27695 
27696 		/*
27697 		 * update any incomplete nce_t found. we lookup the ctable
27698 		 * and find the nce from the ire->ire_nce because we need
27699 		 * to pass the ire to ip_xmit_v4 later, and can find both
27700 		 * ire and nce in one lookup from the ctable.
27701 		 */
27702 		fake_ire = (ire_t *)mp->b_rptr;
27703 		/*
27704 		 * By the time we come back here from ARP
27705 		 * the logical outgoing interface  of the incomplete ire
27706 		 * we added in ire_forward could have disappeared,
27707 		 * causing the incomplete ire to also have
27708 		 * dissapeared. So we need to retreive the
27709 		 * proper ipif for the ire  before looking
27710 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27711 		 */
27712 		ill = q->q_ptr;
27713 
27714 		/* Get the outgoing ipif */
27715 		mutex_enter(&ill->ill_lock);
27716 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27717 			mutex_exit(&ill->ill_lock);
27718 			freemsg(mp); /* fake ire */
27719 			freeb(mp1);  /* dl_unitdata response */
27720 			return;
27721 		}
27722 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27723 
27724 		if (ipif == NULL) {
27725 			mutex_exit(&ill->ill_lock);
27726 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27727 			freemsg(mp);
27728 			freeb(mp1);
27729 			return;
27730 		}
27731 		ipif_refhold_locked(ipif);
27732 		mutex_exit(&ill->ill_lock);
27733 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27734 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27735 		    ipif, fake_ire->ire_zoneid, NULL,
27736 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27737 		ipif_refrele(ipif);
27738 		if (ire == NULL) {
27739 			/*
27740 			 * no ire was found; check if there is an nce
27741 			 * for this lookup; if it has no ire's pointing at it
27742 			 * cleanup.
27743 			 */
27744 			if ((nce = ndp_lookup_v4(ill,
27745 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27746 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27747 			    B_FALSE)) != NULL) {
27748 				/*
27749 				 * cleanup:
27750 				 * We check for refcnt 2 (one for the nce
27751 				 * hash list + 1 for the ref taken by
27752 				 * ndp_lookup_v4) to check that there are
27753 				 * no ire's pointing at the nce.
27754 				 */
27755 				if (nce->nce_refcnt == 2)
27756 					ndp_delete(nce);
27757 				NCE_REFRELE(nce);
27758 			}
27759 			freeb(mp1);  /* dl_unitdata response */
27760 			freemsg(mp); /* fake ire */
27761 			return;
27762 		}
27763 		nce = ire->ire_nce;
27764 		DTRACE_PROBE2(ire__arpresolve__type,
27765 		    ire_t *, ire, nce_t *, nce);
27766 		ASSERT(nce->nce_state != ND_INITIAL);
27767 		mutex_enter(&nce->nce_lock);
27768 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27769 		if (nce->nce_state == ND_REACHABLE) {
27770 			/*
27771 			 * Someone resolved this before us;
27772 			 * our response is not needed any more.
27773 			 */
27774 			mutex_exit(&nce->nce_lock);
27775 			freeb(mp1);  /* dl_unitdata response */
27776 		} else {
27777 			ASSERT(nce->nce_res_mp == NULL);
27778 			nce->nce_res_mp = mp1;
27779 			nce->nce_state = ND_REACHABLE;
27780 			mutex_exit(&nce->nce_lock);
27781 			nce_fastpath(nce);
27782 		}
27783 		/*
27784 		 * The cached nce_t has been updated to be reachable;
27785 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27786 		 */
27787 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27788 		freemsg(mp);
27789 		/*
27790 		 * send out queued packets.
27791 		 */
27792 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27793 
27794 		IRE_REFRELE(ire);
27795 		return;
27796 	}
27797 	default:
27798 		break;
27799 	}
27800 	if (q->q_next) {
27801 		putnext(q, mp);
27802 	} else
27803 		freemsg(mp);
27804 	return;
27805 
27806 protonak:
27807 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27808 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27809 		qreply(q, mp);
27810 }
27811 
27812 /*
27813  * Process IP options in an outbound packet.  Modify the destination if there
27814  * is a source route option.
27815  * Returns non-zero if something fails in which case an ICMP error has been
27816  * sent and mp freed.
27817  */
27818 static int
27819 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27820     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27821 {
27822 	ipoptp_t	opts;
27823 	uchar_t		*opt;
27824 	uint8_t		optval;
27825 	uint8_t		optlen;
27826 	ipaddr_t	dst;
27827 	intptr_t	code = 0;
27828 	mblk_t		*mp;
27829 	ire_t		*ire = NULL;
27830 
27831 	ip2dbg(("ip_wput_options\n"));
27832 	mp = ipsec_mp;
27833 	if (mctl_present) {
27834 		mp = ipsec_mp->b_cont;
27835 	}
27836 
27837 	dst = ipha->ipha_dst;
27838 	for (optval = ipoptp_first(&opts, ipha);
27839 	    optval != IPOPT_EOL;
27840 	    optval = ipoptp_next(&opts)) {
27841 		opt = opts.ipoptp_cur;
27842 		optlen = opts.ipoptp_len;
27843 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27844 		    optval, optlen));
27845 		switch (optval) {
27846 			uint32_t off;
27847 		case IPOPT_SSRR:
27848 		case IPOPT_LSRR:
27849 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27850 				ip1dbg((
27851 				    "ip_wput_options: bad option offset\n"));
27852 				code = (char *)&opt[IPOPT_OLEN] -
27853 				    (char *)ipha;
27854 				goto param_prob;
27855 			}
27856 			off = opt[IPOPT_OFFSET];
27857 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27858 			    ntohl(dst)));
27859 			/*
27860 			 * For strict: verify that dst is directly
27861 			 * reachable.
27862 			 */
27863 			if (optval == IPOPT_SSRR) {
27864 				ire = ire_ftable_lookup(dst, 0, 0,
27865 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27866 				    MBLK_GETLABEL(mp),
27867 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27868 				if (ire == NULL) {
27869 					ip1dbg(("ip_wput_options: SSRR not"
27870 					    " directly reachable: 0x%x\n",
27871 					    ntohl(dst)));
27872 					goto bad_src_route;
27873 				}
27874 				ire_refrele(ire);
27875 			}
27876 			break;
27877 		case IPOPT_RR:
27878 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27879 				ip1dbg((
27880 				    "ip_wput_options: bad option offset\n"));
27881 				code = (char *)&opt[IPOPT_OLEN] -
27882 				    (char *)ipha;
27883 				goto param_prob;
27884 			}
27885 			break;
27886 		case IPOPT_TS:
27887 			/*
27888 			 * Verify that length >=5 and that there is either
27889 			 * room for another timestamp or that the overflow
27890 			 * counter is not maxed out.
27891 			 */
27892 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27893 			if (optlen < IPOPT_MINLEN_IT) {
27894 				goto param_prob;
27895 			}
27896 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27897 				ip1dbg((
27898 				    "ip_wput_options: bad option offset\n"));
27899 				code = (char *)&opt[IPOPT_OFFSET] -
27900 				    (char *)ipha;
27901 				goto param_prob;
27902 			}
27903 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27904 			case IPOPT_TS_TSONLY:
27905 				off = IPOPT_TS_TIMELEN;
27906 				break;
27907 			case IPOPT_TS_TSANDADDR:
27908 			case IPOPT_TS_PRESPEC:
27909 			case IPOPT_TS_PRESPEC_RFC791:
27910 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27911 				break;
27912 			default:
27913 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27914 				    (char *)ipha;
27915 				goto param_prob;
27916 			}
27917 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27918 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27919 				/*
27920 				 * No room and the overflow counter is 15
27921 				 * already.
27922 				 */
27923 				goto param_prob;
27924 			}
27925 			break;
27926 		}
27927 	}
27928 
27929 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27930 		return (0);
27931 
27932 	ip1dbg(("ip_wput_options: error processing IP options."));
27933 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27934 
27935 param_prob:
27936 	/*
27937 	 * Since ip_wput() isn't close to finished, we fill
27938 	 * in enough of the header for credible error reporting.
27939 	 */
27940 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27941 		/* Failed */
27942 		freemsg(ipsec_mp);
27943 		return (-1);
27944 	}
27945 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27946 	return (-1);
27947 
27948 bad_src_route:
27949 	/*
27950 	 * Since ip_wput() isn't close to finished, we fill
27951 	 * in enough of the header for credible error reporting.
27952 	 */
27953 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27954 		/* Failed */
27955 		freemsg(ipsec_mp);
27956 		return (-1);
27957 	}
27958 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27959 	return (-1);
27960 }
27961 
27962 /*
27963  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27964  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27965  * thru /etc/system.
27966  */
27967 #define	CONN_MAXDRAINCNT	64
27968 
27969 static void
27970 conn_drain_init(ip_stack_t *ipst)
27971 {
27972 	int i;
27973 
27974 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27975 
27976 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27977 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27978 		/*
27979 		 * Default value of the number of drainers is the
27980 		 * number of cpus, subject to maximum of 8 drainers.
27981 		 */
27982 		if (boot_max_ncpus != -1)
27983 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27984 		else
27985 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27986 	}
27987 
27988 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27989 	    sizeof (idl_t), KM_SLEEP);
27990 
27991 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27992 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27993 		    MUTEX_DEFAULT, NULL);
27994 	}
27995 }
27996 
27997 static void
27998 conn_drain_fini(ip_stack_t *ipst)
27999 {
28000 	int i;
28001 
28002 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28003 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28004 	kmem_free(ipst->ips_conn_drain_list,
28005 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28006 	ipst->ips_conn_drain_list = NULL;
28007 }
28008 
28009 /*
28010  * Note: For an overview of how flowcontrol is handled in IP please see the
28011  * IP Flowcontrol notes at the top of this file.
28012  *
28013  * Flow control has blocked us from proceeding. Insert the given conn in one
28014  * of the conn drain lists. These conn wq's will be qenabled later on when
28015  * STREAMS flow control does a backenable. conn_walk_drain will enable
28016  * the first conn in each of these drain lists. Each of these qenabled conns
28017  * in turn enables the next in the list, after it runs, or when it closes,
28018  * thus sustaining the drain process.
28019  *
28020  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28021  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28022  * running at any time, on a given conn, since there can be only 1 service proc
28023  * running on a queue at any time.
28024  */
28025 void
28026 conn_drain_insert(conn_t *connp)
28027 {
28028 	idl_t	*idl;
28029 	uint_t	index;
28030 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28031 
28032 	mutex_enter(&connp->conn_lock);
28033 	if (connp->conn_state_flags & CONN_CLOSING) {
28034 		/*
28035 		 * The conn is closing as a result of which CONN_CLOSING
28036 		 * is set. Return.
28037 		 */
28038 		mutex_exit(&connp->conn_lock);
28039 		return;
28040 	} else if (connp->conn_idl == NULL) {
28041 		/*
28042 		 * Assign the next drain list round robin. We dont' use
28043 		 * a lock, and thus it may not be strictly round robin.
28044 		 * Atomicity of load/stores is enough to make sure that
28045 		 * conn_drain_list_index is always within bounds.
28046 		 */
28047 		index = ipst->ips_conn_drain_list_index;
28048 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28049 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28050 		index++;
28051 		if (index == ipst->ips_conn_drain_list_cnt)
28052 			index = 0;
28053 		ipst->ips_conn_drain_list_index = index;
28054 	}
28055 	mutex_exit(&connp->conn_lock);
28056 
28057 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28058 	if ((connp->conn_drain_prev != NULL) ||
28059 	    (connp->conn_state_flags & CONN_CLOSING)) {
28060 		/*
28061 		 * The conn is already in the drain list, OR
28062 		 * the conn is closing. We need to check again for
28063 		 * the closing case again since close can happen
28064 		 * after we drop the conn_lock, and before we
28065 		 * acquire the CONN_DRAIN_LIST_LOCK.
28066 		 */
28067 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28068 		return;
28069 	} else {
28070 		idl = connp->conn_idl;
28071 	}
28072 
28073 	/*
28074 	 * The conn is not in the drain list. Insert it at the
28075 	 * tail of the drain list. The drain list is circular
28076 	 * and doubly linked. idl_conn points to the 1st element
28077 	 * in the list.
28078 	 */
28079 	if (idl->idl_conn == NULL) {
28080 		idl->idl_conn = connp;
28081 		connp->conn_drain_next = connp;
28082 		connp->conn_drain_prev = connp;
28083 	} else {
28084 		conn_t *head = idl->idl_conn;
28085 
28086 		connp->conn_drain_next = head;
28087 		connp->conn_drain_prev = head->conn_drain_prev;
28088 		head->conn_drain_prev->conn_drain_next = connp;
28089 		head->conn_drain_prev = connp;
28090 	}
28091 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28092 }
28093 
28094 /*
28095  * This conn is closing, and we are called from ip_close. OR
28096  * This conn has been serviced by ip_wsrv, and we need to do the tail
28097  * processing.
28098  * If this conn is part of the drain list, we may need to sustain the drain
28099  * process by qenabling the next conn in the drain list. We may also need to
28100  * remove this conn from the list, if it is done.
28101  */
28102 static void
28103 conn_drain_tail(conn_t *connp, boolean_t closing)
28104 {
28105 	idl_t *idl;
28106 
28107 	/*
28108 	 * connp->conn_idl is stable at this point, and no lock is needed
28109 	 * to check it. If we are called from ip_close, close has already
28110 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28111 	 * called us only because conn_idl is non-null. If we are called thru
28112 	 * service, conn_idl could be null, but it cannot change because
28113 	 * service is single-threaded per queue, and there cannot be another
28114 	 * instance of service trying to call conn_drain_insert on this conn
28115 	 * now.
28116 	 */
28117 	ASSERT(!closing || (connp->conn_idl != NULL));
28118 
28119 	/*
28120 	 * If connp->conn_idl is null, the conn has not been inserted into any
28121 	 * drain list even once since creation of the conn. Just return.
28122 	 */
28123 	if (connp->conn_idl == NULL)
28124 		return;
28125 
28126 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28127 
28128 	if (connp->conn_drain_prev == NULL) {
28129 		/* This conn is currently not in the drain list.  */
28130 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28131 		return;
28132 	}
28133 	idl = connp->conn_idl;
28134 	if (idl->idl_conn_draining == connp) {
28135 		/*
28136 		 * This conn is the current drainer. If this is the last conn
28137 		 * in the drain list, we need to do more checks, in the 'if'
28138 		 * below. Otherwwise we need to just qenable the next conn,
28139 		 * to sustain the draining, and is handled in the 'else'
28140 		 * below.
28141 		 */
28142 		if (connp->conn_drain_next == idl->idl_conn) {
28143 			/*
28144 			 * This conn is the last in this list. This round
28145 			 * of draining is complete. If idl_repeat is set,
28146 			 * it means another flow enabling has happened from
28147 			 * the driver/streams and we need to another round
28148 			 * of draining.
28149 			 * If there are more than 2 conns in the drain list,
28150 			 * do a left rotate by 1, so that all conns except the
28151 			 * conn at the head move towards the head by 1, and the
28152 			 * the conn at the head goes to the tail. This attempts
28153 			 * a more even share for all queues that are being
28154 			 * drained.
28155 			 */
28156 			if ((connp->conn_drain_next != connp) &&
28157 			    (idl->idl_conn->conn_drain_next != connp)) {
28158 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28159 			}
28160 			if (idl->idl_repeat) {
28161 				qenable(idl->idl_conn->conn_wq);
28162 				idl->idl_conn_draining = idl->idl_conn;
28163 				idl->idl_repeat = 0;
28164 			} else {
28165 				idl->idl_conn_draining = NULL;
28166 			}
28167 		} else {
28168 			/*
28169 			 * If the next queue that we are now qenable'ing,
28170 			 * is closing, it will remove itself from this list
28171 			 * and qenable the subsequent queue in ip_close().
28172 			 * Serialization is acheived thru idl_lock.
28173 			 */
28174 			qenable(connp->conn_drain_next->conn_wq);
28175 			idl->idl_conn_draining = connp->conn_drain_next;
28176 		}
28177 	}
28178 	if (!connp->conn_did_putbq || closing) {
28179 		/*
28180 		 * Remove ourself from the drain list, if we did not do
28181 		 * a putbq, or if the conn is closing.
28182 		 * Note: It is possible that q->q_first is non-null. It means
28183 		 * that these messages landed after we did a enableok() in
28184 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28185 		 * service them.
28186 		 */
28187 		if (connp->conn_drain_next == connp) {
28188 			/* Singleton in the list */
28189 			ASSERT(connp->conn_drain_prev == connp);
28190 			idl->idl_conn = NULL;
28191 			idl->idl_conn_draining = NULL;
28192 		} else {
28193 			connp->conn_drain_prev->conn_drain_next =
28194 			    connp->conn_drain_next;
28195 			connp->conn_drain_next->conn_drain_prev =
28196 			    connp->conn_drain_prev;
28197 			if (idl->idl_conn == connp)
28198 				idl->idl_conn = connp->conn_drain_next;
28199 			ASSERT(idl->idl_conn_draining != connp);
28200 
28201 		}
28202 		connp->conn_drain_next = NULL;
28203 		connp->conn_drain_prev = NULL;
28204 	}
28205 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28206 }
28207 
28208 /*
28209  * Write service routine. Shared perimeter entry point.
28210  * ip_wsrv can be called in any of the following ways.
28211  * 1. The device queue's messages has fallen below the low water mark
28212  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28213  *    the drain lists and backenable the first conn in each list.
28214  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28215  *    qenabled non-tcp upper layers. We start dequeing messages and call
28216  *    ip_wput for each message.
28217  */
28218 
28219 void
28220 ip_wsrv(queue_t *q)
28221 {
28222 	conn_t	*connp;
28223 	ill_t	*ill;
28224 	mblk_t	*mp;
28225 
28226 	if (q->q_next) {
28227 		ill = (ill_t *)q->q_ptr;
28228 		if (ill->ill_state_flags == 0) {
28229 			/*
28230 			 * The device flow control has opened up.
28231 			 * Walk through conn drain lists and qenable the
28232 			 * first conn in each list. This makes sense only
28233 			 * if the stream is fully plumbed and setup.
28234 			 * Hence the if check above.
28235 			 */
28236 			ip1dbg(("ip_wsrv: walking\n"));
28237 			conn_walk_drain(ill->ill_ipst);
28238 		}
28239 		return;
28240 	}
28241 
28242 	connp = Q_TO_CONN(q);
28243 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28244 
28245 	/*
28246 	 * 1. Set conn_draining flag to signal that service is active.
28247 	 *
28248 	 * 2. ip_output determines whether it has been called from service,
28249 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28250 	 *    has been called from service.
28251 	 *
28252 	 * 3. Message ordering is preserved by the following logic.
28253 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28254 	 *    the message at the tail, if conn_draining is set (i.e. service
28255 	 *    is running) or if q->q_first is non-null.
28256 	 *
28257 	 *    ii. If ip_output is called from service, and if ip_output cannot
28258 	 *    putnext due to flow control, it does a putbq.
28259 	 *
28260 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28261 	 *    (causing an infinite loop).
28262 	 */
28263 	ASSERT(!connp->conn_did_putbq);
28264 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28265 		connp->conn_draining = 1;
28266 		noenable(q);
28267 		while ((mp = getq(q)) != NULL) {
28268 			ASSERT(CONN_Q(q));
28269 
28270 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28271 			if (connp->conn_did_putbq) {
28272 				/* ip_wput did a putbq */
28273 				break;
28274 			}
28275 		}
28276 		/*
28277 		 * At this point, a thread coming down from top, calling
28278 		 * ip_wput, may end up queueing the message. We have not yet
28279 		 * enabled the queue, so ip_wsrv won't be called again.
28280 		 * To avoid this race, check q->q_first again (in the loop)
28281 		 * If the other thread queued the message before we call
28282 		 * enableok(), we will catch it in the q->q_first check.
28283 		 * If the other thread queues the message after we call
28284 		 * enableok(), ip_wsrv will be called again by STREAMS.
28285 		 */
28286 		connp->conn_draining = 0;
28287 		enableok(q);
28288 	}
28289 
28290 	/* Enable the next conn for draining */
28291 	conn_drain_tail(connp, B_FALSE);
28292 
28293 	connp->conn_did_putbq = 0;
28294 }
28295 
28296 /*
28297  * Walk the list of all conn's calling the function provided with the
28298  * specified argument for each.	 Note that this only walks conn's that
28299  * have been bound.
28300  * Applies to both IPv4 and IPv6.
28301  */
28302 static void
28303 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28304 {
28305 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28306 	    ipst->ips_ipcl_udp_fanout_size,
28307 	    func, arg, zoneid);
28308 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28309 	    ipst->ips_ipcl_conn_fanout_size,
28310 	    func, arg, zoneid);
28311 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28312 	    ipst->ips_ipcl_bind_fanout_size,
28313 	    func, arg, zoneid);
28314 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28315 	    IPPROTO_MAX, func, arg, zoneid);
28316 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28317 	    IPPROTO_MAX, func, arg, zoneid);
28318 }
28319 
28320 /*
28321  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28322  * of conns that need to be drained, check if drain is already in progress.
28323  * If so set the idl_repeat bit, indicating that the last conn in the list
28324  * needs to reinitiate the drain once again, for the list. If drain is not
28325  * in progress for the list, initiate the draining, by qenabling the 1st
28326  * conn in the list. The drain is self-sustaining, each qenabled conn will
28327  * in turn qenable the next conn, when it is done/blocked/closing.
28328  */
28329 static void
28330 conn_walk_drain(ip_stack_t *ipst)
28331 {
28332 	int i;
28333 	idl_t *idl;
28334 
28335 	IP_STAT(ipst, ip_conn_walk_drain);
28336 
28337 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28338 		idl = &ipst->ips_conn_drain_list[i];
28339 		mutex_enter(&idl->idl_lock);
28340 		if (idl->idl_conn == NULL) {
28341 			mutex_exit(&idl->idl_lock);
28342 			continue;
28343 		}
28344 		/*
28345 		 * If this list is not being drained currently by
28346 		 * an ip_wsrv thread, start the process.
28347 		 */
28348 		if (idl->idl_conn_draining == NULL) {
28349 			ASSERT(idl->idl_repeat == 0);
28350 			qenable(idl->idl_conn->conn_wq);
28351 			idl->idl_conn_draining = idl->idl_conn;
28352 		} else {
28353 			idl->idl_repeat = 1;
28354 		}
28355 		mutex_exit(&idl->idl_lock);
28356 	}
28357 }
28358 
28359 /*
28360  * Walk an conn hash table of `count' buckets, calling func for each entry.
28361  */
28362 static void
28363 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28364     zoneid_t zoneid)
28365 {
28366 	conn_t	*connp;
28367 
28368 	while (count-- > 0) {
28369 		mutex_enter(&connfp->connf_lock);
28370 		for (connp = connfp->connf_head; connp != NULL;
28371 		    connp = connp->conn_next) {
28372 			if (zoneid == GLOBAL_ZONEID ||
28373 			    zoneid == connp->conn_zoneid) {
28374 				CONN_INC_REF(connp);
28375 				mutex_exit(&connfp->connf_lock);
28376 				(*func)(connp, arg);
28377 				mutex_enter(&connfp->connf_lock);
28378 				CONN_DEC_REF(connp);
28379 			}
28380 		}
28381 		mutex_exit(&connfp->connf_lock);
28382 		connfp++;
28383 	}
28384 }
28385 
28386 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28387 static void
28388 conn_report1(conn_t *connp, void *mp)
28389 {
28390 	char	buf1[INET6_ADDRSTRLEN];
28391 	char	buf2[INET6_ADDRSTRLEN];
28392 	uint_t	print_len, buf_len;
28393 
28394 	ASSERT(connp != NULL);
28395 
28396 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28397 	if (buf_len <= 0)
28398 		return;
28399 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28400 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28401 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28402 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28403 	    "%5d %s/%05d %s/%05d\n",
28404 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28405 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28406 	    buf1, connp->conn_lport,
28407 	    buf2, connp->conn_fport);
28408 	if (print_len < buf_len) {
28409 		((mblk_t *)mp)->b_wptr += print_len;
28410 	} else {
28411 		((mblk_t *)mp)->b_wptr += buf_len;
28412 	}
28413 }
28414 
28415 /*
28416  * Named Dispatch routine to produce a formatted report on all conns
28417  * that are listed in one of the fanout tables.
28418  * This report is accessed by using the ndd utility to "get" ND variable
28419  * "ip_conn_status".
28420  */
28421 /* ARGSUSED */
28422 static int
28423 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28424 {
28425 	conn_t *connp = Q_TO_CONN(q);
28426 
28427 	(void) mi_mpprintf(mp,
28428 	    "CONN      " MI_COL_HDRPAD_STR
28429 	    "rfq      " MI_COL_HDRPAD_STR
28430 	    "stq      " MI_COL_HDRPAD_STR
28431 	    " zone local                 remote");
28432 
28433 	/*
28434 	 * Because of the ndd constraint, at most we can have 64K buffer
28435 	 * to put in all conn info.  So to be more efficient, just
28436 	 * allocate a 64K buffer here, assuming we need that large buffer.
28437 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28438 	 */
28439 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28440 		/* The following may work even if we cannot get a large buf. */
28441 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28442 		return (0);
28443 	}
28444 
28445 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28446 	    connp->conn_netstack->netstack_ip);
28447 	return (0);
28448 }
28449 
28450 /*
28451  * Determine if the ill and multicast aspects of that packets
28452  * "matches" the conn.
28453  */
28454 boolean_t
28455 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28456     zoneid_t zoneid)
28457 {
28458 	ill_t *in_ill;
28459 	boolean_t found;
28460 	ipif_t *ipif;
28461 	ire_t *ire;
28462 	ipaddr_t dst, src;
28463 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28464 
28465 	dst = ipha->ipha_dst;
28466 	src = ipha->ipha_src;
28467 
28468 	/*
28469 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28470 	 * unicast, broadcast and multicast reception to
28471 	 * conn_incoming_ill. conn_wantpacket itself is called
28472 	 * only for BROADCAST and multicast.
28473 	 *
28474 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28475 	 *    is part of a group. Hence, we should be receiving
28476 	 *    just one copy of broadcast for the whole group.
28477 	 *    Thus, if it is part of the group the packet could
28478 	 *    come on any ill of the group and hence we need a
28479 	 *    match on the group. Otherwise, match on ill should
28480 	 *    be sufficient.
28481 	 *
28482 	 * 2) ip_rput does not suppress duplicate multicast packets.
28483 	 *    If there are two interfaces in a ill group and we have
28484 	 *    2 applications (conns) joined a multicast group G on
28485 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28486 	 *    will give us two packets because we join G on both the
28487 	 *    interfaces rather than nominating just one interface
28488 	 *    for receiving multicast like broadcast above. So,
28489 	 *    we have to call ilg_lookup_ill to filter out duplicate
28490 	 *    copies, if ill is part of a group.
28491 	 */
28492 	in_ill = connp->conn_incoming_ill;
28493 	if (in_ill != NULL) {
28494 		if (in_ill->ill_group == NULL) {
28495 			if (in_ill != ill)
28496 				return (B_FALSE);
28497 		} else if (in_ill->ill_group != ill->ill_group) {
28498 			return (B_FALSE);
28499 		}
28500 	}
28501 
28502 	if (!CLASSD(dst)) {
28503 		if (IPCL_ZONE_MATCH(connp, zoneid))
28504 			return (B_TRUE);
28505 		/*
28506 		 * The conn is in a different zone; we need to check that this
28507 		 * broadcast address is configured in the application's zone and
28508 		 * on one ill in the group.
28509 		 */
28510 		ipif = ipif_get_next_ipif(NULL, ill);
28511 		if (ipif == NULL)
28512 			return (B_FALSE);
28513 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28514 		    connp->conn_zoneid, NULL,
28515 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28516 		ipif_refrele(ipif);
28517 		if (ire != NULL) {
28518 			ire_refrele(ire);
28519 			return (B_TRUE);
28520 		} else {
28521 			return (B_FALSE);
28522 		}
28523 	}
28524 
28525 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28526 	    connp->conn_zoneid == zoneid) {
28527 		/*
28528 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28529 		 * disabled, therefore we don't dispatch the multicast packet to
28530 		 * the sending zone.
28531 		 */
28532 		return (B_FALSE);
28533 	}
28534 
28535 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28536 		/*
28537 		 * Multicast packet on the loopback interface: we only match
28538 		 * conns who joined the group in the specified zone.
28539 		 */
28540 		return (B_FALSE);
28541 	}
28542 
28543 	if (connp->conn_multi_router) {
28544 		/* multicast packet and multicast router socket: send up */
28545 		return (B_TRUE);
28546 	}
28547 
28548 	mutex_enter(&connp->conn_lock);
28549 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28550 	mutex_exit(&connp->conn_lock);
28551 	return (found);
28552 }
28553 
28554 /*
28555  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28556  */
28557 /* ARGSUSED */
28558 static void
28559 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28560 {
28561 	ill_t *ill = (ill_t *)q->q_ptr;
28562 	mblk_t	*mp1, *mp2;
28563 	ipif_t  *ipif;
28564 	int err = 0;
28565 	conn_t *connp = NULL;
28566 	ipsq_t	*ipsq;
28567 	arc_t	*arc;
28568 
28569 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28570 
28571 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28572 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28573 
28574 	ASSERT(IAM_WRITER_ILL(ill));
28575 	mp2 = mp->b_cont;
28576 	mp->b_cont = NULL;
28577 
28578 	/*
28579 	 * We have now received the arp bringup completion message
28580 	 * from ARP. Mark the arp bringup as done. Also if the arp
28581 	 * stream has already started closing, send up the AR_ARP_CLOSING
28582 	 * ack now since ARP is waiting in close for this ack.
28583 	 */
28584 	mutex_enter(&ill->ill_lock);
28585 	ill->ill_arp_bringup_pending = 0;
28586 	if (ill->ill_arp_closing) {
28587 		mutex_exit(&ill->ill_lock);
28588 		/* Let's reuse the mp for sending the ack */
28589 		arc = (arc_t *)mp->b_rptr;
28590 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28591 		arc->arc_cmd = AR_ARP_CLOSING;
28592 		qreply(q, mp);
28593 	} else {
28594 		mutex_exit(&ill->ill_lock);
28595 		freeb(mp);
28596 	}
28597 
28598 	ipsq = ill->ill_phyint->phyint_ipsq;
28599 	ipif = ipsq->ipsq_pending_ipif;
28600 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28601 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28602 	if (mp1 == NULL) {
28603 		/* bringup was aborted by the user */
28604 		freemsg(mp2);
28605 		return;
28606 	}
28607 
28608 	/*
28609 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28610 	 * must have an associated conn_t.  Otherwise, we're bringing this
28611 	 * interface back up as part of handling an asynchronous event (e.g.,
28612 	 * physical address change).
28613 	 */
28614 	if (ipsq->ipsq_current_ioctl != 0) {
28615 		ASSERT(connp != NULL);
28616 		q = CONNP_TO_WQ(connp);
28617 	} else {
28618 		ASSERT(connp == NULL);
28619 		q = ill->ill_rq;
28620 	}
28621 
28622 	/*
28623 	 * If the DL_BIND_REQ fails, it is noted
28624 	 * in arc_name_offset.
28625 	 */
28626 	err = *((int *)mp2->b_rptr);
28627 	if (err == 0) {
28628 		if (ipif->ipif_isv6) {
28629 			if ((err = ipif_up_done_v6(ipif)) != 0)
28630 				ip0dbg(("ip_arp_done: init failed\n"));
28631 		} else {
28632 			if ((err = ipif_up_done(ipif)) != 0)
28633 				ip0dbg(("ip_arp_done: init failed\n"));
28634 		}
28635 	} else {
28636 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28637 	}
28638 
28639 	freemsg(mp2);
28640 
28641 	if ((err == 0) && (ill->ill_up_ipifs)) {
28642 		err = ill_up_ipifs(ill, q, mp1);
28643 		if (err == EINPROGRESS)
28644 			return;
28645 	}
28646 
28647 	if (ill->ill_up_ipifs)
28648 		ill_group_cleanup(ill);
28649 
28650 	/*
28651 	 * The operation must complete without EINPROGRESS since
28652 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28653 	 * Otherwise, the operation will be stuck forever in the ipsq.
28654 	 */
28655 	ASSERT(err != EINPROGRESS);
28656 	if (ipsq->ipsq_current_ioctl != 0)
28657 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28658 	else
28659 		ipsq_current_finish(ipsq);
28660 }
28661 
28662 /* Allocate the private structure */
28663 static int
28664 ip_priv_alloc(void **bufp)
28665 {
28666 	void	*buf;
28667 
28668 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28669 		return (ENOMEM);
28670 
28671 	*bufp = buf;
28672 	return (0);
28673 }
28674 
28675 /* Function to delete the private structure */
28676 void
28677 ip_priv_free(void *buf)
28678 {
28679 	ASSERT(buf != NULL);
28680 	kmem_free(buf, sizeof (ip_priv_t));
28681 }
28682 
28683 /*
28684  * The entry point for IPPF processing.
28685  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28686  * routine just returns.
28687  *
28688  * When called, ip_process generates an ipp_packet_t structure
28689  * which holds the state information for this packet and invokes the
28690  * the classifier (via ipp_packet_process). The classification, depending on
28691  * configured filters, results in a list of actions for this packet. Invoking
28692  * an action may cause the packet to be dropped, in which case the resulting
28693  * mblk (*mpp) is NULL. proc indicates the callout position for
28694  * this packet and ill_index is the interface this packet on or will leave
28695  * on (inbound and outbound resp.).
28696  */
28697 void
28698 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28699 {
28700 	mblk_t		*mp;
28701 	ip_priv_t	*priv;
28702 	ipp_action_id_t	aid;
28703 	int		rc = 0;
28704 	ipp_packet_t	*pp;
28705 #define	IP_CLASS	"ip"
28706 
28707 	/* If the classifier is not loaded, return  */
28708 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28709 		return;
28710 	}
28711 
28712 	mp = *mpp;
28713 	ASSERT(mp != NULL);
28714 
28715 	/* Allocate the packet structure */
28716 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28717 	if (rc != 0) {
28718 		*mpp = NULL;
28719 		freemsg(mp);
28720 		return;
28721 	}
28722 
28723 	/* Allocate the private structure */
28724 	rc = ip_priv_alloc((void **)&priv);
28725 	if (rc != 0) {
28726 		*mpp = NULL;
28727 		freemsg(mp);
28728 		ipp_packet_free(pp);
28729 		return;
28730 	}
28731 	priv->proc = proc;
28732 	priv->ill_index = ill_index;
28733 	ipp_packet_set_private(pp, priv, ip_priv_free);
28734 	ipp_packet_set_data(pp, mp);
28735 
28736 	/* Invoke the classifier */
28737 	rc = ipp_packet_process(&pp);
28738 	if (pp != NULL) {
28739 		mp = ipp_packet_get_data(pp);
28740 		ipp_packet_free(pp);
28741 		if (rc != 0) {
28742 			freemsg(mp);
28743 			*mpp = NULL;
28744 		}
28745 	} else {
28746 		*mpp = NULL;
28747 	}
28748 #undef	IP_CLASS
28749 }
28750 
28751 /*
28752  * Propagate a multicast group membership operation (add/drop) on
28753  * all the interfaces crossed by the related multirt routes.
28754  * The call is considered successful if the operation succeeds
28755  * on at least one interface.
28756  */
28757 static int
28758 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28759     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28760     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28761     mblk_t *first_mp)
28762 {
28763 	ire_t		*ire_gw;
28764 	irb_t		*irb;
28765 	int		error = 0;
28766 	opt_restart_t	*or;
28767 	ip_stack_t	*ipst = ire->ire_ipst;
28768 
28769 	irb = ire->ire_bucket;
28770 	ASSERT(irb != NULL);
28771 
28772 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28773 
28774 	or = (opt_restart_t *)first_mp->b_rptr;
28775 	IRB_REFHOLD(irb);
28776 	for (; ire != NULL; ire = ire->ire_next) {
28777 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28778 			continue;
28779 		if (ire->ire_addr != group)
28780 			continue;
28781 
28782 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28783 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28784 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28785 		/* No resolver exists for the gateway; skip this ire. */
28786 		if (ire_gw == NULL)
28787 			continue;
28788 
28789 		/*
28790 		 * This function can return EINPROGRESS. If so the operation
28791 		 * will be restarted from ip_restart_optmgmt which will
28792 		 * call ip_opt_set and option processing will restart for
28793 		 * this option. So we may end up calling 'fn' more than once.
28794 		 * This requires that 'fn' is idempotent except for the
28795 		 * return value. The operation is considered a success if
28796 		 * it succeeds at least once on any one interface.
28797 		 */
28798 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28799 		    NULL, fmode, src, first_mp);
28800 		if (error == 0)
28801 			or->or_private = CGTP_MCAST_SUCCESS;
28802 
28803 		if (ip_debug > 0) {
28804 			ulong_t	off;
28805 			char	*ksym;
28806 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28807 			ip2dbg(("ip_multirt_apply_membership: "
28808 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28809 			    "error %d [success %u]\n",
28810 			    ksym ? ksym : "?",
28811 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28812 			    error, or->or_private));
28813 		}
28814 
28815 		ire_refrele(ire_gw);
28816 		if (error == EINPROGRESS) {
28817 			IRB_REFRELE(irb);
28818 			return (error);
28819 		}
28820 	}
28821 	IRB_REFRELE(irb);
28822 	/*
28823 	 * Consider the call as successful if we succeeded on at least
28824 	 * one interface. Otherwise, return the last encountered error.
28825 	 */
28826 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28827 }
28828 
28829 
28830 /*
28831  * Issue a warning regarding a route crossing an interface with an
28832  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28833  * amount of time is logged.
28834  */
28835 static void
28836 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28837 {
28838 	hrtime_t	current = gethrtime();
28839 	char		buf[INET_ADDRSTRLEN];
28840 	ip_stack_t	*ipst = ire->ire_ipst;
28841 
28842 	/* Convert interval in ms to hrtime in ns */
28843 	if (ipst->ips_multirt_bad_mtu_last_time +
28844 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28845 	    current) {
28846 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28847 		    "to %s, incorrect MTU %u (expected %u)\n",
28848 		    ip_dot_addr(ire->ire_addr, buf),
28849 		    ire->ire_max_frag, max_frag);
28850 
28851 		ipst->ips_multirt_bad_mtu_last_time = current;
28852 	}
28853 }
28854 
28855 
28856 /*
28857  * Get the CGTP (multirouting) filtering status.
28858  * If 0, the CGTP hooks are transparent.
28859  */
28860 /* ARGSUSED */
28861 static int
28862 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28863 {
28864 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28865 
28866 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28867 	return (0);
28868 }
28869 
28870 
28871 /*
28872  * Set the CGTP (multirouting) filtering status.
28873  * If the status is changed from active to transparent
28874  * or from transparent to active, forward the new status
28875  * to the filtering module (if loaded).
28876  */
28877 /* ARGSUSED */
28878 static int
28879 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28880     cred_t *ioc_cr)
28881 {
28882 	long		new_value;
28883 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28884 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28885 
28886 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28887 		return (EPERM);
28888 
28889 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28890 	    new_value < 0 || new_value > 1) {
28891 		return (EINVAL);
28892 	}
28893 
28894 	if ((!*ip_cgtp_filter_value) && new_value) {
28895 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28896 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28897 		    " (module not loaded)" : "");
28898 	}
28899 	if (*ip_cgtp_filter_value && (!new_value)) {
28900 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28901 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28902 		    " (module not loaded)" : "");
28903 	}
28904 
28905 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28906 		int	res;
28907 		netstackid_t stackid;
28908 
28909 		stackid = ipst->ips_netstack->netstack_stackid;
28910 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28911 		    new_value);
28912 		if (res)
28913 			return (res);
28914 	}
28915 
28916 	*ip_cgtp_filter_value = (boolean_t)new_value;
28917 
28918 	return (0);
28919 }
28920 
28921 
28922 /*
28923  * Return the expected CGTP hooks version number.
28924  */
28925 int
28926 ip_cgtp_filter_supported(void)
28927 {
28928 	return (ip_cgtp_filter_rev);
28929 }
28930 
28931 
28932 /*
28933  * CGTP hooks can be registered by invoking this function.
28934  * Checks that the version number matches.
28935  */
28936 int
28937 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28938 {
28939 	netstack_t *ns;
28940 	ip_stack_t *ipst;
28941 
28942 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28943 		return (ENOTSUP);
28944 
28945 	ns = netstack_find_by_stackid(stackid);
28946 	if (ns == NULL)
28947 		return (EINVAL);
28948 	ipst = ns->netstack_ip;
28949 	ASSERT(ipst != NULL);
28950 
28951 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28952 		netstack_rele(ns);
28953 		return (EALREADY);
28954 	}
28955 
28956 	ipst->ips_ip_cgtp_filter_ops = ops;
28957 	netstack_rele(ns);
28958 	return (0);
28959 }
28960 
28961 /*
28962  * CGTP hooks can be unregistered by invoking this function.
28963  * Returns ENXIO if there was no registration.
28964  * Returns EBUSY if the ndd variable has not been turned off.
28965  */
28966 int
28967 ip_cgtp_filter_unregister(netstackid_t stackid)
28968 {
28969 	netstack_t *ns;
28970 	ip_stack_t *ipst;
28971 
28972 	ns = netstack_find_by_stackid(stackid);
28973 	if (ns == NULL)
28974 		return (EINVAL);
28975 	ipst = ns->netstack_ip;
28976 	ASSERT(ipst != NULL);
28977 
28978 	if (ipst->ips_ip_cgtp_filter) {
28979 		netstack_rele(ns);
28980 		return (EBUSY);
28981 	}
28982 
28983 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28984 		netstack_rele(ns);
28985 		return (ENXIO);
28986 	}
28987 	ipst->ips_ip_cgtp_filter_ops = NULL;
28988 	netstack_rele(ns);
28989 	return (0);
28990 }
28991 
28992 /*
28993  * Check whether there is a CGTP filter registration.
28994  * Returns non-zero if there is a registration, otherwise returns zero.
28995  * Note: returns zero if bad stackid.
28996  */
28997 int
28998 ip_cgtp_filter_is_registered(netstackid_t stackid)
28999 {
29000 	netstack_t *ns;
29001 	ip_stack_t *ipst;
29002 	int ret;
29003 
29004 	ns = netstack_find_by_stackid(stackid);
29005 	if (ns == NULL)
29006 		return (0);
29007 	ipst = ns->netstack_ip;
29008 	ASSERT(ipst != NULL);
29009 
29010 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29011 		ret = 1;
29012 	else
29013 		ret = 0;
29014 
29015 	netstack_rele(ns);
29016 	return (ret);
29017 }
29018 
29019 static squeue_func_t
29020 ip_squeue_switch(int val)
29021 {
29022 	squeue_func_t rval = squeue_fill;
29023 
29024 	switch (val) {
29025 	case IP_SQUEUE_ENTER_NODRAIN:
29026 		rval = squeue_enter_nodrain;
29027 		break;
29028 	case IP_SQUEUE_ENTER:
29029 		rval = squeue_enter;
29030 		break;
29031 	default:
29032 		break;
29033 	}
29034 	return (rval);
29035 }
29036 
29037 /* ARGSUSED */
29038 static int
29039 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29040     caddr_t addr, cred_t *cr)
29041 {
29042 	int *v = (int *)addr;
29043 	long new_value;
29044 
29045 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29046 		return (EPERM);
29047 
29048 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29049 		return (EINVAL);
29050 
29051 	ip_input_proc = ip_squeue_switch(new_value);
29052 	*v = new_value;
29053 	return (0);
29054 }
29055 
29056 /* ARGSUSED */
29057 static int
29058 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29059     caddr_t addr, cred_t *cr)
29060 {
29061 	int *v = (int *)addr;
29062 	long new_value;
29063 
29064 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29065 		return (EPERM);
29066 
29067 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29068 		return (EINVAL);
29069 
29070 	*v = new_value;
29071 	return (0);
29072 }
29073 
29074 /*
29075  * Handle changes to ipmp_hook_emulation ndd variable.
29076  * Need to update phyint_hook_ifindex.
29077  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29078  */
29079 static void
29080 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29081 {
29082 	phyint_t *phyi;
29083 	phyint_t *phyi_tmp;
29084 	char *groupname;
29085 	int namelen;
29086 	ill_t	*ill;
29087 	boolean_t new_group;
29088 
29089 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29090 	/*
29091 	 * Group indicies are stored in the phyint - a common structure
29092 	 * to both IPv4 and IPv6.
29093 	 */
29094 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29095 	for (; phyi != NULL;
29096 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29097 	    phyi, AVL_AFTER)) {
29098 		/* Ignore the ones that do not have a group */
29099 		if (phyi->phyint_groupname_len == 0)
29100 			continue;
29101 
29102 		/*
29103 		 * Look for other phyint in group.
29104 		 * Clear name/namelen so the lookup doesn't find ourselves.
29105 		 */
29106 		namelen = phyi->phyint_groupname_len;
29107 		groupname = phyi->phyint_groupname;
29108 		phyi->phyint_groupname_len = 0;
29109 		phyi->phyint_groupname = NULL;
29110 
29111 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29112 		/* Restore */
29113 		phyi->phyint_groupname_len = namelen;
29114 		phyi->phyint_groupname = groupname;
29115 
29116 		new_group = B_FALSE;
29117 		if (ipst->ips_ipmp_hook_emulation) {
29118 			/*
29119 			 * If the group already exists and has already
29120 			 * been assigned a group ifindex, we use the existing
29121 			 * group_ifindex, otherwise we pick a new group_ifindex
29122 			 * here.
29123 			 */
29124 			if (phyi_tmp != NULL &&
29125 			    phyi_tmp->phyint_group_ifindex != 0) {
29126 				phyi->phyint_group_ifindex =
29127 				    phyi_tmp->phyint_group_ifindex;
29128 			} else {
29129 				/* XXX We need a recovery strategy here. */
29130 				if (!ip_assign_ifindex(
29131 				    &phyi->phyint_group_ifindex, ipst))
29132 					cmn_err(CE_PANIC,
29133 					    "ip_assign_ifindex() failed");
29134 				new_group = B_TRUE;
29135 			}
29136 		} else {
29137 			phyi->phyint_group_ifindex = 0;
29138 		}
29139 		if (ipst->ips_ipmp_hook_emulation)
29140 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29141 		else
29142 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29143 
29144 		/*
29145 		 * For IP Filter to find out the relationship between
29146 		 * names and interface indicies, we need to generate
29147 		 * a NE_PLUMB event when a new group can appear.
29148 		 * We always generate events when a new interface appears
29149 		 * (even when ipmp_hook_emulation is set) so there
29150 		 * is no need to generate NE_PLUMB events when
29151 		 * ipmp_hook_emulation is turned off.
29152 		 * And since it isn't critical for IP Filter to get
29153 		 * the NE_UNPLUMB events we skip those here.
29154 		 */
29155 		if (new_group) {
29156 			/*
29157 			 * First phyint in group - generate group PLUMB event.
29158 			 * Since we are not running inside the ipsq we do
29159 			 * the dispatch immediately.
29160 			 */
29161 			if (phyi->phyint_illv4 != NULL)
29162 				ill = phyi->phyint_illv4;
29163 			else
29164 				ill = phyi->phyint_illv6;
29165 
29166 			if (ill != NULL) {
29167 				mutex_enter(&ill->ill_lock);
29168 				ill_nic_info_plumb(ill, B_TRUE);
29169 				ill_nic_info_dispatch(ill);
29170 				mutex_exit(&ill->ill_lock);
29171 			}
29172 		}
29173 	}
29174 	rw_exit(&ipst->ips_ill_g_lock);
29175 }
29176 
29177 /* ARGSUSED */
29178 static int
29179 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29180     caddr_t addr, cred_t *cr)
29181 {
29182 	int *v = (int *)addr;
29183 	long new_value;
29184 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29185 
29186 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29187 		return (EINVAL);
29188 
29189 	if (*v != new_value) {
29190 		*v = new_value;
29191 		ipmp_hook_emulation_changed(ipst);
29192 	}
29193 	return (0);
29194 }
29195 
29196 static void *
29197 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29198 {
29199 	kstat_t *ksp;
29200 
29201 	ip_stat_t template = {
29202 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29203 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29204 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29205 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29206 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29207 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29208 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29209 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29210 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29211 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29212 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29213 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29214 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29215 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29216 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29217 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29218 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29219 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29220 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29221 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29222 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29223 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29224 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29225 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29226 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29227 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29228 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29229 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29230 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29231 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29232 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29233 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29234 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29235 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29236 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29237 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29238 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29239 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29240 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29241 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29242 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29243 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29244 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29245 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29246 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29247 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29248 	};
29249 
29250 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29251 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29252 	    KSTAT_FLAG_VIRTUAL, stackid);
29253 
29254 	if (ksp == NULL)
29255 		return (NULL);
29256 
29257 	bcopy(&template, ip_statisticsp, sizeof (template));
29258 	ksp->ks_data = (void *)ip_statisticsp;
29259 	ksp->ks_private = (void *)(uintptr_t)stackid;
29260 
29261 	kstat_install(ksp);
29262 	return (ksp);
29263 }
29264 
29265 static void
29266 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29267 {
29268 	if (ksp != NULL) {
29269 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29270 		kstat_delete_netstack(ksp, stackid);
29271 	}
29272 }
29273 
29274 static void *
29275 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29276 {
29277 	kstat_t	*ksp;
29278 
29279 	ip_named_kstat_t template = {
29280 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29281 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29282 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29283 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29284 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29285 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29286 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29287 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29288 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29289 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29290 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29291 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29292 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29293 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29294 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29295 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29296 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29297 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29298 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29299 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29300 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29301 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29302 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29303 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29304 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29305 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29306 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29307 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29308 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29309 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29310 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29311 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29312 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29313 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29314 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29315 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29316 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29317 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29318 	};
29319 
29320 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29321 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29322 	if (ksp == NULL || ksp->ks_data == NULL)
29323 		return (NULL);
29324 
29325 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29326 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29327 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29328 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29329 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29330 
29331 	template.netToMediaEntrySize.value.i32 =
29332 	    sizeof (mib2_ipNetToMediaEntry_t);
29333 
29334 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29335 
29336 	bcopy(&template, ksp->ks_data, sizeof (template));
29337 	ksp->ks_update = ip_kstat_update;
29338 	ksp->ks_private = (void *)(uintptr_t)stackid;
29339 
29340 	kstat_install(ksp);
29341 	return (ksp);
29342 }
29343 
29344 static void
29345 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29346 {
29347 	if (ksp != NULL) {
29348 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29349 		kstat_delete_netstack(ksp, stackid);
29350 	}
29351 }
29352 
29353 static int
29354 ip_kstat_update(kstat_t *kp, int rw)
29355 {
29356 	ip_named_kstat_t *ipkp;
29357 	mib2_ipIfStatsEntry_t ipmib;
29358 	ill_walk_context_t ctx;
29359 	ill_t *ill;
29360 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29361 	netstack_t	*ns;
29362 	ip_stack_t	*ipst;
29363 
29364 	if (kp == NULL || kp->ks_data == NULL)
29365 		return (EIO);
29366 
29367 	if (rw == KSTAT_WRITE)
29368 		return (EACCES);
29369 
29370 	ns = netstack_find_by_stackid(stackid);
29371 	if (ns == NULL)
29372 		return (-1);
29373 	ipst = ns->netstack_ip;
29374 	if (ipst == NULL) {
29375 		netstack_rele(ns);
29376 		return (-1);
29377 	}
29378 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29379 
29380 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29381 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29382 	ill = ILL_START_WALK_V4(&ctx, ipst);
29383 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29384 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29385 	rw_exit(&ipst->ips_ill_g_lock);
29386 
29387 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29388 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29389 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29390 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29391 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29392 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29393 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29394 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29395 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29396 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29397 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29398 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29399 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29400 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29401 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29402 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29403 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29404 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29405 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29406 
29407 	ipkp->routingDiscards.value.ui32 =	0;
29408 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29409 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29410 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29411 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29412 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29413 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29414 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29415 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29416 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29417 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29418 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29419 
29420 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29421 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29422 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29423 
29424 	netstack_rele(ns);
29425 
29426 	return (0);
29427 }
29428 
29429 static void *
29430 icmp_kstat_init(netstackid_t stackid)
29431 {
29432 	kstat_t	*ksp;
29433 
29434 	icmp_named_kstat_t template = {
29435 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29436 		{ "inErrors",		KSTAT_DATA_UINT32 },
29437 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29438 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29439 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29440 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29441 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29442 		{ "inEchos",		KSTAT_DATA_UINT32 },
29443 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29444 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29445 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29446 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29447 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29448 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29449 		{ "outErrors",		KSTAT_DATA_UINT32 },
29450 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29451 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29452 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29453 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29454 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29455 		{ "outEchos",		KSTAT_DATA_UINT32 },
29456 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29457 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29458 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29459 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29460 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29461 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29462 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29463 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29464 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29465 		{ "outDrops",		KSTAT_DATA_UINT32 },
29466 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29467 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29468 	};
29469 
29470 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29471 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29472 	if (ksp == NULL || ksp->ks_data == NULL)
29473 		return (NULL);
29474 
29475 	bcopy(&template, ksp->ks_data, sizeof (template));
29476 
29477 	ksp->ks_update = icmp_kstat_update;
29478 	ksp->ks_private = (void *)(uintptr_t)stackid;
29479 
29480 	kstat_install(ksp);
29481 	return (ksp);
29482 }
29483 
29484 static void
29485 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29486 {
29487 	if (ksp != NULL) {
29488 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29489 		kstat_delete_netstack(ksp, stackid);
29490 	}
29491 }
29492 
29493 static int
29494 icmp_kstat_update(kstat_t *kp, int rw)
29495 {
29496 	icmp_named_kstat_t *icmpkp;
29497 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29498 	netstack_t	*ns;
29499 	ip_stack_t	*ipst;
29500 
29501 	if ((kp == NULL) || (kp->ks_data == NULL))
29502 		return (EIO);
29503 
29504 	if (rw == KSTAT_WRITE)
29505 		return (EACCES);
29506 
29507 	ns = netstack_find_by_stackid(stackid);
29508 	if (ns == NULL)
29509 		return (-1);
29510 	ipst = ns->netstack_ip;
29511 	if (ipst == NULL) {
29512 		netstack_rele(ns);
29513 		return (-1);
29514 	}
29515 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29516 
29517 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29518 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29519 	icmpkp->inDestUnreachs.value.ui32 =
29520 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29521 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29522 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29523 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29524 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29525 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29526 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29527 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29528 	icmpkp->inTimestampReps.value.ui32 =
29529 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29530 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29531 	icmpkp->inAddrMaskReps.value.ui32 =
29532 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29533 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29534 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29535 	icmpkp->outDestUnreachs.value.ui32 =
29536 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29537 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29538 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29539 	icmpkp->outSrcQuenchs.value.ui32 =
29540 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29541 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29542 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29543 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29544 	icmpkp->outTimestamps.value.ui32 =
29545 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29546 	icmpkp->outTimestampReps.value.ui32 =
29547 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29548 	icmpkp->outAddrMasks.value.ui32 =
29549 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29550 	icmpkp->outAddrMaskReps.value.ui32 =
29551 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29552 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29553 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29554 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29555 	icmpkp->outFragNeeded.value.ui32 =
29556 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29557 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29558 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29559 	icmpkp->inBadRedirects.value.ui32 =
29560 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29561 
29562 	netstack_rele(ns);
29563 	return (0);
29564 }
29565 
29566 /*
29567  * This is the fanout function for raw socket opened for SCTP.  Note
29568  * that it is called after SCTP checks that there is no socket which
29569  * wants a packet.  Then before SCTP handles this out of the blue packet,
29570  * this function is called to see if there is any raw socket for SCTP.
29571  * If there is and it is bound to the correct address, the packet will
29572  * be sent to that socket.  Note that only one raw socket can be bound to
29573  * a port.  This is assured in ipcl_sctp_hash_insert();
29574  */
29575 void
29576 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29577     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29578     zoneid_t zoneid)
29579 {
29580 	conn_t		*connp;
29581 	queue_t		*rq;
29582 	mblk_t		*first_mp;
29583 	boolean_t	secure;
29584 	ip6_t		*ip6h;
29585 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29586 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29587 
29588 	first_mp = mp;
29589 	if (mctl_present) {
29590 		mp = first_mp->b_cont;
29591 		secure = ipsec_in_is_secure(first_mp);
29592 		ASSERT(mp != NULL);
29593 	} else {
29594 		secure = B_FALSE;
29595 	}
29596 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29597 
29598 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29599 	if (connp == NULL) {
29600 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29601 		return;
29602 	}
29603 	rq = connp->conn_rq;
29604 	if (!canputnext(rq)) {
29605 		CONN_DEC_REF(connp);
29606 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29607 		freemsg(first_mp);
29608 		return;
29609 	}
29610 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29611 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29612 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29613 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29614 		if (first_mp == NULL) {
29615 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29616 			CONN_DEC_REF(connp);
29617 			return;
29618 		}
29619 	}
29620 	/*
29621 	 * We probably should not send M_CTL message up to
29622 	 * raw socket.
29623 	 */
29624 	if (mctl_present)
29625 		freeb(first_mp);
29626 
29627 	/* Initiate IPPF processing here if needed. */
29628 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29629 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29630 		ip_process(IPP_LOCAL_IN, &mp,
29631 		    recv_ill->ill_phyint->phyint_ifindex);
29632 		if (mp == NULL) {
29633 			CONN_DEC_REF(connp);
29634 			return;
29635 		}
29636 	}
29637 
29638 	if (connp->conn_recvif || connp->conn_recvslla ||
29639 	    ((connp->conn_ip_recvpktinfo ||
29640 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29641 	    (flags & IP_FF_IPINFO))) {
29642 		int in_flags = 0;
29643 
29644 		/*
29645 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29646 		 * IPF_RECVIF.
29647 		 */
29648 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29649 			in_flags = IPF_RECVIF;
29650 		}
29651 		if (connp->conn_recvslla) {
29652 			in_flags |= IPF_RECVSLLA;
29653 		}
29654 		if (isv4) {
29655 			mp = ip_add_info(mp, recv_ill, in_flags,
29656 			    IPCL_ZONEID(connp), ipst);
29657 		} else {
29658 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29659 			if (mp == NULL) {
29660 				BUMP_MIB(recv_ill->ill_ip_mib,
29661 				    ipIfStatsInDiscards);
29662 				CONN_DEC_REF(connp);
29663 				return;
29664 			}
29665 		}
29666 	}
29667 
29668 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29669 	/*
29670 	 * We are sending the IPSEC_IN message also up. Refer
29671 	 * to comments above this function.
29672 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29673 	 */
29674 	(connp->conn_recv)(connp, mp, NULL);
29675 	CONN_DEC_REF(connp);
29676 }
29677 
29678 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29679 {									\
29680 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29681 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29682 }
29683 /*
29684  * This function should be called only if all packet processing
29685  * including fragmentation is complete. Callers of this function
29686  * must set mp->b_prev to one of these values:
29687  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29688  * prior to handing over the mp as first argument to this function.
29689  *
29690  * If the ire passed by caller is incomplete, this function
29691  * queues the packet and if necessary, sends ARP request and bails.
29692  * If the ire passed is fully resolved, we simply prepend
29693  * the link-layer header to the packet, do ipsec hw acceleration
29694  * work if necessary, and send the packet out on the wire.
29695  *
29696  * NOTE: IPsec will only call this function with fully resolved
29697  * ires if hw acceleration is involved.
29698  * TODO list :
29699  * 	a Handle M_MULTIDATA so that
29700  *	  tcp_multisend->tcp_multisend_data can
29701  *	  call ip_xmit_v4 directly
29702  *	b Handle post-ARP work for fragments so that
29703  *	  ip_wput_frag can call this function.
29704  */
29705 ipxmit_state_t
29706 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29707 {
29708 	nce_t		*arpce;
29709 	queue_t		*q;
29710 	int		ill_index;
29711 	mblk_t		*nxt_mp, *first_mp;
29712 	boolean_t	xmit_drop = B_FALSE;
29713 	ip_proc_t	proc;
29714 	ill_t		*out_ill;
29715 	int		pkt_len;
29716 
29717 	arpce = ire->ire_nce;
29718 	ASSERT(arpce != NULL);
29719 
29720 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29721 
29722 	mutex_enter(&arpce->nce_lock);
29723 	switch (arpce->nce_state) {
29724 	case ND_REACHABLE:
29725 		/* If there are other queued packets, queue this packet */
29726 		if (arpce->nce_qd_mp != NULL) {
29727 			if (mp != NULL)
29728 				nce_queue_mp_common(arpce, mp, B_FALSE);
29729 			mp = arpce->nce_qd_mp;
29730 		}
29731 		arpce->nce_qd_mp = NULL;
29732 		mutex_exit(&arpce->nce_lock);
29733 
29734 		/*
29735 		 * Flush the queue.  In the common case, where the
29736 		 * ARP is already resolved,  it will go through the
29737 		 * while loop only once.
29738 		 */
29739 		while (mp != NULL) {
29740 
29741 			nxt_mp = mp->b_next;
29742 			mp->b_next = NULL;
29743 			ASSERT(mp->b_datap->db_type != M_CTL);
29744 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29745 			/*
29746 			 * This info is needed for IPQOS to do COS marking
29747 			 * in ip_wput_attach_llhdr->ip_process.
29748 			 */
29749 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29750 			mp->b_prev = NULL;
29751 
29752 			/* set up ill index for outbound qos processing */
29753 			out_ill = ire_to_ill(ire);
29754 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29755 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29756 			    ill_index);
29757 			if (first_mp == NULL) {
29758 				xmit_drop = B_TRUE;
29759 				BUMP_MIB(out_ill->ill_ip_mib,
29760 				    ipIfStatsOutDiscards);
29761 				goto next_mp;
29762 			}
29763 			/* non-ipsec hw accel case */
29764 			if (io == NULL || !io->ipsec_out_accelerated) {
29765 				/* send it */
29766 				q = ire->ire_stq;
29767 				if (proc == IPP_FWD_OUT) {
29768 					UPDATE_IB_PKT_COUNT(ire);
29769 				} else {
29770 					UPDATE_OB_PKT_COUNT(ire);
29771 				}
29772 				ire->ire_last_used_time = lbolt;
29773 
29774 				if (flow_ctl_enabled || canputnext(q)) {
29775 					if (proc == IPP_FWD_OUT) {
29776 
29777 					BUMP_MIB(out_ill->ill_ip_mib,
29778 					    ipIfStatsHCOutForwDatagrams);
29779 
29780 					}
29781 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29782 					    pkt_len);
29783 
29784 					putnext(q, first_mp);
29785 				} else {
29786 					BUMP_MIB(out_ill->ill_ip_mib,
29787 					    ipIfStatsOutDiscards);
29788 					xmit_drop = B_TRUE;
29789 					freemsg(first_mp);
29790 				}
29791 			} else {
29792 				/*
29793 				 * Safety Pup says: make sure this
29794 				 *  is going to the right interface!
29795 				 */
29796 				ill_t *ill1 =
29797 				    (ill_t *)ire->ire_stq->q_ptr;
29798 				int ifindex =
29799 				    ill1->ill_phyint->phyint_ifindex;
29800 				if (ifindex !=
29801 				    io->ipsec_out_capab_ill_index) {
29802 					xmit_drop = B_TRUE;
29803 					freemsg(mp);
29804 				} else {
29805 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29806 					    pkt_len);
29807 					ipsec_hw_putnext(ire->ire_stq, mp);
29808 				}
29809 			}
29810 next_mp:
29811 			mp = nxt_mp;
29812 		} /* while (mp != NULL) */
29813 		if (xmit_drop)
29814 			return (SEND_FAILED);
29815 		else
29816 			return (SEND_PASSED);
29817 
29818 	case ND_INITIAL:
29819 	case ND_INCOMPLETE:
29820 
29821 		/*
29822 		 * While we do send off packets to dests that
29823 		 * use fully-resolved CGTP routes, we do not
29824 		 * handle unresolved CGTP routes.
29825 		 */
29826 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29827 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29828 
29829 		if (mp != NULL) {
29830 			/* queue the packet */
29831 			nce_queue_mp_common(arpce, mp, B_FALSE);
29832 		}
29833 
29834 		if (arpce->nce_state == ND_INCOMPLETE) {
29835 			mutex_exit(&arpce->nce_lock);
29836 			DTRACE_PROBE3(ip__xmit__incomplete,
29837 			    (ire_t *), ire, (mblk_t *), mp,
29838 			    (ipsec_out_t *), io);
29839 			return (LOOKUP_IN_PROGRESS);
29840 		}
29841 
29842 		arpce->nce_state = ND_INCOMPLETE;
29843 		mutex_exit(&arpce->nce_lock);
29844 		/*
29845 		 * Note that ire_add() (called from ire_forward())
29846 		 * holds a ref on the ire until ARP is completed.
29847 		 */
29848 
29849 		ire_arpresolve(ire, ire_to_ill(ire));
29850 		return (LOOKUP_IN_PROGRESS);
29851 	default:
29852 		ASSERT(0);
29853 		mutex_exit(&arpce->nce_lock);
29854 		return (LLHDR_RESLV_FAILED);
29855 	}
29856 }
29857 
29858 #undef	UPDATE_IP_MIB_OB_COUNTERS
29859 
29860 /*
29861  * Return B_TRUE if the buffers differ in length or content.
29862  * This is used for comparing extension header buffers.
29863  * Note that an extension header would be declared different
29864  * even if all that changed was the next header value in that header i.e.
29865  * what really changed is the next extension header.
29866  */
29867 boolean_t
29868 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29869     uint_t blen)
29870 {
29871 	if (!b_valid)
29872 		blen = 0;
29873 
29874 	if (alen != blen)
29875 		return (B_TRUE);
29876 	if (alen == 0)
29877 		return (B_FALSE);	/* Both zero length */
29878 	return (bcmp(abuf, bbuf, alen));
29879 }
29880 
29881 /*
29882  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29883  * Return B_FALSE if memory allocation fails - don't change any state!
29884  */
29885 boolean_t
29886 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29887     const void *src, uint_t srclen)
29888 {
29889 	void *dst;
29890 
29891 	if (!src_valid)
29892 		srclen = 0;
29893 
29894 	ASSERT(*dstlenp == 0);
29895 	if (src != NULL && srclen != 0) {
29896 		dst = mi_alloc(srclen, BPRI_MED);
29897 		if (dst == NULL)
29898 			return (B_FALSE);
29899 	} else {
29900 		dst = NULL;
29901 	}
29902 	if (*dstp != NULL)
29903 		mi_free(*dstp);
29904 	*dstp = dst;
29905 	*dstlenp = dst == NULL ? 0 : srclen;
29906 	return (B_TRUE);
29907 }
29908 
29909 /*
29910  * Replace what is in *dst, *dstlen with the source.
29911  * Assumes ip_allocbuf has already been called.
29912  */
29913 void
29914 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29915     const void *src, uint_t srclen)
29916 {
29917 	if (!src_valid)
29918 		srclen = 0;
29919 
29920 	ASSERT(*dstlenp == srclen);
29921 	if (src != NULL && srclen != 0)
29922 		bcopy(src, *dstp, srclen);
29923 }
29924 
29925 /*
29926  * Free the storage pointed to by the members of an ip6_pkt_t.
29927  */
29928 void
29929 ip6_pkt_free(ip6_pkt_t *ipp)
29930 {
29931 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29932 
29933 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29934 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29935 		ipp->ipp_hopopts = NULL;
29936 		ipp->ipp_hopoptslen = 0;
29937 	}
29938 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29939 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29940 		ipp->ipp_rtdstopts = NULL;
29941 		ipp->ipp_rtdstoptslen = 0;
29942 	}
29943 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29944 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29945 		ipp->ipp_dstopts = NULL;
29946 		ipp->ipp_dstoptslen = 0;
29947 	}
29948 	if (ipp->ipp_fields & IPPF_RTHDR) {
29949 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29950 		ipp->ipp_rthdr = NULL;
29951 		ipp->ipp_rthdrlen = 0;
29952 	}
29953 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29954 	    IPPF_RTHDR);
29955 }
29956