xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision f83ffe1aa13dc057aa65c36bacc83297b35f9be2)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
823     zoneid_t);
824 static void	conn_setqfull(conn_t *);
825 static void	conn_clrqfull(conn_t *);
826 
827 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
828 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
829 static void	ip_stack_fini(netstackid_t stackid, void *arg);
830 
831 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
832     zoneid_t);
833 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
834     void *dummy_arg);
835 
836 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
837 
838 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
839     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
840     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
841 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
842 
843 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
844 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
845     caddr_t, cred_t *);
846 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
847     cred_t *, boolean_t);
848 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
849     caddr_t cp, cred_t *cr);
850 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
851     cred_t *);
852 static int	ip_squeue_switch(int);
853 
854 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
855 static void	ip_kstat_fini(netstackid_t, kstat_t *);
856 static int	ip_kstat_update(kstat_t *kp, int rw);
857 static void	*icmp_kstat_init(netstackid_t);
858 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
859 static int	icmp_kstat_update(kstat_t *kp, int rw);
860 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
861 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
862 
863 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
864 
865 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
866     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
867 
868 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
869     ipha_t *, ill_t *, boolean_t, boolean_t);
870 
871 static void ipobs_init(ip_stack_t *);
872 static void ipobs_fini(ip_stack_t *);
873 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
874 
875 /* How long, in seconds, we allow frags to hang around. */
876 #define	IP_FRAG_TIMEOUT	15
877 
878 /*
879  * Threshold which determines whether MDT should be used when
880  * generating IP fragments; payload size must be greater than
881  * this threshold for MDT to take place.
882  */
883 #define	IP_WPUT_FRAG_MDT_MIN	32768
884 
885 /* Setable in /etc/system only */
886 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
887 
888 static long ip_rput_pullups;
889 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
890 
891 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
892 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
893 
894 int	ip_debug;
895 
896 #ifdef DEBUG
897 uint32_t ipsechw_debug = 0;
898 #endif
899 
900 /*
901  * Multirouting/CGTP stuff
902  */
903 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
904 
905 /*
906  * XXX following really should only be in a header. Would need more
907  * header and .c clean up first.
908  */
909 extern optdb_obj_t	ip_opt_obj;
910 
911 ulong_t ip_squeue_enter_unbound = 0;
912 
913 /*
914  * Named Dispatch Parameter Table.
915  * All of these are alterable, within the min/max values given, at run time.
916  */
917 static ipparam_t	lcl_param_arr[] = {
918 	/* min	max	value	name */
919 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
920 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
921 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
922 	{  0,	1,	0,	"ip_respond_to_timestamp"},
923 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
924 	{  0,	1,	1,	"ip_send_redirects"},
925 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
926 	{  0,	10,	0,	"ip_mrtdebug"},
927 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
928 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
929 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
930 	{  1,	255,	255,	"ip_def_ttl" },
931 	{  0,	1,	0,	"ip_forward_src_routed"},
932 	{  0,	256,	32,	"ip_wroff_extra" },
933 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
934 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
935 	{  0,	1,	1,	"ip_path_mtu_discovery" },
936 	{  0,	240,	30,	"ip_ignore_delete_time" },
937 	{  0,	1,	0,	"ip_ignore_redirect" },
938 	{  0,	1,	1,	"ip_output_queue" },
939 	{  1,	254,	1,	"ip_broadcast_ttl" },
940 	{  0,	99999,	100,	"ip_icmp_err_interval" },
941 	{  1,	99999,	10,	"ip_icmp_err_burst" },
942 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
943 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
944 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
945 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
946 	{  0,	1,	1,	"icmp_accept_clear_messages" },
947 	{  0,	1,	1,	"igmp_accept_clear_messages" },
948 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
949 				"ip_ndp_delay_first_probe_time"},
950 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
951 				"ip_ndp_max_unicast_solicit"},
952 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
953 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
954 	{  0,	1,	0,	"ip6_forward_src_routed"},
955 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
956 	{  0,	1,	1,	"ip6_send_redirects"},
957 	{  0,	1,	0,	"ip6_ignore_redirect" },
958 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
959 
960 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
961 
962 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
963 
964 	{  0,	1,	1,	"pim_accept_clear_messages" },
965 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
966 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
967 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
968 	{  0,	15,	0,	"ip_policy_mask" },
969 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
970 	{  0,	255,	1,	"ip_multirt_ttl" },
971 	{  0,	1,	1,	"ip_multidata_outbound" },
972 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
973 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
974 	{  0,	1000,	1,	"ip_max_temp_defend" },
975 	{  0,	1000,	3,	"ip_max_defend" },
976 	{  0,	999999,	30,	"ip_defend_interval" },
977 	{  0,	3600000, 300000, "ip_dup_recovery" },
978 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
979 	{  0,	1,	1,	"ip_lso_outbound" },
980 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
981 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
982 	{ 68,	65535,	576,	"ip_pmtu_min" },
983 #ifdef DEBUG
984 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
985 #else
986 	{  0,	0,	0,	"" },
987 #endif
988 };
989 
990 /*
991  * Extended NDP table
992  * The addresses for the first two are filled in to be ips_ip_g_forward
993  * and ips_ipv6_forward at init time.
994  */
995 static ipndp_t	lcl_ndp_arr[] = {
996 	/* getf			setf		data			name */
997 #define	IPNDP_IP_FORWARDING_OFFSET	0
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip_forwarding" },
1000 #define	IPNDP_IP6_FORWARDING_OFFSET	1
1001 	{  ip_param_generic_get,	ip_forward_set,	NULL,
1002 	    "ip6_forwarding" },
1003 	{  ip_ill_report,	NULL,		NULL,
1004 	    "ip_ill_status" },
1005 	{  ip_ipif_report,	NULL,		NULL,
1006 	    "ip_ipif_status" },
1007 	{  ip_conn_report,	NULL,		NULL,
1008 	    "ip_conn_status" },
1009 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1010 	    "ip_rput_pullups" },
1011 	{  ip_srcid_report,	NULL,		NULL,
1012 	    "ip_srcid_status" },
1013 	{ ip_param_generic_get, ip_input_proc_set,
1014 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1015 	{ ip_param_generic_get, ip_int_set,
1016 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1017 #define	IPNDP_CGTP_FILTER_OFFSET	9
1018 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1019 	    "ip_cgtp_filter" },
1020 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1021 	    "ip_debug" },
1022 };
1023 
1024 /*
1025  * Table of IP ioctls encoding the various properties of the ioctl and
1026  * indexed based on the last byte of the ioctl command. Occasionally there
1027  * is a clash, and there is more than 1 ioctl with the same last byte.
1028  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1029  * ioctls are encoded in the misc table. An entry in the ndx table is
1030  * retrieved by indexing on the last byte of the ioctl command and comparing
1031  * the ioctl command with the value in the ndx table. In the event of a
1032  * mismatch the misc table is then searched sequentially for the desired
1033  * ioctl command.
1034  *
1035  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1036  */
1037 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1038 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 
1049 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1050 			MISC_CMD, ip_siocaddrt, NULL },
1051 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1052 			MISC_CMD, ip_siocdelrt, NULL },
1053 
1054 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1055 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1056 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1057 			IF_CMD, ip_sioctl_get_addr, NULL },
1058 
1059 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1060 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1061 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1062 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1063 
1064 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1065 			IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1067 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1068 			IPI_MODOK | IPI_GET_CMD,
1069 			IF_CMD, ip_sioctl_get_flags, NULL },
1070 
1071 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 
1074 	/* copyin size cannot be coded for SIOCGIFCONF */
1075 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1076 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1077 
1078 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1079 			IF_CMD, ip_sioctl_mtu, NULL },
1080 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1081 			IF_CMD, ip_sioctl_get_mtu, NULL },
1082 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1083 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1084 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1085 			IF_CMD, ip_sioctl_brdaddr, NULL },
1086 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1087 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1088 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1089 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1090 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1091 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1092 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1093 			IF_CMD, ip_sioctl_metric, NULL },
1094 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 
1096 	/* See 166-168 below for extended SIOC*XARP ioctls */
1097 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1098 			ARP_CMD, ip_sioctl_arp, NULL },
1099 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1100 			ARP_CMD, ip_sioctl_arp, NULL },
1101 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1102 			ARP_CMD, ip_sioctl_arp, NULL },
1103 
1104 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 
1126 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1127 			MISC_CMD, if_unitsel, if_unitsel_restart },
1128 
1129 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 
1148 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1149 			IPI_PRIV | IPI_WR | IPI_MODOK,
1150 			IF_CMD, ip_sioctl_sifname, NULL },
1151 
1152 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 
1166 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1167 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1168 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1169 			IF_CMD, ip_sioctl_get_muxid, NULL },
1170 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1171 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1172 
1173 	/* Both if and lif variants share same func */
1174 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1175 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1176 	/* Both if and lif variants share same func */
1177 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1178 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1179 
1180 	/* copyin size cannot be coded for SIOCGIFCONF */
1181 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1182 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1183 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 
1201 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1202 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1203 			ip_sioctl_removeif_restart },
1204 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1205 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1206 			LIF_CMD, ip_sioctl_addif, NULL },
1207 #define	SIOCLIFADDR_NDX 112
1208 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1209 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1210 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1211 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1212 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1213 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1214 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1215 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1216 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1217 			IPI_PRIV | IPI_WR,
1218 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1219 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1220 			IPI_GET_CMD | IPI_MODOK,
1221 			LIF_CMD, ip_sioctl_get_flags, NULL },
1222 
1223 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 
1226 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1227 			ip_sioctl_get_lifconf, NULL },
1228 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_mtu, NULL },
1230 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1231 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1232 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1233 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1234 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1235 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1236 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1237 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1238 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1239 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1240 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1241 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1242 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 			LIF_CMD, ip_sioctl_metric, NULL },
1244 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR | IPI_MODOK,
1246 			LIF_CMD, ip_sioctl_slifname,
1247 			ip_sioctl_slifname_restart },
1248 
1249 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1250 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1251 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1252 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1253 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1255 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1256 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1257 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1258 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1259 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1260 			LIF_CMD, ip_sioctl_token, NULL },
1261 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1262 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1263 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1264 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1265 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1266 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1267 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1268 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1269 
1270 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1271 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1272 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1273 			LIF_CMD, ip_siocdelndp_v6, NULL },
1274 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1275 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1276 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1277 			LIF_CMD, ip_siocsetndp_v6, NULL },
1278 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1279 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1280 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1281 			MISC_CMD, ip_sioctl_tonlink, NULL },
1282 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1283 			MISC_CMD, ip_sioctl_tmysite, NULL },
1284 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1285 			TUN_CMD, ip_sioctl_tunparam, NULL },
1286 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1287 		    IPI_PRIV | IPI_WR,
1288 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1289 
1290 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1291 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1292 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1293 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1294 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1295 
1296 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 
1298 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1299 			LIF_CMD, ip_sioctl_get_binding, NULL },
1300 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR,
1302 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1303 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1304 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1305 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1306 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1307 
1308 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1309 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1310 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1311 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1312 
1313 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1314 
1315 	/* These are handled in ip_sioctl_copyin_setup itself */
1316 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1317 			MISC_CMD, NULL, NULL },
1318 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1319 			MISC_CMD, NULL, NULL },
1320 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1321 
1322 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1323 			ip_sioctl_get_lifconf, NULL },
1324 
1325 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1326 			XARP_CMD, ip_sioctl_arp, NULL },
1327 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1328 			XARP_CMD, ip_sioctl_arp, NULL },
1329 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1330 			XARP_CMD, ip_sioctl_arp, NULL },
1331 
1332 	/* SIOCPOPSOCKFS is not handled by IP */
1333 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1334 
1335 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1336 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1337 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1338 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1339 			ip_sioctl_slifzone_restart },
1340 	/* 172-174 are SCTP ioctls and not handled by IP */
1341 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1342 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1343 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1344 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1345 			IPI_GET_CMD, LIF_CMD,
1346 			ip_sioctl_get_lifusesrc, 0 },
1347 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1348 			IPI_PRIV | IPI_WR,
1349 			LIF_CMD, ip_sioctl_slifusesrc,
1350 			NULL },
1351 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1352 			ip_sioctl_get_lifsrcof, NULL },
1353 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1354 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1355 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1356 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1357 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1358 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1359 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1360 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1361 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* SIOCSENABLESDP is handled by SDP */
1363 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1364 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1365 };
1366 
1367 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1368 
1369 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1370 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1371 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1372 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1373 		TUN_CMD, ip_sioctl_tunparam, NULL },
1374 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1375 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1376 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1377 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1378 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1379 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1380 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1381 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1382 		MISC_CMD, mrt_ioctl},
1383 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1384 		MISC_CMD, mrt_ioctl},
1385 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1386 		MISC_CMD, mrt_ioctl}
1387 };
1388 
1389 int ip_misc_ioctl_count =
1390     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1391 
1392 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1393 					/* Settable in /etc/system */
1394 /* Defined in ip_ire.c */
1395 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1396 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1397 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1398 
1399 static nv_t	ire_nv_arr[] = {
1400 	{ IRE_BROADCAST, "BROADCAST" },
1401 	{ IRE_LOCAL, "LOCAL" },
1402 	{ IRE_LOOPBACK, "LOOPBACK" },
1403 	{ IRE_CACHE, "CACHE" },
1404 	{ IRE_DEFAULT, "DEFAULT" },
1405 	{ IRE_PREFIX, "PREFIX" },
1406 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1407 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1408 	{ IRE_HOST, "HOST" },
1409 	{ 0 }
1410 };
1411 
1412 nv_t	*ire_nv_tbl = ire_nv_arr;
1413 
1414 /* Simple ICMP IP Header Template */
1415 static ipha_t icmp_ipha = {
1416 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1417 };
1418 
1419 struct module_info ip_mod_info = {
1420 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1421 	IP_MOD_LOWAT
1422 };
1423 
1424 /*
1425  * Duplicate static symbols within a module confuses mdb; so we avoid the
1426  * problem by making the symbols here distinct from those in udp.c.
1427  */
1428 
1429 /*
1430  * Entry points for IP as a device and as a module.
1431  * FIXME: down the road we might want a separate module and driver qinit.
1432  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1433  */
1434 static struct qinit iprinitv4 = {
1435 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1436 	&ip_mod_info
1437 };
1438 
1439 struct qinit iprinitv6 = {
1440 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1441 	&ip_mod_info
1442 };
1443 
1444 static struct qinit ipwinitv4 = {
1445 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1446 	&ip_mod_info
1447 };
1448 
1449 struct qinit ipwinitv6 = {
1450 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1451 	&ip_mod_info
1452 };
1453 
1454 static struct qinit iplrinit = {
1455 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1456 	&ip_mod_info
1457 };
1458 
1459 static struct qinit iplwinit = {
1460 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1461 	&ip_mod_info
1462 };
1463 
1464 /* For AF_INET aka /dev/ip */
1465 struct streamtab ipinfov4 = {
1466 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1467 };
1468 
1469 /* For AF_INET6 aka /dev/ip6 */
1470 struct streamtab ipinfov6 = {
1471 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1472 };
1473 
1474 #ifdef	DEBUG
1475 static boolean_t skip_sctp_cksum = B_FALSE;
1476 #endif
1477 
1478 /*
1479  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1480  * ip_rput_v6(), ip_output(), etc.  If the message
1481  * block already has a M_CTL at the front of it, then simply set the zoneid
1482  * appropriately.
1483  */
1484 mblk_t *
1485 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1486 {
1487 	mblk_t		*first_mp;
1488 	ipsec_out_t	*io;
1489 
1490 	ASSERT(zoneid != ALL_ZONES);
1491 	if (mp->b_datap->db_type == M_CTL) {
1492 		io = (ipsec_out_t *)mp->b_rptr;
1493 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1494 		io->ipsec_out_zoneid = zoneid;
1495 		return (mp);
1496 	}
1497 
1498 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1499 	if (first_mp == NULL)
1500 		return (NULL);
1501 	io = (ipsec_out_t *)first_mp->b_rptr;
1502 	/* This is not a secure packet */
1503 	io->ipsec_out_secure = B_FALSE;
1504 	io->ipsec_out_zoneid = zoneid;
1505 	first_mp->b_cont = mp;
1506 	return (first_mp);
1507 }
1508 
1509 /*
1510  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1511  */
1512 mblk_t *
1513 ip_copymsg(mblk_t *mp)
1514 {
1515 	mblk_t *nmp;
1516 	ipsec_info_t *in;
1517 
1518 	if (mp->b_datap->db_type != M_CTL)
1519 		return (copymsg(mp));
1520 
1521 	in = (ipsec_info_t *)mp->b_rptr;
1522 
1523 	/*
1524 	 * Note that M_CTL is also used for delivering ICMP error messages
1525 	 * upstream to transport layers.
1526 	 */
1527 	if (in->ipsec_info_type != IPSEC_OUT &&
1528 	    in->ipsec_info_type != IPSEC_IN)
1529 		return (copymsg(mp));
1530 
1531 	nmp = copymsg(mp->b_cont);
1532 
1533 	if (in->ipsec_info_type == IPSEC_OUT) {
1534 		return (ipsec_out_tag(mp, nmp,
1535 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1536 	} else {
1537 		return (ipsec_in_tag(mp, nmp,
1538 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1539 	}
1540 }
1541 
1542 /* Generate an ICMP fragmentation needed message. */
1543 static void
1544 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1545     ip_stack_t *ipst)
1546 {
1547 	icmph_t	icmph;
1548 	mblk_t *first_mp;
1549 	boolean_t mctl_present;
1550 
1551 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1552 
1553 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1554 		if (mctl_present)
1555 			freeb(first_mp);
1556 		return;
1557 	}
1558 
1559 	bzero(&icmph, sizeof (icmph_t));
1560 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1561 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1562 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1563 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1564 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1565 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1566 	    ipst);
1567 }
1568 
1569 /*
1570  * icmp_inbound deals with ICMP messages in the following ways.
1571  *
1572  * 1) It needs to send a reply back and possibly delivering it
1573  *    to the "interested" upper clients.
1574  * 2) It needs to send it to the upper clients only.
1575  * 3) It needs to change some values in IP only.
1576  * 4) It needs to change some values in IP and upper layers e.g TCP.
1577  *
1578  * We need to accomodate icmp messages coming in clear until we get
1579  * everything secure from the wire. If icmp_accept_clear_messages
1580  * is zero we check with the global policy and act accordingly. If
1581  * it is non-zero, we accept the message without any checks. But
1582  * *this does not mean* that this will be delivered to the upper
1583  * clients. By accepting we might send replies back, change our MTU
1584  * value etc. but delivery to the ULP/clients depends on their policy
1585  * dispositions.
1586  *
1587  * We handle the above 4 cases in the context of IPsec in the
1588  * following way :
1589  *
1590  * 1) Send the reply back in the same way as the request came in.
1591  *    If it came in encrypted, it goes out encrypted. If it came in
1592  *    clear, it goes out in clear. Thus, this will prevent chosen
1593  *    plain text attack.
1594  * 2) The client may or may not expect things to come in secure.
1595  *    If it comes in secure, the policy constraints are checked
1596  *    before delivering it to the upper layers. If it comes in
1597  *    clear, ipsec_inbound_accept_clear will decide whether to
1598  *    accept this in clear or not. In both the cases, if the returned
1599  *    message (IP header + 8 bytes) that caused the icmp message has
1600  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1601  *    sending up. If there are only 8 bytes of returned message, then
1602  *    upper client will not be notified.
1603  * 3) Check with global policy to see whether it matches the constaints.
1604  *    But this will be done only if icmp_accept_messages_in_clear is
1605  *    zero.
1606  * 4) If we need to change both in IP and ULP, then the decision taken
1607  *    while affecting the values in IP and while delivering up to TCP
1608  *    should be the same.
1609  *
1610  * 	There are two cases.
1611  *
1612  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1613  *	   failed), we will not deliver it to the ULP, even though they
1614  *	   are *willing* to accept in *clear*. This is fine as our global
1615  *	   disposition to icmp messages asks us reject the datagram.
1616  *
1617  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1618  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1619  *	   to deliver it to ULP (policy failed), it can lead to
1620  *	   consistency problems. The cases known at this time are
1621  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1622  *	   values :
1623  *
1624  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1625  *	     and Upper layer rejects. Then the communication will
1626  *	     come to a stop. This is solved by making similar decisions
1627  *	     at both levels. Currently, when we are unable to deliver
1628  *	     to the Upper Layer (due to policy failures) while IP has
1629  *	     adjusted ire_max_frag, the next outbound datagram would
1630  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1631  *	     will be with the right level of protection. Thus the right
1632  *	     value will be communicated even if we are not able to
1633  *	     communicate when we get from the wire initially. But this
1634  *	     assumes there would be at least one outbound datagram after
1635  *	     IP has adjusted its ire_max_frag value. To make things
1636  *	     simpler, we accept in clear after the validation of
1637  *	     AH/ESP headers.
1638  *
1639  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1640  *	     upper layer depending on the level of protection the upper
1641  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1642  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1643  *	     should be accepted in clear when the Upper layer expects secure.
1644  *	     Thus the communication may get aborted by some bad ICMP
1645  *	     packets.
1646  *
1647  * IPQoS Notes:
1648  * The only instance when a packet is sent for processing is when there
1649  * isn't an ICMP client and if we are interested in it.
1650  * If there is a client, IPPF processing will take place in the
1651  * ip_fanout_proto routine.
1652  *
1653  * Zones notes:
1654  * The packet is only processed in the context of the specified zone: typically
1655  * only this zone will reply to an echo request, and only interested clients in
1656  * this zone will receive a copy of the packet. This means that the caller must
1657  * call icmp_inbound() for each relevant zone.
1658  */
1659 static void
1660 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1661     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1662     ill_t *recv_ill, zoneid_t zoneid)
1663 {
1664 	icmph_t	*icmph;
1665 	ipha_t	*ipha;
1666 	int	iph_hdr_length;
1667 	int	hdr_length;
1668 	boolean_t	interested;
1669 	uint32_t	ts;
1670 	uchar_t	*wptr;
1671 	ipif_t	*ipif;
1672 	mblk_t *first_mp;
1673 	ipsec_in_t *ii;
1674 	timestruc_t now;
1675 	uint32_t ill_index;
1676 	ip_stack_t *ipst;
1677 
1678 	ASSERT(ill != NULL);
1679 	ipst = ill->ill_ipst;
1680 
1681 	first_mp = mp;
1682 	if (mctl_present) {
1683 		mp = first_mp->b_cont;
1684 		ASSERT(mp != NULL);
1685 	}
1686 
1687 	ipha = (ipha_t *)mp->b_rptr;
1688 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1689 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1690 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1691 		if (first_mp == NULL)
1692 			return;
1693 	}
1694 
1695 	/*
1696 	 * On a labeled system, we have to check whether the zone itself is
1697 	 * permitted to receive raw traffic.
1698 	 */
1699 	if (is_system_labeled()) {
1700 		if (zoneid == ALL_ZONES)
1701 			zoneid = tsol_packet_to_zoneid(mp);
1702 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1703 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1704 			    zoneid));
1705 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1706 			freemsg(first_mp);
1707 			return;
1708 		}
1709 	}
1710 
1711 	/*
1712 	 * We have accepted the ICMP message. It means that we will
1713 	 * respond to the packet if needed. It may not be delivered
1714 	 * to the upper client depending on the policy constraints
1715 	 * and the disposition in ipsec_inbound_accept_clear.
1716 	 */
1717 
1718 	ASSERT(ill != NULL);
1719 
1720 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1721 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1722 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1723 		/* Last chance to get real. */
1724 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1725 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1726 			freemsg(first_mp);
1727 			return;
1728 		}
1729 		/* Refresh iph following the pullup. */
1730 		ipha = (ipha_t *)mp->b_rptr;
1731 	}
1732 	/* ICMP header checksum, including checksum field, should be zero. */
1733 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1734 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1736 		freemsg(first_mp);
1737 		return;
1738 	}
1739 	/* The IP header will always be a multiple of four bytes */
1740 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1741 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1742 	    icmph->icmph_code));
1743 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1744 	/* We will set "interested" to "true" if we want a copy */
1745 	interested = B_FALSE;
1746 	switch (icmph->icmph_type) {
1747 	case ICMP_ECHO_REPLY:
1748 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1749 		break;
1750 	case ICMP_DEST_UNREACHABLE:
1751 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1752 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1753 		interested = B_TRUE;	/* Pass up to transport */
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1755 		break;
1756 	case ICMP_SOURCE_QUENCH:
1757 		interested = B_TRUE;	/* Pass up to transport */
1758 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1759 		break;
1760 	case ICMP_REDIRECT:
1761 		if (!ipst->ips_ip_ignore_redirect)
1762 			interested = B_TRUE;
1763 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1764 		break;
1765 	case ICMP_ECHO_REQUEST:
1766 		/*
1767 		 * Whether to respond to echo requests that come in as IP
1768 		 * broadcasts or as IP multicast is subject to debate
1769 		 * (what isn't?).  We aim to please, you pick it.
1770 		 * Default is do it.
1771 		 */
1772 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1773 			/* unicast: always respond */
1774 			interested = B_TRUE;
1775 		} else if (CLASSD(ipha->ipha_dst)) {
1776 			/* multicast: respond based on tunable */
1777 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1778 		} else if (broadcast) {
1779 			/* broadcast: respond based on tunable */
1780 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1781 		}
1782 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1783 		break;
1784 	case ICMP_ROUTER_ADVERTISEMENT:
1785 	case ICMP_ROUTER_SOLICITATION:
1786 		break;
1787 	case ICMP_TIME_EXCEEDED:
1788 		interested = B_TRUE;	/* Pass up to transport */
1789 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1790 		break;
1791 	case ICMP_PARAM_PROBLEM:
1792 		interested = B_TRUE;	/* Pass up to transport */
1793 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1794 		break;
1795 	case ICMP_TIME_STAMP_REQUEST:
1796 		/* Response to Time Stamp Requests is local policy. */
1797 		if (ipst->ips_ip_g_resp_to_timestamp &&
1798 		    /* So is whether to respond if it was an IP broadcast. */
1799 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1800 			int tstamp_len = 3 * sizeof (uint32_t);
1801 
1802 			if (wptr +  tstamp_len > mp->b_wptr) {
1803 				if (!pullupmsg(mp, wptr + tstamp_len -
1804 				    mp->b_rptr)) {
1805 					BUMP_MIB(ill->ill_ip_mib,
1806 					    ipIfStatsInDiscards);
1807 					freemsg(first_mp);
1808 					return;
1809 				}
1810 				/* Refresh ipha following the pullup. */
1811 				ipha = (ipha_t *)mp->b_rptr;
1812 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1813 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1814 			}
1815 			interested = B_TRUE;
1816 		}
1817 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1818 		break;
1819 	case ICMP_TIME_STAMP_REPLY:
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1821 		break;
1822 	case ICMP_INFO_REQUEST:
1823 		/* Per RFC 1122 3.2.2.7, ignore this. */
1824 	case ICMP_INFO_REPLY:
1825 		break;
1826 	case ICMP_ADDRESS_MASK_REQUEST:
1827 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1828 		    !broadcast) &&
1829 		    /* TODO m_pullup of complete header? */
1830 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1831 			interested = B_TRUE;
1832 		}
1833 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1834 		break;
1835 	case ICMP_ADDRESS_MASK_REPLY:
1836 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1837 		break;
1838 	default:
1839 		interested = B_TRUE;	/* Pass up to transport */
1840 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1841 		break;
1842 	}
1843 	/* See if there is an ICMP client. */
1844 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1845 		/* If there is an ICMP client and we want one too, copy it. */
1846 		mblk_t *first_mp1;
1847 
1848 		if (!interested) {
1849 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1850 			    ip_policy, recv_ill, zoneid);
1851 			return;
1852 		}
1853 		first_mp1 = ip_copymsg(first_mp);
1854 		if (first_mp1 != NULL) {
1855 			ip_fanout_proto(q, first_mp1, ill, ipha,
1856 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1857 		}
1858 	} else if (!interested) {
1859 		freemsg(first_mp);
1860 		return;
1861 	} else {
1862 		/*
1863 		 * Initiate policy processing for this packet if ip_policy
1864 		 * is true.
1865 		 */
1866 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1867 			ill_index = ill->ill_phyint->phyint_ifindex;
1868 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1869 			if (mp == NULL) {
1870 				if (mctl_present) {
1871 					freeb(first_mp);
1872 				}
1873 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1874 				return;
1875 			}
1876 		}
1877 	}
1878 	/* We want to do something with it. */
1879 	/* Check db_ref to make sure we can modify the packet. */
1880 	if (mp->b_datap->db_ref > 1) {
1881 		mblk_t	*first_mp1;
1882 
1883 		first_mp1 = ip_copymsg(first_mp);
1884 		freemsg(first_mp);
1885 		if (!first_mp1) {
1886 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1887 			return;
1888 		}
1889 		first_mp = first_mp1;
1890 		if (mctl_present) {
1891 			mp = first_mp->b_cont;
1892 			ASSERT(mp != NULL);
1893 		} else {
1894 			mp = first_mp;
1895 		}
1896 		ipha = (ipha_t *)mp->b_rptr;
1897 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1898 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1899 	}
1900 	switch (icmph->icmph_type) {
1901 	case ICMP_ADDRESS_MASK_REQUEST:
1902 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1903 		if (ipif == NULL) {
1904 			freemsg(first_mp);
1905 			return;
1906 		}
1907 		/*
1908 		 * outging interface must be IPv4
1909 		 */
1910 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1911 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1912 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1913 		ipif_refrele(ipif);
1914 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1915 		break;
1916 	case ICMP_ECHO_REQUEST:
1917 		icmph->icmph_type = ICMP_ECHO_REPLY;
1918 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1919 		break;
1920 	case ICMP_TIME_STAMP_REQUEST: {
1921 		uint32_t *tsp;
1922 
1923 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1924 		tsp = (uint32_t *)wptr;
1925 		tsp++;		/* Skip past 'originate time' */
1926 		/* Compute # of milliseconds since midnight */
1927 		gethrestime(&now);
1928 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1929 		    now.tv_nsec / (NANOSEC / MILLISEC);
1930 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1931 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1932 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1933 		break;
1934 	}
1935 	default:
1936 		ipha = (ipha_t *)&icmph[1];
1937 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1938 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1939 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1940 				freemsg(first_mp);
1941 				return;
1942 			}
1943 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1944 			ipha = (ipha_t *)&icmph[1];
1945 		}
1946 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1947 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 			freemsg(first_mp);
1949 			return;
1950 		}
1951 		hdr_length = IPH_HDR_LENGTH(ipha);
1952 		if (hdr_length < sizeof (ipha_t)) {
1953 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1954 			freemsg(first_mp);
1955 			return;
1956 		}
1957 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1958 			if (!pullupmsg(mp,
1959 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1960 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1961 				freemsg(first_mp);
1962 				return;
1963 			}
1964 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1965 			ipha = (ipha_t *)&icmph[1];
1966 		}
1967 		switch (icmph->icmph_type) {
1968 		case ICMP_REDIRECT:
1969 			/*
1970 			 * As there is no upper client to deliver, we don't
1971 			 * need the first_mp any more.
1972 			 */
1973 			if (mctl_present) {
1974 				freeb(first_mp);
1975 			}
1976 			icmp_redirect(ill, mp);
1977 			return;
1978 		case ICMP_DEST_UNREACHABLE:
1979 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1980 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1981 				    zoneid, mp, iph_hdr_length, ipst)) {
1982 					freemsg(first_mp);
1983 					return;
1984 				}
1985 				/*
1986 				 * icmp_inbound_too_big() may alter mp.
1987 				 * Resynch ipha and icmph accordingly.
1988 				 */
1989 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1990 				ipha = (ipha_t *)&icmph[1];
1991 			}
1992 			/* FALLTHRU */
1993 		default :
1994 			/*
1995 			 * IPQoS notes: Since we have already done IPQoS
1996 			 * processing we don't want to do it again in
1997 			 * the fanout routines called by
1998 			 * icmp_inbound_error_fanout, hence the last
1999 			 * argument, ip_policy, is B_FALSE.
2000 			 */
2001 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2002 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2003 			    B_FALSE, recv_ill, zoneid);
2004 		}
2005 		return;
2006 	}
2007 	/* Send out an ICMP packet */
2008 	icmph->icmph_checksum = 0;
2009 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2010 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2011 		ipif_t	*ipif_chosen;
2012 		/*
2013 		 * Make it look like it was directed to us, so we don't look
2014 		 * like a fool with a broadcast or multicast source address.
2015 		 */
2016 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2017 		/*
2018 		 * Make sure that we haven't grabbed an interface that's DOWN.
2019 		 */
2020 		if (ipif != NULL) {
2021 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2022 			    ipha->ipha_src, zoneid);
2023 			if (ipif_chosen != NULL) {
2024 				ipif_refrele(ipif);
2025 				ipif = ipif_chosen;
2026 			}
2027 		}
2028 		if (ipif == NULL) {
2029 			ip0dbg(("icmp_inbound: "
2030 			    "No source for broadcast/multicast:\n"
2031 			    "\tsrc 0x%x dst 0x%x ill %p "
2032 			    "ipif_lcl_addr 0x%x\n",
2033 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2034 			    (void *)ill,
2035 			    ill->ill_ipif->ipif_lcl_addr));
2036 			freemsg(first_mp);
2037 			return;
2038 		}
2039 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2040 		ipha->ipha_dst = ipif->ipif_src_addr;
2041 		ipif_refrele(ipif);
2042 	}
2043 	/* Reset time to live. */
2044 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2045 	{
2046 		/* Swap source and destination addresses */
2047 		ipaddr_t tmp;
2048 
2049 		tmp = ipha->ipha_src;
2050 		ipha->ipha_src = ipha->ipha_dst;
2051 		ipha->ipha_dst = tmp;
2052 	}
2053 	ipha->ipha_ident = 0;
2054 	if (!IS_SIMPLE_IPH(ipha))
2055 		icmp_options_update(ipha);
2056 
2057 	if (!mctl_present) {
2058 		/*
2059 		 * This packet should go out the same way as it
2060 		 * came in i.e in clear. To make sure that global
2061 		 * policy will not be applied to this in ip_wput_ire,
2062 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2063 		 */
2064 		ASSERT(first_mp == mp);
2065 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2066 		if (first_mp == NULL) {
2067 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2068 			freemsg(mp);
2069 			return;
2070 		}
2071 		ii = (ipsec_in_t *)first_mp->b_rptr;
2072 
2073 		/* This is not a secure packet */
2074 		ii->ipsec_in_secure = B_FALSE;
2075 		first_mp->b_cont = mp;
2076 	} else {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2079 	}
2080 	ii->ipsec_in_zoneid = zoneid;
2081 	ASSERT(zoneid != ALL_ZONES);
2082 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2083 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2084 		return;
2085 	}
2086 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2087 	put(WR(q), first_mp);
2088 }
2089 
2090 static ipaddr_t
2091 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2092 {
2093 	conn_t *connp;
2094 	connf_t *connfp;
2095 	ipaddr_t nexthop_addr = INADDR_ANY;
2096 	int hdr_length = IPH_HDR_LENGTH(ipha);
2097 	uint16_t *up;
2098 	uint32_t ports;
2099 	ip_stack_t *ipst = ill->ill_ipst;
2100 
2101 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 	switch (ipha->ipha_protocol) {
2103 		case IPPROTO_TCP:
2104 		{
2105 			tcph_t *tcph;
2106 
2107 			/* do a reverse lookup */
2108 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2109 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2110 			    TCPS_LISTEN, ipst);
2111 			break;
2112 		}
2113 		case IPPROTO_UDP:
2114 		{
2115 			uint32_t dstport, srcport;
2116 
2117 			((uint16_t *)&ports)[0] = up[1];
2118 			((uint16_t *)&ports)[1] = up[0];
2119 
2120 			/* Extract ports in net byte order */
2121 			dstport = htons(ntohl(ports) & 0xFFFF);
2122 			srcport = htons(ntohl(ports) >> 16);
2123 
2124 			connfp = &ipst->ips_ipcl_udp_fanout[
2125 			    IPCL_UDP_HASH(dstport, ipst)];
2126 			mutex_enter(&connfp->connf_lock);
2127 			connp = connfp->connf_head;
2128 
2129 			/* do a reverse lookup */
2130 			while ((connp != NULL) &&
2131 			    (!IPCL_UDP_MATCH(connp, dstport,
2132 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2133 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2134 				connp = connp->conn_next;
2135 			}
2136 			if (connp != NULL)
2137 				CONN_INC_REF(connp);
2138 			mutex_exit(&connfp->connf_lock);
2139 			break;
2140 		}
2141 		case IPPROTO_SCTP:
2142 		{
2143 			in6_addr_t map_src, map_dst;
2144 
2145 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2146 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2147 			((uint16_t *)&ports)[0] = up[1];
2148 			((uint16_t *)&ports)[1] = up[0];
2149 
2150 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2151 			    zoneid, ipst->ips_netstack->netstack_sctp);
2152 			if (connp == NULL) {
2153 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2154 				    zoneid, ports, ipha, ipst);
2155 			} else {
2156 				CONN_INC_REF(connp);
2157 				SCTP_REFRELE(CONN2SCTP(connp));
2158 			}
2159 			break;
2160 		}
2161 		default:
2162 		{
2163 			ipha_t ripha;
2164 
2165 			ripha.ipha_src = ipha->ipha_dst;
2166 			ripha.ipha_dst = ipha->ipha_src;
2167 			ripha.ipha_protocol = ipha->ipha_protocol;
2168 
2169 			connfp = &ipst->ips_ipcl_proto_fanout[
2170 			    ipha->ipha_protocol];
2171 			mutex_enter(&connfp->connf_lock);
2172 			connp = connfp->connf_head;
2173 			for (connp = connfp->connf_head; connp != NULL;
2174 			    connp = connp->conn_next) {
2175 				if (IPCL_PROTO_MATCH(connp,
2176 				    ipha->ipha_protocol, &ripha, ill,
2177 				    0, zoneid)) {
2178 					CONN_INC_REF(connp);
2179 					break;
2180 				}
2181 			}
2182 			mutex_exit(&connfp->connf_lock);
2183 		}
2184 	}
2185 	if (connp != NULL) {
2186 		if (connp->conn_nexthop_set)
2187 			nexthop_addr = connp->conn_nexthop_v4;
2188 		CONN_DEC_REF(connp);
2189 	}
2190 	return (nexthop_addr);
2191 }
2192 
2193 /* Table from RFC 1191 */
2194 static int icmp_frag_size_table[] =
2195 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2196 
2197 /*
2198  * Process received ICMP Packet too big.
2199  * After updating any IRE it does the fanout to any matching transport streams.
2200  * Assumes the message has been pulled up till the IP header that caused
2201  * the error.
2202  *
2203  * Returns B_FALSE on failure and B_TRUE on success.
2204  */
2205 static boolean_t
2206 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2207     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2208     ip_stack_t *ipst)
2209 {
2210 	ire_t	*ire, *first_ire;
2211 	int	mtu, orig_mtu;
2212 	int	hdr_length;
2213 	ipaddr_t nexthop_addr;
2214 	boolean_t disable_pmtud;
2215 
2216 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2217 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2218 	ASSERT(ill != NULL);
2219 
2220 	hdr_length = IPH_HDR_LENGTH(ipha);
2221 
2222 	/* Drop if the original packet contained a source route */
2223 	if (ip_source_route_included(ipha)) {
2224 		return (B_FALSE);
2225 	}
2226 	/*
2227 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2228 	 * header.
2229 	 */
2230 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2231 	    mp->b_wptr) {
2232 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2233 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2234 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2235 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2236 			return (B_FALSE);
2237 		}
2238 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2239 		ipha = (ipha_t *)&icmph[1];
2240 	}
2241 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2242 	if (nexthop_addr != INADDR_ANY) {
2243 		/* nexthop set */
2244 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2245 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2246 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2247 	} else {
2248 		/* nexthop not set */
2249 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2250 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2251 	}
2252 
2253 	if (!first_ire) {
2254 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2255 		    ntohl(ipha->ipha_dst)));
2256 		return (B_FALSE);
2257 	}
2258 
2259 	/* Check for MTU discovery advice as described in RFC 1191 */
2260 	mtu = ntohs(icmph->icmph_du_mtu);
2261 	orig_mtu = mtu;
2262 	disable_pmtud = B_FALSE;
2263 
2264 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2265 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2266 	    ire = ire->ire_next) {
2267 		/*
2268 		 * Look for the connection to which this ICMP message is
2269 		 * directed. If it has the IP_NEXTHOP option set, then the
2270 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2271 		 * option. Else the search is limited to regular IREs.
2272 		 */
2273 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2274 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2275 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2276 		    (nexthop_addr != INADDR_ANY)))
2277 			continue;
2278 
2279 		mutex_enter(&ire->ire_lock);
2280 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2281 			uint32_t length;
2282 			int	i;
2283 
2284 			/*
2285 			 * Use the table from RFC 1191 to figure out
2286 			 * the next "plateau" based on the length in
2287 			 * the original IP packet.
2288 			 */
2289 			length = ntohs(ipha->ipha_length);
2290 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2291 			    uint32_t, length);
2292 			if (ire->ire_max_frag <= length &&
2293 			    ire->ire_max_frag >= length - hdr_length) {
2294 				/*
2295 				 * Handle broken BSD 4.2 systems that
2296 				 * return the wrong iph_length in ICMP
2297 				 * errors.
2298 				 */
2299 				length -= hdr_length;
2300 			}
2301 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2302 				if (length > icmp_frag_size_table[i])
2303 					break;
2304 			}
2305 			if (i == A_CNT(icmp_frag_size_table)) {
2306 				/* Smaller than 68! */
2307 				disable_pmtud = B_TRUE;
2308 				mtu = ipst->ips_ip_pmtu_min;
2309 			} else {
2310 				mtu = icmp_frag_size_table[i];
2311 				if (mtu < ipst->ips_ip_pmtu_min) {
2312 					mtu = ipst->ips_ip_pmtu_min;
2313 					disable_pmtud = B_TRUE;
2314 				}
2315 			}
2316 			/* Fool the ULP into believing our guessed PMTU. */
2317 			icmph->icmph_du_zero = 0;
2318 			icmph->icmph_du_mtu = htons(mtu);
2319 		}
2320 		if (disable_pmtud)
2321 			ire->ire_frag_flag = 0;
2322 		/* Reduce the IRE max frag value as advised. */
2323 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2324 		mutex_exit(&ire->ire_lock);
2325 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2326 		    ire, int, orig_mtu, int, mtu);
2327 	}
2328 	rw_exit(&first_ire->ire_bucket->irb_lock);
2329 	ire_refrele(first_ire);
2330 	return (B_TRUE);
2331 }
2332 
2333 /*
2334  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2335  * calls this function.
2336  */
2337 static mblk_t *
2338 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2339 {
2340 	ipha_t *ipha;
2341 	icmph_t *icmph;
2342 	ipha_t *in_ipha;
2343 	int length;
2344 
2345 	ASSERT(mp->b_datap->db_type == M_DATA);
2346 
2347 	/*
2348 	 * For Self-encapsulated packets, we added an extra IP header
2349 	 * without the options. Inner IP header is the one from which
2350 	 * the outer IP header was formed. Thus, we need to remove the
2351 	 * outer IP header. To do this, we pullup the whole message
2352 	 * and overlay whatever follows the outer IP header over the
2353 	 * outer IP header.
2354 	 */
2355 
2356 	if (!pullupmsg(mp, -1))
2357 		return (NULL);
2358 
2359 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2360 	ipha = (ipha_t *)&icmph[1];
2361 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2362 
2363 	/*
2364 	 * The length that we want to overlay is following the inner
2365 	 * IP header. Subtracting the IP header + icmp header + outer
2366 	 * IP header's length should give us the length that we want to
2367 	 * overlay.
2368 	 */
2369 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2370 	    hdr_length;
2371 	/*
2372 	 * Overlay whatever follows the inner header over the
2373 	 * outer header.
2374 	 */
2375 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2376 
2377 	/* Set the wptr to account for the outer header */
2378 	mp->b_wptr -= hdr_length;
2379 	return (mp);
2380 }
2381 
2382 /*
2383  * Try to pass the ICMP message upstream in case the ULP cares.
2384  *
2385  * If the packet that caused the ICMP error is secure, we send
2386  * it to AH/ESP to make sure that the attached packet has a
2387  * valid association. ipha in the code below points to the
2388  * IP header of the packet that caused the error.
2389  *
2390  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2391  * in the context of IPsec. Normally we tell the upper layer
2392  * whenever we send the ire (including ip_bind), the IPsec header
2393  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2394  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2395  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2396  * same thing. As TCP has the IPsec options size that needs to be
2397  * adjusted, we just pass the MTU unchanged.
2398  *
2399  * IFN could have been generated locally or by some router.
2400  *
2401  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2402  *	    This happens because IP adjusted its value of MTU on an
2403  *	    earlier IFN message and could not tell the upper layer,
2404  *	    the new adjusted value of MTU e.g. Packet was encrypted
2405  *	    or there was not enough information to fanout to upper
2406  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2407  *	    generates the IFN, where IPsec processing has *not* been
2408  *	    done.
2409  *
2410  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2411  *	    could have generated this. This happens because ire_max_frag
2412  *	    value in IP was set to a new value, while the IPsec processing
2413  *	    was being done and after we made the fragmentation check in
2414  *	    ip_wput_ire. Thus on return from IPsec processing,
2415  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2416  *	    and generates the IFN. As IPsec processing is over, we fanout
2417  *	    to AH/ESP to remove the header.
2418  *
2419  *	    In both these cases, ipsec_in_loopback will be set indicating
2420  *	    that IFN was generated locally.
2421  *
2422  * ROUTER : IFN could be secure or non-secure.
2423  *
2424  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2425  *	      packet in error has AH/ESP headers to validate the AH/ESP
2426  *	      headers. AH/ESP will verify whether there is a valid SA or
2427  *	      not and send it back. We will fanout again if we have more
2428  *	      data in the packet.
2429  *
2430  *	      If the packet in error does not have AH/ESP, we handle it
2431  *	      like any other case.
2432  *
2433  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2434  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2435  *	      for validation. AH/ESP will verify whether there is a
2436  *	      valid SA or not and send it back. We will fanout again if
2437  *	      we have more data in the packet.
2438  *
2439  *	      If the packet in error does not have AH/ESP, we handle it
2440  *	      like any other case.
2441  */
2442 static void
2443 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2444     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2445     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2446     zoneid_t zoneid)
2447 {
2448 	uint16_t *up;	/* Pointer to ports in ULP header */
2449 	uint32_t ports;	/* reversed ports for fanout */
2450 	ipha_t ripha;	/* With reversed addresses */
2451 	mblk_t *first_mp;
2452 	ipsec_in_t *ii;
2453 	tcph_t	*tcph;
2454 	conn_t	*connp;
2455 	ip_stack_t *ipst;
2456 
2457 	ASSERT(ill != NULL);
2458 
2459 	ASSERT(recv_ill != NULL);
2460 	ipst = recv_ill->ill_ipst;
2461 
2462 	first_mp = mp;
2463 	if (mctl_present) {
2464 		mp = first_mp->b_cont;
2465 		ASSERT(mp != NULL);
2466 
2467 		ii = (ipsec_in_t *)first_mp->b_rptr;
2468 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2469 	} else {
2470 		ii = NULL;
2471 	}
2472 
2473 	switch (ipha->ipha_protocol) {
2474 	case IPPROTO_UDP:
2475 		/*
2476 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2477 		 * transport header.
2478 		 */
2479 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2480 		    mp->b_wptr) {
2481 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2482 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2483 				goto discard_pkt;
2484 			}
2485 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2486 			ipha = (ipha_t *)&icmph[1];
2487 		}
2488 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2489 
2490 		/*
2491 		 * Attempt to find a client stream based on port.
2492 		 * Note that we do a reverse lookup since the header is
2493 		 * in the form we sent it out.
2494 		 * The ripha header is only used for the IP_UDP_MATCH and we
2495 		 * only set the src and dst addresses and protocol.
2496 		 */
2497 		ripha.ipha_src = ipha->ipha_dst;
2498 		ripha.ipha_dst = ipha->ipha_src;
2499 		ripha.ipha_protocol = ipha->ipha_protocol;
2500 		((uint16_t *)&ports)[0] = up[1];
2501 		((uint16_t *)&ports)[1] = up[0];
2502 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2503 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2504 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2505 		    icmph->icmph_type, icmph->icmph_code));
2506 
2507 		/* Have to change db_type after any pullupmsg */
2508 		DB_TYPE(mp) = M_CTL;
2509 
2510 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2511 		    mctl_present, ip_policy, recv_ill, zoneid);
2512 		return;
2513 
2514 	case IPPROTO_TCP:
2515 		/*
2516 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2517 		 * transport header.
2518 		 */
2519 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2520 		    mp->b_wptr) {
2521 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2522 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2523 				goto discard_pkt;
2524 			}
2525 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2526 			ipha = (ipha_t *)&icmph[1];
2527 		}
2528 		/*
2529 		 * Find a TCP client stream for this packet.
2530 		 * Note that we do a reverse lookup since the header is
2531 		 * in the form we sent it out.
2532 		 */
2533 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2534 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2535 		    ipst);
2536 		if (connp == NULL)
2537 			goto discard_pkt;
2538 
2539 		/* Have to change db_type after any pullupmsg */
2540 		DB_TYPE(mp) = M_CTL;
2541 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2542 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2543 		return;
2544 
2545 	case IPPROTO_SCTP:
2546 		/*
2547 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2548 		 * transport header.
2549 		 */
2550 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2551 		    mp->b_wptr) {
2552 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2553 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2554 				goto discard_pkt;
2555 			}
2556 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2557 			ipha = (ipha_t *)&icmph[1];
2558 		}
2559 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2560 		/*
2561 		 * Find a SCTP client stream for this packet.
2562 		 * Note that we do a reverse lookup since the header is
2563 		 * in the form we sent it out.
2564 		 * The ripha header is only used for the matching and we
2565 		 * only set the src and dst addresses, protocol, and version.
2566 		 */
2567 		ripha.ipha_src = ipha->ipha_dst;
2568 		ripha.ipha_dst = ipha->ipha_src;
2569 		ripha.ipha_protocol = ipha->ipha_protocol;
2570 		ripha.ipha_version_and_hdr_length =
2571 		    ipha->ipha_version_and_hdr_length;
2572 		((uint16_t *)&ports)[0] = up[1];
2573 		((uint16_t *)&ports)[1] = up[0];
2574 
2575 		/* Have to change db_type after any pullupmsg */
2576 		DB_TYPE(mp) = M_CTL;
2577 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2578 		    mctl_present, ip_policy, zoneid);
2579 		return;
2580 
2581 	case IPPROTO_ESP:
2582 	case IPPROTO_AH: {
2583 		int ipsec_rc;
2584 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2585 
2586 		/*
2587 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2588 		 * We will re-use the IPSEC_IN if it is already present as
2589 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2590 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2591 		 * one and attach it in the front.
2592 		 */
2593 		if (ii != NULL) {
2594 			/*
2595 			 * ip_fanout_proto_again converts the ICMP errors
2596 			 * that come back from AH/ESP to M_DATA so that
2597 			 * if it is non-AH/ESP and we do a pullupmsg in
2598 			 * this function, it would work. Convert it back
2599 			 * to M_CTL before we send up as this is a ICMP
2600 			 * error. This could have been generated locally or
2601 			 * by some router. Validate the inner IPsec
2602 			 * headers.
2603 			 *
2604 			 * NOTE : ill_index is used by ip_fanout_proto_again
2605 			 * to locate the ill.
2606 			 */
2607 			ASSERT(ill != NULL);
2608 			ii->ipsec_in_ill_index =
2609 			    ill->ill_phyint->phyint_ifindex;
2610 			ii->ipsec_in_rill_index =
2611 			    recv_ill->ill_phyint->phyint_ifindex;
2612 			DB_TYPE(first_mp->b_cont) = M_CTL;
2613 		} else {
2614 			/*
2615 			 * IPSEC_IN is not present. We attach a ipsec_in
2616 			 * message and send up to IPsec for validating
2617 			 * and removing the IPsec headers. Clear
2618 			 * ipsec_in_secure so that when we return
2619 			 * from IPsec, we don't mistakenly think that this
2620 			 * is a secure packet came from the network.
2621 			 *
2622 			 * NOTE : ill_index is used by ip_fanout_proto_again
2623 			 * to locate the ill.
2624 			 */
2625 			ASSERT(first_mp == mp);
2626 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2627 			if (first_mp == NULL) {
2628 				freemsg(mp);
2629 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2630 				return;
2631 			}
2632 			ii = (ipsec_in_t *)first_mp->b_rptr;
2633 
2634 			/* This is not a secure packet */
2635 			ii->ipsec_in_secure = B_FALSE;
2636 			first_mp->b_cont = mp;
2637 			DB_TYPE(mp) = M_CTL;
2638 			ASSERT(ill != NULL);
2639 			ii->ipsec_in_ill_index =
2640 			    ill->ill_phyint->phyint_ifindex;
2641 			ii->ipsec_in_rill_index =
2642 			    recv_ill->ill_phyint->phyint_ifindex;
2643 		}
2644 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2645 
2646 		if (!ipsec_loaded(ipss)) {
2647 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2648 			return;
2649 		}
2650 
2651 		if (ipha->ipha_protocol == IPPROTO_ESP)
2652 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2653 		else
2654 			ipsec_rc = ipsecah_icmp_error(first_mp);
2655 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2656 			return;
2657 
2658 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2659 		return;
2660 	}
2661 	default:
2662 		/*
2663 		 * The ripha header is only used for the lookup and we
2664 		 * only set the src and dst addresses and protocol.
2665 		 */
2666 		ripha.ipha_src = ipha->ipha_dst;
2667 		ripha.ipha_dst = ipha->ipha_src;
2668 		ripha.ipha_protocol = ipha->ipha_protocol;
2669 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2670 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2671 		    ntohl(ipha->ipha_dst),
2672 		    icmph->icmph_type, icmph->icmph_code));
2673 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2674 			ipha_t *in_ipha;
2675 
2676 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2677 			    mp->b_wptr) {
2678 				if (!pullupmsg(mp, (uchar_t *)ipha +
2679 				    hdr_length + sizeof (ipha_t) -
2680 				    mp->b_rptr)) {
2681 					goto discard_pkt;
2682 				}
2683 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2684 				ipha = (ipha_t *)&icmph[1];
2685 			}
2686 			/*
2687 			 * Caller has verified that length has to be
2688 			 * at least the size of IP header.
2689 			 */
2690 			ASSERT(hdr_length >= sizeof (ipha_t));
2691 			/*
2692 			 * Check the sanity of the inner IP header like
2693 			 * we did for the outer header.
2694 			 */
2695 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2696 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2697 				goto discard_pkt;
2698 			}
2699 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2700 				goto discard_pkt;
2701 			}
2702 			/* Check for Self-encapsulated tunnels */
2703 			if (in_ipha->ipha_src == ipha->ipha_src &&
2704 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2705 
2706 				mp = icmp_inbound_self_encap_error(mp,
2707 				    iph_hdr_length, hdr_length);
2708 				if (mp == NULL)
2709 					goto discard_pkt;
2710 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2711 				ipha = (ipha_t *)&icmph[1];
2712 				hdr_length = IPH_HDR_LENGTH(ipha);
2713 				/*
2714 				 * The packet in error is self-encapsualted.
2715 				 * And we are finding it further encapsulated
2716 				 * which we could not have possibly generated.
2717 				 */
2718 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2719 					goto discard_pkt;
2720 				}
2721 				icmp_inbound_error_fanout(q, ill, first_mp,
2722 				    icmph, ipha, iph_hdr_length, hdr_length,
2723 				    mctl_present, ip_policy, recv_ill, zoneid);
2724 				return;
2725 			}
2726 		}
2727 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2728 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2729 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2730 		    ii != NULL &&
2731 		    ii->ipsec_in_loopback &&
2732 		    ii->ipsec_in_secure) {
2733 			/*
2734 			 * For IP tunnels that get a looped-back
2735 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2736 			 * reported new MTU to take into account the IPsec
2737 			 * headers protecting this configured tunnel.
2738 			 *
2739 			 * This allows the tunnel module (tun.c) to blindly
2740 			 * accept the MTU reported in an ICMP "too big"
2741 			 * message.
2742 			 *
2743 			 * Non-looped back ICMP messages will just be
2744 			 * handled by the security protocols (if needed),
2745 			 * and the first subsequent packet will hit this
2746 			 * path.
2747 			 */
2748 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2749 			    ipsec_in_extra_length(first_mp));
2750 		}
2751 		/* Have to change db_type after any pullupmsg */
2752 		DB_TYPE(mp) = M_CTL;
2753 
2754 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2755 		    ip_policy, recv_ill, zoneid);
2756 		return;
2757 	}
2758 	/* NOTREACHED */
2759 discard_pkt:
2760 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2761 drop_pkt:;
2762 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2763 	freemsg(first_mp);
2764 }
2765 
2766 /*
2767  * Common IP options parser.
2768  *
2769  * Setup routine: fill in *optp with options-parsing state, then
2770  * tail-call ipoptp_next to return the first option.
2771  */
2772 uint8_t
2773 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2774 {
2775 	uint32_t totallen; /* total length of all options */
2776 
2777 	totallen = ipha->ipha_version_and_hdr_length -
2778 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2779 	totallen <<= 2;
2780 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2781 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2782 	optp->ipoptp_flags = 0;
2783 	return (ipoptp_next(optp));
2784 }
2785 
2786 /*
2787  * Common IP options parser: extract next option.
2788  */
2789 uint8_t
2790 ipoptp_next(ipoptp_t *optp)
2791 {
2792 	uint8_t *end = optp->ipoptp_end;
2793 	uint8_t *cur = optp->ipoptp_next;
2794 	uint8_t opt, len, pointer;
2795 
2796 	/*
2797 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2798 	 * has been corrupted.
2799 	 */
2800 	ASSERT(cur <= end);
2801 
2802 	if (cur == end)
2803 		return (IPOPT_EOL);
2804 
2805 	opt = cur[IPOPT_OPTVAL];
2806 
2807 	/*
2808 	 * Skip any NOP options.
2809 	 */
2810 	while (opt == IPOPT_NOP) {
2811 		cur++;
2812 		if (cur == end)
2813 			return (IPOPT_EOL);
2814 		opt = cur[IPOPT_OPTVAL];
2815 	}
2816 
2817 	if (opt == IPOPT_EOL)
2818 		return (IPOPT_EOL);
2819 
2820 	/*
2821 	 * Option requiring a length.
2822 	 */
2823 	if ((cur + 1) >= end) {
2824 		optp->ipoptp_flags |= IPOPTP_ERROR;
2825 		return (IPOPT_EOL);
2826 	}
2827 	len = cur[IPOPT_OLEN];
2828 	if (len < 2) {
2829 		optp->ipoptp_flags |= IPOPTP_ERROR;
2830 		return (IPOPT_EOL);
2831 	}
2832 	optp->ipoptp_cur = cur;
2833 	optp->ipoptp_len = len;
2834 	optp->ipoptp_next = cur + len;
2835 	if (cur + len > end) {
2836 		optp->ipoptp_flags |= IPOPTP_ERROR;
2837 		return (IPOPT_EOL);
2838 	}
2839 
2840 	/*
2841 	 * For the options which require a pointer field, make sure
2842 	 * its there, and make sure it points to either something
2843 	 * inside this option, or the end of the option.
2844 	 */
2845 	switch (opt) {
2846 	case IPOPT_RR:
2847 	case IPOPT_TS:
2848 	case IPOPT_LSRR:
2849 	case IPOPT_SSRR:
2850 		if (len <= IPOPT_OFFSET) {
2851 			optp->ipoptp_flags |= IPOPTP_ERROR;
2852 			return (opt);
2853 		}
2854 		pointer = cur[IPOPT_OFFSET];
2855 		if (pointer - 1 > len) {
2856 			optp->ipoptp_flags |= IPOPTP_ERROR;
2857 			return (opt);
2858 		}
2859 		break;
2860 	}
2861 
2862 	/*
2863 	 * Sanity check the pointer field based on the type of the
2864 	 * option.
2865 	 */
2866 	switch (opt) {
2867 	case IPOPT_RR:
2868 	case IPOPT_SSRR:
2869 	case IPOPT_LSRR:
2870 		if (pointer < IPOPT_MINOFF_SR)
2871 			optp->ipoptp_flags |= IPOPTP_ERROR;
2872 		break;
2873 	case IPOPT_TS:
2874 		if (pointer < IPOPT_MINOFF_IT)
2875 			optp->ipoptp_flags |= IPOPTP_ERROR;
2876 		/*
2877 		 * Note that the Internet Timestamp option also
2878 		 * contains two four bit fields (the Overflow field,
2879 		 * and the Flag field), which follow the pointer
2880 		 * field.  We don't need to check that these fields
2881 		 * fall within the length of the option because this
2882 		 * was implicitely done above.  We've checked that the
2883 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2884 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2885 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2886 		 */
2887 		ASSERT(len > IPOPT_POS_OV_FLG);
2888 		break;
2889 	}
2890 
2891 	return (opt);
2892 }
2893 
2894 /*
2895  * Use the outgoing IP header to create an IP_OPTIONS option the way
2896  * it was passed down from the application.
2897  */
2898 int
2899 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2900 {
2901 	ipoptp_t	opts;
2902 	const uchar_t	*opt;
2903 	uint8_t		optval;
2904 	uint8_t		optlen;
2905 	uint32_t	len = 0;
2906 	uchar_t	*buf1 = buf;
2907 
2908 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2909 	len += IP_ADDR_LEN;
2910 	bzero(buf1, IP_ADDR_LEN);
2911 
2912 	/*
2913 	 * OK to cast away const here, as we don't store through the returned
2914 	 * opts.ipoptp_cur pointer.
2915 	 */
2916 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2917 	    optval != IPOPT_EOL;
2918 	    optval = ipoptp_next(&opts)) {
2919 		int	off;
2920 
2921 		opt = opts.ipoptp_cur;
2922 		optlen = opts.ipoptp_len;
2923 		switch (optval) {
2924 		case IPOPT_SSRR:
2925 		case IPOPT_LSRR:
2926 
2927 			/*
2928 			 * Insert ipha_dst as the first entry in the source
2929 			 * route and move down the entries on step.
2930 			 * The last entry gets placed at buf1.
2931 			 */
2932 			buf[IPOPT_OPTVAL] = optval;
2933 			buf[IPOPT_OLEN] = optlen;
2934 			buf[IPOPT_OFFSET] = optlen;
2935 
2936 			off = optlen - IP_ADDR_LEN;
2937 			if (off < 0) {
2938 				/* No entries in source route */
2939 				break;
2940 			}
2941 			/* Last entry in source route */
2942 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2943 			off -= IP_ADDR_LEN;
2944 
2945 			while (off > 0) {
2946 				bcopy(opt + off,
2947 				    buf + off + IP_ADDR_LEN,
2948 				    IP_ADDR_LEN);
2949 				off -= IP_ADDR_LEN;
2950 			}
2951 			/* ipha_dst into first slot */
2952 			bcopy(&ipha->ipha_dst,
2953 			    buf + off + IP_ADDR_LEN,
2954 			    IP_ADDR_LEN);
2955 			buf += optlen;
2956 			len += optlen;
2957 			break;
2958 
2959 		case IPOPT_COMSEC:
2960 		case IPOPT_SECURITY:
2961 			/* if passing up a label is not ok, then remove */
2962 			if (is_system_labeled())
2963 				break;
2964 			/* FALLTHROUGH */
2965 		default:
2966 			bcopy(opt, buf, optlen);
2967 			buf += optlen;
2968 			len += optlen;
2969 			break;
2970 		}
2971 	}
2972 done:
2973 	/* Pad the resulting options */
2974 	while (len & 0x3) {
2975 		*buf++ = IPOPT_EOL;
2976 		len++;
2977 	}
2978 	return (len);
2979 }
2980 
2981 /*
2982  * Update any record route or timestamp options to include this host.
2983  * Reverse any source route option.
2984  * This routine assumes that the options are well formed i.e. that they
2985  * have already been checked.
2986  */
2987 static void
2988 icmp_options_update(ipha_t *ipha)
2989 {
2990 	ipoptp_t	opts;
2991 	uchar_t		*opt;
2992 	uint8_t		optval;
2993 	ipaddr_t	src;		/* Our local address */
2994 	ipaddr_t	dst;
2995 
2996 	ip2dbg(("icmp_options_update\n"));
2997 	src = ipha->ipha_src;
2998 	dst = ipha->ipha_dst;
2999 
3000 	for (optval = ipoptp_first(&opts, ipha);
3001 	    optval != IPOPT_EOL;
3002 	    optval = ipoptp_next(&opts)) {
3003 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3004 		opt = opts.ipoptp_cur;
3005 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3006 		    optval, opts.ipoptp_len));
3007 		switch (optval) {
3008 			int off1, off2;
3009 		case IPOPT_SSRR:
3010 		case IPOPT_LSRR:
3011 			/*
3012 			 * Reverse the source route.  The first entry
3013 			 * should be the next to last one in the current
3014 			 * source route (the last entry is our address).
3015 			 * The last entry should be the final destination.
3016 			 */
3017 			off1 = IPOPT_MINOFF_SR - 1;
3018 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3019 			if (off2 < 0) {
3020 				/* No entries in source route */
3021 				ip1dbg((
3022 				    "icmp_options_update: bad src route\n"));
3023 				break;
3024 			}
3025 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3026 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3027 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3028 			off2 -= IP_ADDR_LEN;
3029 
3030 			while (off1 < off2) {
3031 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3032 				bcopy((char *)opt + off2, (char *)opt + off1,
3033 				    IP_ADDR_LEN);
3034 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3035 				off1 += IP_ADDR_LEN;
3036 				off2 -= IP_ADDR_LEN;
3037 			}
3038 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3039 			break;
3040 		}
3041 	}
3042 }
3043 
3044 /*
3045  * Process received ICMP Redirect messages.
3046  */
3047 static void
3048 icmp_redirect(ill_t *ill, mblk_t *mp)
3049 {
3050 	ipha_t	*ipha;
3051 	int	iph_hdr_length;
3052 	icmph_t	*icmph;
3053 	ipha_t	*ipha_err;
3054 	ire_t	*ire;
3055 	ire_t	*prev_ire;
3056 	ire_t	*save_ire;
3057 	ipaddr_t  src, dst, gateway;
3058 	iulp_t	ulp_info = { 0 };
3059 	int	error;
3060 	ip_stack_t *ipst;
3061 
3062 	ASSERT(ill != NULL);
3063 	ipst = ill->ill_ipst;
3064 
3065 	ipha = (ipha_t *)mp->b_rptr;
3066 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3067 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3068 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3069 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3070 		freemsg(mp);
3071 		return;
3072 	}
3073 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3074 	ipha_err = (ipha_t *)&icmph[1];
3075 	src = ipha->ipha_src;
3076 	dst = ipha_err->ipha_dst;
3077 	gateway = icmph->icmph_rd_gateway;
3078 	/* Make sure the new gateway is reachable somehow. */
3079 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3080 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3081 	/*
3082 	 * Make sure we had a route for the dest in question and that
3083 	 * that route was pointing to the old gateway (the source of the
3084 	 * redirect packet.)
3085 	 */
3086 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3087 	    NULL, MATCH_IRE_GW, ipst);
3088 	/*
3089 	 * Check that
3090 	 *	the redirect was not from ourselves
3091 	 *	the new gateway and the old gateway are directly reachable
3092 	 */
3093 	if (!prev_ire ||
3094 	    !ire ||
3095 	    ire->ire_type == IRE_LOCAL) {
3096 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3097 		freemsg(mp);
3098 		if (ire != NULL)
3099 			ire_refrele(ire);
3100 		if (prev_ire != NULL)
3101 			ire_refrele(prev_ire);
3102 		return;
3103 	}
3104 
3105 	/*
3106 	 * Should we use the old ULP info to create the new gateway?  From
3107 	 * a user's perspective, we should inherit the info so that it
3108 	 * is a "smooth" transition.  If we do not do that, then new
3109 	 * connections going thru the new gateway will have no route metrics,
3110 	 * which is counter-intuitive to user.  From a network point of
3111 	 * view, this may or may not make sense even though the new gateway
3112 	 * is still directly connected to us so the route metrics should not
3113 	 * change much.
3114 	 *
3115 	 * But if the old ire_uinfo is not initialized, we do another
3116 	 * recursive lookup on the dest using the new gateway.  There may
3117 	 * be a route to that.  If so, use it to initialize the redirect
3118 	 * route.
3119 	 */
3120 	if (prev_ire->ire_uinfo.iulp_set) {
3121 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3122 	} else {
3123 		ire_t *tmp_ire;
3124 		ire_t *sire;
3125 
3126 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3127 		    ALL_ZONES, 0, NULL,
3128 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3129 		    ipst);
3130 		if (sire != NULL) {
3131 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3132 			/*
3133 			 * If sire != NULL, ire_ftable_lookup() should not
3134 			 * return a NULL value.
3135 			 */
3136 			ASSERT(tmp_ire != NULL);
3137 			ire_refrele(tmp_ire);
3138 			ire_refrele(sire);
3139 		} else if (tmp_ire != NULL) {
3140 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3141 			    sizeof (iulp_t));
3142 			ire_refrele(tmp_ire);
3143 		}
3144 	}
3145 	if (prev_ire->ire_type == IRE_CACHE)
3146 		ire_delete(prev_ire);
3147 	ire_refrele(prev_ire);
3148 	/*
3149 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3150 	 * require TOS routing
3151 	 */
3152 	switch (icmph->icmph_code) {
3153 	case 0:
3154 	case 1:
3155 		/* TODO: TOS specificity for cases 2 and 3 */
3156 	case 2:
3157 	case 3:
3158 		break;
3159 	default:
3160 		freemsg(mp);
3161 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3162 		ire_refrele(ire);
3163 		return;
3164 	}
3165 	/*
3166 	 * Create a Route Association.  This will allow us to remember that
3167 	 * someone we believe told us to use the particular gateway.
3168 	 */
3169 	save_ire = ire;
3170 	ire = ire_create(
3171 	    (uchar_t *)&dst,			/* dest addr */
3172 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3173 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3174 	    (uchar_t *)&gateway,		/* gateway addr */
3175 	    &save_ire->ire_max_frag,		/* max frag */
3176 	    NULL,				/* no src nce */
3177 	    NULL,				/* no rfq */
3178 	    NULL,				/* no stq */
3179 	    IRE_HOST,
3180 	    NULL,				/* ipif */
3181 	    0,					/* cmask */
3182 	    0,					/* phandle */
3183 	    0,					/* ihandle */
3184 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3185 	    &ulp_info,
3186 	    NULL,				/* tsol_gc_t */
3187 	    NULL,				/* gcgrp */
3188 	    ipst);
3189 
3190 	if (ire == NULL) {
3191 		freemsg(mp);
3192 		ire_refrele(save_ire);
3193 		return;
3194 	}
3195 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3196 	ire_refrele(save_ire);
3197 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3198 
3199 	if (error == 0) {
3200 		ire_refrele(ire);		/* Held in ire_add_v4 */
3201 		/* tell routing sockets that we received a redirect */
3202 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3203 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3204 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3205 	}
3206 
3207 	/*
3208 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3209 	 * This together with the added IRE has the effect of
3210 	 * modifying an existing redirect.
3211 	 */
3212 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3213 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3214 	if (prev_ire != NULL) {
3215 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3216 			ire_delete(prev_ire);
3217 		ire_refrele(prev_ire);
3218 	}
3219 
3220 	freemsg(mp);
3221 }
3222 
3223 /*
3224  * Generate an ICMP parameter problem message.
3225  */
3226 static void
3227 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3228 	ip_stack_t *ipst)
3229 {
3230 	icmph_t	icmph;
3231 	boolean_t mctl_present;
3232 	mblk_t *first_mp;
3233 
3234 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3235 
3236 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3237 		if (mctl_present)
3238 			freeb(first_mp);
3239 		return;
3240 	}
3241 
3242 	bzero(&icmph, sizeof (icmph_t));
3243 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3244 	icmph.icmph_pp_ptr = ptr;
3245 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3246 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3247 	    ipst);
3248 }
3249 
3250 /*
3251  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3252  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3253  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3254  * an icmp error packet can be sent.
3255  * Assigns an appropriate source address to the packet. If ipha_dst is
3256  * one of our addresses use it for source. Otherwise pick a source based
3257  * on a route lookup back to ipha_src.
3258  * Note that ipha_src must be set here since the
3259  * packet is likely to arrive on an ill queue in ip_wput() which will
3260  * not set a source address.
3261  */
3262 static void
3263 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3264     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3265 {
3266 	ipaddr_t dst;
3267 	icmph_t	*icmph;
3268 	ipha_t	*ipha;
3269 	uint_t	len_needed;
3270 	size_t	msg_len;
3271 	mblk_t	*mp1;
3272 	ipaddr_t src;
3273 	ire_t	*ire;
3274 	mblk_t *ipsec_mp;
3275 	ipsec_out_t	*io = NULL;
3276 
3277 	if (mctl_present) {
3278 		/*
3279 		 * If it is :
3280 		 *
3281 		 * 1) a IPSEC_OUT, then this is caused by outbound
3282 		 *    datagram originating on this host. IPsec processing
3283 		 *    may or may not have been done. Refer to comments above
3284 		 *    icmp_inbound_error_fanout for details.
3285 		 *
3286 		 * 2) a IPSEC_IN if we are generating a icmp_message
3287 		 *    for an incoming datagram destined for us i.e called
3288 		 *    from ip_fanout_send_icmp.
3289 		 */
3290 		ipsec_info_t *in;
3291 		ipsec_mp = mp;
3292 		mp = ipsec_mp->b_cont;
3293 
3294 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3295 		ipha = (ipha_t *)mp->b_rptr;
3296 
3297 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3298 		    in->ipsec_info_type == IPSEC_IN);
3299 
3300 		if (in->ipsec_info_type == IPSEC_IN) {
3301 			/*
3302 			 * Convert the IPSEC_IN to IPSEC_OUT.
3303 			 */
3304 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3305 				BUMP_MIB(&ipst->ips_ip_mib,
3306 				    ipIfStatsOutDiscards);
3307 				return;
3308 			}
3309 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3310 		} else {
3311 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3312 			io = (ipsec_out_t *)in;
3313 			/*
3314 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3315 			 * ire lookup.
3316 			 */
3317 			io->ipsec_out_proc_begin = B_FALSE;
3318 		}
3319 		ASSERT(zoneid == io->ipsec_out_zoneid);
3320 		ASSERT(zoneid != ALL_ZONES);
3321 	} else {
3322 		/*
3323 		 * This is in clear. The icmp message we are building
3324 		 * here should go out in clear.
3325 		 *
3326 		 * Pardon the convolution of it all, but it's easier to
3327 		 * allocate a "use cleartext" IPSEC_IN message and convert
3328 		 * it than it is to allocate a new one.
3329 		 */
3330 		ipsec_in_t *ii;
3331 		ASSERT(DB_TYPE(mp) == M_DATA);
3332 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3333 		if (ipsec_mp == NULL) {
3334 			freemsg(mp);
3335 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3336 			return;
3337 		}
3338 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3339 
3340 		/* This is not a secure packet */
3341 		ii->ipsec_in_secure = B_FALSE;
3342 		/*
3343 		 * For trusted extensions using a shared IP address we can
3344 		 * send using any zoneid.
3345 		 */
3346 		if (zoneid == ALL_ZONES)
3347 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3348 		else
3349 			ii->ipsec_in_zoneid = zoneid;
3350 		ipsec_mp->b_cont = mp;
3351 		ipha = (ipha_t *)mp->b_rptr;
3352 		/*
3353 		 * Convert the IPSEC_IN to IPSEC_OUT.
3354 		 */
3355 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3356 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3357 			return;
3358 		}
3359 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3360 	}
3361 
3362 	/* Remember our eventual destination */
3363 	dst = ipha->ipha_src;
3364 
3365 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3366 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3367 	if (ire != NULL &&
3368 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3369 		src = ipha->ipha_dst;
3370 	} else {
3371 		if (ire != NULL)
3372 			ire_refrele(ire);
3373 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3374 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3375 		    ipst);
3376 		if (ire == NULL) {
3377 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3378 			freemsg(ipsec_mp);
3379 			return;
3380 		}
3381 		src = ire->ire_src_addr;
3382 	}
3383 
3384 	if (ire != NULL)
3385 		ire_refrele(ire);
3386 
3387 	/*
3388 	 * Check if we can send back more then 8 bytes in addition to
3389 	 * the IP header.  We try to send 64 bytes of data and the internal
3390 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3391 	 */
3392 	len_needed = IPH_HDR_LENGTH(ipha);
3393 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3394 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3395 
3396 		if (!pullupmsg(mp, -1)) {
3397 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3398 			freemsg(ipsec_mp);
3399 			return;
3400 		}
3401 		ipha = (ipha_t *)mp->b_rptr;
3402 
3403 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3404 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3405 			    len_needed));
3406 		} else {
3407 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3408 
3409 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3410 			len_needed += ip_hdr_length_v6(mp, ip6h);
3411 		}
3412 	}
3413 	len_needed += ipst->ips_ip_icmp_return;
3414 	msg_len = msgdsize(mp);
3415 	if (msg_len > len_needed) {
3416 		(void) adjmsg(mp, len_needed - msg_len);
3417 		msg_len = len_needed;
3418 	}
3419 	/* Make sure we propagate the cred/label for TX */
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 	ip_stack_t *ipst = ill->ill_ipst;
3712 
3713 	ipif->ipif_recovery_id = 0;
3714 
3715 	/*
3716 	 * No lock needed for moving or condemned check, as this is just an
3717 	 * optimization.
3718 	 */
3719 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3720 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3721 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3722 		/* No reason to try to bring this address back. */
3723 		return;
3724 	}
3725 
3726 	/* ACE_F_UNVERIFIED restarts DAD */
3727 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == 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 	putnext(ill->ill_rq, arp_add_mp);
3737 	return;
3738 
3739 alloc_fail:
3740 	/*
3741 	 * On allocation failure, just restart the timer.  Note that the ipif
3742 	 * is down here, so no other thread could be trying to start a recovery
3743 	 * timer.  The ill_lock protects the condemned flag and the recovery
3744 	 * timer ID.
3745 	 */
3746 	freemsg(arp_add_mp);
3747 	mutex_enter(&ill->ill_lock);
3748 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3749 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3750 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3751 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3752 	}
3753 	mutex_exit(&ill->ill_lock);
3754 }
3755 
3756 /*
3757  * This is for exclusive changes due to ARP.  Either tear down an interface due
3758  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3759  */
3760 /* ARGSUSED */
3761 static void
3762 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3763 {
3764 	ill_t	*ill = rq->q_ptr;
3765 	arh_t *arh;
3766 	ipaddr_t src;
3767 	ipif_t	*ipif;
3768 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3769 	char hbuf[MAC_STR_LEN];
3770 	char sbuf[INET_ADDRSTRLEN];
3771 	const char *failtype;
3772 	boolean_t bring_up;
3773 	ip_stack_t *ipst = ill->ill_ipst;
3774 
3775 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3776 	case AR_CN_READY:
3777 		failtype = NULL;
3778 		bring_up = B_TRUE;
3779 		break;
3780 	case AR_CN_FAILED:
3781 		failtype = "in use";
3782 		bring_up = B_FALSE;
3783 		break;
3784 	default:
3785 		failtype = "claimed";
3786 		bring_up = B_FALSE;
3787 		break;
3788 	}
3789 
3790 	arh = (arh_t *)mp->b_cont->b_rptr;
3791 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3792 
3793 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3794 	    sizeof (hbuf));
3795 	(void) ip_dot_addr(src, sbuf);
3796 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3797 
3798 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3799 		    ipif->ipif_lcl_addr != src) {
3800 			continue;
3801 		}
3802 
3803 		/*
3804 		 * If we failed on a recovery probe, then restart the timer to
3805 		 * try again later.
3806 		 */
3807 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3808 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3809 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3810 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3811 		    ipst->ips_ip_dup_recovery > 0 &&
3812 		    ipif->ipif_recovery_id == 0) {
3813 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3814 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3815 			continue;
3816 		}
3817 
3818 		/*
3819 		 * If what we're trying to do has already been done, then do
3820 		 * nothing.
3821 		 */
3822 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3823 			continue;
3824 
3825 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3826 
3827 		if (failtype == NULL) {
3828 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3829 			    ibuf);
3830 		} else {
3831 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3832 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3833 		}
3834 
3835 		if (bring_up) {
3836 			ASSERT(ill->ill_dl_up);
3837 			/*
3838 			 * Free up the ARP delete message so we can allocate
3839 			 * a fresh one through the normal path.
3840 			 */
3841 			freemsg(ipif->ipif_arp_del_mp);
3842 			ipif->ipif_arp_del_mp = NULL;
3843 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3844 			    EINPROGRESS) {
3845 				ipif->ipif_addr_ready = 1;
3846 				(void) ipif_up_done(ipif);
3847 				ASSERT(ill->ill_move_ipif == NULL);
3848 			}
3849 			continue;
3850 		}
3851 
3852 		mutex_enter(&ill->ill_lock);
3853 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3854 		ipif->ipif_flags |= IPIF_DUPLICATE;
3855 		ill->ill_ipif_dup_count++;
3856 		mutex_exit(&ill->ill_lock);
3857 		/*
3858 		 * Already exclusive on the ill; no need to handle deferred
3859 		 * processing here.
3860 		 */
3861 		(void) ipif_down(ipif, NULL, NULL);
3862 		ipif_down_tail(ipif);
3863 		mutex_enter(&ill->ill_lock);
3864 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3865 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3866 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3867 		    ipst->ips_ip_dup_recovery > 0) {
3868 			ASSERT(ipif->ipif_recovery_id == 0);
3869 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3870 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3871 		}
3872 		mutex_exit(&ill->ill_lock);
3873 	}
3874 	freemsg(mp);
3875 }
3876 
3877 /* ARGSUSED */
3878 static void
3879 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3880 {
3881 	ill_t	*ill = rq->q_ptr;
3882 	arh_t *arh;
3883 	ipaddr_t src;
3884 	ipif_t	*ipif;
3885 
3886 	arh = (arh_t *)mp->b_cont->b_rptr;
3887 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3888 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3889 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3890 			(void) ipif_resolver_up(ipif, Res_act_defend);
3891 	}
3892 	freemsg(mp);
3893 }
3894 
3895 /*
3896  * News from ARP.  ARP sends notification of interesting events down
3897  * to its clients using M_CTL messages with the interesting ARP packet
3898  * attached via b_cont.
3899  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3900  * queue as opposed to ARP sending the message to all the clients, i.e. all
3901  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3902  * table if a cache IRE is found to delete all the entries for the address in
3903  * the packet.
3904  */
3905 static void
3906 ip_arp_news(queue_t *q, mblk_t *mp)
3907 {
3908 	arcn_t		*arcn;
3909 	arh_t		*arh;
3910 	ire_t		*ire = NULL;
3911 	char		hbuf[MAC_STR_LEN];
3912 	char		sbuf[INET_ADDRSTRLEN];
3913 	ipaddr_t	src;
3914 	in6_addr_t	v6src;
3915 	boolean_t	isv6 = B_FALSE;
3916 	ipif_t		*ipif;
3917 	ill_t		*ill;
3918 	ip_stack_t	*ipst;
3919 
3920 	if (CONN_Q(q)) {
3921 		conn_t *connp = Q_TO_CONN(q);
3922 
3923 		ipst = connp->conn_netstack->netstack_ip;
3924 	} else {
3925 		ill_t *ill = (ill_t *)q->q_ptr;
3926 
3927 		ipst = ill->ill_ipst;
3928 	}
3929 
3930 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3931 		if (q->q_next) {
3932 			putnext(q, mp);
3933 		} else
3934 			freemsg(mp);
3935 		return;
3936 	}
3937 	arh = (arh_t *)mp->b_cont->b_rptr;
3938 	/* Is it one we are interested in? */
3939 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3940 		isv6 = B_TRUE;
3941 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3942 		    IPV6_ADDR_LEN);
3943 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3944 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3945 		    IP_ADDR_LEN);
3946 	} else {
3947 		freemsg(mp);
3948 		return;
3949 	}
3950 
3951 	ill = q->q_ptr;
3952 
3953 	arcn = (arcn_t *)mp->b_rptr;
3954 	switch (arcn->arcn_code) {
3955 	case AR_CN_BOGON:
3956 		/*
3957 		 * Someone is sending ARP packets with a source protocol
3958 		 * address that we have published and for which we believe our
3959 		 * entry is authoritative and (when ill_arp_extend is set)
3960 		 * verified to be unique on the network.
3961 		 *
3962 		 * The ARP module internally handles the cases where the sender
3963 		 * is just probing (for DAD) and where the hardware address of
3964 		 * a non-authoritative entry has changed.  Thus, these are the
3965 		 * real conflicts, and we have to do resolution.
3966 		 *
3967 		 * We back away quickly from the address if it's from DHCP or
3968 		 * otherwise temporary and hasn't been used recently (or at
3969 		 * all).  We'd like to include "deprecated" addresses here as
3970 		 * well (as there's no real reason to defend something we're
3971 		 * discarding), but IPMP "reuses" this flag to mean something
3972 		 * other than the standard meaning.
3973 		 *
3974 		 * If the ARP module above is not extended (meaning that it
3975 		 * doesn't know how to defend the address), then we just log
3976 		 * the problem as we always did and continue on.  It's not
3977 		 * right, but there's little else we can do, and those old ATM
3978 		 * users are going away anyway.
3979 		 */
3980 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3981 		    hbuf, sizeof (hbuf));
3982 		(void) ip_dot_addr(src, sbuf);
3983 		if (isv6) {
3984 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3985 			    ipst);
3986 		} else {
3987 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3988 		}
3989 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3990 			uint32_t now;
3991 			uint32_t maxage;
3992 			clock_t lused;
3993 			uint_t maxdefense;
3994 			uint_t defs;
3995 
3996 			/*
3997 			 * First, figure out if this address hasn't been used
3998 			 * in a while.  If it hasn't, then it's a better
3999 			 * candidate for abandoning.
4000 			 */
4001 			ipif = ire->ire_ipif;
4002 			ASSERT(ipif != NULL);
4003 			now = gethrestime_sec();
4004 			maxage = now - ire->ire_create_time;
4005 			if (maxage > ipst->ips_ip_max_temp_idle)
4006 				maxage = ipst->ips_ip_max_temp_idle;
4007 			lused = drv_hztousec(ddi_get_lbolt() -
4008 			    ire->ire_last_used_time) / MICROSEC + 1;
4009 			if (lused >= maxage && (ipif->ipif_flags &
4010 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4011 				maxdefense = ipst->ips_ip_max_temp_defend;
4012 			else
4013 				maxdefense = ipst->ips_ip_max_defend;
4014 
4015 			/*
4016 			 * Now figure out how many times we've defended
4017 			 * ourselves.  Ignore defenses that happened long in
4018 			 * the past.
4019 			 */
4020 			mutex_enter(&ire->ire_lock);
4021 			if ((defs = ire->ire_defense_count) > 0 &&
4022 			    now - ire->ire_defense_time >
4023 			    ipst->ips_ip_defend_interval) {
4024 				ire->ire_defense_count = defs = 0;
4025 			}
4026 			ire->ire_defense_count++;
4027 			ire->ire_defense_time = now;
4028 			mutex_exit(&ire->ire_lock);
4029 			ill_refhold(ill);
4030 			ire_refrele(ire);
4031 
4032 			/*
4033 			 * If we've defended ourselves too many times already,
4034 			 * then give up and tear down the interface(s) using
4035 			 * this address.  Otherwise, defend by sending out a
4036 			 * gratuitous ARP.
4037 			 */
4038 			if (defs >= maxdefense && ill->ill_arp_extend) {
4039 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4040 				    B_FALSE);
4041 			} else {
4042 				cmn_err(CE_WARN,
4043 				    "node %s is using our IP address %s on %s",
4044 				    hbuf, sbuf, ill->ill_name);
4045 				/*
4046 				 * If this is an old (ATM) ARP module, then
4047 				 * don't try to defend the address.  Remain
4048 				 * compatible with the old behavior.  Defend
4049 				 * only with new ARP.
4050 				 */
4051 				if (ill->ill_arp_extend) {
4052 					qwriter_ip(ill, q, mp, ip_arp_defend,
4053 					    NEW_OP, B_FALSE);
4054 				} else {
4055 					ill_refrele(ill);
4056 				}
4057 			}
4058 			return;
4059 		}
4060 		cmn_err(CE_WARN,
4061 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4062 		    hbuf, sbuf, ill->ill_name);
4063 		if (ire != NULL)
4064 			ire_refrele(ire);
4065 		break;
4066 	case AR_CN_ANNOUNCE:
4067 		if (isv6) {
4068 			/*
4069 			 * For XRESOLV interfaces.
4070 			 * Delete the IRE cache entry and NCE for this
4071 			 * v6 address
4072 			 */
4073 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4074 			/*
4075 			 * If v6src is a non-zero, it's a router address
4076 			 * as below. Do the same sort of thing to clean
4077 			 * out off-net IRE_CACHE entries that go through
4078 			 * the router.
4079 			 */
4080 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4081 				ire_walk_v6(ire_delete_cache_gw_v6,
4082 				    (char *)&v6src, ALL_ZONES, ipst);
4083 			}
4084 		} else {
4085 			nce_hw_map_t hwm;
4086 
4087 			/*
4088 			 * ARP gives us a copy of any packet where it thinks
4089 			 * the address has changed, so that we can update our
4090 			 * caches.  We're responsible for caching known answers
4091 			 * in the current design.  We check whether the
4092 			 * hardware address really has changed in all of our
4093 			 * entries that have cached this mapping, and if so, we
4094 			 * blow them away.  This way we will immediately pick
4095 			 * up the rare case of a host changing hardware
4096 			 * address.
4097 			 */
4098 			if (src == 0)
4099 				break;
4100 			hwm.hwm_addr = src;
4101 			hwm.hwm_hwlen = arh->arh_hlen;
4102 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4103 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4104 			ndp_walk_common(ipst->ips_ndp4, NULL,
4105 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4106 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4107 		}
4108 		break;
4109 	case AR_CN_READY:
4110 		/* No external v6 resolver has a contract to use this */
4111 		if (isv6)
4112 			break;
4113 		/* If the link is down, we'll retry this later */
4114 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4115 			break;
4116 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4117 		    NULL, NULL, ipst);
4118 		if (ipif != NULL) {
4119 			/*
4120 			 * If this is a duplicate recovery, then we now need to
4121 			 * go exclusive to bring this thing back up.
4122 			 */
4123 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4124 			    IPIF_DUPLICATE) {
4125 				ipif_refrele(ipif);
4126 				ill_refhold(ill);
4127 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4128 				    B_FALSE);
4129 				return;
4130 			}
4131 			/*
4132 			 * If this is the first notice that this address is
4133 			 * ready, then let the user know now.
4134 			 */
4135 			if ((ipif->ipif_flags & IPIF_UP) &&
4136 			    !ipif->ipif_addr_ready) {
4137 				ipif_mask_reply(ipif);
4138 				ipif_up_notify(ipif);
4139 			}
4140 			ipif->ipif_addr_ready = 1;
4141 			ipif_refrele(ipif);
4142 		}
4143 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4144 		if (ire != NULL) {
4145 			ire->ire_defense_count = 0;
4146 			ire_refrele(ire);
4147 		}
4148 		break;
4149 	case AR_CN_FAILED:
4150 		/* No external v6 resolver has a contract to use this */
4151 		if (isv6)
4152 			break;
4153 		if (!ill->ill_arp_extend) {
4154 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4155 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4156 			(void) ip_dot_addr(src, sbuf);
4157 
4158 			cmn_err(CE_WARN,
4159 			    "node %s is using our IP address %s on %s",
4160 			    hbuf, sbuf, ill->ill_name);
4161 			break;
4162 		}
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 	boolean_t	ipmp_ill_held = B_FALSE;
4185 
4186 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4187 	if (mp == NULL) {
4188 		ip1dbg(("ip_add_info: allocation failure.\n"));
4189 		return (data_mp);
4190 	}
4191 
4192 	ipha = (ipha_t *)data_mp->b_rptr;
4193 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4194 	bzero(pinfo, sizeof (ip_pktinfo_t));
4195 	pinfo->ip_pkt_flags = (uchar_t)flags;
4196 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4197 
4198 	pether = (struct ether_header *)((char *)ipha
4199 	    - sizeof (struct ether_header));
4200 
4201 	/*
4202 	 * Make sure the interface is an ethernet type, since this option
4203 	 * is currently supported only on this type of interface. Also make
4204 	 * sure we are pointing correctly above db_base.
4205 	 */
4206 	if ((flags & IPF_RECVSLLA) &&
4207 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4208 	    (ill->ill_type == IFT_ETHER) &&
4209 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4210 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4211 		bcopy(pether->ether_shost.ether_addr_octet,
4212 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4213 	} else {
4214 		/*
4215 		 * Clear the bit. Indicate to upper layer that IP is not
4216 		 * sending this ancillary info.
4217 		 */
4218 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4219 	}
4220 
4221 	/*
4222 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4223 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4224 	 * IPF_RECVADDR support on test addresses is not needed.)
4225 	 *
4226 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4227 	 * processing a packet looped back to an IPMP data address
4228 	 * (since those IRE_LOCALs are tied to IPMP ills).
4229 	 */
4230 	if (IS_UNDER_IPMP(ill)) {
4231 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4232 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4233 			freemsg(mp);
4234 			return (data_mp);
4235 		}
4236 		ipmp_ill_held = B_TRUE;
4237 	}
4238 
4239 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4240 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4241 	if (flags & IPF_RECVADDR) {
4242 		ipif_t	*ipif;
4243 		ire_t	*ire;
4244 
4245 		/*
4246 		 * Only valid for V4
4247 		 */
4248 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4249 		    (IPV4_VERSION << 4));
4250 
4251 		ipif = ipif_get_next_ipif(NULL, ill);
4252 		if (ipif != NULL) {
4253 			/*
4254 			 * Since a decision has already been made to deliver the
4255 			 * packet, there is no need to test for SECATTR and
4256 			 * ZONEONLY.
4257 			 * When a multicast packet is transmitted
4258 			 * a cache entry is created for the multicast address.
4259 			 * When delivering a copy of the packet or when new
4260 			 * packets are received we do not want to match on the
4261 			 * cached entry so explicitly match on
4262 			 * IRE_LOCAL and IRE_LOOPBACK
4263 			 */
4264 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4265 			    IRE_LOCAL | IRE_LOOPBACK,
4266 			    ipif, zoneid, NULL,
4267 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4268 			if (ire == NULL) {
4269 				/*
4270 				 * packet must have come on a different
4271 				 * interface.
4272 				 * Since a decision has already been made to
4273 				 * deliver the packet, there is no need to test
4274 				 * for SECATTR and ZONEONLY.
4275 				 * Only match on local and broadcast ire's.
4276 				 * See detailed comment above.
4277 				 */
4278 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4279 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4280 				    NULL, MATCH_IRE_TYPE, ipst);
4281 			}
4282 
4283 			if (ire == NULL) {
4284 				/*
4285 				 * This is either a multicast packet or
4286 				 * the address has been removed since
4287 				 * the packet was received.
4288 				 * Return INADDR_ANY so that normal source
4289 				 * selection occurs for the response.
4290 				 */
4291 
4292 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4293 			} else {
4294 				pinfo->ip_pkt_match_addr.s_addr =
4295 				    ire->ire_src_addr;
4296 				ire_refrele(ire);
4297 			}
4298 			ipif_refrele(ipif);
4299 		} else {
4300 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4301 		}
4302 	}
4303 
4304 	if (ipmp_ill_held)
4305 		ill_refrele(ill);
4306 
4307 	mp->b_datap->db_type = M_CTL;
4308 	mp->b_wptr += sizeof (ip_pktinfo_t);
4309 	mp->b_cont = data_mp;
4310 
4311 	return (mp);
4312 }
4313 
4314 /*
4315  * Used to determine the most accurate cred_t to use for TX.
4316  * First priority is SCM_UCRED having set the label in the message,
4317  * which is used for MLP on UDP. Second priority is the peers label (aka
4318  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4319  * open credentials.
4320  */
4321 cred_t *
4322 ip_best_cred(mblk_t *mp, conn_t *connp)
4323 {
4324 	cred_t *cr;
4325 
4326 	cr = msg_getcred(mp, NULL);
4327 	if (cr != NULL && crgetlabel(cr) != NULL)
4328 		return (cr);
4329 	return (CONN_CRED(connp));
4330 }
4331 
4332 /*
4333  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4334  * part of the bind request.
4335  */
4336 
4337 boolean_t
4338 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4339 {
4340 	ipsec_in_t *ii;
4341 
4342 	ASSERT(policy_mp != NULL);
4343 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4344 
4345 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4346 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4347 
4348 	connp->conn_policy = ii->ipsec_in_policy;
4349 	ii->ipsec_in_policy = NULL;
4350 
4351 	if (ii->ipsec_in_action != NULL) {
4352 		if (connp->conn_latch == NULL) {
4353 			connp->conn_latch = iplatch_create();
4354 			if (connp->conn_latch == NULL)
4355 				return (B_FALSE);
4356 		}
4357 		ipsec_latch_inbound(connp->conn_latch, ii);
4358 	}
4359 	return (B_TRUE);
4360 }
4361 
4362 static void
4363 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4364 {
4365 	/*
4366 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4367 	 * We can't do this in ip_bind_get_ire because the policy
4368 	 * may not have been inherited at that point in time and hence
4369 	 * conn_out_enforce_policy may not be set.
4370 	 */
4371 	if (ire_requested && connp->conn_out_enforce_policy &&
4372 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4373 		ire_t *ire = (ire_t *)mp->b_rptr;
4374 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4375 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4376 	}
4377 }
4378 
4379 /*
4380  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4381  * and to arrange for power-fanout assist.  The ULP is identified by
4382  * adding a single byte at the end of the original bind message.
4383  * A ULP other than UDP or TCP that wishes to be recognized passes
4384  * down a bind with a zero length address.
4385  *
4386  * The binding works as follows:
4387  * - A zero byte address means just bind to the protocol.
4388  * - A four byte address is treated as a request to validate
4389  *   that the address is a valid local address, appropriate for
4390  *   an application to bind to. This does not affect any fanout
4391  *   information in IP.
4392  * - A sizeof sin_t byte address is used to bind to only the local address
4393  *   and port.
4394  * - A sizeof ipa_conn_t byte address contains complete fanout information
4395  *   consisting of local and remote addresses and ports.  In
4396  *   this case, the addresses are both validated as appropriate
4397  *   for this operation, and, if so, the information is retained
4398  *   for use in the inbound fanout.
4399  *
4400  * The ULP (except in the zero-length bind) can append an
4401  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4402  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4403  * a copy of the source or destination IRE (source for local bind;
4404  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4405  * policy information contained should be copied on to the conn.
4406  *
4407  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4408  */
4409 mblk_t *
4410 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4411 {
4412 	ssize_t		len;
4413 	struct T_bind_req	*tbr;
4414 	sin_t		*sin;
4415 	ipa_conn_t	*ac;
4416 	uchar_t		*ucp;
4417 	mblk_t		*mp1;
4418 	boolean_t	ire_requested;
4419 	int		error = 0;
4420 	int		protocol;
4421 	ipa_conn_x_t	*acx;
4422 	cred_t		*cr;
4423 
4424 	/*
4425 	 * All Solaris components should pass a db_credp
4426 	 * for this TPI message, hence we ASSERT.
4427 	 * But in case there is some other M_PROTO that looks
4428 	 * like a TPI message sent by some other kernel
4429 	 * component, we check and return an error.
4430 	 */
4431 	cr = msg_getcred(mp, NULL);
4432 	ASSERT(cr != NULL);
4433 	if (cr == NULL) {
4434 		error = EINVAL;
4435 		goto bad_addr;
4436 	}
4437 
4438 	ASSERT(!connp->conn_af_isv6);
4439 	connp->conn_pkt_isv6 = B_FALSE;
4440 
4441 	len = MBLKL(mp);
4442 	if (len < (sizeof (*tbr) + 1)) {
4443 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4444 		    "ip_bind: bogus msg, len %ld", len);
4445 		/* XXX: Need to return something better */
4446 		goto bad_addr;
4447 	}
4448 	/* Back up and extract the protocol identifier. */
4449 	mp->b_wptr--;
4450 	protocol = *mp->b_wptr & 0xFF;
4451 	tbr = (struct T_bind_req *)mp->b_rptr;
4452 	/* Reset the message type in preparation for shipping it back. */
4453 	DB_TYPE(mp) = M_PCPROTO;
4454 
4455 	connp->conn_ulp = (uint8_t)protocol;
4456 
4457 	/*
4458 	 * Check for a zero length address.  This is from a protocol that
4459 	 * wants to register to receive all packets of its type.
4460 	 */
4461 	if (tbr->ADDR_length == 0) {
4462 		/*
4463 		 * These protocols are now intercepted in ip_bind_v6().
4464 		 * Reject protocol-level binds here for now.
4465 		 *
4466 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4467 		 * so that the protocol type cannot be SCTP.
4468 		 */
4469 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4470 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4471 			goto bad_addr;
4472 		}
4473 
4474 		/*
4475 		 *
4476 		 * The udp module never sends down a zero-length address,
4477 		 * and allowing this on a labeled system will break MLP
4478 		 * functionality.
4479 		 */
4480 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4481 			goto bad_addr;
4482 
4483 		if (connp->conn_mac_exempt)
4484 			goto bad_addr;
4485 
4486 		/* No hash here really.  The table is big enough. */
4487 		connp->conn_srcv6 = ipv6_all_zeros;
4488 
4489 		ipcl_proto_insert(connp, protocol);
4490 
4491 		tbr->PRIM_type = T_BIND_ACK;
4492 		return (mp);
4493 	}
4494 
4495 	/* Extract the address pointer from the message. */
4496 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4497 	    tbr->ADDR_length);
4498 	if (ucp == NULL) {
4499 		ip1dbg(("ip_bind: no address\n"));
4500 		goto bad_addr;
4501 	}
4502 	if (!OK_32PTR(ucp)) {
4503 		ip1dbg(("ip_bind: unaligned address\n"));
4504 		goto bad_addr;
4505 	}
4506 	/*
4507 	 * Check for trailing mps.
4508 	 */
4509 
4510 	mp1 = mp->b_cont;
4511 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4512 
4513 	switch (tbr->ADDR_length) {
4514 	default:
4515 		ip1dbg(("ip_bind: bad address length %d\n",
4516 		    (int)tbr->ADDR_length));
4517 		goto bad_addr;
4518 
4519 	case IP_ADDR_LEN:
4520 		/* Verification of local address only */
4521 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4522 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4523 		break;
4524 
4525 	case sizeof (sin_t):
4526 		sin = (sin_t *)ucp;
4527 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4528 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4529 		break;
4530 
4531 	case sizeof (ipa_conn_t):
4532 		ac = (ipa_conn_t *)ucp;
4533 		/* For raw socket, the local port is not set. */
4534 		if (ac->ac_lport == 0)
4535 			ac->ac_lport = connp->conn_lport;
4536 		/* Always verify destination reachability. */
4537 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4538 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4539 		    B_TRUE, B_TRUE, cr);
4540 		break;
4541 
4542 	case sizeof (ipa_conn_x_t):
4543 		acx = (ipa_conn_x_t *)ucp;
4544 		/*
4545 		 * Whether or not to verify destination reachability depends
4546 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4547 		 */
4548 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4549 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4550 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4551 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4552 		break;
4553 	}
4554 	ASSERT(error != EINPROGRESS);
4555 	if (error != 0)
4556 		goto bad_addr;
4557 
4558 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4559 
4560 	/* Send it home. */
4561 	mp->b_datap->db_type = M_PCPROTO;
4562 	tbr->PRIM_type = T_BIND_ACK;
4563 	return (mp);
4564 
4565 bad_addr:
4566 	/*
4567 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4568 	 * a unix errno.
4569 	 */
4570 	if (error > 0)
4571 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4572 	else
4573 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4574 	return (mp);
4575 }
4576 
4577 /*
4578  * Here address is verified to be a valid local address.
4579  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4580  * address is also considered a valid local address.
4581  * In the case of a broadcast/multicast address, however, the
4582  * upper protocol is expected to reset the src address
4583  * to 0 if it sees a IRE_BROADCAST type returned so that
4584  * no packets are emitted with broadcast/multicast address as
4585  * source address (that violates hosts requirements RFC 1122)
4586  * The addresses valid for bind are:
4587  *	(1) - INADDR_ANY (0)
4588  *	(2) - IP address of an UP interface
4589  *	(3) - IP address of a DOWN interface
4590  *	(4) - valid local IP broadcast addresses. In this case
4591  *	the conn will only receive packets destined to
4592  *	the specified broadcast address.
4593  *	(5) - a multicast address. In this case
4594  *	the conn will only receive packets destined to
4595  *	the specified multicast address. Note: the
4596  *	application still has to issue an
4597  *	IP_ADD_MEMBERSHIP socket option.
4598  *
4599  * On error, return -1 for TBADADDR otherwise pass the
4600  * errno with TSYSERR reply.
4601  *
4602  * In all the above cases, the bound address must be valid in the current zone.
4603  * When the address is loopback, multicast or broadcast, there might be many
4604  * matching IREs so bind has to look up based on the zone.
4605  *
4606  * Note: lport is in network byte order.
4607  *
4608  */
4609 int
4610 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4611     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4612 {
4613 	int		error = 0;
4614 	ire_t		*src_ire;
4615 	zoneid_t	zoneid;
4616 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4617 	mblk_t		*mp = NULL;
4618 	boolean_t	ire_requested = B_FALSE;
4619 	boolean_t	ipsec_policy_set = B_FALSE;
4620 
4621 	if (mpp)
4622 		mp = *mpp;
4623 
4624 	if (mp != NULL) {
4625 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4626 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4627 	}
4628 
4629 	/*
4630 	 * If it was previously connected, conn_fully_bound would have
4631 	 * been set.
4632 	 */
4633 	connp->conn_fully_bound = B_FALSE;
4634 
4635 	src_ire = NULL;
4636 
4637 	zoneid = IPCL_ZONEID(connp);
4638 
4639 	if (src_addr) {
4640 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4641 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4642 		/*
4643 		 * If an address other than 0.0.0.0 is requested,
4644 		 * we verify that it is a valid address for bind
4645 		 * Note: Following code is in if-else-if form for
4646 		 * readability compared to a condition check.
4647 		 */
4648 		/* LINTED - statement has no consequence */
4649 		if (IRE_IS_LOCAL(src_ire)) {
4650 			/*
4651 			 * (2) Bind to address of local UP interface
4652 			 */
4653 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4654 			/*
4655 			 * (4) Bind to broadcast address
4656 			 * Note: permitted only from transports that
4657 			 * request IRE
4658 			 */
4659 			if (!ire_requested)
4660 				error = EADDRNOTAVAIL;
4661 		} else {
4662 			/*
4663 			 * (3) Bind to address of local DOWN interface
4664 			 * (ipif_lookup_addr() looks up all interfaces
4665 			 * but we do not get here for UP interfaces
4666 			 * - case (2) above)
4667 			 */
4668 			/* LINTED - statement has no consequent */
4669 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4670 				/* The address exists */
4671 			} else if (CLASSD(src_addr)) {
4672 				error = 0;
4673 				if (src_ire != NULL)
4674 					ire_refrele(src_ire);
4675 				/*
4676 				 * (5) bind to multicast address.
4677 				 * Fake out the IRE returned to upper
4678 				 * layer to be a broadcast IRE.
4679 				 */
4680 				src_ire = ire_ctable_lookup(
4681 				    INADDR_BROADCAST, INADDR_ANY,
4682 				    IRE_BROADCAST, NULL, zoneid, NULL,
4683 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4684 				    ipst);
4685 				if (src_ire == NULL || !ire_requested)
4686 					error = EADDRNOTAVAIL;
4687 			} else {
4688 				/*
4689 				 * Not a valid address for bind
4690 				 */
4691 				error = EADDRNOTAVAIL;
4692 			}
4693 		}
4694 		if (error) {
4695 			/* Red Alert!  Attempting to be a bogon! */
4696 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4697 			    ntohl(src_addr)));
4698 			goto bad_addr;
4699 		}
4700 	}
4701 
4702 	/*
4703 	 * Allow setting new policies. For example, disconnects come
4704 	 * down as ipa_t bind. As we would have set conn_policy_cached
4705 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4706 	 * can change after the disconnect.
4707 	 */
4708 	connp->conn_policy_cached = B_FALSE;
4709 
4710 	/*
4711 	 * If not fanout_insert this was just an address verification
4712 	 */
4713 	if (fanout_insert) {
4714 		/*
4715 		 * The addresses have been verified. Time to insert in
4716 		 * the correct fanout list.
4717 		 */
4718 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4719 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4720 		connp->conn_lport = lport;
4721 		connp->conn_fport = 0;
4722 		/*
4723 		 * Do we need to add a check to reject Multicast packets
4724 		 */
4725 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4726 	}
4727 
4728 	if (error == 0) {
4729 		if (ire_requested) {
4730 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4731 				error = -1;
4732 				/* Falls through to bad_addr */
4733 			}
4734 		} else if (ipsec_policy_set) {
4735 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4736 				error = -1;
4737 				/* Falls through to bad_addr */
4738 			}
4739 		}
4740 	}
4741 bad_addr:
4742 	if (error != 0) {
4743 		if (connp->conn_anon_port) {
4744 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4745 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4746 			    B_FALSE);
4747 		}
4748 		connp->conn_mlp_type = mlptSingle;
4749 	}
4750 	if (src_ire != NULL)
4751 		IRE_REFRELE(src_ire);
4752 	return (error);
4753 }
4754 
4755 int
4756 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4757     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4758 {
4759 	int error;
4760 	mblk_t	*mp = NULL;
4761 	boolean_t ire_requested;
4762 
4763 	if (ire_mpp)
4764 		mp = *ire_mpp;
4765 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4766 
4767 	ASSERT(!connp->conn_af_isv6);
4768 	connp->conn_pkt_isv6 = B_FALSE;
4769 	connp->conn_ulp = protocol;
4770 
4771 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4772 	    fanout_insert);
4773 	if (error == 0) {
4774 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4775 		    ire_requested);
4776 	} else if (error < 0) {
4777 		error = -TBADADDR;
4778 	}
4779 	return (error);
4780 }
4781 
4782 /*
4783  * Verify that both the source and destination addresses
4784  * are valid.  If verify_dst is false, then the destination address may be
4785  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4786  * destination reachability, while tunnels do not.
4787  * Note that we allow connect to broadcast and multicast
4788  * addresses when ire_requested is set. Thus the ULP
4789  * has to check for IRE_BROADCAST and multicast.
4790  *
4791  * Returns zero if ok.
4792  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4793  * (for use with TSYSERR reply).
4794  *
4795  * Note: lport and fport are in network byte order.
4796  */
4797 int
4798 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4799     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4800     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4801 {
4802 
4803 	ire_t		*src_ire;
4804 	ire_t		*dst_ire;
4805 	int		error = 0;
4806 	ire_t		*sire = NULL;
4807 	ire_t		*md_dst_ire = NULL;
4808 	ire_t		*lso_dst_ire = NULL;
4809 	ill_t		*ill = NULL;
4810 	zoneid_t	zoneid;
4811 	ipaddr_t	src_addr = *src_addrp;
4812 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4813 	mblk_t		*mp = NULL;
4814 	boolean_t	ire_requested = B_FALSE;
4815 	boolean_t	ipsec_policy_set = B_FALSE;
4816 	ts_label_t	*tsl = NULL;
4817 
4818 	if (mpp)
4819 		mp = *mpp;
4820 
4821 	if (mp != NULL) {
4822 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4823 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4824 	}
4825 	if (cr != NULL)
4826 		tsl = crgetlabel(cr);
4827 
4828 	src_ire = dst_ire = NULL;
4829 
4830 	/*
4831 	 * If we never got a disconnect before, clear it now.
4832 	 */
4833 	connp->conn_fully_bound = B_FALSE;
4834 
4835 	zoneid = IPCL_ZONEID(connp);
4836 
4837 	if (CLASSD(dst_addr)) {
4838 		/* Pick up an IRE_BROADCAST */
4839 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4840 		    NULL, zoneid, tsl,
4841 		    (MATCH_IRE_RECURSIVE |
4842 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4843 		    MATCH_IRE_SECATTR), ipst);
4844 	} else {
4845 		/*
4846 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4847 		 * and onlink ipif is not found set ENETUNREACH error.
4848 		 */
4849 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4850 			ipif_t *ipif;
4851 
4852 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4853 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4854 			if (ipif == NULL) {
4855 				error = ENETUNREACH;
4856 				goto bad_addr;
4857 			}
4858 			ipif_refrele(ipif);
4859 		}
4860 
4861 		if (connp->conn_nexthop_set) {
4862 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4863 			    0, 0, NULL, NULL, zoneid, tsl,
4864 			    MATCH_IRE_SECATTR, ipst);
4865 		} else {
4866 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4867 			    &sire, zoneid, tsl,
4868 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4869 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4870 			    MATCH_IRE_SECATTR), ipst);
4871 		}
4872 	}
4873 	/*
4874 	 * dst_ire can't be a broadcast when not ire_requested.
4875 	 * We also prevent ire's with src address INADDR_ANY to
4876 	 * be used, which are created temporarily for
4877 	 * sending out packets from endpoints that have
4878 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4879 	 * reachable.  If verify_dst is false, the destination needn't be
4880 	 * reachable.
4881 	 *
4882 	 * If we match on a reject or black hole, then we've got a
4883 	 * local failure.  May as well fail out the connect() attempt,
4884 	 * since it's never going to succeed.
4885 	 */
4886 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4887 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4888 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4889 		/*
4890 		 * If we're verifying destination reachability, we always want
4891 		 * to complain here.
4892 		 *
4893 		 * If we're not verifying destination reachability but the
4894 		 * destination has a route, we still want to fail on the
4895 		 * temporary address and broadcast address tests.
4896 		 */
4897 		if (verify_dst || (dst_ire != NULL)) {
4898 			if (ip_debug > 2) {
4899 				pr_addr_dbg("ip_bind_connected_v4:"
4900 				    "bad connected dst %s\n",
4901 				    AF_INET, &dst_addr);
4902 			}
4903 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4904 				error = ENETUNREACH;
4905 			else
4906 				error = EHOSTUNREACH;
4907 			goto bad_addr;
4908 		}
4909 	}
4910 
4911 	/*
4912 	 * We now know that routing will allow us to reach the destination.
4913 	 * Check whether Trusted Solaris policy allows communication with this
4914 	 * host, and pretend that the destination is unreachable if not.
4915 	 *
4916 	 * This is never a problem for TCP, since that transport is known to
4917 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4918 	 * handling.  If the remote is unreachable, it will be detected at that
4919 	 * point, so there's no reason to check it here.
4920 	 *
4921 	 * Note that for sendto (and other datagram-oriented friends), this
4922 	 * check is done as part of the data path label computation instead.
4923 	 * The check here is just to make non-TCP connect() report the right
4924 	 * error.
4925 	 */
4926 	if (dst_ire != NULL && is_system_labeled() &&
4927 	    !IPCL_IS_TCP(connp) &&
4928 	    tsol_compute_label(cr, dst_addr, NULL,
4929 	    connp->conn_mac_exempt, ipst) != 0) {
4930 		error = EHOSTUNREACH;
4931 		if (ip_debug > 2) {
4932 			pr_addr_dbg("ip_bind_connected_v4:"
4933 			    " no label for dst %s\n",
4934 			    AF_INET, &dst_addr);
4935 		}
4936 		goto bad_addr;
4937 	}
4938 
4939 	/*
4940 	 * If the app does a connect(), it means that it will most likely
4941 	 * send more than 1 packet to the destination.  It makes sense
4942 	 * to clear the temporary flag.
4943 	 */
4944 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4945 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4946 		irb_t *irb = dst_ire->ire_bucket;
4947 
4948 		rw_enter(&irb->irb_lock, RW_WRITER);
4949 		/*
4950 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4951 		 * the lock to guarantee irb_tmp_ire_cnt.
4952 		 */
4953 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4954 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4955 			irb->irb_tmp_ire_cnt--;
4956 		}
4957 		rw_exit(&irb->irb_lock);
4958 	}
4959 
4960 	/*
4961 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4962 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4963 	 * eligibility tests for passive connects are handled separately
4964 	 * through tcp_adapt_ire().  We do this before the source address
4965 	 * selection, because dst_ire may change after a call to
4966 	 * ipif_select_source().  This is a best-effort check, as the
4967 	 * packet for this connection may not actually go through
4968 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4969 	 * calling ip_newroute().  This is why we further check on the
4970 	 * IRE during LSO/Multidata packet transmission in
4971 	 * tcp_lsosend()/tcp_multisend().
4972 	 */
4973 	if (!ipsec_policy_set && dst_ire != NULL &&
4974 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4975 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4976 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4977 			lso_dst_ire = dst_ire;
4978 			IRE_REFHOLD(lso_dst_ire);
4979 		} else if (ipst->ips_ip_multidata_outbound &&
4980 		    ILL_MDT_CAPABLE(ill)) {
4981 			md_dst_ire = dst_ire;
4982 			IRE_REFHOLD(md_dst_ire);
4983 		}
4984 	}
4985 
4986 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4987 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4988 		/*
4989 		 * If the IRE belongs to a different zone, look for a matching
4990 		 * route in the forwarding table and use the source address from
4991 		 * that route.
4992 		 */
4993 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4994 		    zoneid, 0, NULL,
4995 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4996 		    MATCH_IRE_RJ_BHOLE, ipst);
4997 		if (src_ire == NULL) {
4998 			error = EHOSTUNREACH;
4999 			goto bad_addr;
5000 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5001 			if (!(src_ire->ire_type & IRE_HOST))
5002 				error = ENETUNREACH;
5003 			else
5004 				error = EHOSTUNREACH;
5005 			goto bad_addr;
5006 		}
5007 		if (src_addr == INADDR_ANY)
5008 			src_addr = src_ire->ire_src_addr;
5009 		ire_refrele(src_ire);
5010 		src_ire = NULL;
5011 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5012 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5013 			src_addr = sire->ire_src_addr;
5014 			ire_refrele(dst_ire);
5015 			dst_ire = sire;
5016 			sire = NULL;
5017 		} else {
5018 			/*
5019 			 * Pick a source address so that a proper inbound
5020 			 * load spreading would happen.
5021 			 */
5022 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5023 			ipif_t *src_ipif = NULL;
5024 			ire_t *ipif_ire;
5025 
5026 			/*
5027 			 * Supply a local source address such that inbound
5028 			 * load spreading happens.
5029 			 *
5030 			 * Determine the best source address on this ill for
5031 			 * the destination.
5032 			 *
5033 			 * 1) For broadcast, we should return a broadcast ire
5034 			 *    found above so that upper layers know that the
5035 			 *    destination address is a broadcast address.
5036 			 *
5037 			 * 2) If the ipif is DEPRECATED, select a better
5038 			 *    source address.  Similarly, if the ipif is on
5039 			 *    the IPMP meta-interface, pick a source address
5040 			 *    at random to improve inbound load spreading.
5041 			 *
5042 			 * 3) If the outgoing interface is part of a usesrc
5043 			 *    group, then try selecting a source address from
5044 			 *    the usesrc ILL.
5045 			 */
5046 			if ((dst_ire->ire_zoneid != zoneid &&
5047 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5048 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5049 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5050 			    (IS_IPMP(ire_ill) ||
5051 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5052 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5053 				/*
5054 				 * If the destination is reachable via a
5055 				 * given gateway, the selected source address
5056 				 * should be in the same subnet as the gateway.
5057 				 * Otherwise, the destination is not reachable.
5058 				 *
5059 				 * If there are no interfaces on the same subnet
5060 				 * as the destination, ipif_select_source gives
5061 				 * first non-deprecated interface which might be
5062 				 * on a different subnet than the gateway.
5063 				 * This is not desirable. Hence pass the dst_ire
5064 				 * source address to ipif_select_source.
5065 				 * It is sure that the destination is reachable
5066 				 * with the dst_ire source address subnet.
5067 				 * So passing dst_ire source address to
5068 				 * ipif_select_source will make sure that the
5069 				 * selected source will be on the same subnet
5070 				 * as dst_ire source address.
5071 				 */
5072 				ipaddr_t saddr =
5073 				    dst_ire->ire_ipif->ipif_src_addr;
5074 				src_ipif = ipif_select_source(ire_ill,
5075 				    saddr, zoneid);
5076 				if (src_ipif != NULL) {
5077 					if (IS_VNI(src_ipif->ipif_ill)) {
5078 						/*
5079 						 * For VNI there is no
5080 						 * interface route
5081 						 */
5082 						src_addr =
5083 						    src_ipif->ipif_src_addr;
5084 					} else {
5085 						ipif_ire =
5086 						    ipif_to_ire(src_ipif);
5087 						if (ipif_ire != NULL) {
5088 							IRE_REFRELE(dst_ire);
5089 							dst_ire = ipif_ire;
5090 						}
5091 						src_addr =
5092 						    dst_ire->ire_src_addr;
5093 					}
5094 					ipif_refrele(src_ipif);
5095 				} else {
5096 					src_addr = dst_ire->ire_src_addr;
5097 				}
5098 			} else {
5099 				src_addr = dst_ire->ire_src_addr;
5100 			}
5101 		}
5102 	}
5103 
5104 	/*
5105 	 * We do ire_route_lookup() here (and not
5106 	 * interface lookup as we assert that
5107 	 * src_addr should only come from an
5108 	 * UP interface for hard binding.
5109 	 */
5110 	ASSERT(src_ire == NULL);
5111 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5112 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5113 	/* src_ire must be a local|loopback */
5114 	if (!IRE_IS_LOCAL(src_ire)) {
5115 		if (ip_debug > 2) {
5116 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5117 			    "src %s\n", AF_INET, &src_addr);
5118 		}
5119 		error = EADDRNOTAVAIL;
5120 		goto bad_addr;
5121 	}
5122 
5123 	/*
5124 	 * If the source address is a loopback address, the
5125 	 * destination had best be local or multicast.
5126 	 * The transports that can't handle multicast will reject
5127 	 * those addresses.
5128 	 */
5129 	if (src_ire->ire_type == IRE_LOOPBACK &&
5130 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5131 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5132 		error = -1;
5133 		goto bad_addr;
5134 	}
5135 
5136 	/*
5137 	 * Allow setting new policies. For example, disconnects come
5138 	 * down as ipa_t bind. As we would have set conn_policy_cached
5139 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5140 	 * can change after the disconnect.
5141 	 */
5142 	connp->conn_policy_cached = B_FALSE;
5143 
5144 	/*
5145 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5146 	 * can handle their passed-in conn's.
5147 	 */
5148 
5149 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5150 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5151 	connp->conn_lport = lport;
5152 	connp->conn_fport = fport;
5153 	*src_addrp = src_addr;
5154 
5155 	ASSERT(!(ipsec_policy_set && ire_requested));
5156 	if (ire_requested) {
5157 		iulp_t *ulp_info = NULL;
5158 
5159 		/*
5160 		 * Note that sire will not be NULL if this is an off-link
5161 		 * connection and there is not cache for that dest yet.
5162 		 *
5163 		 * XXX Because of an existing bug, if there are multiple
5164 		 * default routes, the IRE returned now may not be the actual
5165 		 * default route used (default routes are chosen in a
5166 		 * round robin fashion).  So if the metrics for different
5167 		 * default routes are different, we may return the wrong
5168 		 * metrics.  This will not be a problem if the existing
5169 		 * bug is fixed.
5170 		 */
5171 		if (sire != NULL) {
5172 			ulp_info = &(sire->ire_uinfo);
5173 		}
5174 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5175 			error = -1;
5176 			goto bad_addr;
5177 		}
5178 		mp = *mpp;
5179 	} else if (ipsec_policy_set) {
5180 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5181 			error = -1;
5182 			goto bad_addr;
5183 		}
5184 	}
5185 
5186 	/*
5187 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5188 	 * we'll cache that.  If we don't, we'll inherit global policy.
5189 	 *
5190 	 * We can't insert until the conn reflects the policy. Note that
5191 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5192 	 * connections where we don't have a policy. This is to prevent
5193 	 * global policy lookups in the inbound path.
5194 	 *
5195 	 * If we insert before we set conn_policy_cached,
5196 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5197 	 * because global policy cound be non-empty. We normally call
5198 	 * ipsec_check_policy() for conn_policy_cached connections only if
5199 	 * ipc_in_enforce_policy is set. But in this case,
5200 	 * conn_policy_cached can get set anytime since we made the
5201 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5202 	 * called, which will make the above assumption false.  Thus, we
5203 	 * need to insert after we set conn_policy_cached.
5204 	 */
5205 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5206 		goto bad_addr;
5207 
5208 	if (fanout_insert) {
5209 		/*
5210 		 * The addresses have been verified. Time to insert in
5211 		 * the correct fanout list.
5212 		 */
5213 		error = ipcl_conn_insert(connp, protocol, src_addr,
5214 		    dst_addr, connp->conn_ports);
5215 	}
5216 
5217 	if (error == 0) {
5218 		connp->conn_fully_bound = B_TRUE;
5219 		/*
5220 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5221 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5222 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5223 		 * ip_xxinfo_return(), which performs further checks
5224 		 * against them and upon success, returns the LSO/MDT info
5225 		 * mblk which we will attach to the bind acknowledgment.
5226 		 */
5227 		if (lso_dst_ire != NULL) {
5228 			mblk_t *lsoinfo_mp;
5229 
5230 			ASSERT(ill->ill_lso_capab != NULL);
5231 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5232 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5233 				if (mp == NULL) {
5234 					*mpp = lsoinfo_mp;
5235 				} else {
5236 					linkb(mp, lsoinfo_mp);
5237 				}
5238 			}
5239 		} else if (md_dst_ire != NULL) {
5240 			mblk_t *mdinfo_mp;
5241 
5242 			ASSERT(ill->ill_mdt_capab != NULL);
5243 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5244 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5245 				if (mp == NULL) {
5246 					*mpp = mdinfo_mp;
5247 				} else {
5248 					linkb(mp, mdinfo_mp);
5249 				}
5250 			}
5251 		}
5252 	}
5253 bad_addr:
5254 	if (ipsec_policy_set) {
5255 		ASSERT(mp != NULL);
5256 		freeb(mp);
5257 		/*
5258 		 * As of now assume that nothing else accompanies
5259 		 * IPSEC_POLICY_SET.
5260 		 */
5261 		*mpp = NULL;
5262 	}
5263 	if (src_ire != NULL)
5264 		IRE_REFRELE(src_ire);
5265 	if (dst_ire != NULL)
5266 		IRE_REFRELE(dst_ire);
5267 	if (sire != NULL)
5268 		IRE_REFRELE(sire);
5269 	if (md_dst_ire != NULL)
5270 		IRE_REFRELE(md_dst_ire);
5271 	if (lso_dst_ire != NULL)
5272 		IRE_REFRELE(lso_dst_ire);
5273 	return (error);
5274 }
5275 
5276 int
5277 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5278     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5279     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5280 {
5281 	int error;
5282 	mblk_t	*mp = NULL;
5283 	boolean_t ire_requested;
5284 
5285 	if (ire_mpp)
5286 		mp = *ire_mpp;
5287 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5288 
5289 	ASSERT(!connp->conn_af_isv6);
5290 	connp->conn_pkt_isv6 = B_FALSE;
5291 	connp->conn_ulp = protocol;
5292 
5293 	/* For raw socket, the local port is not set. */
5294 	if (lport == 0)
5295 		lport = connp->conn_lport;
5296 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5297 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5298 	if (error == 0) {
5299 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5300 		    ire_requested);
5301 	} else if (error < 0) {
5302 		error = -TBADADDR;
5303 	}
5304 	return (error);
5305 }
5306 
5307 /*
5308  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5309  * Prefers dst_ire over src_ire.
5310  */
5311 static boolean_t
5312 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5313 {
5314 	mblk_t	*mp = *mpp;
5315 	ire_t	*ret_ire;
5316 
5317 	ASSERT(mp != NULL);
5318 
5319 	if (ire != NULL) {
5320 		/*
5321 		 * mp initialized above to IRE_DB_REQ_TYPE
5322 		 * appended mblk. Its <upper protocol>'s
5323 		 * job to make sure there is room.
5324 		 */
5325 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5326 			return (B_FALSE);
5327 
5328 		mp->b_datap->db_type = IRE_DB_TYPE;
5329 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5330 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5331 		ret_ire = (ire_t *)mp->b_rptr;
5332 		/*
5333 		 * Pass the latest setting of the ip_path_mtu_discovery and
5334 		 * copy the ulp info if any.
5335 		 */
5336 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5337 		    IPH_DF : 0;
5338 		if (ulp_info != NULL) {
5339 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5340 			    sizeof (iulp_t));
5341 		}
5342 		ret_ire->ire_mp = mp;
5343 	} else {
5344 		/*
5345 		 * No IRE was found. Remove IRE mblk.
5346 		 */
5347 		*mpp = mp->b_cont;
5348 		freeb(mp);
5349 	}
5350 	return (B_TRUE);
5351 }
5352 
5353 /*
5354  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5355  * the final piece where we don't.  Return a pointer to the first mblk in the
5356  * result, and update the pointer to the next mblk to chew on.  If anything
5357  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5358  * NULL pointer.
5359  */
5360 mblk_t *
5361 ip_carve_mp(mblk_t **mpp, ssize_t len)
5362 {
5363 	mblk_t	*mp0;
5364 	mblk_t	*mp1;
5365 	mblk_t	*mp2;
5366 
5367 	if (!len || !mpp || !(mp0 = *mpp))
5368 		return (NULL);
5369 	/* If we aren't going to consume the first mblk, we need a dup. */
5370 	if (mp0->b_wptr - mp0->b_rptr > len) {
5371 		mp1 = dupb(mp0);
5372 		if (mp1) {
5373 			/* Partition the data between the two mblks. */
5374 			mp1->b_wptr = mp1->b_rptr + len;
5375 			mp0->b_rptr = mp1->b_wptr;
5376 			/*
5377 			 * after adjustments if mblk not consumed is now
5378 			 * unaligned, try to align it. If this fails free
5379 			 * all messages and let upper layer recover.
5380 			 */
5381 			if (!OK_32PTR(mp0->b_rptr)) {
5382 				if (!pullupmsg(mp0, -1)) {
5383 					freemsg(mp0);
5384 					freemsg(mp1);
5385 					*mpp = NULL;
5386 					return (NULL);
5387 				}
5388 			}
5389 		}
5390 		return (mp1);
5391 	}
5392 	/* Eat through as many mblks as we need to get len bytes. */
5393 	len -= mp0->b_wptr - mp0->b_rptr;
5394 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5395 		if (mp2->b_wptr - mp2->b_rptr > len) {
5396 			/*
5397 			 * We won't consume the entire last mblk.  Like
5398 			 * above, dup and partition it.
5399 			 */
5400 			mp1->b_cont = dupb(mp2);
5401 			mp1 = mp1->b_cont;
5402 			if (!mp1) {
5403 				/*
5404 				 * Trouble.  Rather than go to a lot of
5405 				 * trouble to clean up, we free the messages.
5406 				 * This won't be any worse than losing it on
5407 				 * the wire.
5408 				 */
5409 				freemsg(mp0);
5410 				freemsg(mp2);
5411 				*mpp = NULL;
5412 				return (NULL);
5413 			}
5414 			mp1->b_wptr = mp1->b_rptr + len;
5415 			mp2->b_rptr = mp1->b_wptr;
5416 			/*
5417 			 * after adjustments if mblk not consumed is now
5418 			 * unaligned, try to align it. If this fails free
5419 			 * all messages and let upper layer recover.
5420 			 */
5421 			if (!OK_32PTR(mp2->b_rptr)) {
5422 				if (!pullupmsg(mp2, -1)) {
5423 					freemsg(mp0);
5424 					freemsg(mp2);
5425 					*mpp = NULL;
5426 					return (NULL);
5427 				}
5428 			}
5429 			*mpp = mp2;
5430 			return (mp0);
5431 		}
5432 		/* Decrement len by the amount we just got. */
5433 		len -= mp2->b_wptr - mp2->b_rptr;
5434 	}
5435 	/*
5436 	 * len should be reduced to zero now.  If not our caller has
5437 	 * screwed up.
5438 	 */
5439 	if (len) {
5440 		/* Shouldn't happen! */
5441 		freemsg(mp0);
5442 		*mpp = NULL;
5443 		return (NULL);
5444 	}
5445 	/*
5446 	 * We consumed up to exactly the end of an mblk.  Detach the part
5447 	 * we are returning from the rest of the chain.
5448 	 */
5449 	mp1->b_cont = NULL;
5450 	*mpp = mp2;
5451 	return (mp0);
5452 }
5453 
5454 /* The ill stream is being unplumbed. Called from ip_close */
5455 int
5456 ip_modclose(ill_t *ill)
5457 {
5458 	boolean_t success;
5459 	ipsq_t	*ipsq;
5460 	ipif_t	*ipif;
5461 	queue_t	*q = ill->ill_rq;
5462 	ip_stack_t	*ipst = ill->ill_ipst;
5463 	int	i;
5464 
5465 	/*
5466 	 * The punlink prior to this may have initiated a capability
5467 	 * negotiation. But ipsq_enter will block until that finishes or
5468 	 * times out.
5469 	 */
5470 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5471 
5472 	/*
5473 	 * Open/close/push/pop is guaranteed to be single threaded
5474 	 * per stream by STREAMS. FS guarantees that all references
5475 	 * from top are gone before close is called. So there can't
5476 	 * be another close thread that has set CONDEMNED on this ill.
5477 	 * and cause ipsq_enter to return failure.
5478 	 */
5479 	ASSERT(success);
5480 	ipsq = ill->ill_phyint->phyint_ipsq;
5481 
5482 	/*
5483 	 * Mark it condemned. No new reference will be made to this ill.
5484 	 * Lookup functions will return an error. Threads that try to
5485 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5486 	 * that the refcnt will drop down to zero.
5487 	 */
5488 	mutex_enter(&ill->ill_lock);
5489 	ill->ill_state_flags |= ILL_CONDEMNED;
5490 	for (ipif = ill->ill_ipif; ipif != NULL;
5491 	    ipif = ipif->ipif_next) {
5492 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5493 	}
5494 	/*
5495 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5496 	 * returns  error if ILL_CONDEMNED is set
5497 	 */
5498 	cv_broadcast(&ill->ill_cv);
5499 	mutex_exit(&ill->ill_lock);
5500 
5501 	/*
5502 	 * Send all the deferred DLPI messages downstream which came in
5503 	 * during the small window right before ipsq_enter(). We do this
5504 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5505 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5506 	 */
5507 	ill_dlpi_send_deferred(ill);
5508 
5509 	/*
5510 	 * Shut down fragmentation reassembly.
5511 	 * ill_frag_timer won't start a timer again.
5512 	 * Now cancel any existing timer
5513 	 */
5514 	(void) untimeout(ill->ill_frag_timer_id);
5515 	(void) ill_frag_timeout(ill, 0);
5516 
5517 	/*
5518 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5519 	 * this ill. Then wait for the refcnts to drop to zero.
5520 	 * ill_is_freeable checks whether the ill is really quiescent.
5521 	 * Then make sure that threads that are waiting to enter the
5522 	 * ipsq have seen the error returned by ipsq_enter and have
5523 	 * gone away. Then we call ill_delete_tail which does the
5524 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5525 	 */
5526 	ill_delete(ill);
5527 	mutex_enter(&ill->ill_lock);
5528 	while (!ill_is_freeable(ill))
5529 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5530 	while (ill->ill_waiters)
5531 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5532 
5533 	mutex_exit(&ill->ill_lock);
5534 
5535 	/*
5536 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5537 	 * it held until the end of the function since the cleanup
5538 	 * below needs to be able to use the ip_stack_t.
5539 	 */
5540 	netstack_hold(ipst->ips_netstack);
5541 
5542 	/* qprocsoff is done via ill_delete_tail */
5543 	ill_delete_tail(ill);
5544 	ASSERT(ill->ill_ipst == NULL);
5545 
5546 	/*
5547 	 * Walk through all upper (conn) streams and qenable
5548 	 * those that have queued data.
5549 	 * close synchronization needs this to
5550 	 * be done to ensure that all upper layers blocked
5551 	 * due to flow control to the closing device
5552 	 * get unblocked.
5553 	 */
5554 	ip1dbg(("ip_wsrv: walking\n"));
5555 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5556 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5557 	}
5558 
5559 	mutex_enter(&ipst->ips_ip_mi_lock);
5560 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5561 	mutex_exit(&ipst->ips_ip_mi_lock);
5562 
5563 	/*
5564 	 * credp could be null if the open didn't succeed and ip_modopen
5565 	 * itself calls ip_close.
5566 	 */
5567 	if (ill->ill_credp != NULL)
5568 		crfree(ill->ill_credp);
5569 
5570 	/*
5571 	 * Now we are done with the module close pieces that
5572 	 * need the netstack_t.
5573 	 */
5574 	netstack_rele(ipst->ips_netstack);
5575 
5576 	mi_close_free((IDP)ill);
5577 	q->q_ptr = WR(q)->q_ptr = NULL;
5578 
5579 	ipsq_exit(ipsq);
5580 
5581 	return (0);
5582 }
5583 
5584 /*
5585  * This is called as part of close() for IP, UDP, ICMP, and RTS
5586  * in order to quiesce the conn.
5587  */
5588 void
5589 ip_quiesce_conn(conn_t *connp)
5590 {
5591 	boolean_t	drain_cleanup_reqd = B_FALSE;
5592 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5593 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5594 	ip_stack_t	*ipst;
5595 
5596 	ASSERT(!IPCL_IS_TCP(connp));
5597 	ipst = connp->conn_netstack->netstack_ip;
5598 
5599 	/*
5600 	 * Mark the conn as closing, and this conn must not be
5601 	 * inserted in future into any list. Eg. conn_drain_insert(),
5602 	 * won't insert this conn into the conn_drain_list.
5603 	 * Similarly ill_pending_mp_add() will not add any mp to
5604 	 * the pending mp list, after this conn has started closing.
5605 	 *
5606 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5607 	 * cannot get set henceforth.
5608 	 */
5609 	mutex_enter(&connp->conn_lock);
5610 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5611 	connp->conn_state_flags |= CONN_CLOSING;
5612 	if (connp->conn_idl != NULL)
5613 		drain_cleanup_reqd = B_TRUE;
5614 	if (connp->conn_oper_pending_ill != NULL)
5615 		conn_ioctl_cleanup_reqd = B_TRUE;
5616 	if (connp->conn_dhcpinit_ill != NULL) {
5617 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5618 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5619 		connp->conn_dhcpinit_ill = NULL;
5620 	}
5621 	if (connp->conn_ilg_inuse != 0)
5622 		ilg_cleanup_reqd = B_TRUE;
5623 	mutex_exit(&connp->conn_lock);
5624 
5625 	if (conn_ioctl_cleanup_reqd)
5626 		conn_ioctl_cleanup(connp);
5627 
5628 	if (is_system_labeled() && connp->conn_anon_port) {
5629 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5630 		    connp->conn_mlp_type, connp->conn_ulp,
5631 		    ntohs(connp->conn_lport), B_FALSE);
5632 		connp->conn_anon_port = 0;
5633 	}
5634 	connp->conn_mlp_type = mlptSingle;
5635 
5636 	/*
5637 	 * Remove this conn from any fanout list it is on.
5638 	 * and then wait for any threads currently operating
5639 	 * on this endpoint to finish
5640 	 */
5641 	ipcl_hash_remove(connp);
5642 
5643 	/*
5644 	 * Remove this conn from the drain list, and do
5645 	 * any other cleanup that may be required.
5646 	 * (Only non-tcp streams may have a non-null conn_idl.
5647 	 * TCP streams are never flow controlled, and
5648 	 * conn_idl will be null)
5649 	 */
5650 	if (drain_cleanup_reqd)
5651 		conn_drain_tail(connp, B_TRUE);
5652 
5653 	if (connp == ipst->ips_ip_g_mrouter)
5654 		(void) ip_mrouter_done(NULL, ipst);
5655 
5656 	if (ilg_cleanup_reqd)
5657 		ilg_delete_all(connp);
5658 
5659 	conn_delete_ire(connp, NULL);
5660 
5661 	/*
5662 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5663 	 * callers from write side can't be there now because close
5664 	 * is in progress. The only other caller is ipcl_walk
5665 	 * which checks for the condemned flag.
5666 	 */
5667 	mutex_enter(&connp->conn_lock);
5668 	connp->conn_state_flags |= CONN_CONDEMNED;
5669 	while (connp->conn_ref != 1)
5670 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5671 	connp->conn_state_flags |= CONN_QUIESCED;
5672 	mutex_exit(&connp->conn_lock);
5673 }
5674 
5675 /* ARGSUSED */
5676 int
5677 ip_close(queue_t *q, int flags)
5678 {
5679 	conn_t		*connp;
5680 
5681 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5682 
5683 	/*
5684 	 * Call the appropriate delete routine depending on whether this is
5685 	 * a module or device.
5686 	 */
5687 	if (WR(q)->q_next != NULL) {
5688 		/* This is a module close */
5689 		return (ip_modclose((ill_t *)q->q_ptr));
5690 	}
5691 
5692 	connp = q->q_ptr;
5693 	ip_quiesce_conn(connp);
5694 
5695 	qprocsoff(q);
5696 
5697 	/*
5698 	 * Now we are truly single threaded on this stream, and can
5699 	 * delete the things hanging off the connp, and finally the connp.
5700 	 * We removed this connp from the fanout list, it cannot be
5701 	 * accessed thru the fanouts, and we already waited for the
5702 	 * conn_ref to drop to 0. We are already in close, so
5703 	 * there cannot be any other thread from the top. qprocsoff
5704 	 * has completed, and service has completed or won't run in
5705 	 * future.
5706 	 */
5707 	ASSERT(connp->conn_ref == 1);
5708 
5709 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5710 
5711 	connp->conn_ref--;
5712 	ipcl_conn_destroy(connp);
5713 
5714 	q->q_ptr = WR(q)->q_ptr = NULL;
5715 	return (0);
5716 }
5717 
5718 /*
5719  * Wapper around putnext() so that ip_rts_request can merely use
5720  * conn_recv.
5721  */
5722 /*ARGSUSED2*/
5723 static void
5724 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5725 {
5726 	conn_t *connp = (conn_t *)arg1;
5727 
5728 	putnext(connp->conn_rq, mp);
5729 }
5730 
5731 /*
5732  * Called when the module is about to be unloaded
5733  */
5734 void
5735 ip_ddi_destroy(void)
5736 {
5737 	tnet_fini();
5738 
5739 	icmp_ddi_g_destroy();
5740 	rts_ddi_g_destroy();
5741 	udp_ddi_g_destroy();
5742 	sctp_ddi_g_destroy();
5743 	tcp_ddi_g_destroy();
5744 	ipsec_policy_g_destroy();
5745 	ipcl_g_destroy();
5746 	ip_net_g_destroy();
5747 	ip_ire_g_fini();
5748 	inet_minor_destroy(ip_minor_arena_sa);
5749 #if defined(_LP64)
5750 	inet_minor_destroy(ip_minor_arena_la);
5751 #endif
5752 
5753 #ifdef DEBUG
5754 	list_destroy(&ip_thread_list);
5755 	rw_destroy(&ip_thread_rwlock);
5756 	tsd_destroy(&ip_thread_data);
5757 #endif
5758 
5759 	netstack_unregister(NS_IP);
5760 }
5761 
5762 /*
5763  * First step in cleanup.
5764  */
5765 /* ARGSUSED */
5766 static void
5767 ip_stack_shutdown(netstackid_t stackid, void *arg)
5768 {
5769 	ip_stack_t *ipst = (ip_stack_t *)arg;
5770 
5771 #ifdef NS_DEBUG
5772 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5773 #endif
5774 
5775 	/* Get rid of loopback interfaces and their IREs */
5776 	ip_loopback_cleanup(ipst);
5777 
5778 	/*
5779 	 * The *_hook_shutdown()s start the process of notifying any
5780 	 * consumers that things are going away.... nothing is destroyed.
5781 	 */
5782 	ipv4_hook_shutdown(ipst);
5783 	ipv6_hook_shutdown(ipst);
5784 
5785 	mutex_enter(&ipst->ips_capab_taskq_lock);
5786 	ipst->ips_capab_taskq_quit = B_TRUE;
5787 	cv_signal(&ipst->ips_capab_taskq_cv);
5788 	mutex_exit(&ipst->ips_capab_taskq_lock);
5789 
5790 	mutex_enter(&ipst->ips_mrt_lock);
5791 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5792 	cv_signal(&ipst->ips_mrt_cv);
5793 	mutex_exit(&ipst->ips_mrt_lock);
5794 }
5795 
5796 /*
5797  * Free the IP stack instance.
5798  */
5799 static void
5800 ip_stack_fini(netstackid_t stackid, void *arg)
5801 {
5802 	ip_stack_t *ipst = (ip_stack_t *)arg;
5803 	int ret;
5804 
5805 #ifdef NS_DEBUG
5806 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5807 #endif
5808 	/*
5809 	 * At this point, all of the notifications that the events and
5810 	 * protocols are going away have been run, meaning that we can
5811 	 * now set about starting to clean things up.
5812 	 */
5813 	ipv4_hook_destroy(ipst);
5814 	ipv6_hook_destroy(ipst);
5815 	ip_net_destroy(ipst);
5816 
5817 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5818 	cv_destroy(&ipst->ips_capab_taskq_cv);
5819 	list_destroy(&ipst->ips_capab_taskq_list);
5820 
5821 	mutex_enter(&ipst->ips_mrt_lock);
5822 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5823 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5824 	mutex_destroy(&ipst->ips_mrt_lock);
5825 	cv_destroy(&ipst->ips_mrt_cv);
5826 	cv_destroy(&ipst->ips_mrt_done_cv);
5827 
5828 	ipmp_destroy(ipst);
5829 	rw_destroy(&ipst->ips_srcid_lock);
5830 
5831 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5832 	ipst->ips_ip_mibkp = NULL;
5833 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5834 	ipst->ips_icmp_mibkp = NULL;
5835 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5836 	ipst->ips_ip_kstat = NULL;
5837 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5838 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5839 	ipst->ips_ip6_kstat = NULL;
5840 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5841 
5842 	nd_free(&ipst->ips_ip_g_nd);
5843 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5844 	ipst->ips_param_arr = NULL;
5845 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5846 	ipst->ips_ndp_arr = NULL;
5847 
5848 	ip_mrouter_stack_destroy(ipst);
5849 
5850 	mutex_destroy(&ipst->ips_ip_mi_lock);
5851 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5852 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5853 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5854 
5855 	ret = untimeout(ipst->ips_igmp_timeout_id);
5856 	if (ret == -1) {
5857 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5858 	} else {
5859 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5860 		ipst->ips_igmp_timeout_id = 0;
5861 	}
5862 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5867 		ipst->ips_igmp_slowtimeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_mld_timeout_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_mld_timeout_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_mld_timeout_id != 0);
5874 		ipst->ips_mld_timeout_id = 0;
5875 	}
5876 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5877 	if (ret == -1) {
5878 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5879 	} else {
5880 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5881 		ipst->ips_mld_slowtimeout_id = 0;
5882 	}
5883 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5884 	if (ret == -1) {
5885 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5886 	} else {
5887 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5888 		ipst->ips_ip_ire_expire_id = 0;
5889 	}
5890 
5891 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5892 	mutex_destroy(&ipst->ips_mld_timer_lock);
5893 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5894 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5895 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5896 	rw_destroy(&ipst->ips_ill_g_lock);
5897 
5898 	ipobs_fini(ipst);
5899 	ip_ire_fini(ipst);
5900 	ip6_asp_free(ipst);
5901 	conn_drain_fini(ipst);
5902 	ipcl_destroy(ipst);
5903 
5904 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5905 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5906 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5907 	ipst->ips_ndp4 = NULL;
5908 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5909 	ipst->ips_ndp6 = NULL;
5910 
5911 	if (ipst->ips_loopback_ksp != NULL) {
5912 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5913 		ipst->ips_loopback_ksp = NULL;
5914 	}
5915 
5916 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5917 	ipst->ips_phyint_g_list = NULL;
5918 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5919 	ipst->ips_ill_g_heads = NULL;
5920 
5921 	ldi_ident_release(ipst->ips_ldi_ident);
5922 	kmem_free(ipst, sizeof (*ipst));
5923 }
5924 
5925 /*
5926  * This function is called from the TSD destructor, and is used to debug
5927  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5928  * details.
5929  */
5930 static void
5931 ip_thread_exit(void *phash)
5932 {
5933 	th_hash_t *thh = phash;
5934 
5935 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5936 	list_remove(&ip_thread_list, thh);
5937 	rw_exit(&ip_thread_rwlock);
5938 	mod_hash_destroy_hash(thh->thh_hash);
5939 	kmem_free(thh, sizeof (*thh));
5940 }
5941 
5942 /*
5943  * Called when the IP kernel module is loaded into the kernel
5944  */
5945 void
5946 ip_ddi_init(void)
5947 {
5948 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5949 
5950 	/*
5951 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5952 	 * initial devices: ip, ip6, tcp, tcp6.
5953 	 */
5954 	/*
5955 	 * If this is a 64-bit kernel, then create two separate arenas -
5956 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5957 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5958 	 */
5959 	ip_minor_arena_la = NULL;
5960 	ip_minor_arena_sa = NULL;
5961 #if defined(_LP64)
5962 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5963 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5964 		cmn_err(CE_PANIC,
5965 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5966 	}
5967 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5968 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5969 		cmn_err(CE_PANIC,
5970 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5971 	}
5972 #else
5973 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5974 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5975 		cmn_err(CE_PANIC,
5976 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5977 	}
5978 #endif
5979 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5980 
5981 	ipcl_g_init();
5982 	ip_ire_g_init();
5983 	ip_net_g_init();
5984 
5985 #ifdef DEBUG
5986 	tsd_create(&ip_thread_data, ip_thread_exit);
5987 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5988 	list_create(&ip_thread_list, sizeof (th_hash_t),
5989 	    offsetof(th_hash_t, thh_link));
5990 #endif
5991 
5992 	/*
5993 	 * We want to be informed each time a stack is created or
5994 	 * destroyed in the kernel, so we can maintain the
5995 	 * set of udp_stack_t's.
5996 	 */
5997 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5998 	    ip_stack_fini);
5999 
6000 	ipsec_policy_g_init();
6001 	tcp_ddi_g_init();
6002 	sctp_ddi_g_init();
6003 
6004 	tnet_init();
6005 
6006 	udp_ddi_g_init();
6007 	rts_ddi_g_init();
6008 	icmp_ddi_g_init();
6009 }
6010 
6011 /*
6012  * Initialize the IP stack instance.
6013  */
6014 static void *
6015 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6016 {
6017 	ip_stack_t	*ipst;
6018 	ipparam_t	*pa;
6019 	ipndp_t		*na;
6020 	major_t		major;
6021 
6022 #ifdef NS_DEBUG
6023 	printf("ip_stack_init(stack %d)\n", stackid);
6024 #endif
6025 
6026 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6027 	ipst->ips_netstack = ns;
6028 
6029 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6030 	    KM_SLEEP);
6031 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6032 	    KM_SLEEP);
6033 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6034 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6035 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6036 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6037 
6038 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6039 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6040 	ipst->ips_igmp_deferred_next = INFINITY;
6041 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6042 	ipst->ips_mld_deferred_next = INFINITY;
6043 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6044 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6045 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6046 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6048 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6049 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6050 
6051 	ipcl_init(ipst);
6052 	ip_ire_init(ipst);
6053 	ip6_asp_init(ipst);
6054 	ipif_init(ipst);
6055 	conn_drain_init(ipst);
6056 	ip_mrouter_stack_init(ipst);
6057 
6058 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6059 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6060 
6061 	ipst->ips_ip_multirt_log_interval = 1000;
6062 
6063 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6064 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6065 	ipst->ips_ill_index = 1;
6066 
6067 	ipst->ips_saved_ip_g_forward = -1;
6068 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6069 
6070 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6071 	ipst->ips_param_arr = pa;
6072 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6073 
6074 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6075 	ipst->ips_ndp_arr = na;
6076 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6077 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6078 	    (caddr_t)&ipst->ips_ip_g_forward;
6079 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6080 	    (caddr_t)&ipst->ips_ipv6_forward;
6081 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6082 	    "ip_cgtp_filter") == 0);
6083 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6084 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6085 
6086 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6087 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6088 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6089 
6090 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6091 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6092 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6093 	ipst->ips_ip6_kstat =
6094 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6095 
6096 	ipst->ips_ip_src_id = 1;
6097 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6098 
6099 	ipobs_init(ipst);
6100 	ip_net_init(ipst, ns);
6101 	ipv4_hook_init(ipst);
6102 	ipv6_hook_init(ipst);
6103 	ipmp_init(ipst);
6104 
6105 	/*
6106 	 * Create the taskq dispatcher thread and initialize related stuff.
6107 	 */
6108 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6109 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6110 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6111 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6112 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6113 	    offsetof(mblk_t, b_next));
6114 
6115 	/*
6116 	 * Create the mcast_restart_timers_thread() worker thread.
6117 	 */
6118 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6119 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6120 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6121 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6122 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6123 
6124 	major = mod_name_to_major(INET_NAME);
6125 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6126 	return (ipst);
6127 }
6128 
6129 /*
6130  * Allocate and initialize a DLPI template of the specified length.  (May be
6131  * called as writer.)
6132  */
6133 mblk_t *
6134 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6135 {
6136 	mblk_t	*mp;
6137 
6138 	mp = allocb(len, BPRI_MED);
6139 	if (!mp)
6140 		return (NULL);
6141 
6142 	/*
6143 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6144 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6145 	 * that other DLPI are M_PROTO.
6146 	 */
6147 	if (prim == DL_INFO_REQ) {
6148 		mp->b_datap->db_type = M_PCPROTO;
6149 	} else {
6150 		mp->b_datap->db_type = M_PROTO;
6151 	}
6152 
6153 	mp->b_wptr = mp->b_rptr + len;
6154 	bzero(mp->b_rptr, len);
6155 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6156 	return (mp);
6157 }
6158 
6159 /*
6160  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6161  */
6162 mblk_t *
6163 ip_dlnotify_alloc(uint_t notification, uint_t data)
6164 {
6165 	dl_notify_ind_t	*notifyp;
6166 	mblk_t		*mp;
6167 
6168 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6169 		return (NULL);
6170 
6171 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6172 	notifyp->dl_notification = notification;
6173 	notifyp->dl_data = data;
6174 	return (mp);
6175 }
6176 
6177 /*
6178  * Debug formatting routine.  Returns a character string representation of the
6179  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6180  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6181  *
6182  * Once the ndd table-printing interfaces are removed, this can be changed to
6183  * standard dotted-decimal form.
6184  */
6185 char *
6186 ip_dot_addr(ipaddr_t addr, char *buf)
6187 {
6188 	uint8_t *ap = (uint8_t *)&addr;
6189 
6190 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6191 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6192 	return (buf);
6193 }
6194 
6195 /*
6196  * Write the given MAC address as a printable string in the usual colon-
6197  * separated format.
6198  */
6199 const char *
6200 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6201 {
6202 	char *bp;
6203 
6204 	if (alen == 0 || buflen < 4)
6205 		return ("?");
6206 	bp = buf;
6207 	for (;;) {
6208 		/*
6209 		 * If there are more MAC address bytes available, but we won't
6210 		 * have any room to print them, then add "..." to the string
6211 		 * instead.  See below for the 'magic number' explanation.
6212 		 */
6213 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6214 			(void) strcpy(bp, "...");
6215 			break;
6216 		}
6217 		(void) sprintf(bp, "%02x", *addr++);
6218 		bp += 2;
6219 		if (--alen == 0)
6220 			break;
6221 		*bp++ = ':';
6222 		buflen -= 3;
6223 		/*
6224 		 * At this point, based on the first 'if' statement above,
6225 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6226 		 * buflen >= 4.  The first case leaves room for the final "xx"
6227 		 * number and trailing NUL byte.  The second leaves room for at
6228 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6229 		 * that statement.
6230 		 */
6231 	}
6232 	return (buf);
6233 }
6234 
6235 /*
6236  * Send an ICMP error after patching up the packet appropriately.  Returns
6237  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6238  */
6239 static boolean_t
6240 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6241     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6242     zoneid_t zoneid, ip_stack_t *ipst)
6243 {
6244 	ipha_t *ipha;
6245 	mblk_t *first_mp;
6246 	boolean_t secure;
6247 	unsigned char db_type;
6248 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6249 
6250 	first_mp = mp;
6251 	if (mctl_present) {
6252 		mp = mp->b_cont;
6253 		secure = ipsec_in_is_secure(first_mp);
6254 		ASSERT(mp != NULL);
6255 	} else {
6256 		/*
6257 		 * If this is an ICMP error being reported - which goes
6258 		 * up as M_CTLs, we need to convert them to M_DATA till
6259 		 * we finish checking with global policy because
6260 		 * ipsec_check_global_policy() assumes M_DATA as clear
6261 		 * and M_CTL as secure.
6262 		 */
6263 		db_type = DB_TYPE(mp);
6264 		DB_TYPE(mp) = M_DATA;
6265 		secure = B_FALSE;
6266 	}
6267 	/*
6268 	 * We are generating an icmp error for some inbound packet.
6269 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6270 	 * Before we generate an error, check with global policy
6271 	 * to see whether this is allowed to enter the system. As
6272 	 * there is no "conn", we are checking with global policy.
6273 	 */
6274 	ipha = (ipha_t *)mp->b_rptr;
6275 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6276 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6277 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6278 		if (first_mp == NULL)
6279 			return (B_FALSE);
6280 	}
6281 
6282 	if (!mctl_present)
6283 		DB_TYPE(mp) = db_type;
6284 
6285 	if (flags & IP_FF_SEND_ICMP) {
6286 		if (flags & IP_FF_HDR_COMPLETE) {
6287 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6288 				freemsg(first_mp);
6289 				return (B_TRUE);
6290 			}
6291 		}
6292 		if (flags & IP_FF_CKSUM) {
6293 			/*
6294 			 * Have to correct checksum since
6295 			 * the packet might have been
6296 			 * fragmented and the reassembly code in ip_rput
6297 			 * does not restore the IP checksum.
6298 			 */
6299 			ipha->ipha_hdr_checksum = 0;
6300 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6301 		}
6302 		switch (icmp_type) {
6303 		case ICMP_DEST_UNREACHABLE:
6304 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6305 			    ipst);
6306 			break;
6307 		default:
6308 			freemsg(first_mp);
6309 			break;
6310 		}
6311 	} else {
6312 		freemsg(first_mp);
6313 		return (B_FALSE);
6314 	}
6315 
6316 	return (B_TRUE);
6317 }
6318 
6319 /*
6320  * Used to send an ICMP error message when a packet is received for
6321  * a protocol that is not supported. The mblk passed as argument
6322  * is consumed by this function.
6323  */
6324 void
6325 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6326     ip_stack_t *ipst)
6327 {
6328 	mblk_t *mp;
6329 	ipha_t *ipha;
6330 	ill_t *ill;
6331 	ipsec_in_t *ii;
6332 
6333 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6334 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6335 
6336 	mp = ipsec_mp->b_cont;
6337 	ipsec_mp->b_cont = NULL;
6338 	ipha = (ipha_t *)mp->b_rptr;
6339 	/* Get ill from index in ipsec_in_t. */
6340 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6341 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6342 	    ipst);
6343 	if (ill != NULL) {
6344 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6345 			if (ip_fanout_send_icmp(q, mp, flags,
6346 			    ICMP_DEST_UNREACHABLE,
6347 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6348 				BUMP_MIB(ill->ill_ip_mib,
6349 				    ipIfStatsInUnknownProtos);
6350 			}
6351 		} else {
6352 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6353 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6354 			    0, B_FALSE, zoneid, ipst)) {
6355 				BUMP_MIB(ill->ill_ip_mib,
6356 				    ipIfStatsInUnknownProtos);
6357 			}
6358 		}
6359 		ill_refrele(ill);
6360 	} else { /* re-link for the freemsg() below. */
6361 		ipsec_mp->b_cont = mp;
6362 	}
6363 
6364 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6365 	freemsg(ipsec_mp);
6366 }
6367 
6368 /*
6369  * See if the inbound datagram has had IPsec processing applied to it.
6370  */
6371 boolean_t
6372 ipsec_in_is_secure(mblk_t *ipsec_mp)
6373 {
6374 	ipsec_in_t *ii;
6375 
6376 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6377 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6378 
6379 	if (ii->ipsec_in_loopback) {
6380 		return (ii->ipsec_in_secure);
6381 	} else {
6382 		return (ii->ipsec_in_ah_sa != NULL ||
6383 		    ii->ipsec_in_esp_sa != NULL ||
6384 		    ii->ipsec_in_decaps);
6385 	}
6386 }
6387 
6388 /*
6389  * Handle protocols with which IP is less intimate.  There
6390  * can be more than one stream bound to a particular
6391  * protocol.  When this is the case, normally each one gets a copy
6392  * of any incoming packets.
6393  *
6394  * IPsec NOTE :
6395  *
6396  * Don't allow a secure packet going up a non-secure connection.
6397  * We don't allow this because
6398  *
6399  * 1) Reply might go out in clear which will be dropped at
6400  *    the sending side.
6401  * 2) If the reply goes out in clear it will give the
6402  *    adversary enough information for getting the key in
6403  *    most of the cases.
6404  *
6405  * Moreover getting a secure packet when we expect clear
6406  * implies that SA's were added without checking for
6407  * policy on both ends. This should not happen once ISAKMP
6408  * is used to negotiate SAs as SAs will be added only after
6409  * verifying the policy.
6410  *
6411  * NOTE : If the packet was tunneled and not multicast we only send
6412  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6413  * back to delivering packets to AF_INET6 raw sockets.
6414  *
6415  * IPQoS Notes:
6416  * Once we have determined the client, invoke IPPF processing.
6417  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6418  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6419  * ip_policy will be false.
6420  *
6421  * Zones notes:
6422  * Currently only applications in the global zone can create raw sockets for
6423  * protocols other than ICMP. So unlike the broadcast / multicast case of
6424  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6425  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6426  */
6427 static void
6428 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6429     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6430     zoneid_t zoneid)
6431 {
6432 	queue_t	*rq;
6433 	mblk_t	*mp1, *first_mp1;
6434 	uint_t	protocol = ipha->ipha_protocol;
6435 	ipaddr_t dst;
6436 	boolean_t one_only;
6437 	mblk_t *first_mp = mp;
6438 	boolean_t secure;
6439 	uint32_t ill_index;
6440 	conn_t	*connp, *first_connp, *next_connp;
6441 	connf_t	*connfp;
6442 	boolean_t shared_addr;
6443 	mib2_ipIfStatsEntry_t *mibptr;
6444 	ip_stack_t *ipst = recv_ill->ill_ipst;
6445 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6446 
6447 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6448 	if (mctl_present) {
6449 		mp = first_mp->b_cont;
6450 		secure = ipsec_in_is_secure(first_mp);
6451 		ASSERT(mp != NULL);
6452 	} else {
6453 		secure = B_FALSE;
6454 	}
6455 	dst = ipha->ipha_dst;
6456 	/*
6457 	 * If the packet was tunneled and not multicast we only send to it
6458 	 * the first match.
6459 	 */
6460 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6461 	    !CLASSD(dst));
6462 
6463 	shared_addr = (zoneid == ALL_ZONES);
6464 	if (shared_addr) {
6465 		/*
6466 		 * We don't allow multilevel ports for raw IP, so no need to
6467 		 * check for that here.
6468 		 */
6469 		zoneid = tsol_packet_to_zoneid(mp);
6470 	}
6471 
6472 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6473 	mutex_enter(&connfp->connf_lock);
6474 	connp = connfp->connf_head;
6475 	for (connp = connfp->connf_head; connp != NULL;
6476 	    connp = connp->conn_next) {
6477 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6478 		    zoneid) &&
6479 		    (!is_system_labeled() ||
6480 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6481 		    connp))) {
6482 			break;
6483 		}
6484 	}
6485 
6486 	if (connp == NULL) {
6487 		/*
6488 		 * No one bound to these addresses.  Is
6489 		 * there a client that wants all
6490 		 * unclaimed datagrams?
6491 		 */
6492 		mutex_exit(&connfp->connf_lock);
6493 		/*
6494 		 * Check for IPPROTO_ENCAP...
6495 		 */
6496 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6497 			/*
6498 			 * If an IPsec mblk is here on a multicast
6499 			 * tunnel (using ip_mroute stuff), check policy here,
6500 			 * THEN ship off to ip_mroute_decap().
6501 			 *
6502 			 * BTW,  If I match a configured IP-in-IP
6503 			 * tunnel, this path will not be reached, and
6504 			 * ip_mroute_decap will never be called.
6505 			 */
6506 			first_mp = ipsec_check_global_policy(first_mp, connp,
6507 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6508 			if (first_mp != NULL) {
6509 				if (mctl_present)
6510 					freeb(first_mp);
6511 				ip_mroute_decap(q, mp, ill);
6512 			} /* Else we already freed everything! */
6513 		} else {
6514 			/*
6515 			 * Otherwise send an ICMP protocol unreachable.
6516 			 */
6517 			if (ip_fanout_send_icmp(q, first_mp, flags,
6518 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6519 			    mctl_present, zoneid, ipst)) {
6520 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6521 			}
6522 		}
6523 		return;
6524 	}
6525 
6526 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6527 
6528 	CONN_INC_REF(connp);
6529 	first_connp = connp;
6530 
6531 	/*
6532 	 * Only send message to one tunnel driver by immediately
6533 	 * terminating the loop.
6534 	 */
6535 	connp = one_only ? NULL : connp->conn_next;
6536 
6537 	for (;;) {
6538 		while (connp != NULL) {
6539 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6540 			    flags, zoneid) &&
6541 			    (!is_system_labeled() ||
6542 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6543 			    shared_addr, connp)))
6544 				break;
6545 			connp = connp->conn_next;
6546 		}
6547 
6548 		/*
6549 		 * Copy the packet.
6550 		 */
6551 		if (connp == NULL ||
6552 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6553 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6554 			/*
6555 			 * No more interested clients or memory
6556 			 * allocation failed
6557 			 */
6558 			connp = first_connp;
6559 			break;
6560 		}
6561 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6562 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6563 		CONN_INC_REF(connp);
6564 		mutex_exit(&connfp->connf_lock);
6565 		rq = connp->conn_rq;
6566 
6567 		/*
6568 		 * Check flow control
6569 		 */
6570 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6571 		    (!IPCL_IS_NONSTR(connp) && !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_mp1);
6579 		} else {
6580 			/*
6581 			 * Don't enforce here if we're an actual tunnel -
6582 			 * let "tun" do it instead.
6583 			 */
6584 			if (!IPCL_IS_IPTUN(connp) &&
6585 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6586 			    secure)) {
6587 				first_mp1 = ipsec_check_inbound_policy
6588 				    (first_mp1, connp, ipha, NULL,
6589 				    mctl_present);
6590 			}
6591 			if (first_mp1 != NULL) {
6592 				int in_flags = 0;
6593 				/*
6594 				 * ip_fanout_proto also gets called from
6595 				 * icmp_inbound_error_fanout, in which case
6596 				 * the msg type is M_CTL.  Don't add info
6597 				 * in this case for the time being. In future
6598 				 * when there is a need for knowing the
6599 				 * inbound iface index for ICMP error msgs,
6600 				 * then this can be changed.
6601 				 */
6602 				if (connp->conn_recvif)
6603 					in_flags = IPF_RECVIF;
6604 				/*
6605 				 * The ULP may support IP_RECVPKTINFO for both
6606 				 * IP v4 and v6 so pass the appropriate argument
6607 				 * based on conn IP version.
6608 				 */
6609 				if (connp->conn_ip_recvpktinfo) {
6610 					if (connp->conn_af_isv6) {
6611 						/*
6612 						 * V6 only needs index
6613 						 */
6614 						in_flags |= IPF_RECVIF;
6615 					} else {
6616 						/*
6617 						 * V4 needs index +
6618 						 * matching address.
6619 						 */
6620 						in_flags |= IPF_RECVADDR;
6621 					}
6622 				}
6623 				if ((in_flags != 0) &&
6624 				    (mp->b_datap->db_type != M_CTL)) {
6625 					/*
6626 					 * the actual data will be
6627 					 * contained in b_cont upon
6628 					 * successful return of the
6629 					 * following call else
6630 					 * original mblk is returned
6631 					 */
6632 					ASSERT(recv_ill != NULL);
6633 					mp1 = ip_add_info(mp1, recv_ill,
6634 					    in_flags, IPCL_ZONEID(connp), ipst);
6635 				}
6636 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6637 				if (mctl_present)
6638 					freeb(first_mp1);
6639 				(connp->conn_recv)(connp, mp1, NULL);
6640 			}
6641 		}
6642 		mutex_enter(&connfp->connf_lock);
6643 		/* Follow the next pointer before releasing the conn. */
6644 		next_connp = connp->conn_next;
6645 		CONN_DEC_REF(connp);
6646 		connp = next_connp;
6647 	}
6648 
6649 	/* Last one.  Send it upstream. */
6650 	mutex_exit(&connfp->connf_lock);
6651 
6652 	/*
6653 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6654 	 * will be set to false.
6655 	 */
6656 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6657 		ill_index = ill->ill_phyint->phyint_ifindex;
6658 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6659 		if (mp == NULL) {
6660 			CONN_DEC_REF(connp);
6661 			if (mctl_present) {
6662 				freeb(first_mp);
6663 			}
6664 			return;
6665 		}
6666 	}
6667 
6668 	rq = connp->conn_rq;
6669 	/*
6670 	 * Check flow control
6671 	 */
6672 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6673 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6674 		if (flags & IP_FF_RAWIP) {
6675 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6676 		} else {
6677 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6678 		}
6679 
6680 		freemsg(first_mp);
6681 	} else {
6682 		if (IPCL_IS_IPTUN(connp)) {
6683 			/*
6684 			 * Tunneled packet.  We enforce policy in the tunnel
6685 			 * module itself.
6686 			 *
6687 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6688 			 * a policy check.
6689 			 * FIXME to use conn_recv for tun later.
6690 			 */
6691 			putnext(rq, first_mp);
6692 			CONN_DEC_REF(connp);
6693 			return;
6694 		}
6695 
6696 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6697 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6698 			    ipha, NULL, mctl_present);
6699 		}
6700 
6701 		if (first_mp != NULL) {
6702 			int in_flags = 0;
6703 
6704 			/*
6705 			 * ip_fanout_proto also gets called
6706 			 * from icmp_inbound_error_fanout, in
6707 			 * which case the msg type is M_CTL.
6708 			 * Don't add info in this case for time
6709 			 * being. In future when there is a
6710 			 * need for knowing the inbound iface
6711 			 * index for ICMP error msgs, then this
6712 			 * can be changed
6713 			 */
6714 			if (connp->conn_recvif)
6715 				in_flags = IPF_RECVIF;
6716 			if (connp->conn_ip_recvpktinfo) {
6717 				if (connp->conn_af_isv6) {
6718 					/*
6719 					 * V6 only needs index
6720 					 */
6721 					in_flags |= IPF_RECVIF;
6722 				} else {
6723 					/*
6724 					 * V4 needs index +
6725 					 * matching address.
6726 					 */
6727 					in_flags |= IPF_RECVADDR;
6728 				}
6729 			}
6730 			if ((in_flags != 0) &&
6731 			    (mp->b_datap->db_type != M_CTL)) {
6732 
6733 				/*
6734 				 * the actual data will be contained in
6735 				 * b_cont upon successful return
6736 				 * of the following call else original
6737 				 * mblk is returned
6738 				 */
6739 				ASSERT(recv_ill != NULL);
6740 				mp = ip_add_info(mp, recv_ill,
6741 				    in_flags, IPCL_ZONEID(connp), ipst);
6742 			}
6743 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6744 			(connp->conn_recv)(connp, mp, NULL);
6745 			if (mctl_present)
6746 				freeb(first_mp);
6747 		}
6748 	}
6749 	CONN_DEC_REF(connp);
6750 }
6751 
6752 /*
6753  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6754  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6755  * the correct squeue, in this case the same squeue as a valid listener with
6756  * no current connection state for the packet we are processing. The function
6757  * is called for synchronizing both IPv4 and IPv6.
6758  */
6759 void
6760 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6761     tcp_stack_t *tcps, conn_t *connp)
6762 {
6763 	mblk_t *rst_mp;
6764 	tcp_xmit_reset_event_t *eventp;
6765 
6766 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6767 
6768 	if (rst_mp == NULL) {
6769 		freemsg(mp);
6770 		return;
6771 	}
6772 
6773 	rst_mp->b_datap->db_type = M_PROTO;
6774 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6775 
6776 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6777 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6778 	eventp->tcp_xre_iphdrlen = hdrlen;
6779 	eventp->tcp_xre_zoneid = zoneid;
6780 	eventp->tcp_xre_tcps = tcps;
6781 
6782 	rst_mp->b_cont = mp;
6783 	mp = rst_mp;
6784 
6785 	/*
6786 	 * Increment the connref, this ref will be released by the squeue
6787 	 * framework.
6788 	 */
6789 	CONN_INC_REF(connp);
6790 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6791 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6792 }
6793 
6794 /*
6795  * Fanout for TCP packets
6796  * The caller puts <fport, lport> in the ports parameter.
6797  *
6798  * IPQoS Notes
6799  * Before sending it to the client, invoke IPPF processing.
6800  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6801  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6802  * ip_policy is false.
6803  */
6804 static void
6805 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6806     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6807 {
6808 	mblk_t  *first_mp;
6809 	boolean_t secure;
6810 	uint32_t ill_index;
6811 	int	ip_hdr_len;
6812 	tcph_t	*tcph;
6813 	boolean_t syn_present = B_FALSE;
6814 	conn_t	*connp;
6815 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6816 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6817 
6818 	ASSERT(recv_ill != NULL);
6819 
6820 	first_mp = mp;
6821 	if (mctl_present) {
6822 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6823 		mp = first_mp->b_cont;
6824 		secure = ipsec_in_is_secure(first_mp);
6825 		ASSERT(mp != NULL);
6826 	} else {
6827 		secure = B_FALSE;
6828 	}
6829 
6830 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6831 
6832 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6833 	    zoneid, ipst)) == NULL) {
6834 		/*
6835 		 * No connected connection or listener. Send a
6836 		 * TH_RST via tcp_xmit_listeners_reset.
6837 		 */
6838 
6839 		/* Initiate IPPf processing, if needed. */
6840 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6841 			uint32_t ill_index;
6842 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6843 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6844 			if (first_mp == NULL)
6845 				return;
6846 		}
6847 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6848 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6849 		    zoneid));
6850 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6851 		    ipst->ips_netstack->netstack_tcp, NULL);
6852 		return;
6853 	}
6854 
6855 	/*
6856 	 * Allocate the SYN for the TCP connection here itself
6857 	 */
6858 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6859 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6860 		if (IPCL_IS_TCP(connp)) {
6861 			squeue_t *sqp;
6862 
6863 			/*
6864 			 * For fused tcp loopback, assign the eager's
6865 			 * squeue to be that of the active connect's.
6866 			 * Note that we don't check for IP_FF_LOOPBACK
6867 			 * here since this routine gets called only
6868 			 * for loopback (unlike the IPv6 counterpart).
6869 			 */
6870 			ASSERT(Q_TO_CONN(q) != NULL);
6871 			if (do_tcp_fusion &&
6872 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6873 			    !secure &&
6874 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6875 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6876 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6877 				sqp = Q_TO_CONN(q)->conn_sqp;
6878 			} else {
6879 				sqp = IP_SQUEUE_GET(lbolt);
6880 			}
6881 
6882 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6883 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6884 			syn_present = B_TRUE;
6885 		}
6886 	}
6887 
6888 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6889 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6890 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6891 		if ((flags & TH_RST) || (flags & TH_URG)) {
6892 			CONN_DEC_REF(connp);
6893 			freemsg(first_mp);
6894 			return;
6895 		}
6896 		if (flags & TH_ACK) {
6897 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6898 			    ipst->ips_netstack->netstack_tcp, connp);
6899 			CONN_DEC_REF(connp);
6900 			return;
6901 		}
6902 
6903 		CONN_DEC_REF(connp);
6904 		freemsg(first_mp);
6905 		return;
6906 	}
6907 
6908 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6909 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6910 		    NULL, mctl_present);
6911 		if (first_mp == NULL) {
6912 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6913 			CONN_DEC_REF(connp);
6914 			return;
6915 		}
6916 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6917 			ASSERT(syn_present);
6918 			if (mctl_present) {
6919 				ASSERT(first_mp != mp);
6920 				first_mp->b_datap->db_struioflag |=
6921 				    STRUIO_POLICY;
6922 			} else {
6923 				ASSERT(first_mp == mp);
6924 				mp->b_datap->db_struioflag &=
6925 				    ~STRUIO_EAGER;
6926 				mp->b_datap->db_struioflag |=
6927 				    STRUIO_POLICY;
6928 			}
6929 		} else {
6930 			/*
6931 			 * Discard first_mp early since we're dealing with a
6932 			 * fully-connected conn_t and tcp doesn't do policy in
6933 			 * this case.
6934 			 */
6935 			if (mctl_present) {
6936 				freeb(first_mp);
6937 				mctl_present = B_FALSE;
6938 			}
6939 			first_mp = mp;
6940 		}
6941 	}
6942 
6943 	/*
6944 	 * Initiate policy processing here if needed. If we get here from
6945 	 * icmp_inbound_error_fanout, ip_policy is false.
6946 	 */
6947 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6948 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6949 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6950 		if (mp == NULL) {
6951 			CONN_DEC_REF(connp);
6952 			if (mctl_present)
6953 				freeb(first_mp);
6954 			return;
6955 		} else if (mctl_present) {
6956 			ASSERT(first_mp != mp);
6957 			first_mp->b_cont = mp;
6958 		} else {
6959 			first_mp = mp;
6960 		}
6961 	}
6962 
6963 	/* Handle socket options. */
6964 	if (!syn_present &&
6965 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6966 		/* Add header */
6967 		ASSERT(recv_ill != NULL);
6968 		/*
6969 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6970 		 * IPF_RECVIF.
6971 		 */
6972 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6973 		    ipst);
6974 		if (mp == NULL) {
6975 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6976 			CONN_DEC_REF(connp);
6977 			if (mctl_present)
6978 				freeb(first_mp);
6979 			return;
6980 		} else if (mctl_present) {
6981 			/*
6982 			 * ip_add_info might return a new mp.
6983 			 */
6984 			ASSERT(first_mp != mp);
6985 			first_mp->b_cont = mp;
6986 		} else {
6987 			first_mp = mp;
6988 		}
6989 	}
6990 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6991 	if (IPCL_IS_TCP(connp)) {
6992 		/* do not drain, certain use cases can blow the stack */
6993 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6994 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6995 	} else {
6996 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6997 		(connp->conn_recv)(connp, first_mp, NULL);
6998 		CONN_DEC_REF(connp);
6999 	}
7000 }
7001 
7002 /*
7003  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
7004  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
7005  * is not consumed.
7006  *
7007  * One of four things can happen, all of which affect the passed-in mblk:
7008  *
7009  * 1.) ICMP messages that go through here just get returned TRUE.
7010  *
7011  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7012  *
7013  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7014  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7015  *
7016  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7017  */
7018 static boolean_t
7019 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7020     ipsec_stack_t *ipss)
7021 {
7022 	int shift, plen, iph_len;
7023 	ipha_t *ipha;
7024 	udpha_t *udpha;
7025 	uint32_t *spi;
7026 	uint32_t esp_ports;
7027 	uint8_t *orptr;
7028 	boolean_t free_ire;
7029 
7030 	if (DB_TYPE(mp) == M_CTL) {
7031 		/*
7032 		 * ICMP message with UDP inside.  Don't bother stripping, just
7033 		 * send it up.
7034 		 *
7035 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7036 		 * to ignore errors set by ICMP anyway ('cause they might be
7037 		 * forged), but that's the app's decision, not ours.
7038 		 */
7039 
7040 		/* Bunch of reality checks for DEBUG kernels... */
7041 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7042 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7043 
7044 		return (B_TRUE);
7045 	}
7046 
7047 	ipha = (ipha_t *)mp->b_rptr;
7048 	iph_len = IPH_HDR_LENGTH(ipha);
7049 	plen = ntohs(ipha->ipha_length);
7050 
7051 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7052 		/*
7053 		 * Most likely a keepalive for the benefit of an intervening
7054 		 * NAT.  These aren't for us, per se, so drop it.
7055 		 *
7056 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7057 		 * byte packets (keepalives are 1-byte), but we'll drop them
7058 		 * also.
7059 		 */
7060 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7061 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7062 		return (B_FALSE);
7063 	}
7064 
7065 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7066 		/* might as well pull it all up - it might be ESP. */
7067 		if (!pullupmsg(mp, -1)) {
7068 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7069 			    DROPPER(ipss, ipds_esp_nomem),
7070 			    &ipss->ipsec_dropper);
7071 			return (B_FALSE);
7072 		}
7073 
7074 		ipha = (ipha_t *)mp->b_rptr;
7075 	}
7076 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7077 	if (*spi == 0) {
7078 		/* UDP packet - remove 0-spi. */
7079 		shift = sizeof (uint32_t);
7080 	} else {
7081 		/* ESP-in-UDP packet - reduce to ESP. */
7082 		ipha->ipha_protocol = IPPROTO_ESP;
7083 		shift = sizeof (udpha_t);
7084 	}
7085 
7086 	/* Fix IP header */
7087 	ipha->ipha_length = htons(plen - shift);
7088 	ipha->ipha_hdr_checksum = 0;
7089 
7090 	orptr = mp->b_rptr;
7091 	mp->b_rptr += shift;
7092 
7093 	udpha = (udpha_t *)(orptr + iph_len);
7094 	if (*spi == 0) {
7095 		ASSERT((uint8_t *)ipha == orptr);
7096 		udpha->uha_length = htons(plen - shift - iph_len);
7097 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7098 		esp_ports = 0;
7099 	} else {
7100 		esp_ports = *((uint32_t *)udpha);
7101 		ASSERT(esp_ports != 0);
7102 	}
7103 	ovbcopy(orptr, orptr + shift, iph_len);
7104 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7105 		ipha = (ipha_t *)(orptr + shift);
7106 
7107 		free_ire = (ire == NULL);
7108 		if (free_ire) {
7109 			/* Re-acquire ire. */
7110 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7111 			    ipss->ipsec_netstack->netstack_ip);
7112 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7113 				if (ire != NULL)
7114 					ire_refrele(ire);
7115 				/*
7116 				 * Do a regular freemsg(), as this is an IP
7117 				 * error (no local route) not an IPsec one.
7118 				 */
7119 				freemsg(mp);
7120 			}
7121 		}
7122 
7123 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7124 		if (free_ire)
7125 			ire_refrele(ire);
7126 	}
7127 
7128 	return (esp_ports == 0);
7129 }
7130 
7131 /*
7132  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7133  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7134  * Caller is responsible for dropping references to the conn, and freeing
7135  * first_mp.
7136  *
7137  * IPQoS Notes
7138  * Before sending it to the client, invoke IPPF processing. Policy processing
7139  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7140  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7141  * ip_wput_local, ip_policy is false.
7142  */
7143 static void
7144 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7145     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7146     boolean_t ip_policy)
7147 {
7148 	boolean_t	mctl_present = (first_mp != NULL);
7149 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7150 	uint32_t	ill_index;
7151 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7152 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7153 
7154 	ASSERT(ill != NULL);
7155 
7156 	if (mctl_present)
7157 		first_mp->b_cont = mp;
7158 	else
7159 		first_mp = mp;
7160 
7161 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7162 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7163 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7164 		freemsg(first_mp);
7165 		return;
7166 	}
7167 
7168 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7169 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7170 		    NULL, mctl_present);
7171 		/* Freed by ipsec_check_inbound_policy(). */
7172 		if (first_mp == NULL) {
7173 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7174 			return;
7175 		}
7176 	}
7177 	if (mctl_present)
7178 		freeb(first_mp);
7179 
7180 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7181 	if (connp->conn_udp->udp_nat_t_endpoint) {
7182 		if (mctl_present) {
7183 			/* mctl_present *shouldn't* happen. */
7184 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7185 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7186 			    &ipss->ipsec_dropper);
7187 			return;
7188 		}
7189 
7190 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7191 			return;
7192 	}
7193 
7194 	/* Handle options. */
7195 	if (connp->conn_recvif)
7196 		in_flags = IPF_RECVIF;
7197 	/*
7198 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7199 	 * passed to ip_add_info is based on IP version of connp.
7200 	 */
7201 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7202 		if (connp->conn_af_isv6) {
7203 			/*
7204 			 * V6 only needs index
7205 			 */
7206 			in_flags |= IPF_RECVIF;
7207 		} else {
7208 			/*
7209 			 * V4 needs index + matching address.
7210 			 */
7211 			in_flags |= IPF_RECVADDR;
7212 		}
7213 	}
7214 
7215 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7216 		in_flags |= IPF_RECVSLLA;
7217 
7218 	/*
7219 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7220 	 * freed if the packet is dropped. The caller will do so.
7221 	 */
7222 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7223 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7224 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7225 		if (mp == NULL) {
7226 			return;
7227 		}
7228 	}
7229 	if ((in_flags != 0) &&
7230 	    (mp->b_datap->db_type != M_CTL)) {
7231 		/*
7232 		 * The actual data will be contained in b_cont
7233 		 * upon successful return of the following call
7234 		 * else original mblk is returned
7235 		 */
7236 		ASSERT(recv_ill != NULL);
7237 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7238 		    ipst);
7239 	}
7240 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7241 	/* Send it upstream */
7242 	(connp->conn_recv)(connp, mp, NULL);
7243 }
7244 
7245 /*
7246  * Fanout for UDP packets.
7247  * The caller puts <fport, lport> in the ports parameter.
7248  *
7249  * If SO_REUSEADDR is set all multicast and broadcast packets
7250  * will be delivered to all streams bound to the same port.
7251  *
7252  * Zones notes:
7253  * Multicast and broadcast packets will be distributed to streams in all zones.
7254  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7255  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7256  * packets. To maintain this behavior with multiple zones, the conns are grouped
7257  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7258  * each zone. If unset, all the following conns in the same zone are skipped.
7259  */
7260 static void
7261 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7262     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7263     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7264 {
7265 	uint32_t	dstport, srcport;
7266 	ipaddr_t	dst;
7267 	mblk_t		*first_mp;
7268 	boolean_t	secure;
7269 	in6_addr_t	v6src;
7270 	conn_t		*connp;
7271 	connf_t		*connfp;
7272 	conn_t		*first_connp;
7273 	conn_t		*next_connp;
7274 	mblk_t		*mp1, *first_mp1;
7275 	ipaddr_t	src;
7276 	zoneid_t	last_zoneid;
7277 	boolean_t	reuseaddr;
7278 	boolean_t	shared_addr;
7279 	boolean_t	unlabeled;
7280 	ip_stack_t	*ipst;
7281 
7282 	ASSERT(recv_ill != NULL);
7283 	ipst = recv_ill->ill_ipst;
7284 
7285 	first_mp = mp;
7286 	if (mctl_present) {
7287 		mp = first_mp->b_cont;
7288 		first_mp->b_cont = NULL;
7289 		secure = ipsec_in_is_secure(first_mp);
7290 		ASSERT(mp != NULL);
7291 	} else {
7292 		first_mp = NULL;
7293 		secure = B_FALSE;
7294 	}
7295 
7296 	/* Extract ports in net byte order */
7297 	dstport = htons(ntohl(ports) & 0xFFFF);
7298 	srcport = htons(ntohl(ports) >> 16);
7299 	dst = ipha->ipha_dst;
7300 	src = ipha->ipha_src;
7301 
7302 	unlabeled = B_FALSE;
7303 	if (is_system_labeled())
7304 		/* Cred cannot be null on IPv4 */
7305 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7306 		    TSLF_UNLABELED) != 0;
7307 	shared_addr = (zoneid == ALL_ZONES);
7308 	if (shared_addr) {
7309 		/*
7310 		 * No need to handle exclusive-stack zones since ALL_ZONES
7311 		 * only applies to the shared stack.
7312 		 */
7313 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7314 		/*
7315 		 * If no shared MLP is found, tsol_mlp_findzone returns
7316 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7317 		 * search for the zone based on the packet label.
7318 		 *
7319 		 * If there is such a zone, we prefer to find a
7320 		 * connection in it.  Otherwise, we look for a
7321 		 * MAC-exempt connection in any zone whose label
7322 		 * dominates the default label on the packet.
7323 		 */
7324 		if (zoneid == ALL_ZONES)
7325 			zoneid = tsol_packet_to_zoneid(mp);
7326 		else
7327 			unlabeled = B_FALSE;
7328 	}
7329 
7330 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7331 	mutex_enter(&connfp->connf_lock);
7332 	connp = connfp->connf_head;
7333 	if (!broadcast && !CLASSD(dst)) {
7334 		/*
7335 		 * Not broadcast or multicast. Send to the one (first)
7336 		 * client we find. No need to check conn_wantpacket()
7337 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7338 		 * IPv4 unicast packets.
7339 		 */
7340 		while ((connp != NULL) &&
7341 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7342 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7343 		    !(unlabeled && connp->conn_mac_exempt)))) {
7344 			/*
7345 			 * We keep searching since the conn did not match,
7346 			 * or its zone did not match and it is not either
7347 			 * an allzones conn or a mac exempt conn (if the
7348 			 * sender is unlabeled.)
7349 			 */
7350 			connp = connp->conn_next;
7351 		}
7352 
7353 		if (connp == NULL ||
7354 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7355 			goto notfound;
7356 
7357 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7358 
7359 		if (is_system_labeled() &&
7360 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7361 		    connp))
7362 			goto notfound;
7363 
7364 		CONN_INC_REF(connp);
7365 		mutex_exit(&connfp->connf_lock);
7366 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7367 		    flags, recv_ill, ip_policy);
7368 		IP_STAT(ipst, ip_udp_fannorm);
7369 		CONN_DEC_REF(connp);
7370 		return;
7371 	}
7372 
7373 	/*
7374 	 * Broadcast and multicast case
7375 	 *
7376 	 * Need to check conn_wantpacket().
7377 	 * If SO_REUSEADDR has been set on the first we send the
7378 	 * packet to all clients that have joined the group and
7379 	 * match the port.
7380 	 */
7381 
7382 	while (connp != NULL) {
7383 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7384 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7385 		    (!is_system_labeled() ||
7386 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7387 		    connp)))
7388 			break;
7389 		connp = connp->conn_next;
7390 	}
7391 
7392 	if (connp == NULL ||
7393 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7394 		goto notfound;
7395 
7396 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7397 
7398 	first_connp = connp;
7399 	/*
7400 	 * When SO_REUSEADDR is not set, send the packet only to the first
7401 	 * matching connection in its zone by keeping track of the zoneid.
7402 	 */
7403 	reuseaddr = first_connp->conn_reuseaddr;
7404 	last_zoneid = first_connp->conn_zoneid;
7405 
7406 	CONN_INC_REF(connp);
7407 	connp = connp->conn_next;
7408 	for (;;) {
7409 		while (connp != NULL) {
7410 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7411 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7412 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7413 			    (!is_system_labeled() ||
7414 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7415 			    shared_addr, connp)))
7416 				break;
7417 			connp = connp->conn_next;
7418 		}
7419 		/*
7420 		 * Just copy the data part alone. The mctl part is
7421 		 * needed just for verifying policy and it is never
7422 		 * sent up.
7423 		 */
7424 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7425 		    ((mp1 = copymsg(mp)) == NULL))) {
7426 			/*
7427 			 * No more interested clients or memory
7428 			 * allocation failed
7429 			 */
7430 			connp = first_connp;
7431 			break;
7432 		}
7433 		if (connp->conn_zoneid != last_zoneid) {
7434 			/*
7435 			 * Update the zoneid so that the packet isn't sent to
7436 			 * any more conns in the same zone unless SO_REUSEADDR
7437 			 * is set.
7438 			 */
7439 			reuseaddr = connp->conn_reuseaddr;
7440 			last_zoneid = connp->conn_zoneid;
7441 		}
7442 		if (first_mp != NULL) {
7443 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7444 			    ipsec_info_type == IPSEC_IN);
7445 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7446 			    ipst->ips_netstack);
7447 			if (first_mp1 == NULL) {
7448 				freemsg(mp1);
7449 				connp = first_connp;
7450 				break;
7451 			}
7452 		} else {
7453 			first_mp1 = NULL;
7454 		}
7455 		CONN_INC_REF(connp);
7456 		mutex_exit(&connfp->connf_lock);
7457 		/*
7458 		 * IPQoS notes: We don't send the packet for policy
7459 		 * processing here, will do it for the last one (below).
7460 		 * i.e. we do it per-packet now, but if we do policy
7461 		 * processing per-conn, then we would need to do it
7462 		 * here too.
7463 		 */
7464 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7465 		    ipha, flags, recv_ill, B_FALSE);
7466 		mutex_enter(&connfp->connf_lock);
7467 		/* Follow the next pointer before releasing the conn. */
7468 		next_connp = connp->conn_next;
7469 		IP_STAT(ipst, ip_udp_fanmb);
7470 		CONN_DEC_REF(connp);
7471 		connp = next_connp;
7472 	}
7473 
7474 	/* Last one.  Send it upstream. */
7475 	mutex_exit(&connfp->connf_lock);
7476 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7477 	    recv_ill, ip_policy);
7478 	IP_STAT(ipst, ip_udp_fanmb);
7479 	CONN_DEC_REF(connp);
7480 	return;
7481 
7482 notfound:
7483 
7484 	mutex_exit(&connfp->connf_lock);
7485 	IP_STAT(ipst, ip_udp_fanothers);
7486 	/*
7487 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7488 	 * have already been matched above, since they live in the IPv4
7489 	 * fanout tables. This implies we only need to
7490 	 * check for IPv6 in6addr_any endpoints here.
7491 	 * Thus we compare using ipv6_all_zeros instead of the destination
7492 	 * address, except for the multicast group membership lookup which
7493 	 * uses the IPv4 destination.
7494 	 */
7495 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7496 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7497 	mutex_enter(&connfp->connf_lock);
7498 	connp = connfp->connf_head;
7499 	if (!broadcast && !CLASSD(dst)) {
7500 		while (connp != NULL) {
7501 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7502 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7503 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7504 			    !connp->conn_ipv6_v6only)
7505 				break;
7506 			connp = connp->conn_next;
7507 		}
7508 
7509 		if (connp != NULL && is_system_labeled() &&
7510 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7511 		    connp))
7512 			connp = NULL;
7513 
7514 		if (connp == NULL ||
7515 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7516 			/*
7517 			 * No one bound to this port.  Is
7518 			 * there a client that wants all
7519 			 * unclaimed datagrams?
7520 			 */
7521 			mutex_exit(&connfp->connf_lock);
7522 
7523 			if (mctl_present)
7524 				first_mp->b_cont = mp;
7525 			else
7526 				first_mp = mp;
7527 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7528 			    connf_head != NULL) {
7529 				ip_fanout_proto(q, first_mp, ill, ipha,
7530 				    flags | IP_FF_RAWIP, mctl_present,
7531 				    ip_policy, recv_ill, zoneid);
7532 			} else {
7533 				if (ip_fanout_send_icmp(q, first_mp, flags,
7534 				    ICMP_DEST_UNREACHABLE,
7535 				    ICMP_PORT_UNREACHABLE,
7536 				    mctl_present, zoneid, ipst)) {
7537 					BUMP_MIB(ill->ill_ip_mib,
7538 					    udpIfStatsNoPorts);
7539 				}
7540 			}
7541 			return;
7542 		}
7543 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7544 
7545 		CONN_INC_REF(connp);
7546 		mutex_exit(&connfp->connf_lock);
7547 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7548 		    flags, recv_ill, ip_policy);
7549 		CONN_DEC_REF(connp);
7550 		return;
7551 	}
7552 	/*
7553 	 * IPv4 multicast packet being delivered to an AF_INET6
7554 	 * in6addr_any endpoint.
7555 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7556 	 * and not conn_wantpacket_v6() since any multicast membership is
7557 	 * for an IPv4-mapped multicast address.
7558 	 * The packet is sent to all clients in all zones that have joined the
7559 	 * group and match the port.
7560 	 */
7561 	while (connp != NULL) {
7562 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7563 		    srcport, v6src) &&
7564 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7565 		    (!is_system_labeled() ||
7566 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7567 		    connp)))
7568 			break;
7569 		connp = connp->conn_next;
7570 	}
7571 
7572 	if (connp == NULL ||
7573 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7574 		/*
7575 		 * No one bound to this port.  Is
7576 		 * there a client that wants all
7577 		 * unclaimed datagrams?
7578 		 */
7579 		mutex_exit(&connfp->connf_lock);
7580 
7581 		if (mctl_present)
7582 			first_mp->b_cont = mp;
7583 		else
7584 			first_mp = mp;
7585 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7586 		    NULL) {
7587 			ip_fanout_proto(q, first_mp, ill, ipha,
7588 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7589 			    recv_ill, zoneid);
7590 		} else {
7591 			/*
7592 			 * We used to attempt to send an icmp error here, but
7593 			 * since this is known to be a multicast packet
7594 			 * and we don't send icmp errors in response to
7595 			 * multicast, just drop the packet and give up sooner.
7596 			 */
7597 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7598 			freemsg(first_mp);
7599 		}
7600 		return;
7601 	}
7602 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7603 
7604 	first_connp = connp;
7605 
7606 	CONN_INC_REF(connp);
7607 	connp = connp->conn_next;
7608 	for (;;) {
7609 		while (connp != NULL) {
7610 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7611 			    ipv6_all_zeros, srcport, v6src) &&
7612 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7613 			    (!is_system_labeled() ||
7614 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7615 			    shared_addr, connp)))
7616 				break;
7617 			connp = connp->conn_next;
7618 		}
7619 		/*
7620 		 * Just copy the data part alone. The mctl part is
7621 		 * needed just for verifying policy and it is never
7622 		 * sent up.
7623 		 */
7624 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7625 		    ((mp1 = copymsg(mp)) == NULL))) {
7626 			/*
7627 			 * No more intested clients or memory
7628 			 * allocation failed
7629 			 */
7630 			connp = first_connp;
7631 			break;
7632 		}
7633 		if (first_mp != NULL) {
7634 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7635 			    ipsec_info_type == IPSEC_IN);
7636 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7637 			    ipst->ips_netstack);
7638 			if (first_mp1 == NULL) {
7639 				freemsg(mp1);
7640 				connp = first_connp;
7641 				break;
7642 			}
7643 		} else {
7644 			first_mp1 = NULL;
7645 		}
7646 		CONN_INC_REF(connp);
7647 		mutex_exit(&connfp->connf_lock);
7648 		/*
7649 		 * IPQoS notes: We don't send the packet for policy
7650 		 * processing here, will do it for the last one (below).
7651 		 * i.e. we do it per-packet now, but if we do policy
7652 		 * processing per-conn, then we would need to do it
7653 		 * here too.
7654 		 */
7655 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7656 		    ipha, flags, recv_ill, B_FALSE);
7657 		mutex_enter(&connfp->connf_lock);
7658 		/* Follow the next pointer before releasing the conn. */
7659 		next_connp = connp->conn_next;
7660 		CONN_DEC_REF(connp);
7661 		connp = next_connp;
7662 	}
7663 
7664 	/* Last one.  Send it upstream. */
7665 	mutex_exit(&connfp->connf_lock);
7666 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7667 	    recv_ill, ip_policy);
7668 	CONN_DEC_REF(connp);
7669 }
7670 
7671 /*
7672  * Complete the ip_wput header so that it
7673  * is possible to generate ICMP
7674  * errors.
7675  */
7676 int
7677 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7678 {
7679 	ire_t *ire;
7680 
7681 	if (ipha->ipha_src == INADDR_ANY) {
7682 		ire = ire_lookup_local(zoneid, ipst);
7683 		if (ire == NULL) {
7684 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7685 			return (1);
7686 		}
7687 		ipha->ipha_src = ire->ire_addr;
7688 		ire_refrele(ire);
7689 	}
7690 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7691 	ipha->ipha_hdr_checksum = 0;
7692 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7693 	return (0);
7694 }
7695 
7696 /*
7697  * Nobody should be sending
7698  * packets up this stream
7699  */
7700 static void
7701 ip_lrput(queue_t *q, mblk_t *mp)
7702 {
7703 	mblk_t *mp1;
7704 
7705 	switch (mp->b_datap->db_type) {
7706 	case M_FLUSH:
7707 		/* Turn around */
7708 		if (*mp->b_rptr & FLUSHW) {
7709 			*mp->b_rptr &= ~FLUSHR;
7710 			qreply(q, mp);
7711 			return;
7712 		}
7713 		break;
7714 	}
7715 	/* Could receive messages that passed through ar_rput */
7716 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7717 		mp1->b_prev = mp1->b_next = NULL;
7718 	freemsg(mp);
7719 }
7720 
7721 /* Nobody should be sending packets down this stream */
7722 /* ARGSUSED */
7723 void
7724 ip_lwput(queue_t *q, mblk_t *mp)
7725 {
7726 	freemsg(mp);
7727 }
7728 
7729 /*
7730  * Move the first hop in any source route to ipha_dst and remove that part of
7731  * the source route.  Called by other protocols.  Errors in option formatting
7732  * are ignored - will be handled by ip_wput_options Return the final
7733  * destination (either ipha_dst or the last entry in a source route.)
7734  */
7735 ipaddr_t
7736 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7737 {
7738 	ipoptp_t	opts;
7739 	uchar_t		*opt;
7740 	uint8_t		optval;
7741 	uint8_t		optlen;
7742 	ipaddr_t	dst;
7743 	int		i;
7744 	ire_t		*ire;
7745 	ip_stack_t	*ipst = ns->netstack_ip;
7746 
7747 	ip2dbg(("ip_massage_options\n"));
7748 	dst = ipha->ipha_dst;
7749 	for (optval = ipoptp_first(&opts, ipha);
7750 	    optval != IPOPT_EOL;
7751 	    optval = ipoptp_next(&opts)) {
7752 		opt = opts.ipoptp_cur;
7753 		switch (optval) {
7754 			uint8_t off;
7755 		case IPOPT_SSRR:
7756 		case IPOPT_LSRR:
7757 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7758 				ip1dbg(("ip_massage_options: bad src route\n"));
7759 				break;
7760 			}
7761 			optlen = opts.ipoptp_len;
7762 			off = opt[IPOPT_OFFSET];
7763 			off--;
7764 		redo_srr:
7765 			if (optlen < IP_ADDR_LEN ||
7766 			    off > optlen - IP_ADDR_LEN) {
7767 				/* End of source route */
7768 				ip1dbg(("ip_massage_options: end of SR\n"));
7769 				break;
7770 			}
7771 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7772 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7773 			    ntohl(dst)));
7774 			/*
7775 			 * Check if our address is present more than
7776 			 * once as consecutive hops in source route.
7777 			 * XXX verify per-interface ip_forwarding
7778 			 * for source route?
7779 			 */
7780 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7781 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7782 			if (ire != NULL) {
7783 				ire_refrele(ire);
7784 				off += IP_ADDR_LEN;
7785 				goto redo_srr;
7786 			}
7787 			if (dst == htonl(INADDR_LOOPBACK)) {
7788 				ip1dbg(("ip_massage_options: loopback addr in "
7789 				    "source route!\n"));
7790 				break;
7791 			}
7792 			/*
7793 			 * Update ipha_dst to be the first hop and remove the
7794 			 * first hop from the source route (by overwriting
7795 			 * part of the option with NOP options).
7796 			 */
7797 			ipha->ipha_dst = dst;
7798 			/* Put the last entry in dst */
7799 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7800 			    3;
7801 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7802 
7803 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7804 			    ntohl(dst)));
7805 			/* Move down and overwrite */
7806 			opt[IP_ADDR_LEN] = opt[0];
7807 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7808 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7809 			for (i = 0; i < IP_ADDR_LEN; i++)
7810 				opt[i] = IPOPT_NOP;
7811 			break;
7812 		}
7813 	}
7814 	return (dst);
7815 }
7816 
7817 /*
7818  * Return the network mask
7819  * associated with the specified address.
7820  */
7821 ipaddr_t
7822 ip_net_mask(ipaddr_t addr)
7823 {
7824 	uchar_t	*up = (uchar_t *)&addr;
7825 	ipaddr_t mask = 0;
7826 	uchar_t	*maskp = (uchar_t *)&mask;
7827 
7828 #if defined(__i386) || defined(__amd64)
7829 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7830 #endif
7831 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7832 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7833 #endif
7834 	if (CLASSD(addr)) {
7835 		maskp[0] = 0xF0;
7836 		return (mask);
7837 	}
7838 
7839 	/* We assume Class E default netmask to be 32 */
7840 	if (CLASSE(addr))
7841 		return (0xffffffffU);
7842 
7843 	if (addr == 0)
7844 		return (0);
7845 	maskp[0] = 0xFF;
7846 	if ((up[0] & 0x80) == 0)
7847 		return (mask);
7848 
7849 	maskp[1] = 0xFF;
7850 	if ((up[0] & 0xC0) == 0x80)
7851 		return (mask);
7852 
7853 	maskp[2] = 0xFF;
7854 	if ((up[0] & 0xE0) == 0xC0)
7855 		return (mask);
7856 
7857 	/* Otherwise return no mask */
7858 	return ((ipaddr_t)0);
7859 }
7860 
7861 /*
7862  * Helper ill lookup function used by IPsec.
7863  */
7864 ill_t *
7865 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7866 {
7867 	ill_t *ret_ill;
7868 
7869 	ASSERT(ifindex != 0);
7870 
7871 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7872 	    ipst);
7873 	if (ret_ill == NULL) {
7874 		if (isv6) {
7875 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7876 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7877 			    ifindex));
7878 		} else {
7879 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7880 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7881 			    ifindex));
7882 		}
7883 		freemsg(first_mp);
7884 		return (NULL);
7885 	}
7886 	return (ret_ill);
7887 }
7888 
7889 /*
7890  * IPv4 -
7891  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7892  * out a packet to a destination address for which we do not have specific
7893  * (or sufficient) routing information.
7894  *
7895  * NOTE : These are the scopes of some of the variables that point at IRE,
7896  *	  which needs to be followed while making any future modifications
7897  *	  to avoid memory leaks.
7898  *
7899  *	- ire and sire are the entries looked up initially by
7900  *	  ire_ftable_lookup.
7901  *	- ipif_ire is used to hold the interface ire associated with
7902  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7903  *	  it before branching out to error paths.
7904  *	- save_ire is initialized before ire_create, so that ire returned
7905  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7906  *	  before breaking out of the switch.
7907  *
7908  *	Thus on failures, we have to REFRELE only ire and sire, if they
7909  *	are not NULL.
7910  */
7911 void
7912 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7913     zoneid_t zoneid, ip_stack_t *ipst)
7914 {
7915 	areq_t	*areq;
7916 	ipaddr_t gw = 0;
7917 	ire_t	*ire = NULL;
7918 	mblk_t	*res_mp;
7919 	ipaddr_t *addrp;
7920 	ipaddr_t nexthop_addr;
7921 	ipif_t  *src_ipif = NULL;
7922 	ill_t	*dst_ill = NULL;
7923 	ipha_t  *ipha;
7924 	ire_t	*sire = NULL;
7925 	mblk_t	*first_mp;
7926 	ire_t	*save_ire;
7927 	ushort_t ire_marks = 0;
7928 	boolean_t mctl_present;
7929 	ipsec_out_t *io;
7930 	mblk_t	*saved_mp;
7931 	ire_t	*first_sire = NULL;
7932 	mblk_t	*copy_mp = NULL;
7933 	mblk_t	*xmit_mp = NULL;
7934 	ipaddr_t save_dst;
7935 	uint32_t multirt_flags =
7936 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7937 	boolean_t multirt_is_resolvable;
7938 	boolean_t multirt_resolve_next;
7939 	boolean_t unspec_src;
7940 	boolean_t ip_nexthop = B_FALSE;
7941 	tsol_ire_gw_secattr_t *attrp = NULL;
7942 	tsol_gcgrp_t *gcgrp = NULL;
7943 	tsol_gcgrp_addr_t ga;
7944 
7945 	if (ip_debug > 2) {
7946 		/* ip1dbg */
7947 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7948 	}
7949 
7950 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7951 	if (mctl_present) {
7952 		io = (ipsec_out_t *)first_mp->b_rptr;
7953 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7954 		ASSERT(zoneid == io->ipsec_out_zoneid);
7955 		ASSERT(zoneid != ALL_ZONES);
7956 	}
7957 
7958 	ipha = (ipha_t *)mp->b_rptr;
7959 
7960 	/* All multicast lookups come through ip_newroute_ipif() */
7961 	if (CLASSD(dst)) {
7962 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7963 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7964 		freemsg(first_mp);
7965 		return;
7966 	}
7967 
7968 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7969 		ip_nexthop = B_TRUE;
7970 		nexthop_addr = io->ipsec_out_nexthop_addr;
7971 	}
7972 	/*
7973 	 * If this IRE is created for forwarding or it is not for
7974 	 * traffic for congestion controlled protocols, mark it as temporary.
7975 	 */
7976 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7977 		ire_marks |= IRE_MARK_TEMPORARY;
7978 
7979 	/*
7980 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7981 	 * chain until it gets the most specific information available.
7982 	 * For example, we know that there is no IRE_CACHE for this dest,
7983 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7984 	 * ire_ftable_lookup will look up the gateway, etc.
7985 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7986 	 * to the destination, of equal netmask length in the forward table,
7987 	 * will be recursively explored. If no information is available
7988 	 * for the final gateway of that route, we force the returned ire
7989 	 * to be equal to sire using MATCH_IRE_PARENT.
7990 	 * At least, in this case we have a starting point (in the buckets)
7991 	 * to look for other routes to the destination in the forward table.
7992 	 * This is actually used only for multirouting, where a list
7993 	 * of routes has to be processed in sequence.
7994 	 *
7995 	 * In the process of coming up with the most specific information,
7996 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7997 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7998 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7999 	 * Two caveats when handling incomplete ire's in ip_newroute:
8000 	 * - we should be careful when accessing its ire_nce (specifically
8001 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8002 	 * - not all legacy code path callers are prepared to handle
8003 	 *   incomplete ire's, so we should not create/add incomplete
8004 	 *   ire_cache entries here. (See discussion about temporary solution
8005 	 *   further below).
8006 	 *
8007 	 * In order to minimize packet dropping, and to preserve existing
8008 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8009 	 * gateway, and instead use the IF_RESOLVER ire to send out
8010 	 * another request to ARP (this is achieved by passing the
8011 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8012 	 * arp response comes back in ip_wput_nondata, we will create
8013 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8014 	 *
8015 	 * Note that this is a temporary solution; the correct solution is
8016 	 * to create an incomplete  per-dst ire_cache entry, and send the
8017 	 * packet out when the gw's nce is resolved. In order to achieve this,
8018 	 * all packet processing must have been completed prior to calling
8019 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8020 	 * to be modified to accomodate this solution.
8021 	 */
8022 	if (ip_nexthop) {
8023 		/*
8024 		 * The first time we come here, we look for an IRE_INTERFACE
8025 		 * entry for the specified nexthop, set the dst to be the
8026 		 * nexthop address and create an IRE_CACHE entry for the
8027 		 * nexthop. The next time around, we are able to find an
8028 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8029 		 * nexthop address and create an IRE_CACHE entry for the
8030 		 * destination address via the specified nexthop.
8031 		 */
8032 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8033 		    msg_getlabel(mp), ipst);
8034 		if (ire != NULL) {
8035 			gw = nexthop_addr;
8036 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8037 		} else {
8038 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8039 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8040 			    msg_getlabel(mp),
8041 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8042 			    ipst);
8043 			if (ire != NULL) {
8044 				dst = nexthop_addr;
8045 			}
8046 		}
8047 	} else {
8048 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8049 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8050 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8051 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8052 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8053 		    ipst);
8054 	}
8055 
8056 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8057 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8058 
8059 	/*
8060 	 * This loop is run only once in most cases.
8061 	 * We loop to resolve further routes only when the destination
8062 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8063 	 */
8064 	do {
8065 		/* Clear the previous iteration's values */
8066 		if (src_ipif != NULL) {
8067 			ipif_refrele(src_ipif);
8068 			src_ipif = NULL;
8069 		}
8070 		if (dst_ill != NULL) {
8071 			ill_refrele(dst_ill);
8072 			dst_ill = NULL;
8073 		}
8074 
8075 		multirt_resolve_next = B_FALSE;
8076 		/*
8077 		 * We check if packets have to be multirouted.
8078 		 * In this case, given the current <ire, sire> couple,
8079 		 * we look for the next suitable <ire, sire>.
8080 		 * This check is done in ire_multirt_lookup(),
8081 		 * which applies various criteria to find the next route
8082 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8083 		 * unchanged if it detects it has not been tried yet.
8084 		 */
8085 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8086 			ip3dbg(("ip_newroute: starting next_resolution "
8087 			    "with first_mp %p, tag %d\n",
8088 			    (void *)first_mp,
8089 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8090 
8091 			ASSERT(sire != NULL);
8092 			multirt_is_resolvable =
8093 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8094 			    msg_getlabel(mp), ipst);
8095 
8096 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8097 			    "ire %p, sire %p\n",
8098 			    multirt_is_resolvable,
8099 			    (void *)ire, (void *)sire));
8100 
8101 			if (!multirt_is_resolvable) {
8102 				/*
8103 				 * No more multirt route to resolve; give up
8104 				 * (all routes resolved or no more
8105 				 * resolvable routes).
8106 				 */
8107 				if (ire != NULL) {
8108 					ire_refrele(ire);
8109 					ire = NULL;
8110 				}
8111 			} else {
8112 				ASSERT(sire != NULL);
8113 				ASSERT(ire != NULL);
8114 				/*
8115 				 * We simply use first_sire as a flag that
8116 				 * indicates if a resolvable multirt route
8117 				 * has already been found.
8118 				 * If it is not the case, we may have to send
8119 				 * an ICMP error to report that the
8120 				 * destination is unreachable.
8121 				 * We do not IRE_REFHOLD first_sire.
8122 				 */
8123 				if (first_sire == NULL) {
8124 					first_sire = sire;
8125 				}
8126 			}
8127 		}
8128 		if (ire == NULL) {
8129 			if (ip_debug > 3) {
8130 				/* ip2dbg */
8131 				pr_addr_dbg("ip_newroute: "
8132 				    "can't resolve %s\n", AF_INET, &dst);
8133 			}
8134 			ip3dbg(("ip_newroute: "
8135 			    "ire %p, sire %p, first_sire %p\n",
8136 			    (void *)ire, (void *)sire, (void *)first_sire));
8137 
8138 			if (sire != NULL) {
8139 				ire_refrele(sire);
8140 				sire = NULL;
8141 			}
8142 
8143 			if (first_sire != NULL) {
8144 				/*
8145 				 * At least one multirt route has been found
8146 				 * in the same call to ip_newroute();
8147 				 * there is no need to report an ICMP error.
8148 				 * first_sire was not IRE_REFHOLDed.
8149 				 */
8150 				MULTIRT_DEBUG_UNTAG(first_mp);
8151 				freemsg(first_mp);
8152 				return;
8153 			}
8154 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8155 			    RTA_DST, ipst);
8156 			goto icmp_err_ret;
8157 		}
8158 
8159 		/*
8160 		 * Verify that the returned IRE does not have either
8161 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8162 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8163 		 */
8164 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8165 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8166 			goto icmp_err_ret;
8167 		}
8168 		/*
8169 		 * Increment the ire_ob_pkt_count field for ire if it is an
8170 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8171 		 * increment the same for the parent IRE, sire, if it is some
8172 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8173 		 */
8174 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8175 			UPDATE_OB_PKT_COUNT(ire);
8176 			ire->ire_last_used_time = lbolt;
8177 		}
8178 
8179 		if (sire != NULL) {
8180 			gw = sire->ire_gateway_addr;
8181 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8182 			    IRE_INTERFACE)) == 0);
8183 			UPDATE_OB_PKT_COUNT(sire);
8184 			sire->ire_last_used_time = lbolt;
8185 		}
8186 		/*
8187 		 * We have a route to reach the destination.  Find the
8188 		 * appropriate ill, then get a source address using
8189 		 * ipif_select_source().
8190 		 *
8191 		 * If we are here trying to create an IRE_CACHE for an offlink
8192 		 * destination and have an IRE_CACHE entry for VNI, then use
8193 		 * ire_stq instead since VNI's queue is a black hole.
8194 		 */
8195 		if ((ire->ire_type == IRE_CACHE) &&
8196 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8197 			dst_ill = ire->ire_stq->q_ptr;
8198 			ill_refhold(dst_ill);
8199 		} else {
8200 			ill_t *ill = ire->ire_ipif->ipif_ill;
8201 
8202 			if (IS_IPMP(ill)) {
8203 				dst_ill =
8204 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8205 			} else {
8206 				dst_ill = ill;
8207 				ill_refhold(dst_ill);
8208 			}
8209 		}
8210 
8211 		if (dst_ill == NULL) {
8212 			if (ip_debug > 2) {
8213 				pr_addr_dbg("ip_newroute: no dst "
8214 				    "ill for dst %s\n", AF_INET, &dst);
8215 			}
8216 			goto icmp_err_ret;
8217 		}
8218 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8219 
8220 		/*
8221 		 * Pick the best source address from dst_ill.
8222 		 *
8223 		 * 1) Try to pick the source address from the destination
8224 		 *    route. Clustering assumes that when we have multiple
8225 		 *    prefixes hosted on an interface, the prefix of the
8226 		 *    source address matches the prefix of the destination
8227 		 *    route. We do this only if the address is not
8228 		 *    DEPRECATED.
8229 		 *
8230 		 * 2) If the conn is in a different zone than the ire, we
8231 		 *    need to pick a source address from the right zone.
8232 		 */
8233 		ASSERT(src_ipif == NULL);
8234 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8235 			/*
8236 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8237 			 * Check that the ipif matching the requested source
8238 			 * address still exists.
8239 			 */
8240 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8241 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8242 		}
8243 
8244 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8245 
8246 		if (src_ipif == NULL &&
8247 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8248 			ire_marks |= IRE_MARK_USESRC_CHECK;
8249 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8250 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8251 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8252 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8253 			    ire->ire_zoneid != ALL_ZONES) ||
8254 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8255 				/*
8256 				 * If the destination is reachable via a
8257 				 * given gateway, the selected source address
8258 				 * should be in the same subnet as the gateway.
8259 				 * Otherwise, the destination is not reachable.
8260 				 *
8261 				 * If there are no interfaces on the same subnet
8262 				 * as the destination, ipif_select_source gives
8263 				 * first non-deprecated interface which might be
8264 				 * on a different subnet than the gateway.
8265 				 * This is not desirable. Hence pass the dst_ire
8266 				 * source address to ipif_select_source.
8267 				 * It is sure that the destination is reachable
8268 				 * with the dst_ire source address subnet.
8269 				 * So passing dst_ire source address to
8270 				 * ipif_select_source will make sure that the
8271 				 * selected source will be on the same subnet
8272 				 * as dst_ire source address.
8273 				 */
8274 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8275 
8276 				src_ipif = ipif_select_source(dst_ill, saddr,
8277 				    zoneid);
8278 				if (src_ipif == NULL) {
8279 					if (ip_debug > 2) {
8280 						pr_addr_dbg("ip_newroute: "
8281 						    "no src for dst %s ",
8282 						    AF_INET, &dst);
8283 						printf("on interface %s\n",
8284 						    dst_ill->ill_name);
8285 					}
8286 					goto icmp_err_ret;
8287 				}
8288 			} else {
8289 				src_ipif = ire->ire_ipif;
8290 				ASSERT(src_ipif != NULL);
8291 				/* hold src_ipif for uniformity */
8292 				ipif_refhold(src_ipif);
8293 			}
8294 		}
8295 
8296 		/*
8297 		 * Assign a source address while we have the conn.
8298 		 * We can't have ip_wput_ire pick a source address when the
8299 		 * packet returns from arp since we need to look at
8300 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8301 		 * going through arp.
8302 		 *
8303 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8304 		 *	  it uses ip6i to store this information.
8305 		 */
8306 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8307 			ipha->ipha_src = src_ipif->ipif_src_addr;
8308 
8309 		if (ip_debug > 3) {
8310 			/* ip2dbg */
8311 			pr_addr_dbg("ip_newroute: first hop %s\n",
8312 			    AF_INET, &gw);
8313 		}
8314 		ip2dbg(("\tire type %s (%d)\n",
8315 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8316 
8317 		/*
8318 		 * The TTL of multirouted packets is bounded by the
8319 		 * ip_multirt_ttl ndd variable.
8320 		 */
8321 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8322 			/* Force TTL of multirouted packets */
8323 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8324 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8325 				ip2dbg(("ip_newroute: forcing multirt TTL "
8326 				    "to %d (was %d), dst 0x%08x\n",
8327 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8328 				    ntohl(sire->ire_addr)));
8329 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8330 			}
8331 		}
8332 		/*
8333 		 * At this point in ip_newroute(), ire is either the
8334 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8335 		 * destination or an IRE_INTERFACE type that should be used
8336 		 * to resolve an on-subnet destination or an on-subnet
8337 		 * next-hop gateway.
8338 		 *
8339 		 * In the IRE_CACHE case, we have the following :
8340 		 *
8341 		 * 1) src_ipif - used for getting a source address.
8342 		 *
8343 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8344 		 *    means packets using this IRE_CACHE will go out on
8345 		 *    dst_ill.
8346 		 *
8347 		 * 3) The IRE sire will point to the prefix that is the
8348 		 *    longest  matching route for the destination. These
8349 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8350 		 *
8351 		 *    The newly created IRE_CACHE entry for the off-subnet
8352 		 *    destination is tied to both the prefix route and the
8353 		 *    interface route used to resolve the next-hop gateway
8354 		 *    via the ire_phandle and ire_ihandle fields,
8355 		 *    respectively.
8356 		 *
8357 		 * In the IRE_INTERFACE case, we have the following :
8358 		 *
8359 		 * 1) src_ipif - used for getting a source address.
8360 		 *
8361 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8362 		 *    means packets using the IRE_CACHE that we will build
8363 		 *    here will go out on dst_ill.
8364 		 *
8365 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8366 		 *    to be created will only be tied to the IRE_INTERFACE
8367 		 *    that was derived from the ire_ihandle field.
8368 		 *
8369 		 *    If sire is non-NULL, it means the destination is
8370 		 *    off-link and we will first create the IRE_CACHE for the
8371 		 *    gateway. Next time through ip_newroute, we will create
8372 		 *    the IRE_CACHE for the final destination as described
8373 		 *    above.
8374 		 *
8375 		 * In both cases, after the current resolution has been
8376 		 * completed (or possibly initialised, in the IRE_INTERFACE
8377 		 * case), the loop may be re-entered to attempt the resolution
8378 		 * of another RTF_MULTIRT route.
8379 		 *
8380 		 * When an IRE_CACHE entry for the off-subnet destination is
8381 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8382 		 * for further processing in emission loops.
8383 		 */
8384 		save_ire = ire;
8385 		switch (ire->ire_type) {
8386 		case IRE_CACHE: {
8387 			ire_t	*ipif_ire;
8388 
8389 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8390 			if (gw == 0)
8391 				gw = ire->ire_gateway_addr;
8392 			/*
8393 			 * We need 3 ire's to create a new cache ire for an
8394 			 * off-link destination from the cache ire of the
8395 			 * gateway.
8396 			 *
8397 			 *	1. The prefix ire 'sire' (Note that this does
8398 			 *	   not apply to the conn_nexthop_set case)
8399 			 *	2. The cache ire of the gateway 'ire'
8400 			 *	3. The interface ire 'ipif_ire'
8401 			 *
8402 			 * We have (1) and (2). We lookup (3) below.
8403 			 *
8404 			 * If there is no interface route to the gateway,
8405 			 * it is a race condition, where we found the cache
8406 			 * but the interface route has been deleted.
8407 			 */
8408 			if (ip_nexthop) {
8409 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8410 			} else {
8411 				ipif_ire =
8412 				    ire_ihandle_lookup_offlink(ire, sire);
8413 			}
8414 			if (ipif_ire == NULL) {
8415 				ip1dbg(("ip_newroute: "
8416 				    "ire_ihandle_lookup_offlink failed\n"));
8417 				goto icmp_err_ret;
8418 			}
8419 
8420 			/*
8421 			 * Check cached gateway IRE for any security
8422 			 * attributes; if found, associate the gateway
8423 			 * credentials group to the destination IRE.
8424 			 */
8425 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8426 				mutex_enter(&attrp->igsa_lock);
8427 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8428 					GCGRP_REFHOLD(gcgrp);
8429 				mutex_exit(&attrp->igsa_lock);
8430 			}
8431 
8432 			/*
8433 			 * XXX For the source of the resolver mp,
8434 			 * we are using the same DL_UNITDATA_REQ
8435 			 * (from save_ire->ire_nce->nce_res_mp)
8436 			 * though the save_ire is not pointing at the same ill.
8437 			 * This is incorrect. We need to send it up to the
8438 			 * resolver to get the right res_mp. For ethernets
8439 			 * this may be okay (ill_type == DL_ETHER).
8440 			 */
8441 
8442 			ire = ire_create(
8443 			    (uchar_t *)&dst,		/* dest address */
8444 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8445 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8446 			    (uchar_t *)&gw,		/* gateway address */
8447 			    &save_ire->ire_max_frag,
8448 			    save_ire->ire_nce,		/* src nce */
8449 			    dst_ill->ill_rq,		/* recv-from queue */
8450 			    dst_ill->ill_wq,		/* send-to queue */
8451 			    IRE_CACHE,			/* IRE type */
8452 			    src_ipif,
8453 			    (sire != NULL) ?
8454 			    sire->ire_mask : 0, 	/* Parent mask */
8455 			    (sire != NULL) ?
8456 			    sire->ire_phandle : 0,	/* Parent handle */
8457 			    ipif_ire->ire_ihandle,	/* Interface handle */
8458 			    (sire != NULL) ? (sire->ire_flags &
8459 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8460 			    (sire != NULL) ?
8461 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8462 			    NULL,
8463 			    gcgrp,
8464 			    ipst);
8465 
8466 			if (ire == NULL) {
8467 				if (gcgrp != NULL) {
8468 					GCGRP_REFRELE(gcgrp);
8469 					gcgrp = NULL;
8470 				}
8471 				ire_refrele(ipif_ire);
8472 				ire_refrele(save_ire);
8473 				break;
8474 			}
8475 
8476 			/* reference now held by IRE */
8477 			gcgrp = NULL;
8478 
8479 			ire->ire_marks |= ire_marks;
8480 
8481 			/*
8482 			 * Prevent sire and ipif_ire from getting deleted.
8483 			 * The newly created ire is tied to both of them via
8484 			 * the phandle and ihandle respectively.
8485 			 */
8486 			if (sire != NULL) {
8487 				IRB_REFHOLD(sire->ire_bucket);
8488 				/* Has it been removed already ? */
8489 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8490 					IRB_REFRELE(sire->ire_bucket);
8491 					ire_refrele(ipif_ire);
8492 					ire_refrele(save_ire);
8493 					break;
8494 				}
8495 			}
8496 
8497 			IRB_REFHOLD(ipif_ire->ire_bucket);
8498 			/* Has it been removed already ? */
8499 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8500 				IRB_REFRELE(ipif_ire->ire_bucket);
8501 				if (sire != NULL)
8502 					IRB_REFRELE(sire->ire_bucket);
8503 				ire_refrele(ipif_ire);
8504 				ire_refrele(save_ire);
8505 				break;
8506 			}
8507 
8508 			xmit_mp = first_mp;
8509 			/*
8510 			 * In the case of multirouting, a copy
8511 			 * of the packet is done before its sending.
8512 			 * The copy is used to attempt another
8513 			 * route resolution, in a next loop.
8514 			 */
8515 			if (ire->ire_flags & RTF_MULTIRT) {
8516 				copy_mp = copymsg(first_mp);
8517 				if (copy_mp != NULL) {
8518 					xmit_mp = copy_mp;
8519 					MULTIRT_DEBUG_TAG(first_mp);
8520 				}
8521 			}
8522 
8523 			ire_add_then_send(q, ire, xmit_mp);
8524 			ire_refrele(save_ire);
8525 
8526 			/* Assert that sire is not deleted yet. */
8527 			if (sire != NULL) {
8528 				ASSERT(sire->ire_ptpn != NULL);
8529 				IRB_REFRELE(sire->ire_bucket);
8530 			}
8531 
8532 			/* Assert that ipif_ire is not deleted yet. */
8533 			ASSERT(ipif_ire->ire_ptpn != NULL);
8534 			IRB_REFRELE(ipif_ire->ire_bucket);
8535 			ire_refrele(ipif_ire);
8536 
8537 			/*
8538 			 * If copy_mp is not NULL, multirouting was
8539 			 * requested. We loop to initiate a next
8540 			 * route resolution attempt, starting from sire.
8541 			 */
8542 			if (copy_mp != NULL) {
8543 				/*
8544 				 * Search for the next unresolved
8545 				 * multirt route.
8546 				 */
8547 				copy_mp = NULL;
8548 				ipif_ire = NULL;
8549 				ire = NULL;
8550 				multirt_resolve_next = B_TRUE;
8551 				continue;
8552 			}
8553 			if (sire != NULL)
8554 				ire_refrele(sire);
8555 			ipif_refrele(src_ipif);
8556 			ill_refrele(dst_ill);
8557 			return;
8558 		}
8559 		case IRE_IF_NORESOLVER: {
8560 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8561 			    dst_ill->ill_resolver_mp == NULL) {
8562 				ip1dbg(("ip_newroute: dst_ill %p "
8563 				    "for IRE_IF_NORESOLVER ire %p has "
8564 				    "no ill_resolver_mp\n",
8565 				    (void *)dst_ill, (void *)ire));
8566 				break;
8567 			}
8568 
8569 			/*
8570 			 * TSol note: We are creating the ire cache for the
8571 			 * destination 'dst'. If 'dst' is offlink, going
8572 			 * through the first hop 'gw', the security attributes
8573 			 * of 'dst' must be set to point to the gateway
8574 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8575 			 * is possible that 'dst' is a potential gateway that is
8576 			 * referenced by some route that has some security
8577 			 * attributes. Thus in the former case, we need to do a
8578 			 * gcgrp_lookup of 'gw' while in the latter case we
8579 			 * need to do gcgrp_lookup of 'dst' itself.
8580 			 */
8581 			ga.ga_af = AF_INET;
8582 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8583 			    &ga.ga_addr);
8584 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8585 
8586 			ire = ire_create(
8587 			    (uchar_t *)&dst,		/* dest address */
8588 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8589 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8590 			    (uchar_t *)&gw,		/* gateway address */
8591 			    &save_ire->ire_max_frag,
8592 			    NULL,			/* no src nce */
8593 			    dst_ill->ill_rq,		/* recv-from queue */
8594 			    dst_ill->ill_wq,		/* send-to queue */
8595 			    IRE_CACHE,
8596 			    src_ipif,
8597 			    save_ire->ire_mask,		/* Parent mask */
8598 			    (sire != NULL) ?		/* Parent handle */
8599 			    sire->ire_phandle : 0,
8600 			    save_ire->ire_ihandle,	/* Interface handle */
8601 			    (sire != NULL) ? sire->ire_flags &
8602 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8603 			    &(save_ire->ire_uinfo),
8604 			    NULL,
8605 			    gcgrp,
8606 			    ipst);
8607 
8608 			if (ire == NULL) {
8609 				if (gcgrp != NULL) {
8610 					GCGRP_REFRELE(gcgrp);
8611 					gcgrp = NULL;
8612 				}
8613 				ire_refrele(save_ire);
8614 				break;
8615 			}
8616 
8617 			/* reference now held by IRE */
8618 			gcgrp = NULL;
8619 
8620 			ire->ire_marks |= ire_marks;
8621 
8622 			/* Prevent save_ire from getting deleted */
8623 			IRB_REFHOLD(save_ire->ire_bucket);
8624 			/* Has it been removed already ? */
8625 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8626 				IRB_REFRELE(save_ire->ire_bucket);
8627 				ire_refrele(save_ire);
8628 				break;
8629 			}
8630 
8631 			/*
8632 			 * In the case of multirouting, a copy
8633 			 * of the packet is made before it is sent.
8634 			 * The copy is used in the next
8635 			 * loop to attempt another resolution.
8636 			 */
8637 			xmit_mp = first_mp;
8638 			if ((sire != NULL) &&
8639 			    (sire->ire_flags & RTF_MULTIRT)) {
8640 				copy_mp = copymsg(first_mp);
8641 				if (copy_mp != NULL) {
8642 					xmit_mp = copy_mp;
8643 					MULTIRT_DEBUG_TAG(first_mp);
8644 				}
8645 			}
8646 			ire_add_then_send(q, ire, xmit_mp);
8647 
8648 			/* Assert that it is not deleted yet. */
8649 			ASSERT(save_ire->ire_ptpn != NULL);
8650 			IRB_REFRELE(save_ire->ire_bucket);
8651 			ire_refrele(save_ire);
8652 
8653 			if (copy_mp != NULL) {
8654 				/*
8655 				 * If we found a (no)resolver, we ignore any
8656 				 * trailing top priority IRE_CACHE in further
8657 				 * loops. This ensures that we do not omit any
8658 				 * (no)resolver.
8659 				 * This IRE_CACHE, if any, will be processed
8660 				 * by another thread entering ip_newroute().
8661 				 * IRE_CACHE entries, if any, will be processed
8662 				 * by another thread entering ip_newroute(),
8663 				 * (upon resolver response, for instance).
8664 				 * This aims to force parallel multirt
8665 				 * resolutions as soon as a packet must be sent.
8666 				 * In the best case, after the tx of only one
8667 				 * packet, all reachable routes are resolved.
8668 				 * Otherwise, the resolution of all RTF_MULTIRT
8669 				 * routes would require several emissions.
8670 				 */
8671 				multirt_flags &= ~MULTIRT_CACHEGW;
8672 
8673 				/*
8674 				 * Search for the next unresolved multirt
8675 				 * route.
8676 				 */
8677 				copy_mp = NULL;
8678 				save_ire = NULL;
8679 				ire = NULL;
8680 				multirt_resolve_next = B_TRUE;
8681 				continue;
8682 			}
8683 
8684 			/*
8685 			 * Don't need sire anymore
8686 			 */
8687 			if (sire != NULL)
8688 				ire_refrele(sire);
8689 
8690 			ipif_refrele(src_ipif);
8691 			ill_refrele(dst_ill);
8692 			return;
8693 		}
8694 		case IRE_IF_RESOLVER:
8695 			/*
8696 			 * We can't build an IRE_CACHE yet, but at least we
8697 			 * found a resolver that can help.
8698 			 */
8699 			res_mp = dst_ill->ill_resolver_mp;
8700 			if (!OK_RESOLVER_MP(res_mp))
8701 				break;
8702 
8703 			/*
8704 			 * To be at this point in the code with a non-zero gw
8705 			 * means that dst is reachable through a gateway that
8706 			 * we have never resolved.  By changing dst to the gw
8707 			 * addr we resolve the gateway first.
8708 			 * When ire_add_then_send() tries to put the IP dg
8709 			 * to dst, it will reenter ip_newroute() at which
8710 			 * time we will find the IRE_CACHE for the gw and
8711 			 * create another IRE_CACHE in case IRE_CACHE above.
8712 			 */
8713 			if (gw != INADDR_ANY) {
8714 				/*
8715 				 * The source ipif that was determined above was
8716 				 * relative to the destination address, not the
8717 				 * gateway's. If src_ipif was not taken out of
8718 				 * the IRE_IF_RESOLVER entry, we'll need to call
8719 				 * ipif_select_source() again.
8720 				 */
8721 				if (src_ipif != ire->ire_ipif) {
8722 					ipif_refrele(src_ipif);
8723 					src_ipif = ipif_select_source(dst_ill,
8724 					    gw, zoneid);
8725 					if (src_ipif == NULL) {
8726 						if (ip_debug > 2) {
8727 							pr_addr_dbg(
8728 							    "ip_newroute: no "
8729 							    "src for gw %s ",
8730 							    AF_INET, &gw);
8731 							printf("on "
8732 							    "interface %s\n",
8733 							    dst_ill->ill_name);
8734 						}
8735 						goto icmp_err_ret;
8736 					}
8737 				}
8738 				save_dst = dst;
8739 				dst = gw;
8740 				gw = INADDR_ANY;
8741 			}
8742 
8743 			/*
8744 			 * We obtain a partial IRE_CACHE which we will pass
8745 			 * along with the resolver query.  When the response
8746 			 * comes back it will be there ready for us to add.
8747 			 * The ire_max_frag is atomically set under the
8748 			 * irebucket lock in ire_add_v[46].
8749 			 */
8750 
8751 			ire = ire_create_mp(
8752 			    (uchar_t *)&dst,		/* dest address */
8753 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8754 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8755 			    (uchar_t *)&gw,		/* gateway address */
8756 			    NULL,			/* ire_max_frag */
8757 			    NULL,			/* no src nce */
8758 			    dst_ill->ill_rq,		/* recv-from queue */
8759 			    dst_ill->ill_wq,		/* send-to queue */
8760 			    IRE_CACHE,
8761 			    src_ipif,			/* Interface ipif */
8762 			    save_ire->ire_mask,		/* Parent mask */
8763 			    0,
8764 			    save_ire->ire_ihandle,	/* Interface handle */
8765 			    0,				/* flags if any */
8766 			    &(save_ire->ire_uinfo),
8767 			    NULL,
8768 			    NULL,
8769 			    ipst);
8770 
8771 			if (ire == NULL) {
8772 				ire_refrele(save_ire);
8773 				break;
8774 			}
8775 
8776 			if ((sire != NULL) &&
8777 			    (sire->ire_flags & RTF_MULTIRT)) {
8778 				copy_mp = copymsg(first_mp);
8779 				if (copy_mp != NULL)
8780 					MULTIRT_DEBUG_TAG(copy_mp);
8781 			}
8782 
8783 			ire->ire_marks |= ire_marks;
8784 
8785 			/*
8786 			 * Construct message chain for the resolver
8787 			 * of the form:
8788 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8789 			 * Packet could contain a IPSEC_OUT mp.
8790 			 *
8791 			 * NOTE : ire will be added later when the response
8792 			 * comes back from ARP. If the response does not
8793 			 * come back, ARP frees the packet. For this reason,
8794 			 * we can't REFHOLD the bucket of save_ire to prevent
8795 			 * deletions. We may not be able to REFRELE the bucket
8796 			 * if the response never comes back. Thus, before
8797 			 * adding the ire, ire_add_v4 will make sure that the
8798 			 * interface route does not get deleted. This is the
8799 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8800 			 * where we can always prevent deletions because of
8801 			 * the synchronous nature of adding IRES i.e
8802 			 * ire_add_then_send is called after creating the IRE.
8803 			 */
8804 			ASSERT(ire->ire_mp != NULL);
8805 			ire->ire_mp->b_cont = first_mp;
8806 			/* Have saved_mp handy, for cleanup if canput fails */
8807 			saved_mp = mp;
8808 			mp = copyb(res_mp);
8809 			if (mp == NULL) {
8810 				/* Prepare for cleanup */
8811 				mp = saved_mp; /* pkt */
8812 				ire_delete(ire); /* ire_mp */
8813 				ire = NULL;
8814 				ire_refrele(save_ire);
8815 				if (copy_mp != NULL) {
8816 					MULTIRT_DEBUG_UNTAG(copy_mp);
8817 					freemsg(copy_mp);
8818 					copy_mp = NULL;
8819 				}
8820 				break;
8821 			}
8822 			linkb(mp, ire->ire_mp);
8823 
8824 			/*
8825 			 * Fill in the source and dest addrs for the resolver.
8826 			 * NOTE: this depends on memory layouts imposed by
8827 			 * ill_init().
8828 			 */
8829 			areq = (areq_t *)mp->b_rptr;
8830 			addrp = (ipaddr_t *)((char *)areq +
8831 			    areq->areq_sender_addr_offset);
8832 			*addrp = save_ire->ire_src_addr;
8833 
8834 			ire_refrele(save_ire);
8835 			addrp = (ipaddr_t *)((char *)areq +
8836 			    areq->areq_target_addr_offset);
8837 			*addrp = dst;
8838 			/* Up to the resolver. */
8839 			if (canputnext(dst_ill->ill_rq) &&
8840 			    !(dst_ill->ill_arp_closing)) {
8841 				putnext(dst_ill->ill_rq, mp);
8842 				ire = NULL;
8843 				if (copy_mp != NULL) {
8844 					/*
8845 					 * If we found a resolver, we ignore
8846 					 * any trailing top priority IRE_CACHE
8847 					 * in the further loops. This ensures
8848 					 * that we do not omit any resolver.
8849 					 * IRE_CACHE entries, if any, will be
8850 					 * processed next time we enter
8851 					 * ip_newroute().
8852 					 */
8853 					multirt_flags &= ~MULTIRT_CACHEGW;
8854 					/*
8855 					 * Search for the next unresolved
8856 					 * multirt route.
8857 					 */
8858 					first_mp = copy_mp;
8859 					copy_mp = NULL;
8860 					/* Prepare the next resolution loop. */
8861 					mp = first_mp;
8862 					EXTRACT_PKT_MP(mp, first_mp,
8863 					    mctl_present);
8864 					if (mctl_present)
8865 						io = (ipsec_out_t *)
8866 						    first_mp->b_rptr;
8867 					ipha = (ipha_t *)mp->b_rptr;
8868 
8869 					ASSERT(sire != NULL);
8870 
8871 					dst = save_dst;
8872 					multirt_resolve_next = B_TRUE;
8873 					continue;
8874 				}
8875 
8876 				if (sire != NULL)
8877 					ire_refrele(sire);
8878 
8879 				/*
8880 				 * The response will come back in ip_wput
8881 				 * with db_type IRE_DB_TYPE.
8882 				 */
8883 				ipif_refrele(src_ipif);
8884 				ill_refrele(dst_ill);
8885 				return;
8886 			} else {
8887 				/* Prepare for cleanup */
8888 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8889 				    mp);
8890 				mp->b_cont = NULL;
8891 				freeb(mp); /* areq */
8892 				/*
8893 				 * this is an ire that is not added to the
8894 				 * cache. ire_freemblk will handle the release
8895 				 * of any resources associated with the ire.
8896 				 */
8897 				ire_delete(ire); /* ire_mp */
8898 				mp = saved_mp; /* pkt */
8899 				ire = NULL;
8900 				if (copy_mp != NULL) {
8901 					MULTIRT_DEBUG_UNTAG(copy_mp);
8902 					freemsg(copy_mp);
8903 					copy_mp = NULL;
8904 				}
8905 				break;
8906 			}
8907 		default:
8908 			break;
8909 		}
8910 	} while (multirt_resolve_next);
8911 
8912 	ip1dbg(("ip_newroute: dropped\n"));
8913 	/* Did this packet originate externally? */
8914 	if (mp->b_prev) {
8915 		mp->b_next = NULL;
8916 		mp->b_prev = NULL;
8917 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8918 	} else {
8919 		if (dst_ill != NULL) {
8920 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8921 		} else {
8922 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8923 		}
8924 	}
8925 	ASSERT(copy_mp == NULL);
8926 	MULTIRT_DEBUG_UNTAG(first_mp);
8927 	freemsg(first_mp);
8928 	if (ire != NULL)
8929 		ire_refrele(ire);
8930 	if (sire != NULL)
8931 		ire_refrele(sire);
8932 	if (src_ipif != NULL)
8933 		ipif_refrele(src_ipif);
8934 	if (dst_ill != NULL)
8935 		ill_refrele(dst_ill);
8936 	return;
8937 
8938 icmp_err_ret:
8939 	ip1dbg(("ip_newroute: no route\n"));
8940 	if (src_ipif != NULL)
8941 		ipif_refrele(src_ipif);
8942 	if (dst_ill != NULL)
8943 		ill_refrele(dst_ill);
8944 	if (sire != NULL)
8945 		ire_refrele(sire);
8946 	/* Did this packet originate externally? */
8947 	if (mp->b_prev) {
8948 		mp->b_next = NULL;
8949 		mp->b_prev = NULL;
8950 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8951 		q = WR(q);
8952 	} else {
8953 		/*
8954 		 * There is no outgoing ill, so just increment the
8955 		 * system MIB.
8956 		 */
8957 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8958 		/*
8959 		 * Since ip_wput() isn't close to finished, we fill
8960 		 * in enough of the header for credible error reporting.
8961 		 */
8962 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8963 			/* Failed */
8964 			MULTIRT_DEBUG_UNTAG(first_mp);
8965 			freemsg(first_mp);
8966 			if (ire != NULL)
8967 				ire_refrele(ire);
8968 			return;
8969 		}
8970 	}
8971 
8972 	/*
8973 	 * At this point we will have ire only if RTF_BLACKHOLE
8974 	 * or RTF_REJECT flags are set on the IRE. It will not
8975 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8976 	 */
8977 	if (ire != NULL) {
8978 		if (ire->ire_flags & RTF_BLACKHOLE) {
8979 			ire_refrele(ire);
8980 			MULTIRT_DEBUG_UNTAG(first_mp);
8981 			freemsg(first_mp);
8982 			return;
8983 		}
8984 		ire_refrele(ire);
8985 	}
8986 	if (ip_source_routed(ipha, ipst)) {
8987 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8988 		    zoneid, ipst);
8989 		return;
8990 	}
8991 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8992 }
8993 
8994 ip_opt_info_t zero_info;
8995 
8996 /*
8997  * IPv4 -
8998  * ip_newroute_ipif is called by ip_wput_multicast and
8999  * ip_rput_forward_multicast whenever we need to send
9000  * out a packet to a destination address for which we do not have specific
9001  * routing information. It is used when the packet will be sent out
9002  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9003  * socket option is set or icmp error message wants to go out on a particular
9004  * interface for a unicast packet.
9005  *
9006  * In most cases, the destination address is resolved thanks to the ipif
9007  * intrinsic resolver. However, there are some cases where the call to
9008  * ip_newroute_ipif must take into account the potential presence of
9009  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9010  * that uses the interface. This is specified through flags,
9011  * which can be a combination of:
9012  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9013  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9014  *   and flags. Additionally, the packet source address has to be set to
9015  *   the specified address. The caller is thus expected to set this flag
9016  *   if the packet has no specific source address yet.
9017  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9018  *   flag, the resulting ire will inherit the flag. All unresolved routes
9019  *   to the destination must be explored in the same call to
9020  *   ip_newroute_ipif().
9021  */
9022 static void
9023 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9024     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9025 {
9026 	areq_t	*areq;
9027 	ire_t	*ire = NULL;
9028 	mblk_t	*res_mp;
9029 	ipaddr_t *addrp;
9030 	mblk_t *first_mp;
9031 	ire_t	*save_ire = NULL;
9032 	ipif_t	*src_ipif = NULL;
9033 	ushort_t ire_marks = 0;
9034 	ill_t	*dst_ill = NULL;
9035 	ipha_t *ipha;
9036 	mblk_t	*saved_mp;
9037 	ire_t   *fire = NULL;
9038 	mblk_t  *copy_mp = NULL;
9039 	boolean_t multirt_resolve_next;
9040 	boolean_t unspec_src;
9041 	ipaddr_t ipha_dst;
9042 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9043 
9044 	/*
9045 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9046 	 * here for uniformity
9047 	 */
9048 	ipif_refhold(ipif);
9049 
9050 	/*
9051 	 * This loop is run only once in most cases.
9052 	 * We loop to resolve further routes only when the destination
9053 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9054 	 */
9055 	do {
9056 		if (dst_ill != NULL) {
9057 			ill_refrele(dst_ill);
9058 			dst_ill = NULL;
9059 		}
9060 		if (src_ipif != NULL) {
9061 			ipif_refrele(src_ipif);
9062 			src_ipif = NULL;
9063 		}
9064 		multirt_resolve_next = B_FALSE;
9065 
9066 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9067 		    ipif->ipif_ill->ill_name));
9068 
9069 		first_mp = mp;
9070 		if (DB_TYPE(mp) == M_CTL)
9071 			mp = mp->b_cont;
9072 		ipha = (ipha_t *)mp->b_rptr;
9073 
9074 		/*
9075 		 * Save the packet destination address, we may need it after
9076 		 * the packet has been consumed.
9077 		 */
9078 		ipha_dst = ipha->ipha_dst;
9079 
9080 		/*
9081 		 * If the interface is a pt-pt interface we look for an
9082 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9083 		 * local_address and the pt-pt destination address. Otherwise
9084 		 * we just match the local address.
9085 		 * NOTE: dst could be different than ipha->ipha_dst in case
9086 		 * of sending igmp multicast packets over a point-to-point
9087 		 * connection.
9088 		 * Thus we must be careful enough to check ipha_dst to be a
9089 		 * multicast address, otherwise it will take xmit_if path for
9090 		 * multicast packets resulting into kernel stack overflow by
9091 		 * repeated calls to ip_newroute_ipif from ire_send().
9092 		 */
9093 		if (CLASSD(ipha_dst) &&
9094 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9095 			goto err_ret;
9096 		}
9097 
9098 		/*
9099 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9100 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9101 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9102 		 * propagate its flags to the new ire.
9103 		 */
9104 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9105 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9106 			ip2dbg(("ip_newroute_ipif: "
9107 			    "ipif_lookup_multi_ire("
9108 			    "ipif %p, dst %08x) = fire %p\n",
9109 			    (void *)ipif, ntohl(dst), (void *)fire));
9110 		}
9111 
9112 		/*
9113 		 * Note: While we pick a dst_ill we are really only
9114 		 * interested in the ill for load spreading. The source
9115 		 * ipif is determined by source address selection below.
9116 		 */
9117 		if (IS_IPMP(ipif->ipif_ill)) {
9118 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9119 
9120 			if (CLASSD(ipha_dst))
9121 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9122 			else
9123 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9124 		} else {
9125 			dst_ill = ipif->ipif_ill;
9126 			ill_refhold(dst_ill);
9127 		}
9128 
9129 		if (dst_ill == NULL) {
9130 			if (ip_debug > 2) {
9131 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9132 				    "for dst %s\n", AF_INET, &dst);
9133 			}
9134 			goto err_ret;
9135 		}
9136 
9137 		/*
9138 		 * Pick a source address preferring non-deprecated ones.
9139 		 * Unlike ip_newroute, we don't do any source address
9140 		 * selection here since for multicast it really does not help
9141 		 * in inbound load spreading as in the unicast case.
9142 		 */
9143 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9144 		    (fire->ire_flags & RTF_SETSRC)) {
9145 			/*
9146 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9147 			 * on that interface. This ire has RTF_SETSRC flag, so
9148 			 * the source address of the packet must be changed.
9149 			 * Check that the ipif matching the requested source
9150 			 * address still exists.
9151 			 */
9152 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9153 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9154 		}
9155 
9156 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9157 
9158 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9159 		    (IS_IPMP(ipif->ipif_ill) ||
9160 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9161 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9162 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9163 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9164 		    (src_ipif == NULL) &&
9165 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9166 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9167 			if (src_ipif == NULL) {
9168 				if (ip_debug > 2) {
9169 					/* ip1dbg */
9170 					pr_addr_dbg("ip_newroute_ipif: "
9171 					    "no src for dst %s",
9172 					    AF_INET, &dst);
9173 				}
9174 				ip1dbg((" on interface %s\n",
9175 				    dst_ill->ill_name));
9176 				goto err_ret;
9177 			}
9178 			ipif_refrele(ipif);
9179 			ipif = src_ipif;
9180 			ipif_refhold(ipif);
9181 		}
9182 		if (src_ipif == NULL) {
9183 			src_ipif = ipif;
9184 			ipif_refhold(src_ipif);
9185 		}
9186 
9187 		/*
9188 		 * Assign a source address while we have the conn.
9189 		 * We can't have ip_wput_ire pick a source address when the
9190 		 * packet returns from arp since conn_unspec_src might be set
9191 		 * and we lose the conn when going through arp.
9192 		 */
9193 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9194 			ipha->ipha_src = src_ipif->ipif_src_addr;
9195 
9196 		/*
9197 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9198 		 * that the outgoing interface does not have an interface ire.
9199 		 */
9200 		if (CLASSD(ipha_dst) && (connp == NULL ||
9201 		    connp->conn_outgoing_ill == NULL) &&
9202 		    infop->ip_opt_ill_index == 0) {
9203 			/* ipif_to_ire returns an held ire */
9204 			ire = ipif_to_ire(ipif);
9205 			if (ire == NULL)
9206 				goto err_ret;
9207 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9208 				goto err_ret;
9209 			save_ire = ire;
9210 
9211 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9212 			    "flags %04x\n",
9213 			    (void *)ire, (void *)ipif, flags));
9214 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9215 			    (fire->ire_flags & RTF_MULTIRT)) {
9216 				/*
9217 				 * As requested by flags, an IRE_OFFSUBNET was
9218 				 * looked up on that interface. This ire has
9219 				 * RTF_MULTIRT flag, so the resolution loop will
9220 				 * be re-entered to resolve additional routes on
9221 				 * other interfaces. For that purpose, a copy of
9222 				 * the packet is performed at this point.
9223 				 */
9224 				fire->ire_last_used_time = lbolt;
9225 				copy_mp = copymsg(first_mp);
9226 				if (copy_mp) {
9227 					MULTIRT_DEBUG_TAG(copy_mp);
9228 				}
9229 			}
9230 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9231 			    (fire->ire_flags & RTF_SETSRC)) {
9232 				/*
9233 				 * As requested by flags, an IRE_OFFSUBET was
9234 				 * looked up on that interface. This ire has
9235 				 * RTF_SETSRC flag, so the source address of the
9236 				 * packet must be changed.
9237 				 */
9238 				ipha->ipha_src = fire->ire_src_addr;
9239 			}
9240 		} else {
9241 			/*
9242 			 * The only ways we can come here are:
9243 			 * 1) IP_BOUND_IF socket option is set
9244 			 * 2) SO_DONTROUTE socket option is set
9245 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9246 			 * In all cases, the new ire will not be added
9247 			 * into cache table.
9248 			 */
9249 			ASSERT(connp == NULL || connp->conn_dontroute ||
9250 			    connp->conn_outgoing_ill != NULL ||
9251 			    infop->ip_opt_ill_index != 0);
9252 			ire_marks |= IRE_MARK_NOADD;
9253 		}
9254 
9255 		switch (ipif->ipif_net_type) {
9256 		case IRE_IF_NORESOLVER: {
9257 			/* We have what we need to build an IRE_CACHE. */
9258 
9259 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9260 			    (dst_ill->ill_resolver_mp == NULL)) {
9261 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9262 				    "for IRE_IF_NORESOLVER ire %p has "
9263 				    "no ill_resolver_mp\n",
9264 				    (void *)dst_ill, (void *)ire));
9265 				break;
9266 			}
9267 
9268 			/*
9269 			 * The new ire inherits the IRE_OFFSUBNET flags
9270 			 * and source address, if this was requested.
9271 			 */
9272 			ire = ire_create(
9273 			    (uchar_t *)&dst,		/* dest address */
9274 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9275 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9276 			    NULL,			/* gateway address */
9277 			    &ipif->ipif_mtu,
9278 			    NULL,			/* no src nce */
9279 			    dst_ill->ill_rq,		/* recv-from queue */
9280 			    dst_ill->ill_wq,		/* send-to queue */
9281 			    IRE_CACHE,
9282 			    src_ipif,
9283 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9284 			    (fire != NULL) ?		/* Parent handle */
9285 			    fire->ire_phandle : 0,
9286 			    (save_ire != NULL) ?	/* Interface handle */
9287 			    save_ire->ire_ihandle : 0,
9288 			    (fire != NULL) ?
9289 			    (fire->ire_flags &
9290 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9291 			    (save_ire == NULL ? &ire_uinfo_null :
9292 			    &save_ire->ire_uinfo),
9293 			    NULL,
9294 			    NULL,
9295 			    ipst);
9296 
9297 			if (ire == NULL) {
9298 				if (save_ire != NULL)
9299 					ire_refrele(save_ire);
9300 				break;
9301 			}
9302 
9303 			ire->ire_marks |= ire_marks;
9304 
9305 			/*
9306 			 * If IRE_MARK_NOADD is set then we need to convert
9307 			 * the max_fragp to a useable value now. This is
9308 			 * normally done in ire_add_v[46]. We also need to
9309 			 * associate the ire with an nce (normally would be
9310 			 * done in ip_wput_nondata()).
9311 			 *
9312 			 * Note that IRE_MARK_NOADD packets created here
9313 			 * do not have a non-null ire_mp pointer. The null
9314 			 * value of ire_bucket indicates that they were
9315 			 * never added.
9316 			 */
9317 			if (ire->ire_marks & IRE_MARK_NOADD) {
9318 				uint_t  max_frag;
9319 
9320 				max_frag = *ire->ire_max_fragp;
9321 				ire->ire_max_fragp = NULL;
9322 				ire->ire_max_frag = max_frag;
9323 
9324 				if ((ire->ire_nce = ndp_lookup_v4(
9325 				    ire_to_ill(ire),
9326 				    (ire->ire_gateway_addr != INADDR_ANY ?
9327 				    &ire->ire_gateway_addr : &ire->ire_addr),
9328 				    B_FALSE)) == NULL) {
9329 					if (save_ire != NULL)
9330 						ire_refrele(save_ire);
9331 					break;
9332 				}
9333 				ASSERT(ire->ire_nce->nce_state ==
9334 				    ND_REACHABLE);
9335 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9336 			}
9337 
9338 			/* Prevent save_ire from getting deleted */
9339 			if (save_ire != NULL) {
9340 				IRB_REFHOLD(save_ire->ire_bucket);
9341 				/* Has it been removed already ? */
9342 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9343 					IRB_REFRELE(save_ire->ire_bucket);
9344 					ire_refrele(save_ire);
9345 					break;
9346 				}
9347 			}
9348 
9349 			ire_add_then_send(q, ire, first_mp);
9350 
9351 			/* Assert that save_ire is not deleted yet. */
9352 			if (save_ire != NULL) {
9353 				ASSERT(save_ire->ire_ptpn != NULL);
9354 				IRB_REFRELE(save_ire->ire_bucket);
9355 				ire_refrele(save_ire);
9356 				save_ire = NULL;
9357 			}
9358 			if (fire != NULL) {
9359 				ire_refrele(fire);
9360 				fire = NULL;
9361 			}
9362 
9363 			/*
9364 			 * the resolution loop is re-entered if this
9365 			 * was requested through flags and if we
9366 			 * actually are in a multirouting case.
9367 			 */
9368 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9369 				boolean_t need_resolve =
9370 				    ire_multirt_need_resolve(ipha_dst,
9371 				    msg_getlabel(copy_mp), ipst);
9372 				if (!need_resolve) {
9373 					MULTIRT_DEBUG_UNTAG(copy_mp);
9374 					freemsg(copy_mp);
9375 					copy_mp = NULL;
9376 				} else {
9377 					/*
9378 					 * ipif_lookup_group() calls
9379 					 * ire_lookup_multi() that uses
9380 					 * ire_ftable_lookup() to find
9381 					 * an IRE_INTERFACE for the group.
9382 					 * In the multirt case,
9383 					 * ire_lookup_multi() then invokes
9384 					 * ire_multirt_lookup() to find
9385 					 * the next resolvable ire.
9386 					 * As a result, we obtain an new
9387 					 * interface, derived from the
9388 					 * next ire.
9389 					 */
9390 					ipif_refrele(ipif);
9391 					ipif = ipif_lookup_group(ipha_dst,
9392 					    zoneid, ipst);
9393 					ip2dbg(("ip_newroute_ipif: "
9394 					    "multirt dst %08x, ipif %p\n",
9395 					    htonl(dst), (void *)ipif));
9396 					if (ipif != NULL) {
9397 						mp = copy_mp;
9398 						copy_mp = NULL;
9399 						multirt_resolve_next = B_TRUE;
9400 						continue;
9401 					} else {
9402 						freemsg(copy_mp);
9403 					}
9404 				}
9405 			}
9406 			if (ipif != NULL)
9407 				ipif_refrele(ipif);
9408 			ill_refrele(dst_ill);
9409 			ipif_refrele(src_ipif);
9410 			return;
9411 		}
9412 		case IRE_IF_RESOLVER:
9413 			/*
9414 			 * We can't build an IRE_CACHE yet, but at least
9415 			 * we found a resolver that can help.
9416 			 */
9417 			res_mp = dst_ill->ill_resolver_mp;
9418 			if (!OK_RESOLVER_MP(res_mp))
9419 				break;
9420 
9421 			/*
9422 			 * We obtain a partial IRE_CACHE which we will pass
9423 			 * along with the resolver query.  When the response
9424 			 * comes back it will be there ready for us to add.
9425 			 * The new ire inherits the IRE_OFFSUBNET flags
9426 			 * and source address, if this was requested.
9427 			 * The ire_max_frag is atomically set under the
9428 			 * irebucket lock in ire_add_v[46]. Only in the
9429 			 * case of IRE_MARK_NOADD, we set it here itself.
9430 			 */
9431 			ire = ire_create_mp(
9432 			    (uchar_t *)&dst,		/* dest address */
9433 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9434 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9435 			    NULL,			/* gateway address */
9436 			    (ire_marks & IRE_MARK_NOADD) ?
9437 			    ipif->ipif_mtu : 0,		/* max_frag */
9438 			    NULL,			/* no src nce */
9439 			    dst_ill->ill_rq,		/* recv-from queue */
9440 			    dst_ill->ill_wq,		/* send-to queue */
9441 			    IRE_CACHE,
9442 			    src_ipif,
9443 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9444 			    (fire != NULL) ?		/* Parent handle */
9445 			    fire->ire_phandle : 0,
9446 			    (save_ire != NULL) ?	/* Interface handle */
9447 			    save_ire->ire_ihandle : 0,
9448 			    (fire != NULL) ?		/* flags if any */
9449 			    (fire->ire_flags &
9450 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9451 			    (save_ire == NULL ? &ire_uinfo_null :
9452 			    &save_ire->ire_uinfo),
9453 			    NULL,
9454 			    NULL,
9455 			    ipst);
9456 
9457 			if (save_ire != NULL) {
9458 				ire_refrele(save_ire);
9459 				save_ire = NULL;
9460 			}
9461 			if (ire == NULL)
9462 				break;
9463 
9464 			ire->ire_marks |= ire_marks;
9465 			/*
9466 			 * Construct message chain for the resolver of the
9467 			 * form:
9468 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9469 			 *
9470 			 * NOTE : ire will be added later when the response
9471 			 * comes back from ARP. If the response does not
9472 			 * come back, ARP frees the packet. For this reason,
9473 			 * we can't REFHOLD the bucket of save_ire to prevent
9474 			 * deletions. We may not be able to REFRELE the
9475 			 * bucket if the response never comes back.
9476 			 * Thus, before adding the ire, ire_add_v4 will make
9477 			 * sure that the interface route does not get deleted.
9478 			 * This is the only case unlike ip_newroute_v6,
9479 			 * ip_newroute_ipif_v6 where we can always prevent
9480 			 * deletions because ire_add_then_send is called after
9481 			 * creating the IRE.
9482 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9483 			 * does not add this IRE into the IRE CACHE.
9484 			 */
9485 			ASSERT(ire->ire_mp != NULL);
9486 			ire->ire_mp->b_cont = first_mp;
9487 			/* Have saved_mp handy, for cleanup if canput fails */
9488 			saved_mp = mp;
9489 			mp = copyb(res_mp);
9490 			if (mp == NULL) {
9491 				/* Prepare for cleanup */
9492 				mp = saved_mp; /* pkt */
9493 				ire_delete(ire); /* ire_mp */
9494 				ire = NULL;
9495 				if (copy_mp != NULL) {
9496 					MULTIRT_DEBUG_UNTAG(copy_mp);
9497 					freemsg(copy_mp);
9498 					copy_mp = NULL;
9499 				}
9500 				break;
9501 			}
9502 			linkb(mp, ire->ire_mp);
9503 
9504 			/*
9505 			 * Fill in the source and dest addrs for the resolver.
9506 			 * NOTE: this depends on memory layouts imposed by
9507 			 * ill_init().  There are corner cases above where we
9508 			 * might've created the IRE with an INADDR_ANY source
9509 			 * address (e.g., if the zeroth ipif on an underlying
9510 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9511 			 * on the ill has a usable test address).  If so, tell
9512 			 * ARP to use ipha_src as its sender address.
9513 			 */
9514 			areq = (areq_t *)mp->b_rptr;
9515 			addrp = (ipaddr_t *)((char *)areq +
9516 			    areq->areq_sender_addr_offset);
9517 			if (ire->ire_src_addr != INADDR_ANY)
9518 				*addrp = ire->ire_src_addr;
9519 			else
9520 				*addrp = ipha->ipha_src;
9521 			addrp = (ipaddr_t *)((char *)areq +
9522 			    areq->areq_target_addr_offset);
9523 			*addrp = dst;
9524 			/* Up to the resolver. */
9525 			if (canputnext(dst_ill->ill_rq) &&
9526 			    !(dst_ill->ill_arp_closing)) {
9527 				putnext(dst_ill->ill_rq, mp);
9528 				/*
9529 				 * The response will come back in ip_wput
9530 				 * with db_type IRE_DB_TYPE.
9531 				 */
9532 			} else {
9533 				mp->b_cont = NULL;
9534 				freeb(mp); /* areq */
9535 				ire_delete(ire); /* ire_mp */
9536 				saved_mp->b_next = NULL;
9537 				saved_mp->b_prev = NULL;
9538 				freemsg(first_mp); /* pkt */
9539 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9540 			}
9541 
9542 			if (fire != NULL) {
9543 				ire_refrele(fire);
9544 				fire = NULL;
9545 			}
9546 
9547 			/*
9548 			 * The resolution loop is re-entered if this was
9549 			 * requested through flags and we actually are
9550 			 * in a multirouting case.
9551 			 */
9552 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9553 				boolean_t need_resolve =
9554 				    ire_multirt_need_resolve(ipha_dst,
9555 				    msg_getlabel(copy_mp), ipst);
9556 				if (!need_resolve) {
9557 					MULTIRT_DEBUG_UNTAG(copy_mp);
9558 					freemsg(copy_mp);
9559 					copy_mp = NULL;
9560 				} else {
9561 					/*
9562 					 * ipif_lookup_group() calls
9563 					 * ire_lookup_multi() that uses
9564 					 * ire_ftable_lookup() to find
9565 					 * an IRE_INTERFACE for the group.
9566 					 * In the multirt case,
9567 					 * ire_lookup_multi() then invokes
9568 					 * ire_multirt_lookup() to find
9569 					 * the next resolvable ire.
9570 					 * As a result, we obtain an new
9571 					 * interface, derived from the
9572 					 * next ire.
9573 					 */
9574 					ipif_refrele(ipif);
9575 					ipif = ipif_lookup_group(ipha_dst,
9576 					    zoneid, ipst);
9577 					if (ipif != NULL) {
9578 						mp = copy_mp;
9579 						copy_mp = NULL;
9580 						multirt_resolve_next = B_TRUE;
9581 						continue;
9582 					} else {
9583 						freemsg(copy_mp);
9584 					}
9585 				}
9586 			}
9587 			if (ipif != NULL)
9588 				ipif_refrele(ipif);
9589 			ill_refrele(dst_ill);
9590 			ipif_refrele(src_ipif);
9591 			return;
9592 		default:
9593 			break;
9594 		}
9595 	} while (multirt_resolve_next);
9596 
9597 err_ret:
9598 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9599 	if (fire != NULL)
9600 		ire_refrele(fire);
9601 	ipif_refrele(ipif);
9602 	/* Did this packet originate externally? */
9603 	if (dst_ill != NULL)
9604 		ill_refrele(dst_ill);
9605 	if (src_ipif != NULL)
9606 		ipif_refrele(src_ipif);
9607 	if (mp->b_prev || mp->b_next) {
9608 		mp->b_next = NULL;
9609 		mp->b_prev = NULL;
9610 	} else {
9611 		/*
9612 		 * Since ip_wput() isn't close to finished, we fill
9613 		 * in enough of the header for credible error reporting.
9614 		 */
9615 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9616 			/* Failed */
9617 			freemsg(first_mp);
9618 			if (ire != NULL)
9619 				ire_refrele(ire);
9620 			return;
9621 		}
9622 	}
9623 	/*
9624 	 * At this point we will have ire only if RTF_BLACKHOLE
9625 	 * or RTF_REJECT flags are set on the IRE. It will not
9626 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9627 	 */
9628 	if (ire != NULL) {
9629 		if (ire->ire_flags & RTF_BLACKHOLE) {
9630 			ire_refrele(ire);
9631 			freemsg(first_mp);
9632 			return;
9633 		}
9634 		ire_refrele(ire);
9635 	}
9636 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9637 }
9638 
9639 /* Name/Value Table Lookup Routine */
9640 char *
9641 ip_nv_lookup(nv_t *nv, int value)
9642 {
9643 	if (!nv)
9644 		return (NULL);
9645 	for (; nv->nv_name; nv++) {
9646 		if (nv->nv_value == value)
9647 			return (nv->nv_name);
9648 	}
9649 	return ("unknown");
9650 }
9651 
9652 /*
9653  * This is a module open, i.e. this is a control stream for access
9654  * to a DLPI device.  We allocate an ill_t as the instance data in
9655  * this case.
9656  */
9657 int
9658 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9659 {
9660 	ill_t	*ill;
9661 	int	err;
9662 	zoneid_t zoneid;
9663 	netstack_t *ns;
9664 	ip_stack_t *ipst;
9665 
9666 	/*
9667 	 * Prevent unprivileged processes from pushing IP so that
9668 	 * they can't send raw IP.
9669 	 */
9670 	if (secpolicy_net_rawaccess(credp) != 0)
9671 		return (EPERM);
9672 
9673 	ns = netstack_find_by_cred(credp);
9674 	ASSERT(ns != NULL);
9675 	ipst = ns->netstack_ip;
9676 	ASSERT(ipst != NULL);
9677 
9678 	/*
9679 	 * For exclusive stacks we set the zoneid to zero
9680 	 * to make IP operate as if in the global zone.
9681 	 */
9682 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9683 		zoneid = GLOBAL_ZONEID;
9684 	else
9685 		zoneid = crgetzoneid(credp);
9686 
9687 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9688 	q->q_ptr = WR(q)->q_ptr = ill;
9689 	ill->ill_ipst = ipst;
9690 	ill->ill_zoneid = zoneid;
9691 
9692 	/*
9693 	 * ill_init initializes the ill fields and then sends down
9694 	 * down a DL_INFO_REQ after calling qprocson.
9695 	 */
9696 	err = ill_init(q, ill);
9697 	if (err != 0) {
9698 		mi_free(ill);
9699 		netstack_rele(ipst->ips_netstack);
9700 		q->q_ptr = NULL;
9701 		WR(q)->q_ptr = NULL;
9702 		return (err);
9703 	}
9704 
9705 	/* ill_init initializes the ipsq marking this thread as writer */
9706 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9707 	/* Wait for the DL_INFO_ACK */
9708 	mutex_enter(&ill->ill_lock);
9709 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9710 		/*
9711 		 * Return value of 0 indicates a pending signal.
9712 		 */
9713 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9714 		if (err == 0) {
9715 			mutex_exit(&ill->ill_lock);
9716 			(void) ip_close(q, 0);
9717 			return (EINTR);
9718 		}
9719 	}
9720 	mutex_exit(&ill->ill_lock);
9721 
9722 	/*
9723 	 * ip_rput_other could have set an error  in ill_error on
9724 	 * receipt of M_ERROR.
9725 	 */
9726 
9727 	err = ill->ill_error;
9728 	if (err != 0) {
9729 		(void) ip_close(q, 0);
9730 		return (err);
9731 	}
9732 
9733 	ill->ill_credp = credp;
9734 	crhold(credp);
9735 
9736 	mutex_enter(&ipst->ips_ip_mi_lock);
9737 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9738 	    credp);
9739 	mutex_exit(&ipst->ips_ip_mi_lock);
9740 	if (err) {
9741 		(void) ip_close(q, 0);
9742 		return (err);
9743 	}
9744 	return (0);
9745 }
9746 
9747 /* For /dev/ip aka AF_INET open */
9748 int
9749 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9750 {
9751 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9752 }
9753 
9754 /* For /dev/ip6 aka AF_INET6 open */
9755 int
9756 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9757 {
9758 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9759 }
9760 
9761 /* IP open routine. */
9762 int
9763 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9764     boolean_t isv6)
9765 {
9766 	conn_t 		*connp;
9767 	major_t		maj;
9768 	zoneid_t	zoneid;
9769 	netstack_t	*ns;
9770 	ip_stack_t	*ipst;
9771 
9772 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9773 
9774 	/* Allow reopen. */
9775 	if (q->q_ptr != NULL)
9776 		return (0);
9777 
9778 	if (sflag & MODOPEN) {
9779 		/* This is a module open */
9780 		return (ip_modopen(q, devp, flag, sflag, credp));
9781 	}
9782 
9783 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9784 		/*
9785 		 * Non streams based socket looking for a stream
9786 		 * to access IP
9787 		 */
9788 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9789 		    credp, isv6));
9790 	}
9791 
9792 	ns = netstack_find_by_cred(credp);
9793 	ASSERT(ns != NULL);
9794 	ipst = ns->netstack_ip;
9795 	ASSERT(ipst != NULL);
9796 
9797 	/*
9798 	 * For exclusive stacks we set the zoneid to zero
9799 	 * to make IP operate as if in the global zone.
9800 	 */
9801 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9802 		zoneid = GLOBAL_ZONEID;
9803 	else
9804 		zoneid = crgetzoneid(credp);
9805 
9806 	/*
9807 	 * We are opening as a device. This is an IP client stream, and we
9808 	 * allocate an conn_t as the instance data.
9809 	 */
9810 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9811 
9812 	/*
9813 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9814 	 * done by netstack_find_by_cred()
9815 	 */
9816 	netstack_rele(ipst->ips_netstack);
9817 
9818 	connp->conn_zoneid = zoneid;
9819 	connp->conn_sqp = NULL;
9820 	connp->conn_initial_sqp = NULL;
9821 	connp->conn_final_sqp = NULL;
9822 
9823 	connp->conn_upq = q;
9824 	q->q_ptr = WR(q)->q_ptr = connp;
9825 
9826 	if (flag & SO_SOCKSTR)
9827 		connp->conn_flags |= IPCL_SOCKET;
9828 
9829 	/* Minor tells us which /dev entry was opened */
9830 	if (isv6) {
9831 		connp->conn_flags |= IPCL_ISV6;
9832 		connp->conn_af_isv6 = B_TRUE;
9833 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9834 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9835 	} else {
9836 		connp->conn_af_isv6 = B_FALSE;
9837 		connp->conn_pkt_isv6 = B_FALSE;
9838 	}
9839 
9840 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9841 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9842 		connp->conn_minor_arena = ip_minor_arena_la;
9843 	} else {
9844 		/*
9845 		 * Either minor numbers in the large arena were exhausted
9846 		 * or a non socket application is doing the open.
9847 		 * Try to allocate from the small arena.
9848 		 */
9849 		if ((connp->conn_dev =
9850 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9851 			/* CONN_DEC_REF takes care of netstack_rele() */
9852 			q->q_ptr = WR(q)->q_ptr = NULL;
9853 			CONN_DEC_REF(connp);
9854 			return (EBUSY);
9855 		}
9856 		connp->conn_minor_arena = ip_minor_arena_sa;
9857 	}
9858 
9859 	maj = getemajor(*devp);
9860 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9861 
9862 	/*
9863 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9864 	 */
9865 	connp->conn_cred = credp;
9866 
9867 	/*
9868 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9869 	 */
9870 	connp->conn_recv = ip_conn_input;
9871 
9872 	crhold(connp->conn_cred);
9873 
9874 	/*
9875 	 * If the caller has the process-wide flag set, then default to MAC
9876 	 * exempt mode.  This allows read-down to unlabeled hosts.
9877 	 */
9878 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9879 		connp->conn_mac_exempt = B_TRUE;
9880 
9881 	connp->conn_rq = q;
9882 	connp->conn_wq = WR(q);
9883 
9884 	/* Non-zero default values */
9885 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9886 
9887 	/*
9888 	 * Make the conn globally visible to walkers
9889 	 */
9890 	ASSERT(connp->conn_ref == 1);
9891 	mutex_enter(&connp->conn_lock);
9892 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9893 	mutex_exit(&connp->conn_lock);
9894 
9895 	qprocson(q);
9896 
9897 	return (0);
9898 }
9899 
9900 /*
9901  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9902  * Note that there is no race since either ip_output function works - it
9903  * is just an optimization to enter the best ip_output routine directly.
9904  */
9905 void
9906 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9907     ip_stack_t *ipst)
9908 {
9909 	if (isv6)  {
9910 		if (bump_mib) {
9911 			BUMP_MIB(&ipst->ips_ip6_mib,
9912 			    ipIfStatsOutSwitchIPVersion);
9913 		}
9914 		connp->conn_send = ip_output_v6;
9915 		connp->conn_pkt_isv6 = B_TRUE;
9916 	} else {
9917 		if (bump_mib) {
9918 			BUMP_MIB(&ipst->ips_ip_mib,
9919 			    ipIfStatsOutSwitchIPVersion);
9920 		}
9921 		connp->conn_send = ip_output;
9922 		connp->conn_pkt_isv6 = B_FALSE;
9923 	}
9924 
9925 }
9926 
9927 /*
9928  * See if IPsec needs loading because of the options in mp.
9929  */
9930 static boolean_t
9931 ipsec_opt_present(mblk_t *mp)
9932 {
9933 	uint8_t *optcp, *next_optcp, *opt_endcp;
9934 	struct opthdr *opt;
9935 	struct T_opthdr *topt;
9936 	int opthdr_len;
9937 	t_uscalar_t optname, optlevel;
9938 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9939 	ipsec_req_t *ipsr;
9940 
9941 	/*
9942 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9943 	 * return TRUE.
9944 	 */
9945 
9946 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9947 	opt_endcp = optcp + tor->OPT_length;
9948 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9949 		opthdr_len = sizeof (struct T_opthdr);
9950 	} else {		/* O_OPTMGMT_REQ */
9951 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9952 		opthdr_len = sizeof (struct opthdr);
9953 	}
9954 	for (; optcp < opt_endcp; optcp = next_optcp) {
9955 		if (optcp + opthdr_len > opt_endcp)
9956 			return (B_FALSE);	/* Not enough option header. */
9957 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9958 			topt = (struct T_opthdr *)optcp;
9959 			optlevel = topt->level;
9960 			optname = topt->name;
9961 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9962 		} else {
9963 			opt = (struct opthdr *)optcp;
9964 			optlevel = opt->level;
9965 			optname = opt->name;
9966 			next_optcp = optcp + opthdr_len +
9967 			    _TPI_ALIGN_OPT(opt->len);
9968 		}
9969 		if ((next_optcp < optcp) || /* wraparound pointer space */
9970 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9971 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9972 			return (B_FALSE); /* bad option buffer */
9973 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9974 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9975 			/*
9976 			 * Check to see if it's an all-bypass or all-zeroes
9977 			 * IPsec request.  Don't bother loading IPsec if
9978 			 * the socket doesn't want to use it.  (A good example
9979 			 * is a bypass request.)
9980 			 *
9981 			 * Basically, if any of the non-NEVER bits are set,
9982 			 * load IPsec.
9983 			 */
9984 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9985 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9986 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9987 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9988 			    != 0)
9989 				return (B_TRUE);
9990 		}
9991 	}
9992 	return (B_FALSE);
9993 }
9994 
9995 /*
9996  * If conn is is waiting for ipsec to finish loading, kick it.
9997  */
9998 /* ARGSUSED */
9999 static void
10000 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10001 {
10002 	t_scalar_t	optreq_prim;
10003 	mblk_t		*mp;
10004 	cred_t		*cr;
10005 	int		err = 0;
10006 
10007 	/*
10008 	 * This function is called, after ipsec loading is complete.
10009 	 * Since IP checks exclusively and atomically (i.e it prevents
10010 	 * ipsec load from completing until ip_optcom_req completes)
10011 	 * whether ipsec load is complete, there cannot be a race with IP
10012 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10013 	 */
10014 	mutex_enter(&connp->conn_lock);
10015 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10016 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10017 		mp = connp->conn_ipsec_opt_mp;
10018 		connp->conn_ipsec_opt_mp = NULL;
10019 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10020 		mutex_exit(&connp->conn_lock);
10021 
10022 		/*
10023 		 * All Solaris components should pass a db_credp
10024 		 * for this TPI message, hence we ASSERT.
10025 		 * But in case there is some other M_PROTO that looks
10026 		 * like a TPI message sent by some other kernel
10027 		 * component, we check and return an error.
10028 		 */
10029 		cr = msg_getcred(mp, NULL);
10030 		ASSERT(cr != NULL);
10031 		if (cr == NULL) {
10032 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10033 			if (mp != NULL)
10034 				qreply(connp->conn_wq, mp);
10035 			return;
10036 		}
10037 
10038 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10039 
10040 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10041 		if (optreq_prim == T_OPTMGMT_REQ) {
10042 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10043 			    &ip_opt_obj, B_FALSE);
10044 		} else {
10045 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10046 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10047 			    &ip_opt_obj, B_FALSE);
10048 		}
10049 		if (err != EINPROGRESS)
10050 			CONN_OPER_PENDING_DONE(connp);
10051 		return;
10052 	}
10053 	mutex_exit(&connp->conn_lock);
10054 }
10055 
10056 /*
10057  * Called from the ipsec_loader thread, outside any perimeter, to tell
10058  * ip qenable any of the queues waiting for the ipsec loader to
10059  * complete.
10060  */
10061 void
10062 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10063 {
10064 	netstack_t *ns = ipss->ipsec_netstack;
10065 
10066 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10067 }
10068 
10069 /*
10070  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10071  * determines the grp on which it has to become exclusive, queues the mp
10072  * and IPSQ draining restarts the optmgmt
10073  */
10074 static boolean_t
10075 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10076 {
10077 	conn_t *connp = Q_TO_CONN(q);
10078 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10079 
10080 	/*
10081 	 * Take IPsec requests and treat them special.
10082 	 */
10083 	if (ipsec_opt_present(mp)) {
10084 		/* First check if IPsec is loaded. */
10085 		mutex_enter(&ipss->ipsec_loader_lock);
10086 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10087 			mutex_exit(&ipss->ipsec_loader_lock);
10088 			return (B_FALSE);
10089 		}
10090 		mutex_enter(&connp->conn_lock);
10091 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10092 
10093 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10094 		connp->conn_ipsec_opt_mp = mp;
10095 		mutex_exit(&connp->conn_lock);
10096 		mutex_exit(&ipss->ipsec_loader_lock);
10097 
10098 		ipsec_loader_loadnow(ipss);
10099 		return (B_TRUE);
10100 	}
10101 	return (B_FALSE);
10102 }
10103 
10104 /*
10105  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10106  * all of them are copied to the conn_t. If the req is "zero", the policy is
10107  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10108  * fields.
10109  * We keep only the latest setting of the policy and thus policy setting
10110  * is not incremental/cumulative.
10111  *
10112  * Requests to set policies with multiple alternative actions will
10113  * go through a different API.
10114  */
10115 int
10116 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10117 {
10118 	uint_t ah_req = 0;
10119 	uint_t esp_req = 0;
10120 	uint_t se_req = 0;
10121 	ipsec_selkey_t sel;
10122 	ipsec_act_t *actp = NULL;
10123 	uint_t nact;
10124 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10125 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10126 	ipsec_policy_root_t *pr;
10127 	ipsec_policy_head_t *ph;
10128 	int fam;
10129 	boolean_t is_pol_reset;
10130 	int error = 0;
10131 	netstack_t	*ns = connp->conn_netstack;
10132 	ip_stack_t	*ipst = ns->netstack_ip;
10133 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10134 
10135 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10136 
10137 	/*
10138 	 * The IP_SEC_OPT option does not allow variable length parameters,
10139 	 * hence a request cannot be NULL.
10140 	 */
10141 	if (req == NULL)
10142 		return (EINVAL);
10143 
10144 	ah_req = req->ipsr_ah_req;
10145 	esp_req = req->ipsr_esp_req;
10146 	se_req = req->ipsr_self_encap_req;
10147 
10148 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10149 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10150 		return (EINVAL);
10151 
10152 	/*
10153 	 * Are we dealing with a request to reset the policy (i.e.
10154 	 * zero requests).
10155 	 */
10156 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10157 	    (esp_req & REQ_MASK) == 0 &&
10158 	    (se_req & REQ_MASK) == 0);
10159 
10160 	if (!is_pol_reset) {
10161 		/*
10162 		 * If we couldn't load IPsec, fail with "protocol
10163 		 * not supported".
10164 		 * IPsec may not have been loaded for a request with zero
10165 		 * policies, so we don't fail in this case.
10166 		 */
10167 		mutex_enter(&ipss->ipsec_loader_lock);
10168 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10169 			mutex_exit(&ipss->ipsec_loader_lock);
10170 			return (EPROTONOSUPPORT);
10171 		}
10172 		mutex_exit(&ipss->ipsec_loader_lock);
10173 
10174 		/*
10175 		 * Test for valid requests. Invalid algorithms
10176 		 * need to be tested by IPsec code because new
10177 		 * algorithms can be added dynamically.
10178 		 */
10179 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10180 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10181 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10182 			return (EINVAL);
10183 		}
10184 
10185 		/*
10186 		 * Only privileged users can issue these
10187 		 * requests.
10188 		 */
10189 		if (((ah_req & IPSEC_PREF_NEVER) ||
10190 		    (esp_req & IPSEC_PREF_NEVER) ||
10191 		    (se_req & IPSEC_PREF_NEVER)) &&
10192 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10193 			return (EPERM);
10194 		}
10195 
10196 		/*
10197 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10198 		 * are mutually exclusive.
10199 		 */
10200 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10201 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10202 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10203 			/* Both of them are set */
10204 			return (EINVAL);
10205 		}
10206 	}
10207 
10208 	mutex_enter(&connp->conn_lock);
10209 
10210 	/*
10211 	 * If we have already cached policies in ip_bind_connected*(), don't
10212 	 * let them change now. We cache policies for connections
10213 	 * whose src,dst [addr, port] is known.
10214 	 */
10215 	if (connp->conn_policy_cached) {
10216 		mutex_exit(&connp->conn_lock);
10217 		return (EINVAL);
10218 	}
10219 
10220 	/*
10221 	 * We have a zero policies, reset the connection policy if already
10222 	 * set. This will cause the connection to inherit the
10223 	 * global policy, if any.
10224 	 */
10225 	if (is_pol_reset) {
10226 		if (connp->conn_policy != NULL) {
10227 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10228 			connp->conn_policy = NULL;
10229 		}
10230 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10231 		connp->conn_in_enforce_policy = B_FALSE;
10232 		connp->conn_out_enforce_policy = B_FALSE;
10233 		mutex_exit(&connp->conn_lock);
10234 		return (0);
10235 	}
10236 
10237 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10238 	    ipst->ips_netstack);
10239 	if (ph == NULL)
10240 		goto enomem;
10241 
10242 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10243 	if (actp == NULL)
10244 		goto enomem;
10245 
10246 	/*
10247 	 * Always allocate IPv4 policy entries, since they can also
10248 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10249 	 */
10250 	bzero(&sel, sizeof (sel));
10251 	sel.ipsl_valid = IPSL_IPV4;
10252 
10253 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10254 	    ipst->ips_netstack);
10255 	if (pin4 == NULL)
10256 		goto enomem;
10257 
10258 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10259 	    ipst->ips_netstack);
10260 	if (pout4 == NULL)
10261 		goto enomem;
10262 
10263 	if (connp->conn_af_isv6) {
10264 		/*
10265 		 * We're looking at a v6 socket, also allocate the
10266 		 * v6-specific entries...
10267 		 */
10268 		sel.ipsl_valid = IPSL_IPV6;
10269 		pin6 = ipsec_policy_create(&sel, actp, nact,
10270 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10271 		if (pin6 == NULL)
10272 			goto enomem;
10273 
10274 		pout6 = ipsec_policy_create(&sel, actp, nact,
10275 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10276 		if (pout6 == NULL)
10277 			goto enomem;
10278 
10279 		/*
10280 		 * .. and file them away in the right place.
10281 		 */
10282 		fam = IPSEC_AF_V6;
10283 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10284 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10285 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10286 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10287 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10288 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10289 	}
10290 
10291 	ipsec_actvec_free(actp, nact);
10292 
10293 	/*
10294 	 * File the v4 policies.
10295 	 */
10296 	fam = IPSEC_AF_V4;
10297 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10298 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10299 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10300 
10301 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10302 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10303 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10304 
10305 	/*
10306 	 * If the requests need security, set enforce_policy.
10307 	 * If the requests are IPSEC_PREF_NEVER, one should
10308 	 * still set conn_out_enforce_policy so that an ipsec_out
10309 	 * gets attached in ip_wput. This is needed so that
10310 	 * for connections that we don't cache policy in ip_bind,
10311 	 * if global policy matches in ip_wput_attach_policy, we
10312 	 * don't wrongly inherit global policy. Similarly, we need
10313 	 * to set conn_in_enforce_policy also so that we don't verify
10314 	 * policy wrongly.
10315 	 */
10316 	if ((ah_req & REQ_MASK) != 0 ||
10317 	    (esp_req & REQ_MASK) != 0 ||
10318 	    (se_req & REQ_MASK) != 0) {
10319 		connp->conn_in_enforce_policy = B_TRUE;
10320 		connp->conn_out_enforce_policy = B_TRUE;
10321 		connp->conn_flags |= IPCL_CHECK_POLICY;
10322 	}
10323 
10324 	mutex_exit(&connp->conn_lock);
10325 	return (error);
10326 #undef REQ_MASK
10327 
10328 	/*
10329 	 * Common memory-allocation-failure exit path.
10330 	 */
10331 enomem:
10332 	mutex_exit(&connp->conn_lock);
10333 	if (actp != NULL)
10334 		ipsec_actvec_free(actp, nact);
10335 	if (pin4 != NULL)
10336 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10337 	if (pout4 != NULL)
10338 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10339 	if (pin6 != NULL)
10340 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10341 	if (pout6 != NULL)
10342 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10343 	return (ENOMEM);
10344 }
10345 
10346 /*
10347  * Only for options that pass in an IP addr. Currently only V4 options
10348  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10349  * So this function assumes level is IPPROTO_IP
10350  */
10351 int
10352 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10353     mblk_t *first_mp)
10354 {
10355 	ipif_t *ipif = NULL;
10356 	int error;
10357 	ill_t *ill;
10358 	int zoneid;
10359 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10360 
10361 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10362 
10363 	if (addr != INADDR_ANY || checkonly) {
10364 		ASSERT(connp != NULL);
10365 		zoneid = IPCL_ZONEID(connp);
10366 		if (option == IP_NEXTHOP) {
10367 			ipif = ipif_lookup_onlink_addr(addr,
10368 			    connp->conn_zoneid, ipst);
10369 		} else {
10370 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10371 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10372 			    &error, ipst);
10373 		}
10374 		if (ipif == NULL) {
10375 			if (error == EINPROGRESS)
10376 				return (error);
10377 			if ((option == IP_MULTICAST_IF) ||
10378 			    (option == IP_NEXTHOP))
10379 				return (EHOSTUNREACH);
10380 			else
10381 				return (EINVAL);
10382 		} else if (checkonly) {
10383 			if (option == IP_MULTICAST_IF) {
10384 				ill = ipif->ipif_ill;
10385 				/* not supported by the virtual network iface */
10386 				if (IS_VNI(ill)) {
10387 					ipif_refrele(ipif);
10388 					return (EINVAL);
10389 				}
10390 			}
10391 			ipif_refrele(ipif);
10392 			return (0);
10393 		}
10394 		ill = ipif->ipif_ill;
10395 		mutex_enter(&connp->conn_lock);
10396 		mutex_enter(&ill->ill_lock);
10397 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10398 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10399 			mutex_exit(&ill->ill_lock);
10400 			mutex_exit(&connp->conn_lock);
10401 			ipif_refrele(ipif);
10402 			return (option == IP_MULTICAST_IF ?
10403 			    EHOSTUNREACH : EINVAL);
10404 		}
10405 	} else {
10406 		mutex_enter(&connp->conn_lock);
10407 	}
10408 
10409 	/* None of the options below are supported on the VNI */
10410 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10411 		mutex_exit(&ill->ill_lock);
10412 		mutex_exit(&connp->conn_lock);
10413 		ipif_refrele(ipif);
10414 		return (EINVAL);
10415 	}
10416 
10417 	switch (option) {
10418 	case IP_MULTICAST_IF:
10419 		connp->conn_multicast_ipif = ipif;
10420 		break;
10421 	case IP_NEXTHOP:
10422 		connp->conn_nexthop_v4 = addr;
10423 		connp->conn_nexthop_set = B_TRUE;
10424 		break;
10425 	}
10426 
10427 	if (ipif != NULL) {
10428 		mutex_exit(&ill->ill_lock);
10429 		mutex_exit(&connp->conn_lock);
10430 		ipif_refrele(ipif);
10431 		return (0);
10432 	}
10433 	mutex_exit(&connp->conn_lock);
10434 	/* We succeded in cleared the option */
10435 	return (0);
10436 }
10437 
10438 /*
10439  * For options that pass in an ifindex specifying the ill. V6 options always
10440  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10441  */
10442 int
10443 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10444     int level, int option, mblk_t *first_mp)
10445 {
10446 	ill_t *ill = NULL;
10447 	int error = 0;
10448 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10449 
10450 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10451 	if (ifindex != 0) {
10452 		ASSERT(connp != NULL);
10453 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10454 		    first_mp, ip_restart_optmgmt, &error, ipst);
10455 		if (ill != NULL) {
10456 			if (checkonly) {
10457 				/* not supported by the virtual network iface */
10458 				if (IS_VNI(ill)) {
10459 					ill_refrele(ill);
10460 					return (EINVAL);
10461 				}
10462 				ill_refrele(ill);
10463 				return (0);
10464 			}
10465 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10466 			    0, NULL)) {
10467 				ill_refrele(ill);
10468 				ill = NULL;
10469 				mutex_enter(&connp->conn_lock);
10470 				goto setit;
10471 			}
10472 			mutex_enter(&connp->conn_lock);
10473 			mutex_enter(&ill->ill_lock);
10474 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10475 				mutex_exit(&ill->ill_lock);
10476 				mutex_exit(&connp->conn_lock);
10477 				ill_refrele(ill);
10478 				ill = NULL;
10479 				mutex_enter(&connp->conn_lock);
10480 			}
10481 			goto setit;
10482 		} else if (error == EINPROGRESS) {
10483 			return (error);
10484 		} else {
10485 			error = 0;
10486 		}
10487 	}
10488 	mutex_enter(&connp->conn_lock);
10489 setit:
10490 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10491 
10492 	/*
10493 	 * The options below assume that the ILL (if any) transmits and/or
10494 	 * receives traffic. Neither of which is true for the virtual network
10495 	 * interface, so fail setting these on a VNI.
10496 	 */
10497 	if (IS_VNI(ill)) {
10498 		ASSERT(ill != NULL);
10499 		mutex_exit(&ill->ill_lock);
10500 		mutex_exit(&connp->conn_lock);
10501 		ill_refrele(ill);
10502 		return (EINVAL);
10503 	}
10504 
10505 	if (level == IPPROTO_IP) {
10506 		switch (option) {
10507 		case IP_BOUND_IF:
10508 			connp->conn_incoming_ill = ill;
10509 			connp->conn_outgoing_ill = ill;
10510 			break;
10511 
10512 		case IP_MULTICAST_IF:
10513 			/*
10514 			 * This option is an internal special. The socket
10515 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10516 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10517 			 * specifies an ifindex and we try first on V6 ill's.
10518 			 * If we don't find one, we they try using on v4 ill's
10519 			 * intenally and we come here.
10520 			 */
10521 			if (!checkonly && ill != NULL) {
10522 				ipif_t	*ipif;
10523 				ipif = ill->ill_ipif;
10524 
10525 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10526 					mutex_exit(&ill->ill_lock);
10527 					mutex_exit(&connp->conn_lock);
10528 					ill_refrele(ill);
10529 					ill = NULL;
10530 					mutex_enter(&connp->conn_lock);
10531 				} else {
10532 					connp->conn_multicast_ipif = ipif;
10533 				}
10534 			}
10535 			break;
10536 
10537 		case IP_DHCPINIT_IF:
10538 			if (connp->conn_dhcpinit_ill != NULL) {
10539 				/*
10540 				 * We've locked the conn so conn_cleanup_ill()
10541 				 * cannot clear conn_dhcpinit_ill -- so it's
10542 				 * safe to access the ill.
10543 				 */
10544 				ill_t *oill = connp->conn_dhcpinit_ill;
10545 
10546 				ASSERT(oill->ill_dhcpinit != 0);
10547 				atomic_dec_32(&oill->ill_dhcpinit);
10548 				connp->conn_dhcpinit_ill = NULL;
10549 			}
10550 
10551 			if (ill != NULL) {
10552 				connp->conn_dhcpinit_ill = ill;
10553 				atomic_inc_32(&ill->ill_dhcpinit);
10554 			}
10555 			break;
10556 		}
10557 	} else {
10558 		switch (option) {
10559 		case IPV6_BOUND_IF:
10560 			connp->conn_incoming_ill = ill;
10561 			connp->conn_outgoing_ill = ill;
10562 			break;
10563 
10564 		case IPV6_MULTICAST_IF:
10565 			/*
10566 			 * Set conn_multicast_ill to be the IPv6 ill.
10567 			 * Set conn_multicast_ipif to be an IPv4 ipif
10568 			 * for ifindex to make IPv4 mapped addresses
10569 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10570 			 * Even if no IPv6 ill exists for the ifindex
10571 			 * we need to check for an IPv4 ifindex in order
10572 			 * for this to work with mapped addresses. In that
10573 			 * case only set conn_multicast_ipif.
10574 			 */
10575 			if (!checkonly) {
10576 				if (ifindex == 0) {
10577 					connp->conn_multicast_ill = NULL;
10578 					connp->conn_multicast_ipif = NULL;
10579 				} else if (ill != NULL) {
10580 					connp->conn_multicast_ill = ill;
10581 				}
10582 			}
10583 			break;
10584 		}
10585 	}
10586 
10587 	if (ill != NULL) {
10588 		mutex_exit(&ill->ill_lock);
10589 		mutex_exit(&connp->conn_lock);
10590 		ill_refrele(ill);
10591 		return (0);
10592 	}
10593 	mutex_exit(&connp->conn_lock);
10594 	/*
10595 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10596 	 * locate the ill and could not set the option (ifindex != 0)
10597 	 */
10598 	return (ifindex == 0 ? 0 : EINVAL);
10599 }
10600 
10601 /* This routine sets socket options. */
10602 /* ARGSUSED */
10603 int
10604 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10605     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10606     void *dummy, cred_t *cr, mblk_t *first_mp)
10607 {
10608 	int		*i1 = (int *)invalp;
10609 	conn_t		*connp = Q_TO_CONN(q);
10610 	int		error = 0;
10611 	boolean_t	checkonly;
10612 	ire_t		*ire;
10613 	boolean_t	found;
10614 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10615 
10616 	switch (optset_context) {
10617 
10618 	case SETFN_OPTCOM_CHECKONLY:
10619 		checkonly = B_TRUE;
10620 		/*
10621 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10622 		 * inlen != 0 implies value supplied and
10623 		 * 	we have to "pretend" to set it.
10624 		 * inlen == 0 implies that there is no
10625 		 * 	value part in T_CHECK request and just validation
10626 		 * done elsewhere should be enough, we just return here.
10627 		 */
10628 		if (inlen == 0) {
10629 			*outlenp = 0;
10630 			return (0);
10631 		}
10632 		break;
10633 	case SETFN_OPTCOM_NEGOTIATE:
10634 	case SETFN_UD_NEGOTIATE:
10635 	case SETFN_CONN_NEGOTIATE:
10636 		checkonly = B_FALSE;
10637 		break;
10638 	default:
10639 		/*
10640 		 * We should never get here
10641 		 */
10642 		*outlenp = 0;
10643 		return (EINVAL);
10644 	}
10645 
10646 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10647 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10648 
10649 	/*
10650 	 * For fixed length options, no sanity check
10651 	 * of passed in length is done. It is assumed *_optcom_req()
10652 	 * routines do the right thing.
10653 	 */
10654 
10655 	switch (level) {
10656 	case SOL_SOCKET:
10657 		/*
10658 		 * conn_lock protects the bitfields, and is used to
10659 		 * set the fields atomically.
10660 		 */
10661 		switch (name) {
10662 		case SO_BROADCAST:
10663 			if (!checkonly) {
10664 				/* TODO: use value someplace? */
10665 				mutex_enter(&connp->conn_lock);
10666 				connp->conn_broadcast = *i1 ? 1 : 0;
10667 				mutex_exit(&connp->conn_lock);
10668 			}
10669 			break;	/* goto sizeof (int) option return */
10670 		case SO_USELOOPBACK:
10671 			if (!checkonly) {
10672 				/* TODO: use value someplace? */
10673 				mutex_enter(&connp->conn_lock);
10674 				connp->conn_loopback = *i1 ? 1 : 0;
10675 				mutex_exit(&connp->conn_lock);
10676 			}
10677 			break;	/* goto sizeof (int) option return */
10678 		case SO_DONTROUTE:
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_dontroute = *i1 ? 1 : 0;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			break;	/* goto sizeof (int) option return */
10685 		case SO_REUSEADDR:
10686 			if (!checkonly) {
10687 				mutex_enter(&connp->conn_lock);
10688 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10689 				mutex_exit(&connp->conn_lock);
10690 			}
10691 			break;	/* goto sizeof (int) option return */
10692 		case SO_PROTOTYPE:
10693 			if (!checkonly) {
10694 				mutex_enter(&connp->conn_lock);
10695 				connp->conn_proto = *i1;
10696 				mutex_exit(&connp->conn_lock);
10697 			}
10698 			break;	/* goto sizeof (int) option return */
10699 		case SO_ALLZONES:
10700 			if (!checkonly) {
10701 				mutex_enter(&connp->conn_lock);
10702 				if (IPCL_IS_BOUND(connp)) {
10703 					mutex_exit(&connp->conn_lock);
10704 					return (EINVAL);
10705 				}
10706 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10707 				mutex_exit(&connp->conn_lock);
10708 			}
10709 			break;	/* goto sizeof (int) option return */
10710 		case SO_ANON_MLP:
10711 			if (!checkonly) {
10712 				mutex_enter(&connp->conn_lock);
10713 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10714 				mutex_exit(&connp->conn_lock);
10715 			}
10716 			break;	/* goto sizeof (int) option return */
10717 		case SO_MAC_EXEMPT:
10718 			if (secpolicy_net_mac_aware(cr) != 0 ||
10719 			    IPCL_IS_BOUND(connp))
10720 				return (EACCES);
10721 			if (!checkonly) {
10722 				mutex_enter(&connp->conn_lock);
10723 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10724 				mutex_exit(&connp->conn_lock);
10725 			}
10726 			break;	/* goto sizeof (int) option return */
10727 		default:
10728 			/*
10729 			 * "soft" error (negative)
10730 			 * option not handled at this level
10731 			 * Note: Do not modify *outlenp
10732 			 */
10733 			return (-EINVAL);
10734 		}
10735 		break;
10736 	case IPPROTO_IP:
10737 		switch (name) {
10738 		case IP_NEXTHOP:
10739 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10740 				return (EPERM);
10741 			/* FALLTHRU */
10742 		case IP_MULTICAST_IF: {
10743 			ipaddr_t addr = *i1;
10744 
10745 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10746 			    first_mp);
10747 			if (error != 0)
10748 				return (error);
10749 			break;	/* goto sizeof (int) option return */
10750 		}
10751 
10752 		case IP_MULTICAST_TTL:
10753 			/* Recorded in transport above IP */
10754 			*outvalp = *invalp;
10755 			*outlenp = sizeof (uchar_t);
10756 			return (0);
10757 		case IP_MULTICAST_LOOP:
10758 			if (!checkonly) {
10759 				mutex_enter(&connp->conn_lock);
10760 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10761 				mutex_exit(&connp->conn_lock);
10762 			}
10763 			*outvalp = *invalp;
10764 			*outlenp = sizeof (uchar_t);
10765 			return (0);
10766 		case IP_ADD_MEMBERSHIP:
10767 		case MCAST_JOIN_GROUP:
10768 		case IP_DROP_MEMBERSHIP:
10769 		case MCAST_LEAVE_GROUP: {
10770 			struct ip_mreq *mreqp;
10771 			struct group_req *greqp;
10772 			ire_t *ire;
10773 			boolean_t done = B_FALSE;
10774 			ipaddr_t group, ifaddr;
10775 			struct sockaddr_in *sin;
10776 			uint32_t *ifindexp;
10777 			boolean_t mcast_opt = B_TRUE;
10778 			mcast_record_t fmode;
10779 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10780 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10781 
10782 			switch (name) {
10783 			case IP_ADD_MEMBERSHIP:
10784 				mcast_opt = B_FALSE;
10785 				/* FALLTHRU */
10786 			case MCAST_JOIN_GROUP:
10787 				fmode = MODE_IS_EXCLUDE;
10788 				optfn = ip_opt_add_group;
10789 				break;
10790 
10791 			case IP_DROP_MEMBERSHIP:
10792 				mcast_opt = B_FALSE;
10793 				/* FALLTHRU */
10794 			case MCAST_LEAVE_GROUP:
10795 				fmode = MODE_IS_INCLUDE;
10796 				optfn = ip_opt_delete_group;
10797 				break;
10798 			}
10799 
10800 			if (mcast_opt) {
10801 				greqp = (struct group_req *)i1;
10802 				sin = (struct sockaddr_in *)&greqp->gr_group;
10803 				if (sin->sin_family != AF_INET) {
10804 					*outlenp = 0;
10805 					return (ENOPROTOOPT);
10806 				}
10807 				group = (ipaddr_t)sin->sin_addr.s_addr;
10808 				ifaddr = INADDR_ANY;
10809 				ifindexp = &greqp->gr_interface;
10810 			} else {
10811 				mreqp = (struct ip_mreq *)i1;
10812 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10813 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10814 				ifindexp = NULL;
10815 			}
10816 
10817 			/*
10818 			 * In the multirouting case, we need to replicate
10819 			 * the request on all interfaces that will take part
10820 			 * in replication.  We do so because multirouting is
10821 			 * reflective, thus we will probably receive multi-
10822 			 * casts on those interfaces.
10823 			 * The ip_multirt_apply_membership() succeeds if the
10824 			 * operation succeeds on at least one interface.
10825 			 */
10826 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10827 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10828 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10829 			if (ire != NULL) {
10830 				if (ire->ire_flags & RTF_MULTIRT) {
10831 					error = ip_multirt_apply_membership(
10832 					    optfn, ire, connp, checkonly, group,
10833 					    fmode, INADDR_ANY, first_mp);
10834 					done = B_TRUE;
10835 				}
10836 				ire_refrele(ire);
10837 			}
10838 			if (!done) {
10839 				error = optfn(connp, checkonly, group, ifaddr,
10840 				    ifindexp, fmode, INADDR_ANY, first_mp);
10841 			}
10842 			if (error) {
10843 				/*
10844 				 * EINPROGRESS is a soft error, needs retry
10845 				 * so don't make *outlenp zero.
10846 				 */
10847 				if (error != EINPROGRESS)
10848 					*outlenp = 0;
10849 				return (error);
10850 			}
10851 			/* OK return - copy input buffer into output buffer */
10852 			if (invalp != outvalp) {
10853 				/* don't trust bcopy for identical src/dst */
10854 				bcopy(invalp, outvalp, inlen);
10855 			}
10856 			*outlenp = inlen;
10857 			return (0);
10858 		}
10859 		case IP_BLOCK_SOURCE:
10860 		case IP_UNBLOCK_SOURCE:
10861 		case IP_ADD_SOURCE_MEMBERSHIP:
10862 		case IP_DROP_SOURCE_MEMBERSHIP:
10863 		case MCAST_BLOCK_SOURCE:
10864 		case MCAST_UNBLOCK_SOURCE:
10865 		case MCAST_JOIN_SOURCE_GROUP:
10866 		case MCAST_LEAVE_SOURCE_GROUP: {
10867 			struct ip_mreq_source *imreqp;
10868 			struct group_source_req *gsreqp;
10869 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10870 			uint32_t ifindex = 0;
10871 			mcast_record_t fmode;
10872 			struct sockaddr_in *sin;
10873 			ire_t *ire;
10874 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10875 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10876 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10877 
10878 			switch (name) {
10879 			case IP_BLOCK_SOURCE:
10880 				mcast_opt = B_FALSE;
10881 				/* FALLTHRU */
10882 			case MCAST_BLOCK_SOURCE:
10883 				fmode = MODE_IS_EXCLUDE;
10884 				optfn = ip_opt_add_group;
10885 				break;
10886 
10887 			case IP_UNBLOCK_SOURCE:
10888 				mcast_opt = B_FALSE;
10889 				/* FALLTHRU */
10890 			case MCAST_UNBLOCK_SOURCE:
10891 				fmode = MODE_IS_EXCLUDE;
10892 				optfn = ip_opt_delete_group;
10893 				break;
10894 
10895 			case IP_ADD_SOURCE_MEMBERSHIP:
10896 				mcast_opt = B_FALSE;
10897 				/* FALLTHRU */
10898 			case MCAST_JOIN_SOURCE_GROUP:
10899 				fmode = MODE_IS_INCLUDE;
10900 				optfn = ip_opt_add_group;
10901 				break;
10902 
10903 			case IP_DROP_SOURCE_MEMBERSHIP:
10904 				mcast_opt = B_FALSE;
10905 				/* FALLTHRU */
10906 			case MCAST_LEAVE_SOURCE_GROUP:
10907 				fmode = MODE_IS_INCLUDE;
10908 				optfn = ip_opt_delete_group;
10909 				break;
10910 			}
10911 
10912 			if (mcast_opt) {
10913 				gsreqp = (struct group_source_req *)i1;
10914 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10915 					*outlenp = 0;
10916 					return (ENOPROTOOPT);
10917 				}
10918 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10919 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10920 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10921 				src = (ipaddr_t)sin->sin_addr.s_addr;
10922 				ifindex = gsreqp->gsr_interface;
10923 			} else {
10924 				imreqp = (struct ip_mreq_source *)i1;
10925 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10926 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10927 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10928 			}
10929 
10930 			/*
10931 			 * In the multirouting case, we need to replicate
10932 			 * the request as noted in the mcast cases above.
10933 			 */
10934 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10935 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10936 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10937 			if (ire != NULL) {
10938 				if (ire->ire_flags & RTF_MULTIRT) {
10939 					error = ip_multirt_apply_membership(
10940 					    optfn, ire, connp, checkonly, grp,
10941 					    fmode, src, first_mp);
10942 					done = B_TRUE;
10943 				}
10944 				ire_refrele(ire);
10945 			}
10946 			if (!done) {
10947 				error = optfn(connp, checkonly, grp, ifaddr,
10948 				    &ifindex, fmode, src, first_mp);
10949 			}
10950 			if (error != 0) {
10951 				/*
10952 				 * EINPROGRESS is a soft error, needs retry
10953 				 * so don't make *outlenp zero.
10954 				 */
10955 				if (error != EINPROGRESS)
10956 					*outlenp = 0;
10957 				return (error);
10958 			}
10959 			/* OK return - copy input buffer into output buffer */
10960 			if (invalp != outvalp) {
10961 				bcopy(invalp, outvalp, inlen);
10962 			}
10963 			*outlenp = inlen;
10964 			return (0);
10965 		}
10966 		case IP_SEC_OPT:
10967 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10968 			if (error != 0) {
10969 				*outlenp = 0;
10970 				return (error);
10971 			}
10972 			break;
10973 		case IP_HDRINCL:
10974 		case IP_OPTIONS:
10975 		case T_IP_OPTIONS:
10976 		case IP_TOS:
10977 		case T_IP_TOS:
10978 		case IP_TTL:
10979 		case IP_RECVDSTADDR:
10980 		case IP_RECVOPTS:
10981 			/* OK return - copy input buffer into output buffer */
10982 			if (invalp != outvalp) {
10983 				/* don't trust bcopy for identical src/dst */
10984 				bcopy(invalp, outvalp, inlen);
10985 			}
10986 			*outlenp = inlen;
10987 			return (0);
10988 		case IP_RECVIF:
10989 			/* Retrieve the inbound interface index */
10990 			if (!checkonly) {
10991 				mutex_enter(&connp->conn_lock);
10992 				connp->conn_recvif = *i1 ? 1 : 0;
10993 				mutex_exit(&connp->conn_lock);
10994 			}
10995 			break;	/* goto sizeof (int) option return */
10996 		case IP_RECVPKTINFO:
10997 			if (!checkonly) {
10998 				mutex_enter(&connp->conn_lock);
10999 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11000 				mutex_exit(&connp->conn_lock);
11001 			}
11002 			break;	/* goto sizeof (int) option return */
11003 		case IP_RECVSLLA:
11004 			/* Retrieve the source link layer address */
11005 			if (!checkonly) {
11006 				mutex_enter(&connp->conn_lock);
11007 				connp->conn_recvslla = *i1 ? 1 : 0;
11008 				mutex_exit(&connp->conn_lock);
11009 			}
11010 			break;	/* goto sizeof (int) option return */
11011 		case MRT_INIT:
11012 		case MRT_DONE:
11013 		case MRT_ADD_VIF:
11014 		case MRT_DEL_VIF:
11015 		case MRT_ADD_MFC:
11016 		case MRT_DEL_MFC:
11017 		case MRT_ASSERT:
11018 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11019 				*outlenp = 0;
11020 				return (error);
11021 			}
11022 			error = ip_mrouter_set((int)name, q, checkonly,
11023 			    (uchar_t *)invalp, inlen, first_mp);
11024 			if (error) {
11025 				*outlenp = 0;
11026 				return (error);
11027 			}
11028 			/* OK return - copy input buffer into output buffer */
11029 			if (invalp != outvalp) {
11030 				/* don't trust bcopy for identical src/dst */
11031 				bcopy(invalp, outvalp, inlen);
11032 			}
11033 			*outlenp = inlen;
11034 			return (0);
11035 		case IP_BOUND_IF:
11036 		case IP_DHCPINIT_IF:
11037 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11038 			    level, name, first_mp);
11039 			if (error != 0)
11040 				return (error);
11041 			break; 		/* goto sizeof (int) option return */
11042 
11043 		case IP_UNSPEC_SRC:
11044 			/* Allow sending with a zero source address */
11045 			if (!checkonly) {
11046 				mutex_enter(&connp->conn_lock);
11047 				connp->conn_unspec_src = *i1 ? 1 : 0;
11048 				mutex_exit(&connp->conn_lock);
11049 			}
11050 			break;	/* goto sizeof (int) option return */
11051 		default:
11052 			/*
11053 			 * "soft" error (negative)
11054 			 * option not handled at this level
11055 			 * Note: Do not modify *outlenp
11056 			 */
11057 			return (-EINVAL);
11058 		}
11059 		break;
11060 	case IPPROTO_IPV6:
11061 		switch (name) {
11062 		case IPV6_BOUND_IF:
11063 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11064 			    level, name, first_mp);
11065 			if (error != 0)
11066 				return (error);
11067 			break; 		/* goto sizeof (int) option return */
11068 
11069 		case IPV6_MULTICAST_IF:
11070 			/*
11071 			 * The only possible errors are EINPROGRESS and
11072 			 * EINVAL. EINPROGRESS will be restarted and is not
11073 			 * a hard error. We call this option on both V4 and V6
11074 			 * If both return EINVAL, then this call returns
11075 			 * EINVAL. If at least one of them succeeds we
11076 			 * return success.
11077 			 */
11078 			found = B_FALSE;
11079 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11080 			    level, name, first_mp);
11081 			if (error == EINPROGRESS)
11082 				return (error);
11083 			if (error == 0)
11084 				found = B_TRUE;
11085 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11086 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11087 			if (error == 0)
11088 				found = B_TRUE;
11089 			if (!found)
11090 				return (error);
11091 			break; 		/* goto sizeof (int) option return */
11092 
11093 		case IPV6_MULTICAST_HOPS:
11094 			/* Recorded in transport above IP */
11095 			break;	/* goto sizeof (int) option return */
11096 		case IPV6_MULTICAST_LOOP:
11097 			if (!checkonly) {
11098 				mutex_enter(&connp->conn_lock);
11099 				connp->conn_multicast_loop = *i1;
11100 				mutex_exit(&connp->conn_lock);
11101 			}
11102 			break;	/* goto sizeof (int) option return */
11103 		case IPV6_JOIN_GROUP:
11104 		case MCAST_JOIN_GROUP:
11105 		case IPV6_LEAVE_GROUP:
11106 		case MCAST_LEAVE_GROUP: {
11107 			struct ipv6_mreq *ip_mreqp;
11108 			struct group_req *greqp;
11109 			ire_t *ire;
11110 			boolean_t done = B_FALSE;
11111 			in6_addr_t groupv6;
11112 			uint32_t ifindex;
11113 			boolean_t mcast_opt = B_TRUE;
11114 			mcast_record_t fmode;
11115 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11116 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11117 
11118 			switch (name) {
11119 			case IPV6_JOIN_GROUP:
11120 				mcast_opt = B_FALSE;
11121 				/* FALLTHRU */
11122 			case MCAST_JOIN_GROUP:
11123 				fmode = MODE_IS_EXCLUDE;
11124 				optfn = ip_opt_add_group_v6;
11125 				break;
11126 
11127 			case IPV6_LEAVE_GROUP:
11128 				mcast_opt = B_FALSE;
11129 				/* FALLTHRU */
11130 			case MCAST_LEAVE_GROUP:
11131 				fmode = MODE_IS_INCLUDE;
11132 				optfn = ip_opt_delete_group_v6;
11133 				break;
11134 			}
11135 
11136 			if (mcast_opt) {
11137 				struct sockaddr_in *sin;
11138 				struct sockaddr_in6 *sin6;
11139 				greqp = (struct group_req *)i1;
11140 				if (greqp->gr_group.ss_family == AF_INET) {
11141 					sin = (struct sockaddr_in *)
11142 					    &(greqp->gr_group);
11143 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11144 					    &groupv6);
11145 				} else {
11146 					sin6 = (struct sockaddr_in6 *)
11147 					    &(greqp->gr_group);
11148 					groupv6 = sin6->sin6_addr;
11149 				}
11150 				ifindex = greqp->gr_interface;
11151 			} else {
11152 				ip_mreqp = (struct ipv6_mreq *)i1;
11153 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11154 				ifindex = ip_mreqp->ipv6mr_interface;
11155 			}
11156 			/*
11157 			 * In the multirouting case, we need to replicate
11158 			 * the request on all interfaces that will take part
11159 			 * in replication.  We do so because multirouting is
11160 			 * reflective, thus we will probably receive multi-
11161 			 * casts on those interfaces.
11162 			 * The ip_multirt_apply_membership_v6() succeeds if
11163 			 * the operation succeeds on at least one interface.
11164 			 */
11165 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11166 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11167 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11168 			if (ire != NULL) {
11169 				if (ire->ire_flags & RTF_MULTIRT) {
11170 					error = ip_multirt_apply_membership_v6(
11171 					    optfn, ire, connp, checkonly,
11172 					    &groupv6, fmode, &ipv6_all_zeros,
11173 					    first_mp);
11174 					done = B_TRUE;
11175 				}
11176 				ire_refrele(ire);
11177 			}
11178 			if (!done) {
11179 				error = optfn(connp, checkonly, &groupv6,
11180 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11181 			}
11182 			if (error) {
11183 				/*
11184 				 * EINPROGRESS is a soft error, needs retry
11185 				 * so don't make *outlenp zero.
11186 				 */
11187 				if (error != EINPROGRESS)
11188 					*outlenp = 0;
11189 				return (error);
11190 			}
11191 			/* OK return - copy input buffer into output buffer */
11192 			if (invalp != outvalp) {
11193 				/* don't trust bcopy for identical src/dst */
11194 				bcopy(invalp, outvalp, inlen);
11195 			}
11196 			*outlenp = inlen;
11197 			return (0);
11198 		}
11199 		case MCAST_BLOCK_SOURCE:
11200 		case MCAST_UNBLOCK_SOURCE:
11201 		case MCAST_JOIN_SOURCE_GROUP:
11202 		case MCAST_LEAVE_SOURCE_GROUP: {
11203 			struct group_source_req *gsreqp;
11204 			in6_addr_t v6grp, v6src;
11205 			uint32_t ifindex;
11206 			mcast_record_t fmode;
11207 			ire_t *ire;
11208 			boolean_t done = B_FALSE;
11209 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11210 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11211 
11212 			switch (name) {
11213 			case MCAST_BLOCK_SOURCE:
11214 				fmode = MODE_IS_EXCLUDE;
11215 				optfn = ip_opt_add_group_v6;
11216 				break;
11217 			case MCAST_UNBLOCK_SOURCE:
11218 				fmode = MODE_IS_EXCLUDE;
11219 				optfn = ip_opt_delete_group_v6;
11220 				break;
11221 			case MCAST_JOIN_SOURCE_GROUP:
11222 				fmode = MODE_IS_INCLUDE;
11223 				optfn = ip_opt_add_group_v6;
11224 				break;
11225 			case MCAST_LEAVE_SOURCE_GROUP:
11226 				fmode = MODE_IS_INCLUDE;
11227 				optfn = ip_opt_delete_group_v6;
11228 				break;
11229 			}
11230 
11231 			gsreqp = (struct group_source_req *)i1;
11232 			ifindex = gsreqp->gsr_interface;
11233 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11234 				struct sockaddr_in *s;
11235 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11236 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11237 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11238 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11239 			} else {
11240 				struct sockaddr_in6 *s6;
11241 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11242 				v6grp = s6->sin6_addr;
11243 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11244 				v6src = s6->sin6_addr;
11245 			}
11246 
11247 			/*
11248 			 * In the multirouting case, we need to replicate
11249 			 * the request as noted in the mcast cases above.
11250 			 */
11251 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11252 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11253 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11254 			if (ire != NULL) {
11255 				if (ire->ire_flags & RTF_MULTIRT) {
11256 					error = ip_multirt_apply_membership_v6(
11257 					    optfn, ire, connp, checkonly,
11258 					    &v6grp, fmode, &v6src, first_mp);
11259 					done = B_TRUE;
11260 				}
11261 				ire_refrele(ire);
11262 			}
11263 			if (!done) {
11264 				error = optfn(connp, checkonly, &v6grp,
11265 				    ifindex, fmode, &v6src, first_mp);
11266 			}
11267 			if (error != 0) {
11268 				/*
11269 				 * EINPROGRESS is a soft error, needs retry
11270 				 * so don't make *outlenp zero.
11271 				 */
11272 				if (error != EINPROGRESS)
11273 					*outlenp = 0;
11274 				return (error);
11275 			}
11276 			/* OK return - copy input buffer into output buffer */
11277 			if (invalp != outvalp) {
11278 				bcopy(invalp, outvalp, inlen);
11279 			}
11280 			*outlenp = inlen;
11281 			return (0);
11282 		}
11283 		case IPV6_UNICAST_HOPS:
11284 			/* Recorded in transport above IP */
11285 			break;	/* goto sizeof (int) option return */
11286 		case IPV6_UNSPEC_SRC:
11287 			/* Allow sending with a zero source address */
11288 			if (!checkonly) {
11289 				mutex_enter(&connp->conn_lock);
11290 				connp->conn_unspec_src = *i1 ? 1 : 0;
11291 				mutex_exit(&connp->conn_lock);
11292 			}
11293 			break;	/* goto sizeof (int) option return */
11294 		case IPV6_RECVPKTINFO:
11295 			if (!checkonly) {
11296 				mutex_enter(&connp->conn_lock);
11297 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11298 				mutex_exit(&connp->conn_lock);
11299 			}
11300 			break;	/* goto sizeof (int) option return */
11301 		case IPV6_RECVTCLASS:
11302 			if (!checkonly) {
11303 				if (*i1 < 0 || *i1 > 1) {
11304 					return (EINVAL);
11305 				}
11306 				mutex_enter(&connp->conn_lock);
11307 				connp->conn_ipv6_recvtclass = *i1;
11308 				mutex_exit(&connp->conn_lock);
11309 			}
11310 			break;
11311 		case IPV6_RECVPATHMTU:
11312 			if (!checkonly) {
11313 				if (*i1 < 0 || *i1 > 1) {
11314 					return (EINVAL);
11315 				}
11316 				mutex_enter(&connp->conn_lock);
11317 				connp->conn_ipv6_recvpathmtu = *i1;
11318 				mutex_exit(&connp->conn_lock);
11319 			}
11320 			break;
11321 		case IPV6_RECVHOPLIMIT:
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		case IPV6_RECVHOPOPTS:
11329 			if (!checkonly) {
11330 				mutex_enter(&connp->conn_lock);
11331 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11332 				mutex_exit(&connp->conn_lock);
11333 			}
11334 			break;	/* goto sizeof (int) option return */
11335 		case IPV6_RECVDSTOPTS:
11336 			if (!checkonly) {
11337 				mutex_enter(&connp->conn_lock);
11338 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11339 				mutex_exit(&connp->conn_lock);
11340 			}
11341 			break;	/* goto sizeof (int) option return */
11342 		case IPV6_RECVRTHDR:
11343 			if (!checkonly) {
11344 				mutex_enter(&connp->conn_lock);
11345 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11346 				mutex_exit(&connp->conn_lock);
11347 			}
11348 			break;	/* goto sizeof (int) option return */
11349 		case IPV6_RECVRTHDRDSTOPTS:
11350 			if (!checkonly) {
11351 				mutex_enter(&connp->conn_lock);
11352 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11353 				mutex_exit(&connp->conn_lock);
11354 			}
11355 			break;	/* goto sizeof (int) option return */
11356 		case IPV6_PKTINFO:
11357 			if (inlen == 0)
11358 				return (-EINVAL);	/* clearing option */
11359 			error = ip6_set_pktinfo(cr, connp,
11360 			    (struct in6_pktinfo *)invalp);
11361 			if (error != 0)
11362 				*outlenp = 0;
11363 			else
11364 				*outlenp = inlen;
11365 			return (error);
11366 		case IPV6_NEXTHOP: {
11367 			struct sockaddr_in6 *sin6;
11368 
11369 			/* Verify that the nexthop is reachable */
11370 			if (inlen == 0)
11371 				return (-EINVAL);	/* clearing option */
11372 
11373 			sin6 = (struct sockaddr_in6 *)invalp;
11374 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11375 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11376 			    NULL, MATCH_IRE_DEFAULT, ipst);
11377 
11378 			if (ire == NULL) {
11379 				*outlenp = 0;
11380 				return (EHOSTUNREACH);
11381 			}
11382 			ire_refrele(ire);
11383 			return (-EINVAL);
11384 		}
11385 		case IPV6_SEC_OPT:
11386 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11387 			if (error != 0) {
11388 				*outlenp = 0;
11389 				return (error);
11390 			}
11391 			break;
11392 		case IPV6_SRC_PREFERENCES: {
11393 			/*
11394 			 * This is implemented strictly in the ip module
11395 			 * (here and in tcp_opt_*() to accomodate tcp
11396 			 * sockets).  Modules above ip pass this option
11397 			 * down here since ip is the only one that needs to
11398 			 * be aware of source address preferences.
11399 			 *
11400 			 * This socket option only affects connected
11401 			 * sockets that haven't already bound to a specific
11402 			 * IPv6 address.  In other words, sockets that
11403 			 * don't call bind() with an address other than the
11404 			 * unspecified address and that call connect().
11405 			 * ip_bind_connected_v6() passes these preferences
11406 			 * to the ipif_select_source_v6() function.
11407 			 */
11408 			if (inlen != sizeof (uint32_t))
11409 				return (EINVAL);
11410 			error = ip6_set_src_preferences(connp,
11411 			    *(uint32_t *)invalp);
11412 			if (error != 0) {
11413 				*outlenp = 0;
11414 				return (error);
11415 			} else {
11416 				*outlenp = sizeof (uint32_t);
11417 			}
11418 			break;
11419 		}
11420 		case IPV6_V6ONLY:
11421 			if (*i1 < 0 || *i1 > 1) {
11422 				return (EINVAL);
11423 			}
11424 			mutex_enter(&connp->conn_lock);
11425 			connp->conn_ipv6_v6only = *i1;
11426 			mutex_exit(&connp->conn_lock);
11427 			break;
11428 		default:
11429 			return (-EINVAL);
11430 		}
11431 		break;
11432 	default:
11433 		/*
11434 		 * "soft" error (negative)
11435 		 * option not handled at this level
11436 		 * Note: Do not modify *outlenp
11437 		 */
11438 		return (-EINVAL);
11439 	}
11440 	/*
11441 	 * Common case of return from an option that is sizeof (int)
11442 	 */
11443 	*(int *)outvalp = *i1;
11444 	*outlenp = sizeof (int);
11445 	return (0);
11446 }
11447 
11448 /*
11449  * This routine gets default values of certain options whose default
11450  * values are maintained by protocol specific code
11451  */
11452 /* ARGSUSED */
11453 int
11454 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11455 {
11456 	int *i1 = (int *)ptr;
11457 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11458 
11459 	switch (level) {
11460 	case IPPROTO_IP:
11461 		switch (name) {
11462 		case IP_MULTICAST_TTL:
11463 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11464 			return (sizeof (uchar_t));
11465 		case IP_MULTICAST_LOOP:
11466 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11467 			return (sizeof (uchar_t));
11468 		default:
11469 			return (-1);
11470 		}
11471 	case IPPROTO_IPV6:
11472 		switch (name) {
11473 		case IPV6_UNICAST_HOPS:
11474 			*i1 = ipst->ips_ipv6_def_hops;
11475 			return (sizeof (int));
11476 		case IPV6_MULTICAST_HOPS:
11477 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11478 			return (sizeof (int));
11479 		case IPV6_MULTICAST_LOOP:
11480 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11481 			return (sizeof (int));
11482 		case IPV6_V6ONLY:
11483 			*i1 = 1;
11484 			return (sizeof (int));
11485 		default:
11486 			return (-1);
11487 		}
11488 	default:
11489 		return (-1);
11490 	}
11491 	/* NOTREACHED */
11492 }
11493 
11494 /*
11495  * Given a destination address and a pointer to where to put the information
11496  * this routine fills in the mtuinfo.
11497  */
11498 int
11499 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11500     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11501 {
11502 	ire_t *ire;
11503 	ip_stack_t	*ipst = ns->netstack_ip;
11504 
11505 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11506 		return (-1);
11507 
11508 	bzero(mtuinfo, sizeof (*mtuinfo));
11509 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11510 	mtuinfo->ip6m_addr.sin6_port = port;
11511 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11512 
11513 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11514 	if (ire != NULL) {
11515 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11516 		ire_refrele(ire);
11517 	} else {
11518 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11519 	}
11520 	return (sizeof (struct ip6_mtuinfo));
11521 }
11522 
11523 /*
11524  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11525  * checking of cred and that ip_g_mrouter is set should be done and
11526  * isn't.  This doesn't matter as the error checking is done properly for the
11527  * other MRT options coming in through ip_opt_set.
11528  */
11529 int
11530 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11531 {
11532 	conn_t		*connp = Q_TO_CONN(q);
11533 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11534 
11535 	switch (level) {
11536 	case IPPROTO_IP:
11537 		switch (name) {
11538 		case MRT_VERSION:
11539 		case MRT_ASSERT:
11540 			(void) ip_mrouter_get(name, q, ptr);
11541 			return (sizeof (int));
11542 		case IP_SEC_OPT:
11543 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11544 		case IP_NEXTHOP:
11545 			if (connp->conn_nexthop_set) {
11546 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11547 				return (sizeof (ipaddr_t));
11548 			} else
11549 				return (0);
11550 		case IP_RECVPKTINFO:
11551 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11552 			return (sizeof (int));
11553 		default:
11554 			break;
11555 		}
11556 		break;
11557 	case IPPROTO_IPV6:
11558 		switch (name) {
11559 		case IPV6_SEC_OPT:
11560 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11561 		case IPV6_SRC_PREFERENCES: {
11562 			return (ip6_get_src_preferences(connp,
11563 			    (uint32_t *)ptr));
11564 		}
11565 		case IPV6_V6ONLY:
11566 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11567 			return (sizeof (int));
11568 		case IPV6_PATHMTU:
11569 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11570 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11571 		default:
11572 			break;
11573 		}
11574 		break;
11575 	default:
11576 		break;
11577 	}
11578 	return (-1);
11579 }
11580 /* Named Dispatch routine to get a current value out of our parameter table. */
11581 /* ARGSUSED */
11582 static int
11583 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11584 {
11585 	ipparam_t *ippa = (ipparam_t *)cp;
11586 
11587 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11588 	return (0);
11589 }
11590 
11591 /* ARGSUSED */
11592 static int
11593 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11594 {
11595 
11596 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11597 	return (0);
11598 }
11599 
11600 /*
11601  * Set ip{,6}_forwarding values.  This means walking through all of the
11602  * ill's and toggling their forwarding values.
11603  */
11604 /* ARGSUSED */
11605 static int
11606 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11607 {
11608 	long new_value;
11609 	int *forwarding_value = (int *)cp;
11610 	ill_t *ill;
11611 	boolean_t isv6;
11612 	ill_walk_context_t ctx;
11613 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11614 
11615 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11616 
11617 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11618 	    new_value < 0 || new_value > 1) {
11619 		return (EINVAL);
11620 	}
11621 
11622 	*forwarding_value = new_value;
11623 
11624 	/*
11625 	 * Regardless of the current value of ip_forwarding, set all per-ill
11626 	 * values of ip_forwarding to the value being set.
11627 	 *
11628 	 * Bring all the ill's up to date with the new global value.
11629 	 */
11630 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11631 
11632 	if (isv6)
11633 		ill = ILL_START_WALK_V6(&ctx, ipst);
11634 	else
11635 		ill = ILL_START_WALK_V4(&ctx, ipst);
11636 
11637 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11638 		(void) ill_forward_set(ill, new_value != 0);
11639 
11640 	rw_exit(&ipst->ips_ill_g_lock);
11641 	return (0);
11642 }
11643 
11644 /*
11645  * Walk through the param array specified registering each element with the
11646  * Named Dispatch handler. This is called only during init. So it is ok
11647  * not to acquire any locks
11648  */
11649 static boolean_t
11650 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11651     ipndp_t *ipnd, size_t ipnd_cnt)
11652 {
11653 	for (; ippa_cnt-- > 0; ippa++) {
11654 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11655 			if (!nd_load(ndp, ippa->ip_param_name,
11656 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11657 				nd_free(ndp);
11658 				return (B_FALSE);
11659 			}
11660 		}
11661 	}
11662 
11663 	for (; ipnd_cnt-- > 0; ipnd++) {
11664 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11665 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11666 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11667 			    ipnd->ip_ndp_data)) {
11668 				nd_free(ndp);
11669 				return (B_FALSE);
11670 			}
11671 		}
11672 	}
11673 
11674 	return (B_TRUE);
11675 }
11676 
11677 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11678 /* ARGSUSED */
11679 static int
11680 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11681 {
11682 	long		new_value;
11683 	ipparam_t	*ippa = (ipparam_t *)cp;
11684 
11685 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11686 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11687 		return (EINVAL);
11688 	}
11689 	ippa->ip_param_value = new_value;
11690 	return (0);
11691 }
11692 
11693 /*
11694  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11695  * When an ipf is passed here for the first time, if
11696  * we already have in-order fragments on the queue, we convert from the fast-
11697  * path reassembly scheme to the hard-case scheme.  From then on, additional
11698  * fragments are reassembled here.  We keep track of the start and end offsets
11699  * of each piece, and the number of holes in the chain.  When the hole count
11700  * goes to zero, we are done!
11701  *
11702  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11703  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11704  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11705  * after the call to ip_reassemble().
11706  */
11707 int
11708 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11709     size_t msg_len)
11710 {
11711 	uint_t	end;
11712 	mblk_t	*next_mp;
11713 	mblk_t	*mp1;
11714 	uint_t	offset;
11715 	boolean_t incr_dups = B_TRUE;
11716 	boolean_t offset_zero_seen = B_FALSE;
11717 	boolean_t pkt_boundary_checked = B_FALSE;
11718 
11719 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11720 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11721 
11722 	/* Add in byte count */
11723 	ipf->ipf_count += msg_len;
11724 	if (ipf->ipf_end) {
11725 		/*
11726 		 * We were part way through in-order reassembly, but now there
11727 		 * is a hole.  We walk through messages already queued, and
11728 		 * mark them for hard case reassembly.  We know that up till
11729 		 * now they were in order starting from offset zero.
11730 		 */
11731 		offset = 0;
11732 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11733 			IP_REASS_SET_START(mp1, offset);
11734 			if (offset == 0) {
11735 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11736 				offset = -ipf->ipf_nf_hdr_len;
11737 			}
11738 			offset += mp1->b_wptr - mp1->b_rptr;
11739 			IP_REASS_SET_END(mp1, offset);
11740 		}
11741 		/* One hole at the end. */
11742 		ipf->ipf_hole_cnt = 1;
11743 		/* Brand it as a hard case, forever. */
11744 		ipf->ipf_end = 0;
11745 	}
11746 	/* Walk through all the new pieces. */
11747 	do {
11748 		end = start + (mp->b_wptr - mp->b_rptr);
11749 		/*
11750 		 * If start is 0, decrease 'end' only for the first mblk of
11751 		 * the fragment. Otherwise 'end' can get wrong value in the
11752 		 * second pass of the loop if first mblk is exactly the
11753 		 * size of ipf_nf_hdr_len.
11754 		 */
11755 		if (start == 0 && !offset_zero_seen) {
11756 			/* First segment */
11757 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11758 			end -= ipf->ipf_nf_hdr_len;
11759 			offset_zero_seen = B_TRUE;
11760 		}
11761 		next_mp = mp->b_cont;
11762 		/*
11763 		 * We are checking to see if there is any interesing data
11764 		 * to process.  If there isn't and the mblk isn't the
11765 		 * one which carries the unfragmentable header then we
11766 		 * drop it.  It's possible to have just the unfragmentable
11767 		 * header come through without any data.  That needs to be
11768 		 * saved.
11769 		 *
11770 		 * If the assert at the top of this function holds then the
11771 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11772 		 * is infrequently traveled enough that the test is left in
11773 		 * to protect against future code changes which break that
11774 		 * invariant.
11775 		 */
11776 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11777 			/* Empty.  Blast it. */
11778 			IP_REASS_SET_START(mp, 0);
11779 			IP_REASS_SET_END(mp, 0);
11780 			/*
11781 			 * If the ipf points to the mblk we are about to free,
11782 			 * update ipf to point to the next mblk (or NULL
11783 			 * if none).
11784 			 */
11785 			if (ipf->ipf_mp->b_cont == mp)
11786 				ipf->ipf_mp->b_cont = next_mp;
11787 			freeb(mp);
11788 			continue;
11789 		}
11790 		mp->b_cont = NULL;
11791 		IP_REASS_SET_START(mp, start);
11792 		IP_REASS_SET_END(mp, end);
11793 		if (!ipf->ipf_tail_mp) {
11794 			ipf->ipf_tail_mp = mp;
11795 			ipf->ipf_mp->b_cont = mp;
11796 			if (start == 0 || !more) {
11797 				ipf->ipf_hole_cnt = 1;
11798 				/*
11799 				 * if the first fragment comes in more than one
11800 				 * mblk, this loop will be executed for each
11801 				 * mblk. Need to adjust hole count so exiting
11802 				 * this routine will leave hole count at 1.
11803 				 */
11804 				if (next_mp)
11805 					ipf->ipf_hole_cnt++;
11806 			} else
11807 				ipf->ipf_hole_cnt = 2;
11808 			continue;
11809 		} else if (ipf->ipf_last_frag_seen && !more &&
11810 		    !pkt_boundary_checked) {
11811 			/*
11812 			 * We check datagram boundary only if this fragment
11813 			 * claims to be the last fragment and we have seen a
11814 			 * last fragment in the past too. We do this only
11815 			 * once for a given fragment.
11816 			 *
11817 			 * start cannot be 0 here as fragments with start=0
11818 			 * and MF=0 gets handled as a complete packet. These
11819 			 * fragments should not reach here.
11820 			 */
11821 
11822 			if (start + msgdsize(mp) !=
11823 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11824 				/*
11825 				 * We have two fragments both of which claim
11826 				 * to be the last fragment but gives conflicting
11827 				 * information about the whole datagram size.
11828 				 * Something fishy is going on. Drop the
11829 				 * fragment and free up the reassembly list.
11830 				 */
11831 				return (IP_REASS_FAILED);
11832 			}
11833 
11834 			/*
11835 			 * We shouldn't come to this code block again for this
11836 			 * particular fragment.
11837 			 */
11838 			pkt_boundary_checked = B_TRUE;
11839 		}
11840 
11841 		/* New stuff at or beyond tail? */
11842 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11843 		if (start >= offset) {
11844 			if (ipf->ipf_last_frag_seen) {
11845 				/* current fragment is beyond last fragment */
11846 				return (IP_REASS_FAILED);
11847 			}
11848 			/* Link it on end. */
11849 			ipf->ipf_tail_mp->b_cont = mp;
11850 			ipf->ipf_tail_mp = mp;
11851 			if (more) {
11852 				if (start != offset)
11853 					ipf->ipf_hole_cnt++;
11854 			} else if (start == offset && next_mp == NULL)
11855 					ipf->ipf_hole_cnt--;
11856 			continue;
11857 		}
11858 		mp1 = ipf->ipf_mp->b_cont;
11859 		offset = IP_REASS_START(mp1);
11860 		/* New stuff at the front? */
11861 		if (start < offset) {
11862 			if (start == 0) {
11863 				if (end >= offset) {
11864 					/* Nailed the hole at the begining. */
11865 					ipf->ipf_hole_cnt--;
11866 				}
11867 			} else if (end < offset) {
11868 				/*
11869 				 * A hole, stuff, and a hole where there used
11870 				 * to be just a hole.
11871 				 */
11872 				ipf->ipf_hole_cnt++;
11873 			}
11874 			mp->b_cont = mp1;
11875 			/* Check for overlap. */
11876 			while (end > offset) {
11877 				if (end < IP_REASS_END(mp1)) {
11878 					mp->b_wptr -= end - offset;
11879 					IP_REASS_SET_END(mp, offset);
11880 					BUMP_MIB(ill->ill_ip_mib,
11881 					    ipIfStatsReasmPartDups);
11882 					break;
11883 				}
11884 				/* Did we cover another hole? */
11885 				if ((mp1->b_cont &&
11886 				    IP_REASS_END(mp1) !=
11887 				    IP_REASS_START(mp1->b_cont) &&
11888 				    end >= IP_REASS_START(mp1->b_cont)) ||
11889 				    (!ipf->ipf_last_frag_seen && !more)) {
11890 					ipf->ipf_hole_cnt--;
11891 				}
11892 				/* Clip out mp1. */
11893 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11894 					/*
11895 					 * After clipping out mp1, this guy
11896 					 * is now hanging off the end.
11897 					 */
11898 					ipf->ipf_tail_mp = mp;
11899 				}
11900 				IP_REASS_SET_START(mp1, 0);
11901 				IP_REASS_SET_END(mp1, 0);
11902 				/* Subtract byte count */
11903 				ipf->ipf_count -= mp1->b_datap->db_lim -
11904 				    mp1->b_datap->db_base;
11905 				freeb(mp1);
11906 				BUMP_MIB(ill->ill_ip_mib,
11907 				    ipIfStatsReasmPartDups);
11908 				mp1 = mp->b_cont;
11909 				if (!mp1)
11910 					break;
11911 				offset = IP_REASS_START(mp1);
11912 			}
11913 			ipf->ipf_mp->b_cont = mp;
11914 			continue;
11915 		}
11916 		/*
11917 		 * The new piece starts somewhere between the start of the head
11918 		 * and before the end of the tail.
11919 		 */
11920 		for (; mp1; mp1 = mp1->b_cont) {
11921 			offset = IP_REASS_END(mp1);
11922 			if (start < offset) {
11923 				if (end <= offset) {
11924 					/* Nothing new. */
11925 					IP_REASS_SET_START(mp, 0);
11926 					IP_REASS_SET_END(mp, 0);
11927 					/* Subtract byte count */
11928 					ipf->ipf_count -= mp->b_datap->db_lim -
11929 					    mp->b_datap->db_base;
11930 					if (incr_dups) {
11931 						ipf->ipf_num_dups++;
11932 						incr_dups = B_FALSE;
11933 					}
11934 					freeb(mp);
11935 					BUMP_MIB(ill->ill_ip_mib,
11936 					    ipIfStatsReasmDuplicates);
11937 					break;
11938 				}
11939 				/*
11940 				 * Trim redundant stuff off beginning of new
11941 				 * piece.
11942 				 */
11943 				IP_REASS_SET_START(mp, offset);
11944 				mp->b_rptr += offset - start;
11945 				BUMP_MIB(ill->ill_ip_mib,
11946 				    ipIfStatsReasmPartDups);
11947 				start = offset;
11948 				if (!mp1->b_cont) {
11949 					/*
11950 					 * After trimming, this guy is now
11951 					 * hanging off the end.
11952 					 */
11953 					mp1->b_cont = mp;
11954 					ipf->ipf_tail_mp = mp;
11955 					if (!more) {
11956 						ipf->ipf_hole_cnt--;
11957 					}
11958 					break;
11959 				}
11960 			}
11961 			if (start >= IP_REASS_START(mp1->b_cont))
11962 				continue;
11963 			/* Fill a hole */
11964 			if (start > offset)
11965 				ipf->ipf_hole_cnt++;
11966 			mp->b_cont = mp1->b_cont;
11967 			mp1->b_cont = mp;
11968 			mp1 = mp->b_cont;
11969 			offset = IP_REASS_START(mp1);
11970 			if (end >= offset) {
11971 				ipf->ipf_hole_cnt--;
11972 				/* Check for overlap. */
11973 				while (end > offset) {
11974 					if (end < IP_REASS_END(mp1)) {
11975 						mp->b_wptr -= end - offset;
11976 						IP_REASS_SET_END(mp, offset);
11977 						/*
11978 						 * TODO we might bump
11979 						 * this up twice if there is
11980 						 * overlap at both ends.
11981 						 */
11982 						BUMP_MIB(ill->ill_ip_mib,
11983 						    ipIfStatsReasmPartDups);
11984 						break;
11985 					}
11986 					/* Did we cover another hole? */
11987 					if ((mp1->b_cont &&
11988 					    IP_REASS_END(mp1)
11989 					    != IP_REASS_START(mp1->b_cont) &&
11990 					    end >=
11991 					    IP_REASS_START(mp1->b_cont)) ||
11992 					    (!ipf->ipf_last_frag_seen &&
11993 					    !more)) {
11994 						ipf->ipf_hole_cnt--;
11995 					}
11996 					/* Clip out mp1. */
11997 					if ((mp->b_cont = mp1->b_cont) ==
11998 					    NULL) {
11999 						/*
12000 						 * After clipping out mp1,
12001 						 * this guy is now hanging
12002 						 * off the end.
12003 						 */
12004 						ipf->ipf_tail_mp = mp;
12005 					}
12006 					IP_REASS_SET_START(mp1, 0);
12007 					IP_REASS_SET_END(mp1, 0);
12008 					/* Subtract byte count */
12009 					ipf->ipf_count -=
12010 					    mp1->b_datap->db_lim -
12011 					    mp1->b_datap->db_base;
12012 					freeb(mp1);
12013 					BUMP_MIB(ill->ill_ip_mib,
12014 					    ipIfStatsReasmPartDups);
12015 					mp1 = mp->b_cont;
12016 					if (!mp1)
12017 						break;
12018 					offset = IP_REASS_START(mp1);
12019 				}
12020 			}
12021 			break;
12022 		}
12023 	} while (start = end, mp = next_mp);
12024 
12025 	/* Fragment just processed could be the last one. Remember this fact */
12026 	if (!more)
12027 		ipf->ipf_last_frag_seen = B_TRUE;
12028 
12029 	/* Still got holes? */
12030 	if (ipf->ipf_hole_cnt)
12031 		return (IP_REASS_PARTIAL);
12032 	/* Clean up overloaded fields to avoid upstream disasters. */
12033 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12034 		IP_REASS_SET_START(mp1, 0);
12035 		IP_REASS_SET_END(mp1, 0);
12036 	}
12037 	return (IP_REASS_COMPLETE);
12038 }
12039 
12040 /*
12041  * ipsec processing for the fast path, used for input UDP Packets
12042  * Returns true if ready for passup to UDP.
12043  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12044  * was an ESP-in-UDP packet, etc.).
12045  */
12046 static boolean_t
12047 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12048     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12049 {
12050 	uint32_t	ill_index;
12051 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12052 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12053 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12054 	udp_t		*udp = connp->conn_udp;
12055 
12056 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12057 	/* The ill_index of the incoming ILL */
12058 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12059 
12060 	/* pass packet up to the transport */
12061 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12062 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12063 		    NULL, mctl_present);
12064 		if (*first_mpp == NULL) {
12065 			return (B_FALSE);
12066 		}
12067 	}
12068 
12069 	/* Initiate IPPF processing for fastpath UDP */
12070 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12071 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12072 		if (*mpp == NULL) {
12073 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12074 			    "deferred/dropped during IPPF processing\n"));
12075 			return (B_FALSE);
12076 		}
12077 	}
12078 	/*
12079 	 * Remove 0-spi if it's 0, or move everything behind
12080 	 * the UDP header over it and forward to ESP via
12081 	 * ip_proto_input().
12082 	 */
12083 	if (udp->udp_nat_t_endpoint) {
12084 		if (mctl_present) {
12085 			/* mctl_present *shouldn't* happen. */
12086 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12087 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12088 			    &ipss->ipsec_dropper);
12089 			*first_mpp = NULL;
12090 			return (B_FALSE);
12091 		}
12092 
12093 		/* "ill" is "recv_ill" in actuality. */
12094 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12095 			return (B_FALSE);
12096 
12097 		/* Else continue like a normal UDP packet. */
12098 	}
12099 
12100 	/*
12101 	 * We make the checks as below since we are in the fast path
12102 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12103 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12104 	 */
12105 	if (connp->conn_recvif || connp->conn_recvslla ||
12106 	    connp->conn_ip_recvpktinfo) {
12107 		if (connp->conn_recvif) {
12108 			in_flags = IPF_RECVIF;
12109 		}
12110 		/*
12111 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12112 		 * so the flag passed to ip_add_info is based on IP version
12113 		 * of connp.
12114 		 */
12115 		if (connp->conn_ip_recvpktinfo) {
12116 			if (connp->conn_af_isv6) {
12117 				/*
12118 				 * V6 only needs index
12119 				 */
12120 				in_flags |= IPF_RECVIF;
12121 			} else {
12122 				/*
12123 				 * V4 needs index + matching address.
12124 				 */
12125 				in_flags |= IPF_RECVADDR;
12126 			}
12127 		}
12128 		if (connp->conn_recvslla) {
12129 			in_flags |= IPF_RECVSLLA;
12130 		}
12131 		/*
12132 		 * since in_flags are being set ill will be
12133 		 * referenced in ip_add_info, so it better not
12134 		 * be NULL.
12135 		 */
12136 		/*
12137 		 * the actual data will be contained in b_cont
12138 		 * upon successful return of the following call.
12139 		 * If the call fails then the original mblk is
12140 		 * returned.
12141 		 */
12142 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12143 		    ipst);
12144 	}
12145 
12146 	return (B_TRUE);
12147 }
12148 
12149 /*
12150  * Fragmentation reassembly.  Each ILL has a hash table for
12151  * queuing packets undergoing reassembly for all IPIFs
12152  * associated with the ILL.  The hash is based on the packet
12153  * IP ident field.  The ILL frag hash table was allocated
12154  * as a timer block at the time the ILL was created.  Whenever
12155  * there is anything on the reassembly queue, the timer will
12156  * be running.  Returns B_TRUE if successful else B_FALSE;
12157  * frees mp on failure.
12158  */
12159 static boolean_t
12160 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12161     uint32_t *cksum_val, uint16_t *cksum_flags)
12162 {
12163 	uint32_t	frag_offset_flags;
12164 	mblk_t		*mp = *mpp;
12165 	mblk_t		*t_mp;
12166 	ipaddr_t	dst;
12167 	uint8_t		proto = ipha->ipha_protocol;
12168 	uint32_t	sum_val;
12169 	uint16_t	sum_flags;
12170 	ipf_t		*ipf;
12171 	ipf_t		**ipfp;
12172 	ipfb_t		*ipfb;
12173 	uint16_t	ident;
12174 	uint32_t	offset;
12175 	ipaddr_t	src;
12176 	uint_t		hdr_length;
12177 	uint32_t	end;
12178 	mblk_t		*mp1;
12179 	mblk_t		*tail_mp;
12180 	size_t		count;
12181 	size_t		msg_len;
12182 	uint8_t		ecn_info = 0;
12183 	uint32_t	packet_size;
12184 	boolean_t	pruned = B_FALSE;
12185 	ip_stack_t *ipst = ill->ill_ipst;
12186 
12187 	if (cksum_val != NULL)
12188 		*cksum_val = 0;
12189 	if (cksum_flags != NULL)
12190 		*cksum_flags = 0;
12191 
12192 	/*
12193 	 * Drop the fragmented as early as possible, if
12194 	 * we don't have resource(s) to re-assemble.
12195 	 */
12196 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12197 		freemsg(mp);
12198 		return (B_FALSE);
12199 	}
12200 
12201 	/* Check for fragmentation offset; return if there's none */
12202 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12203 	    (IPH_MF | IPH_OFFSET)) == 0)
12204 		return (B_TRUE);
12205 
12206 	/*
12207 	 * We utilize hardware computed checksum info only for UDP since
12208 	 * IP fragmentation is a normal occurrence for the protocol.  In
12209 	 * addition, checksum offload support for IP fragments carrying
12210 	 * UDP payload is commonly implemented across network adapters.
12211 	 */
12212 	ASSERT(recv_ill != NULL);
12213 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12214 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12215 		mblk_t *mp1 = mp->b_cont;
12216 		int32_t len;
12217 
12218 		/* Record checksum information from the packet */
12219 		sum_val = (uint32_t)DB_CKSUM16(mp);
12220 		sum_flags = DB_CKSUMFLAGS(mp);
12221 
12222 		/* IP payload offset from beginning of mblk */
12223 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12224 
12225 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12226 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12227 		    offset >= DB_CKSUMSTART(mp) &&
12228 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12229 			uint32_t adj;
12230 			/*
12231 			 * Partial checksum has been calculated by hardware
12232 			 * and attached to the packet; in addition, any
12233 			 * prepended extraneous data is even byte aligned.
12234 			 * If any such data exists, we adjust the checksum;
12235 			 * this would also handle any postpended data.
12236 			 */
12237 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12238 			    mp, mp1, len, adj);
12239 
12240 			/* One's complement subtract extraneous checksum */
12241 			if (adj >= sum_val)
12242 				sum_val = ~(adj - sum_val) & 0xFFFF;
12243 			else
12244 				sum_val -= adj;
12245 		}
12246 	} else {
12247 		sum_val = 0;
12248 		sum_flags = 0;
12249 	}
12250 
12251 	/* Clear hardware checksumming flag */
12252 	DB_CKSUMFLAGS(mp) = 0;
12253 
12254 	ident = ipha->ipha_ident;
12255 	offset = (frag_offset_flags << 3) & 0xFFFF;
12256 	src = ipha->ipha_src;
12257 	dst = ipha->ipha_dst;
12258 	hdr_length = IPH_HDR_LENGTH(ipha);
12259 	end = ntohs(ipha->ipha_length) - hdr_length;
12260 
12261 	/* If end == 0 then we have a packet with no data, so just free it */
12262 	if (end == 0) {
12263 		freemsg(mp);
12264 		return (B_FALSE);
12265 	}
12266 
12267 	/* Record the ECN field info. */
12268 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12269 	if (offset != 0) {
12270 		/*
12271 		 * If this isn't the first piece, strip the header, and
12272 		 * add the offset to the end value.
12273 		 */
12274 		mp->b_rptr += hdr_length;
12275 		end += offset;
12276 	}
12277 
12278 	msg_len = MBLKSIZE(mp);
12279 	tail_mp = mp;
12280 	while (tail_mp->b_cont != NULL) {
12281 		tail_mp = tail_mp->b_cont;
12282 		msg_len += MBLKSIZE(tail_mp);
12283 	}
12284 
12285 	/* If the reassembly list for this ILL will get too big, prune it */
12286 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12287 	    ipst->ips_ip_reass_queue_bytes) {
12288 		ill_frag_prune(ill,
12289 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12290 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12291 		pruned = B_TRUE;
12292 	}
12293 
12294 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12295 	mutex_enter(&ipfb->ipfb_lock);
12296 
12297 	ipfp = &ipfb->ipfb_ipf;
12298 	/* Try to find an existing fragment queue for this packet. */
12299 	for (;;) {
12300 		ipf = ipfp[0];
12301 		if (ipf != NULL) {
12302 			/*
12303 			 * It has to match on ident and src/dst address.
12304 			 */
12305 			if (ipf->ipf_ident == ident &&
12306 			    ipf->ipf_src == src &&
12307 			    ipf->ipf_dst == dst &&
12308 			    ipf->ipf_protocol == proto) {
12309 				/*
12310 				 * If we have received too many
12311 				 * duplicate fragments for this packet
12312 				 * free it.
12313 				 */
12314 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12315 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12316 					freemsg(mp);
12317 					mutex_exit(&ipfb->ipfb_lock);
12318 					return (B_FALSE);
12319 				}
12320 				/* Found it. */
12321 				break;
12322 			}
12323 			ipfp = &ipf->ipf_hash_next;
12324 			continue;
12325 		}
12326 
12327 		/*
12328 		 * If we pruned the list, do we want to store this new
12329 		 * fragment?. We apply an optimization here based on the
12330 		 * fact that most fragments will be received in order.
12331 		 * So if the offset of this incoming fragment is zero,
12332 		 * it is the first fragment of a new packet. We will
12333 		 * keep it.  Otherwise drop the fragment, as we have
12334 		 * probably pruned the packet already (since the
12335 		 * packet cannot be found).
12336 		 */
12337 		if (pruned && offset != 0) {
12338 			mutex_exit(&ipfb->ipfb_lock);
12339 			freemsg(mp);
12340 			return (B_FALSE);
12341 		}
12342 
12343 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12344 			/*
12345 			 * Too many fragmented packets in this hash
12346 			 * bucket. Free the oldest.
12347 			 */
12348 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12349 		}
12350 
12351 		/* New guy.  Allocate a frag message. */
12352 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12353 		if (mp1 == NULL) {
12354 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12355 			freemsg(mp);
12356 reass_done:
12357 			mutex_exit(&ipfb->ipfb_lock);
12358 			return (B_FALSE);
12359 		}
12360 
12361 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12362 		mp1->b_cont = mp;
12363 
12364 		/* Initialize the fragment header. */
12365 		ipf = (ipf_t *)mp1->b_rptr;
12366 		ipf->ipf_mp = mp1;
12367 		ipf->ipf_ptphn = ipfp;
12368 		ipfp[0] = ipf;
12369 		ipf->ipf_hash_next = NULL;
12370 		ipf->ipf_ident = ident;
12371 		ipf->ipf_protocol = proto;
12372 		ipf->ipf_src = src;
12373 		ipf->ipf_dst = dst;
12374 		ipf->ipf_nf_hdr_len = 0;
12375 		/* Record reassembly start time. */
12376 		ipf->ipf_timestamp = gethrestime_sec();
12377 		/* Record ipf generation and account for frag header */
12378 		ipf->ipf_gen = ill->ill_ipf_gen++;
12379 		ipf->ipf_count = MBLKSIZE(mp1);
12380 		ipf->ipf_last_frag_seen = B_FALSE;
12381 		ipf->ipf_ecn = ecn_info;
12382 		ipf->ipf_num_dups = 0;
12383 		ipfb->ipfb_frag_pkts++;
12384 		ipf->ipf_checksum = 0;
12385 		ipf->ipf_checksum_flags = 0;
12386 
12387 		/* Store checksum value in fragment header */
12388 		if (sum_flags != 0) {
12389 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12390 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12391 			ipf->ipf_checksum = sum_val;
12392 			ipf->ipf_checksum_flags = sum_flags;
12393 		}
12394 
12395 		/*
12396 		 * We handle reassembly two ways.  In the easy case,
12397 		 * where all the fragments show up in order, we do
12398 		 * minimal bookkeeping, and just clip new pieces on
12399 		 * the end.  If we ever see a hole, then we go off
12400 		 * to ip_reassemble which has to mark the pieces and
12401 		 * keep track of the number of holes, etc.  Obviously,
12402 		 * the point of having both mechanisms is so we can
12403 		 * handle the easy case as efficiently as possible.
12404 		 */
12405 		if (offset == 0) {
12406 			/* Easy case, in-order reassembly so far. */
12407 			ipf->ipf_count += msg_len;
12408 			ipf->ipf_tail_mp = tail_mp;
12409 			/*
12410 			 * Keep track of next expected offset in
12411 			 * ipf_end.
12412 			 */
12413 			ipf->ipf_end = end;
12414 			ipf->ipf_nf_hdr_len = hdr_length;
12415 		} else {
12416 			/* Hard case, hole at the beginning. */
12417 			ipf->ipf_tail_mp = NULL;
12418 			/*
12419 			 * ipf_end == 0 means that we have given up
12420 			 * on easy reassembly.
12421 			 */
12422 			ipf->ipf_end = 0;
12423 
12424 			/* Forget checksum offload from now on */
12425 			ipf->ipf_checksum_flags = 0;
12426 
12427 			/*
12428 			 * ipf_hole_cnt is set by ip_reassemble.
12429 			 * ipf_count is updated by ip_reassemble.
12430 			 * No need to check for return value here
12431 			 * as we don't expect reassembly to complete
12432 			 * or fail for the first fragment itself.
12433 			 */
12434 			(void) ip_reassemble(mp, ipf,
12435 			    (frag_offset_flags & IPH_OFFSET) << 3,
12436 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12437 		}
12438 		/* Update per ipfb and ill byte counts */
12439 		ipfb->ipfb_count += ipf->ipf_count;
12440 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12441 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12442 		/* If the frag timer wasn't already going, start it. */
12443 		mutex_enter(&ill->ill_lock);
12444 		ill_frag_timer_start(ill);
12445 		mutex_exit(&ill->ill_lock);
12446 		goto reass_done;
12447 	}
12448 
12449 	/*
12450 	 * If the packet's flag has changed (it could be coming up
12451 	 * from an interface different than the previous, therefore
12452 	 * possibly different checksum capability), then forget about
12453 	 * any stored checksum states.  Otherwise add the value to
12454 	 * the existing one stored in the fragment header.
12455 	 */
12456 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12457 		sum_val += ipf->ipf_checksum;
12458 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12459 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12460 		ipf->ipf_checksum = sum_val;
12461 	} else if (ipf->ipf_checksum_flags != 0) {
12462 		/* Forget checksum offload from now on */
12463 		ipf->ipf_checksum_flags = 0;
12464 	}
12465 
12466 	/*
12467 	 * We have a new piece of a datagram which is already being
12468 	 * reassembled.  Update the ECN info if all IP fragments
12469 	 * are ECN capable.  If there is one which is not, clear
12470 	 * all the info.  If there is at least one which has CE
12471 	 * code point, IP needs to report that up to transport.
12472 	 */
12473 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12474 		if (ecn_info == IPH_ECN_CE)
12475 			ipf->ipf_ecn = IPH_ECN_CE;
12476 	} else {
12477 		ipf->ipf_ecn = IPH_ECN_NECT;
12478 	}
12479 	if (offset && ipf->ipf_end == offset) {
12480 		/* The new fragment fits at the end */
12481 		ipf->ipf_tail_mp->b_cont = mp;
12482 		/* Update the byte count */
12483 		ipf->ipf_count += msg_len;
12484 		/* Update per ipfb and ill byte counts */
12485 		ipfb->ipfb_count += msg_len;
12486 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12487 		atomic_add_32(&ill->ill_frag_count, msg_len);
12488 		if (frag_offset_flags & IPH_MF) {
12489 			/* More to come. */
12490 			ipf->ipf_end = end;
12491 			ipf->ipf_tail_mp = tail_mp;
12492 			goto reass_done;
12493 		}
12494 	} else {
12495 		/* Go do the hard cases. */
12496 		int ret;
12497 
12498 		if (offset == 0)
12499 			ipf->ipf_nf_hdr_len = hdr_length;
12500 
12501 		/* Save current byte count */
12502 		count = ipf->ipf_count;
12503 		ret = ip_reassemble(mp, ipf,
12504 		    (frag_offset_flags & IPH_OFFSET) << 3,
12505 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12506 		/* Count of bytes added and subtracted (freeb()ed) */
12507 		count = ipf->ipf_count - count;
12508 		if (count) {
12509 			/* Update per ipfb and ill byte counts */
12510 			ipfb->ipfb_count += count;
12511 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12512 			atomic_add_32(&ill->ill_frag_count, count);
12513 		}
12514 		if (ret == IP_REASS_PARTIAL) {
12515 			goto reass_done;
12516 		} else if (ret == IP_REASS_FAILED) {
12517 			/* Reassembly failed. Free up all resources */
12518 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12519 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12520 				IP_REASS_SET_START(t_mp, 0);
12521 				IP_REASS_SET_END(t_mp, 0);
12522 			}
12523 			freemsg(mp);
12524 			goto reass_done;
12525 		}
12526 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12527 	}
12528 	/*
12529 	 * We have completed reassembly.  Unhook the frag header from
12530 	 * the reassembly list.
12531 	 *
12532 	 * Before we free the frag header, record the ECN info
12533 	 * to report back to the transport.
12534 	 */
12535 	ecn_info = ipf->ipf_ecn;
12536 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12537 	ipfp = ipf->ipf_ptphn;
12538 
12539 	/* We need to supply these to caller */
12540 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12541 		sum_val = ipf->ipf_checksum;
12542 	else
12543 		sum_val = 0;
12544 
12545 	mp1 = ipf->ipf_mp;
12546 	count = ipf->ipf_count;
12547 	ipf = ipf->ipf_hash_next;
12548 	if (ipf != NULL)
12549 		ipf->ipf_ptphn = ipfp;
12550 	ipfp[0] = ipf;
12551 	atomic_add_32(&ill->ill_frag_count, -count);
12552 	ASSERT(ipfb->ipfb_count >= count);
12553 	ipfb->ipfb_count -= count;
12554 	ipfb->ipfb_frag_pkts--;
12555 	mutex_exit(&ipfb->ipfb_lock);
12556 	/* Ditch the frag header. */
12557 	mp = mp1->b_cont;
12558 
12559 	freeb(mp1);
12560 
12561 	/* Restore original IP length in header. */
12562 	packet_size = (uint32_t)msgdsize(mp);
12563 	if (packet_size > IP_MAXPACKET) {
12564 		freemsg(mp);
12565 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12566 		return (B_FALSE);
12567 	}
12568 
12569 	if (DB_REF(mp) > 1) {
12570 		mblk_t *mp2 = copymsg(mp);
12571 
12572 		freemsg(mp);
12573 		if (mp2 == NULL) {
12574 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12575 			return (B_FALSE);
12576 		}
12577 		mp = mp2;
12578 	}
12579 	ipha = (ipha_t *)mp->b_rptr;
12580 
12581 	ipha->ipha_length = htons((uint16_t)packet_size);
12582 	/* We're now complete, zip the frag state */
12583 	ipha->ipha_fragment_offset_and_flags = 0;
12584 	/* Record the ECN info. */
12585 	ipha->ipha_type_of_service &= 0xFC;
12586 	ipha->ipha_type_of_service |= ecn_info;
12587 	*mpp = mp;
12588 
12589 	/* Reassembly is successful; return checksum information if needed */
12590 	if (cksum_val != NULL)
12591 		*cksum_val = sum_val;
12592 	if (cksum_flags != NULL)
12593 		*cksum_flags = sum_flags;
12594 
12595 	return (B_TRUE);
12596 }
12597 
12598 /*
12599  * Perform ip header check sum update local options.
12600  * return B_TRUE if all is well, else return B_FALSE and release
12601  * the mp. caller is responsible for decrementing ire ref cnt.
12602  */
12603 static boolean_t
12604 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12605     ip_stack_t *ipst)
12606 {
12607 	mblk_t		*first_mp;
12608 	boolean_t	mctl_present;
12609 	uint16_t	sum;
12610 
12611 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12612 	/*
12613 	 * Don't do the checksum if it has gone through AH/ESP
12614 	 * processing.
12615 	 */
12616 	if (!mctl_present) {
12617 		sum = ip_csum_hdr(ipha);
12618 		if (sum != 0) {
12619 			if (ill != NULL) {
12620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12621 			} else {
12622 				BUMP_MIB(&ipst->ips_ip_mib,
12623 				    ipIfStatsInCksumErrs);
12624 			}
12625 			freemsg(first_mp);
12626 			return (B_FALSE);
12627 		}
12628 	}
12629 
12630 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12631 		if (mctl_present)
12632 			freeb(first_mp);
12633 		return (B_FALSE);
12634 	}
12635 
12636 	return (B_TRUE);
12637 }
12638 
12639 /*
12640  * All udp packet are delivered to the local host via this routine.
12641  */
12642 void
12643 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12644     ill_t *recv_ill)
12645 {
12646 	uint32_t	sum;
12647 	uint32_t	u1;
12648 	boolean_t	mctl_present;
12649 	conn_t		*connp;
12650 	mblk_t		*first_mp;
12651 	uint16_t	*up;
12652 	ill_t		*ill = (ill_t *)q->q_ptr;
12653 	uint16_t	reass_hck_flags = 0;
12654 	ip_stack_t	*ipst;
12655 
12656 	ASSERT(recv_ill != NULL);
12657 	ipst = recv_ill->ill_ipst;
12658 
12659 #define	rptr    ((uchar_t *)ipha)
12660 
12661 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12662 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12663 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12664 	ASSERT(ill != NULL);
12665 
12666 	/*
12667 	 * FAST PATH for udp packets
12668 	 */
12669 
12670 	/* u1 is # words of IP options */
12671 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12672 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12673 
12674 	/* IP options present */
12675 	if (u1 != 0)
12676 		goto ipoptions;
12677 
12678 	/* Check the IP header checksum.  */
12679 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12680 		/* Clear the IP header h/w cksum flag */
12681 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12682 	} else if (!mctl_present) {
12683 		/*
12684 		 * Don't verify header checksum if this packet is coming
12685 		 * back from AH/ESP as we already did it.
12686 		 */
12687 #define	uph	((uint16_t *)ipha)
12688 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12689 		    uph[6] + uph[7] + uph[8] + uph[9];
12690 #undef	uph
12691 		/* finish doing IP checksum */
12692 		sum = (sum & 0xFFFF) + (sum >> 16);
12693 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12694 		if (sum != 0 && sum != 0xFFFF) {
12695 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12696 			freemsg(first_mp);
12697 			return;
12698 		}
12699 	}
12700 
12701 	/*
12702 	 * Count for SNMP of inbound packets for ire.
12703 	 * if mctl is present this might be a secure packet and
12704 	 * has already been counted for in ip_proto_input().
12705 	 */
12706 	if (!mctl_present) {
12707 		UPDATE_IB_PKT_COUNT(ire);
12708 		ire->ire_last_used_time = lbolt;
12709 	}
12710 
12711 	/* packet part of fragmented IP packet? */
12712 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12713 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12714 		goto fragmented;
12715 	}
12716 
12717 	/* u1 = IP header length (20 bytes) */
12718 	u1 = IP_SIMPLE_HDR_LENGTH;
12719 
12720 	/* packet does not contain complete IP & UDP headers */
12721 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12722 		goto udppullup;
12723 
12724 	/* up points to UDP header */
12725 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12726 #define	iphs    ((uint16_t *)ipha)
12727 
12728 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12729 	if (up[3] != 0) {
12730 		mblk_t *mp1 = mp->b_cont;
12731 		boolean_t cksum_err;
12732 		uint16_t hck_flags = 0;
12733 
12734 		/* Pseudo-header checksum */
12735 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12736 		    iphs[9] + up[2];
12737 
12738 		/*
12739 		 * Revert to software checksum calculation if the interface
12740 		 * isn't capable of checksum offload or if IPsec is present.
12741 		 */
12742 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12743 			hck_flags = DB_CKSUMFLAGS(mp);
12744 
12745 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12746 			IP_STAT(ipst, ip_in_sw_cksum);
12747 
12748 		IP_CKSUM_RECV(hck_flags, u1,
12749 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12750 		    (int32_t)((uchar_t *)up - rptr),
12751 		    mp, mp1, cksum_err);
12752 
12753 		if (cksum_err) {
12754 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12755 			if (hck_flags & HCK_FULLCKSUM)
12756 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12757 			else if (hck_flags & HCK_PARTIALCKSUM)
12758 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12759 			else
12760 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12761 
12762 			freemsg(first_mp);
12763 			return;
12764 		}
12765 	}
12766 
12767 	/* Non-fragmented broadcast or multicast packet? */
12768 	if (ire->ire_type == IRE_BROADCAST)
12769 		goto udpslowpath;
12770 
12771 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12772 	    ire->ire_zoneid, ipst)) != NULL) {
12773 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12774 		IP_STAT(ipst, ip_udp_fast_path);
12775 
12776 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12777 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12778 			freemsg(mp);
12779 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12780 		} else {
12781 			if (!mctl_present) {
12782 				BUMP_MIB(ill->ill_ip_mib,
12783 				    ipIfStatsHCInDelivers);
12784 			}
12785 			/*
12786 			 * mp and first_mp can change.
12787 			 */
12788 			if (ip_udp_check(q, connp, recv_ill,
12789 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12790 				/* Send it upstream */
12791 				(connp->conn_recv)(connp, mp, NULL);
12792 			}
12793 		}
12794 		/*
12795 		 * freeb() cannot deal with null mblk being passed
12796 		 * in and first_mp can be set to null in the call
12797 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12798 		 */
12799 		if (mctl_present && first_mp != NULL) {
12800 			freeb(first_mp);
12801 		}
12802 		CONN_DEC_REF(connp);
12803 		return;
12804 	}
12805 
12806 	/*
12807 	 * if we got here we know the packet is not fragmented and
12808 	 * has no options. The classifier could not find a conn_t and
12809 	 * most likely its an icmp packet so send it through slow path.
12810 	 */
12811 
12812 	goto udpslowpath;
12813 
12814 ipoptions:
12815 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12816 		goto slow_done;
12817 	}
12818 
12819 	UPDATE_IB_PKT_COUNT(ire);
12820 	ire->ire_last_used_time = lbolt;
12821 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12822 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12823 fragmented:
12824 		/*
12825 		 * "sum" and "reass_hck_flags" are non-zero if the
12826 		 * reassembled packet has a valid hardware computed
12827 		 * checksum information associated with it.
12828 		 */
12829 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12830 		    &reass_hck_flags)) {
12831 			goto slow_done;
12832 		}
12833 
12834 		/*
12835 		 * Make sure that first_mp points back to mp as
12836 		 * the mp we came in with could have changed in
12837 		 * ip_rput_fragment().
12838 		 */
12839 		ASSERT(!mctl_present);
12840 		ipha = (ipha_t *)mp->b_rptr;
12841 		first_mp = mp;
12842 	}
12843 
12844 	/* Now we have a complete datagram, destined for this machine. */
12845 	u1 = IPH_HDR_LENGTH(ipha);
12846 	/* Pull up the UDP header, if necessary. */
12847 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12848 udppullup:
12849 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12850 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12851 			freemsg(first_mp);
12852 			goto slow_done;
12853 		}
12854 		ipha = (ipha_t *)mp->b_rptr;
12855 	}
12856 
12857 	/*
12858 	 * Validate the checksum for the reassembled packet; for the
12859 	 * pullup case we calculate the payload checksum in software.
12860 	 */
12861 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12862 	if (up[3] != 0) {
12863 		boolean_t cksum_err;
12864 
12865 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12866 			IP_STAT(ipst, ip_in_sw_cksum);
12867 
12868 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12869 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12870 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12871 		    iphs[9] + up[2], sum, cksum_err);
12872 
12873 		if (cksum_err) {
12874 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12875 
12876 			if (reass_hck_flags & HCK_FULLCKSUM)
12877 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12878 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12879 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12880 			else
12881 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12882 
12883 			freemsg(first_mp);
12884 			goto slow_done;
12885 		}
12886 	}
12887 udpslowpath:
12888 
12889 	/* Clear hardware checksum flag to be safe */
12890 	DB_CKSUMFLAGS(mp) = 0;
12891 
12892 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12893 	    (ire->ire_type == IRE_BROADCAST),
12894 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12895 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12896 
12897 slow_done:
12898 	IP_STAT(ipst, ip_udp_slow_path);
12899 	return;
12900 
12901 #undef  iphs
12902 #undef  rptr
12903 }
12904 
12905 /* ARGSUSED */
12906 static mblk_t *
12907 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12908     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12909     ill_rx_ring_t *ill_ring)
12910 {
12911 	conn_t		*connp;
12912 	uint32_t	sum;
12913 	uint32_t	u1;
12914 	uint16_t	*up;
12915 	int		offset;
12916 	ssize_t		len;
12917 	mblk_t		*mp1;
12918 	boolean_t	syn_present = B_FALSE;
12919 	tcph_t		*tcph;
12920 	uint_t		tcph_flags;
12921 	uint_t		ip_hdr_len;
12922 	ill_t		*ill = (ill_t *)q->q_ptr;
12923 	zoneid_t	zoneid = ire->ire_zoneid;
12924 	boolean_t	cksum_err;
12925 	uint16_t	hck_flags = 0;
12926 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12927 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12928 
12929 #define	rptr	((uchar_t *)ipha)
12930 
12931 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12932 	ASSERT(ill != NULL);
12933 
12934 	/*
12935 	 * FAST PATH for tcp packets
12936 	 */
12937 
12938 	/* u1 is # words of IP options */
12939 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12940 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12941 
12942 	/* IP options present */
12943 	if (u1) {
12944 		goto ipoptions;
12945 	} else if (!mctl_present) {
12946 		/* Check the IP header checksum.  */
12947 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12948 			/* Clear the IP header h/w cksum flag */
12949 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12950 		} else if (!mctl_present) {
12951 			/*
12952 			 * Don't verify header checksum if this packet
12953 			 * is coming back from AH/ESP as we already did it.
12954 			 */
12955 #define	uph	((uint16_t *)ipha)
12956 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12957 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12958 #undef	uph
12959 			/* finish doing IP checksum */
12960 			sum = (sum & 0xFFFF) + (sum >> 16);
12961 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12962 			if (sum != 0 && sum != 0xFFFF) {
12963 				BUMP_MIB(ill->ill_ip_mib,
12964 				    ipIfStatsInCksumErrs);
12965 				goto error;
12966 			}
12967 		}
12968 	}
12969 
12970 	if (!mctl_present) {
12971 		UPDATE_IB_PKT_COUNT(ire);
12972 		ire->ire_last_used_time = lbolt;
12973 	}
12974 
12975 	/* packet part of fragmented IP packet? */
12976 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12977 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12978 		goto fragmented;
12979 	}
12980 
12981 	/* u1 = IP header length (20 bytes) */
12982 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12983 
12984 	/* does packet contain IP+TCP headers? */
12985 	len = mp->b_wptr - rptr;
12986 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12987 		IP_STAT(ipst, ip_tcppullup);
12988 		goto tcppullup;
12989 	}
12990 
12991 	/* TCP options present? */
12992 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12993 
12994 	/*
12995 	 * If options need to be pulled up, then goto tcpoptions.
12996 	 * otherwise we are still in the fast path
12997 	 */
12998 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12999 		IP_STAT(ipst, ip_tcpoptions);
13000 		goto tcpoptions;
13001 	}
13002 
13003 	/* multiple mblks of tcp data? */
13004 	if ((mp1 = mp->b_cont) != NULL) {
13005 		/* more then two? */
13006 		if (mp1->b_cont != NULL) {
13007 			IP_STAT(ipst, ip_multipkttcp);
13008 			goto multipkttcp;
13009 		}
13010 		len += mp1->b_wptr - mp1->b_rptr;
13011 	}
13012 
13013 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13014 
13015 	/* part of pseudo checksum */
13016 
13017 	/* TCP datagram length */
13018 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13019 
13020 #define	iphs    ((uint16_t *)ipha)
13021 
13022 #ifdef	_BIG_ENDIAN
13023 	u1 += IPPROTO_TCP;
13024 #else
13025 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13026 #endif
13027 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13028 
13029 	/*
13030 	 * Revert to software checksum calculation if the interface
13031 	 * isn't capable of checksum offload or if IPsec is present.
13032 	 */
13033 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13034 		hck_flags = DB_CKSUMFLAGS(mp);
13035 
13036 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13037 		IP_STAT(ipst, ip_in_sw_cksum);
13038 
13039 	IP_CKSUM_RECV(hck_flags, u1,
13040 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13041 	    (int32_t)((uchar_t *)up - rptr),
13042 	    mp, mp1, cksum_err);
13043 
13044 	if (cksum_err) {
13045 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13046 
13047 		if (hck_flags & HCK_FULLCKSUM)
13048 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13049 		else if (hck_flags & HCK_PARTIALCKSUM)
13050 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13051 		else
13052 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13053 
13054 		goto error;
13055 	}
13056 
13057 try_again:
13058 
13059 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13060 	    zoneid, ipst)) == NULL) {
13061 		/* Send the TH_RST */
13062 		goto no_conn;
13063 	}
13064 
13065 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13066 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13067 
13068 	/*
13069 	 * TCP FAST PATH for AF_INET socket.
13070 	 *
13071 	 * TCP fast path to avoid extra work. An AF_INET socket type
13072 	 * does not have facility to receive extra information via
13073 	 * ip_process or ip_add_info. Also, when the connection was
13074 	 * established, we made a check if this connection is impacted
13075 	 * by any global IPsec policy or per connection policy (a
13076 	 * policy that comes in effect later will not apply to this
13077 	 * connection). Since all this can be determined at the
13078 	 * connection establishment time, a quick check of flags
13079 	 * can avoid extra work.
13080 	 */
13081 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13082 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13083 		ASSERT(first_mp == mp);
13084 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13085 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13086 			SET_SQUEUE(mp, tcp_rput_data, connp);
13087 			return (mp);
13088 		}
13089 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13090 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13091 		SET_SQUEUE(mp, tcp_input, connp);
13092 		return (mp);
13093 	}
13094 
13095 	if (tcph_flags == TH_SYN) {
13096 		if (IPCL_IS_TCP(connp)) {
13097 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13098 			DB_CKSUMSTART(mp) =
13099 			    (intptr_t)ip_squeue_get(ill_ring);
13100 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13101 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13102 				BUMP_MIB(ill->ill_ip_mib,
13103 				    ipIfStatsHCInDelivers);
13104 				SET_SQUEUE(mp, connp->conn_recv, connp);
13105 				return (mp);
13106 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13107 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13108 				BUMP_MIB(ill->ill_ip_mib,
13109 				    ipIfStatsHCInDelivers);
13110 				ip_squeue_enter_unbound++;
13111 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13112 				    connp);
13113 				return (mp);
13114 			}
13115 			syn_present = B_TRUE;
13116 		}
13117 	}
13118 
13119 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13120 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13121 
13122 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13123 		/* No need to send this packet to TCP */
13124 		if ((flags & TH_RST) || (flags & TH_URG)) {
13125 			CONN_DEC_REF(connp);
13126 			freemsg(first_mp);
13127 			return (NULL);
13128 		}
13129 		if (flags & TH_ACK) {
13130 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13131 			    ipst->ips_netstack->netstack_tcp, connp);
13132 			CONN_DEC_REF(connp);
13133 			return (NULL);
13134 		}
13135 
13136 		CONN_DEC_REF(connp);
13137 		freemsg(first_mp);
13138 		return (NULL);
13139 	}
13140 
13141 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13142 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13143 		    ipha, NULL, mctl_present);
13144 		if (first_mp == NULL) {
13145 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13146 			CONN_DEC_REF(connp);
13147 			return (NULL);
13148 		}
13149 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13150 			ASSERT(syn_present);
13151 			if (mctl_present) {
13152 				ASSERT(first_mp != mp);
13153 				first_mp->b_datap->db_struioflag |=
13154 				    STRUIO_POLICY;
13155 			} else {
13156 				ASSERT(first_mp == mp);
13157 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13158 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13159 			}
13160 		} else {
13161 			/*
13162 			 * Discard first_mp early since we're dealing with a
13163 			 * fully-connected conn_t and tcp doesn't do policy in
13164 			 * this case.
13165 			 */
13166 			if (mctl_present) {
13167 				freeb(first_mp);
13168 				mctl_present = B_FALSE;
13169 			}
13170 			first_mp = mp;
13171 		}
13172 	}
13173 
13174 	/* Initiate IPPF processing for fastpath */
13175 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13176 		uint32_t	ill_index;
13177 
13178 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13179 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13180 		if (mp == NULL) {
13181 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13182 			    "deferred/dropped during IPPF processing\n"));
13183 			CONN_DEC_REF(connp);
13184 			if (mctl_present)
13185 				freeb(first_mp);
13186 			return (NULL);
13187 		} else if (mctl_present) {
13188 			/*
13189 			 * ip_process might return a new mp.
13190 			 */
13191 			ASSERT(first_mp != mp);
13192 			first_mp->b_cont = mp;
13193 		} else {
13194 			first_mp = mp;
13195 		}
13196 
13197 	}
13198 
13199 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13200 		/*
13201 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13202 		 * make sure IPF_RECVIF is passed to ip_add_info.
13203 		 */
13204 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13205 		    IPCL_ZONEID(connp), ipst);
13206 		if (mp == NULL) {
13207 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13208 			CONN_DEC_REF(connp);
13209 			if (mctl_present)
13210 				freeb(first_mp);
13211 			return (NULL);
13212 		} else if (mctl_present) {
13213 			/*
13214 			 * ip_add_info might return a new mp.
13215 			 */
13216 			ASSERT(first_mp != mp);
13217 			first_mp->b_cont = mp;
13218 		} else {
13219 			first_mp = mp;
13220 		}
13221 	}
13222 
13223 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13224 	if (IPCL_IS_TCP(connp)) {
13225 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13226 		return (first_mp);
13227 	} else {
13228 		/* SOCK_RAW, IPPROTO_TCP case */
13229 		(connp->conn_recv)(connp, first_mp, NULL);
13230 		CONN_DEC_REF(connp);
13231 		return (NULL);
13232 	}
13233 
13234 no_conn:
13235 	/* Initiate IPPf processing, if needed. */
13236 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13237 		uint32_t ill_index;
13238 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13239 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13240 		if (first_mp == NULL) {
13241 			return (NULL);
13242 		}
13243 	}
13244 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13245 
13246 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13247 	    ipst->ips_netstack->netstack_tcp, NULL);
13248 	return (NULL);
13249 ipoptions:
13250 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13251 		goto slow_done;
13252 	}
13253 
13254 	UPDATE_IB_PKT_COUNT(ire);
13255 	ire->ire_last_used_time = lbolt;
13256 
13257 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13258 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13259 fragmented:
13260 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13261 			if (mctl_present)
13262 				freeb(first_mp);
13263 			goto slow_done;
13264 		}
13265 		/*
13266 		 * Make sure that first_mp points back to mp as
13267 		 * the mp we came in with could have changed in
13268 		 * ip_rput_fragment().
13269 		 */
13270 		ASSERT(!mctl_present);
13271 		ipha = (ipha_t *)mp->b_rptr;
13272 		first_mp = mp;
13273 	}
13274 
13275 	/* Now we have a complete datagram, destined for this machine. */
13276 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13277 
13278 	len = mp->b_wptr - mp->b_rptr;
13279 	/* Pull up a minimal TCP header, if necessary. */
13280 	if (len < (u1 + 20)) {
13281 tcppullup:
13282 		if (!pullupmsg(mp, u1 + 20)) {
13283 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13284 			goto error;
13285 		}
13286 		ipha = (ipha_t *)mp->b_rptr;
13287 		len = mp->b_wptr - mp->b_rptr;
13288 	}
13289 
13290 	/*
13291 	 * Extract the offset field from the TCP header.  As usual, we
13292 	 * try to help the compiler more than the reader.
13293 	 */
13294 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13295 	if (offset != 5) {
13296 tcpoptions:
13297 		if (offset < 5) {
13298 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13299 			goto error;
13300 		}
13301 		/*
13302 		 * There must be TCP options.
13303 		 * Make sure we can grab them.
13304 		 */
13305 		offset <<= 2;
13306 		offset += u1;
13307 		if (len < offset) {
13308 			if (!pullupmsg(mp, offset)) {
13309 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13310 				goto error;
13311 			}
13312 			ipha = (ipha_t *)mp->b_rptr;
13313 			len = mp->b_wptr - rptr;
13314 		}
13315 	}
13316 
13317 	/* Get the total packet length in len, including headers. */
13318 	if (mp->b_cont) {
13319 multipkttcp:
13320 		len = msgdsize(mp);
13321 	}
13322 
13323 	/*
13324 	 * Check the TCP checksum by pulling together the pseudo-
13325 	 * header checksum, and passing it to ip_csum to be added in
13326 	 * with the TCP datagram.
13327 	 *
13328 	 * Since we are not using the hwcksum if available we must
13329 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13330 	 * If either of these fails along the way the mblk is freed.
13331 	 * If this logic ever changes and mblk is reused to say send
13332 	 * ICMP's back, then this flag may need to be cleared in
13333 	 * other places as well.
13334 	 */
13335 	DB_CKSUMFLAGS(mp) = 0;
13336 
13337 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13338 
13339 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13340 #ifdef	_BIG_ENDIAN
13341 	u1 += IPPROTO_TCP;
13342 #else
13343 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13344 #endif
13345 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13346 	/*
13347 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13348 	 */
13349 	IP_STAT(ipst, ip_in_sw_cksum);
13350 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13351 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13352 		goto error;
13353 	}
13354 
13355 	IP_STAT(ipst, ip_tcp_slow_path);
13356 	goto try_again;
13357 #undef  iphs
13358 #undef  rptr
13359 
13360 error:
13361 	freemsg(first_mp);
13362 slow_done:
13363 	return (NULL);
13364 }
13365 
13366 /* ARGSUSED */
13367 static void
13368 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13369     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13370 {
13371 	conn_t		*connp;
13372 	uint32_t	sum;
13373 	uint32_t	u1;
13374 	ssize_t		len;
13375 	sctp_hdr_t	*sctph;
13376 	zoneid_t	zoneid = ire->ire_zoneid;
13377 	uint32_t	pktsum;
13378 	uint32_t	calcsum;
13379 	uint32_t	ports;
13380 	in6_addr_t	map_src, map_dst;
13381 	ill_t		*ill = (ill_t *)q->q_ptr;
13382 	ip_stack_t	*ipst;
13383 	sctp_stack_t	*sctps;
13384 	boolean_t	sctp_csum_err = B_FALSE;
13385 
13386 	ASSERT(recv_ill != NULL);
13387 	ipst = recv_ill->ill_ipst;
13388 	sctps = ipst->ips_netstack->netstack_sctp;
13389 
13390 #define	rptr	((uchar_t *)ipha)
13391 
13392 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13393 	ASSERT(ill != NULL);
13394 
13395 	/* u1 is # words of IP options */
13396 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13397 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13398 
13399 	/* IP options present */
13400 	if (u1 > 0) {
13401 		goto ipoptions;
13402 	} else {
13403 		/* Check the IP header checksum.  */
13404 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13405 		    !mctl_present) {
13406 #define	uph	((uint16_t *)ipha)
13407 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13408 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13409 #undef	uph
13410 			/* finish doing IP checksum */
13411 			sum = (sum & 0xFFFF) + (sum >> 16);
13412 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13413 			/*
13414 			 * Don't verify header checksum if this packet
13415 			 * is coming back from AH/ESP as we already did it.
13416 			 */
13417 			if (sum != 0 && sum != 0xFFFF) {
13418 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13419 				goto error;
13420 			}
13421 		}
13422 		/*
13423 		 * Since there is no SCTP h/w cksum support yet, just
13424 		 * clear the flag.
13425 		 */
13426 		DB_CKSUMFLAGS(mp) = 0;
13427 	}
13428 
13429 	/*
13430 	 * Don't verify header checksum if this packet is coming
13431 	 * back from AH/ESP as we already did it.
13432 	 */
13433 	if (!mctl_present) {
13434 		UPDATE_IB_PKT_COUNT(ire);
13435 		ire->ire_last_used_time = lbolt;
13436 	}
13437 
13438 	/* packet part of fragmented IP packet? */
13439 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13440 	if (u1 & (IPH_MF | IPH_OFFSET))
13441 		goto fragmented;
13442 
13443 	/* u1 = IP header length (20 bytes) */
13444 	u1 = IP_SIMPLE_HDR_LENGTH;
13445 
13446 find_sctp_client:
13447 	/* Pullup if we don't have the sctp common header. */
13448 	len = MBLKL(mp);
13449 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13450 		if (mp->b_cont == NULL ||
13451 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13452 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13453 			goto error;
13454 		}
13455 		ipha = (ipha_t *)mp->b_rptr;
13456 		len = MBLKL(mp);
13457 	}
13458 
13459 	sctph = (sctp_hdr_t *)(rptr + u1);
13460 #ifdef	DEBUG
13461 	if (!skip_sctp_cksum) {
13462 #endif
13463 		pktsum = sctph->sh_chksum;
13464 		sctph->sh_chksum = 0;
13465 		calcsum = sctp_cksum(mp, u1);
13466 		sctph->sh_chksum = pktsum;
13467 		if (calcsum != pktsum)
13468 			sctp_csum_err = B_TRUE;
13469 #ifdef	DEBUG	/* skip_sctp_cksum */
13470 	}
13471 #endif
13472 	/* get the ports */
13473 	ports = *(uint32_t *)&sctph->sh_sport;
13474 
13475 	IRE_REFRELE(ire);
13476 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13477 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13478 	if (sctp_csum_err) {
13479 		/*
13480 		 * No potential sctp checksum errors go to the Sun
13481 		 * sctp stack however they might be Adler-32 summed
13482 		 * packets a userland stack bound to a raw IP socket
13483 		 * could reasonably use. Note though that Adler-32 is
13484 		 * a long deprecated algorithm and customer sctp
13485 		 * networks should eventually migrate to CRC-32 at
13486 		 * which time this facility should be removed.
13487 		 */
13488 		flags |= IP_FF_SCTP_CSUM_ERR;
13489 		goto no_conn;
13490 	}
13491 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13492 	    sctps)) == NULL) {
13493 		/* Check for raw socket or OOTB handling */
13494 		goto no_conn;
13495 	}
13496 
13497 	/* Found a client; up it goes */
13498 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13499 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13500 	return;
13501 
13502 no_conn:
13503 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13504 	    ports, mctl_present, flags, B_TRUE, zoneid);
13505 	return;
13506 
13507 ipoptions:
13508 	DB_CKSUMFLAGS(mp) = 0;
13509 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13510 		goto slow_done;
13511 
13512 	UPDATE_IB_PKT_COUNT(ire);
13513 	ire->ire_last_used_time = lbolt;
13514 
13515 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13516 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13517 fragmented:
13518 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13519 			goto slow_done;
13520 		/*
13521 		 * Make sure that first_mp points back to mp as
13522 		 * the mp we came in with could have changed in
13523 		 * ip_rput_fragment().
13524 		 */
13525 		ASSERT(!mctl_present);
13526 		ipha = (ipha_t *)mp->b_rptr;
13527 		first_mp = mp;
13528 	}
13529 
13530 	/* Now we have a complete datagram, destined for this machine. */
13531 	u1 = IPH_HDR_LENGTH(ipha);
13532 	goto find_sctp_client;
13533 #undef  iphs
13534 #undef  rptr
13535 
13536 error:
13537 	freemsg(first_mp);
13538 slow_done:
13539 	IRE_REFRELE(ire);
13540 }
13541 
13542 #define	VER_BITS	0xF0
13543 #define	VERSION_6	0x60
13544 
13545 static boolean_t
13546 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13547     ipaddr_t *dstp, ip_stack_t *ipst)
13548 {
13549 	uint_t	opt_len;
13550 	ipha_t *ipha;
13551 	ssize_t len;
13552 	uint_t	pkt_len;
13553 
13554 	ASSERT(ill != NULL);
13555 	IP_STAT(ipst, ip_ipoptions);
13556 	ipha = *iphapp;
13557 
13558 #define	rptr    ((uchar_t *)ipha)
13559 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13560 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13561 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13562 		freemsg(mp);
13563 		return (B_FALSE);
13564 	}
13565 
13566 	/* multiple mblk or too short */
13567 	pkt_len = ntohs(ipha->ipha_length);
13568 
13569 	/* Get the number of words of IP options in the IP header. */
13570 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13571 	if (opt_len) {
13572 		/* IP Options present!  Validate and process. */
13573 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13574 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13575 			goto done;
13576 		}
13577 		/*
13578 		 * Recompute complete header length and make sure we
13579 		 * have access to all of it.
13580 		 */
13581 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13582 		if (len > (mp->b_wptr - rptr)) {
13583 			if (len > pkt_len) {
13584 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13585 				goto done;
13586 			}
13587 			if (!pullupmsg(mp, len)) {
13588 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13589 				goto done;
13590 			}
13591 			ipha = (ipha_t *)mp->b_rptr;
13592 		}
13593 		/*
13594 		 * Go off to ip_rput_options which returns the next hop
13595 		 * destination address, which may have been affected
13596 		 * by source routing.
13597 		 */
13598 		IP_STAT(ipst, ip_opt);
13599 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13600 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13601 			return (B_FALSE);
13602 		}
13603 	}
13604 	*iphapp = ipha;
13605 	return (B_TRUE);
13606 done:
13607 	/* clear b_prev - used by ip_mroute_decap */
13608 	mp->b_prev = NULL;
13609 	freemsg(mp);
13610 	return (B_FALSE);
13611 #undef  rptr
13612 }
13613 
13614 /*
13615  * Deal with the fact that there is no ire for the destination.
13616  */
13617 static ire_t *
13618 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13619 {
13620 	ipha_t	*ipha;
13621 	ill_t	*ill;
13622 	ire_t	*ire;
13623 	ip_stack_t *ipst;
13624 	enum	ire_forward_action ret_action;
13625 
13626 	ipha = (ipha_t *)mp->b_rptr;
13627 	ill = (ill_t *)q->q_ptr;
13628 
13629 	ASSERT(ill != NULL);
13630 	ipst = ill->ill_ipst;
13631 
13632 	/*
13633 	 * No IRE for this destination, so it can't be for us.
13634 	 * Unless we are forwarding, drop the packet.
13635 	 * We have to let source routed packets through
13636 	 * since we don't yet know if they are 'ping -l'
13637 	 * packets i.e. if they will go out over the
13638 	 * same interface as they came in on.
13639 	 */
13640 	if (ll_multicast) {
13641 		freemsg(mp);
13642 		return (NULL);
13643 	}
13644 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13645 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13646 		freemsg(mp);
13647 		return (NULL);
13648 	}
13649 
13650 	/*
13651 	 * Mark this packet as having originated externally.
13652 	 *
13653 	 * For non-forwarding code path, ire_send later double
13654 	 * checks this interface to see if it is still exists
13655 	 * post-ARP resolution.
13656 	 *
13657 	 * Also, IPQOS uses this to differentiate between
13658 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13659 	 * QOS packet processing in ip_wput_attach_llhdr().
13660 	 * The QoS module can mark the b_band for a fastpath message
13661 	 * or the dl_priority field in a unitdata_req header for
13662 	 * CoS marking. This info can only be found in
13663 	 * ip_wput_attach_llhdr().
13664 	 */
13665 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13666 	/*
13667 	 * Clear the indication that this may have a hardware checksum
13668 	 * as we are not using it
13669 	 */
13670 	DB_CKSUMFLAGS(mp) = 0;
13671 
13672 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13673 	    msg_getlabel(mp), ipst);
13674 
13675 	if (ire == NULL && ret_action == Forward_check_multirt) {
13676 		/* Let ip_newroute handle CGTP  */
13677 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13678 		return (NULL);
13679 	}
13680 
13681 	if (ire != NULL)
13682 		return (ire);
13683 
13684 	mp->b_prev = mp->b_next = 0;
13685 
13686 	if (ret_action == Forward_blackhole) {
13687 		freemsg(mp);
13688 		return (NULL);
13689 	}
13690 	/* send icmp unreachable */
13691 	q = WR(q);
13692 	/* Sent by forwarding path, and router is global zone */
13693 	if (ip_source_routed(ipha, ipst)) {
13694 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13695 		    GLOBAL_ZONEID, ipst);
13696 	} else {
13697 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13698 		    ipst);
13699 	}
13700 
13701 	return (NULL);
13702 
13703 }
13704 
13705 /*
13706  * check ip header length and align it.
13707  */
13708 static boolean_t
13709 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13710 {
13711 	ssize_t len;
13712 	ill_t *ill;
13713 	ipha_t	*ipha;
13714 
13715 	len = MBLKL(mp);
13716 
13717 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13718 		ill = (ill_t *)q->q_ptr;
13719 
13720 		if (!OK_32PTR(mp->b_rptr))
13721 			IP_STAT(ipst, ip_notaligned1);
13722 		else
13723 			IP_STAT(ipst, ip_notaligned2);
13724 		/* Guard against bogus device drivers */
13725 		if (len < 0) {
13726 			/* clear b_prev - used by ip_mroute_decap */
13727 			mp->b_prev = NULL;
13728 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13729 			freemsg(mp);
13730 			return (B_FALSE);
13731 		}
13732 
13733 		if (ip_rput_pullups++ == 0) {
13734 			ipha = (ipha_t *)mp->b_rptr;
13735 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13736 			    "ip_check_and_align_header: %s forced us to "
13737 			    " pullup pkt, hdr len %ld, hdr addr %p",
13738 			    ill->ill_name, len, (void *)ipha);
13739 		}
13740 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13741 			/* clear b_prev - used by ip_mroute_decap */
13742 			mp->b_prev = NULL;
13743 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13744 			freemsg(mp);
13745 			return (B_FALSE);
13746 		}
13747 	}
13748 	return (B_TRUE);
13749 }
13750 
13751 /*
13752  * Handle the situation where a packet came in on `ill' but matched an IRE
13753  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13754  * for interface statistics.
13755  */
13756 ire_t *
13757 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13758 {
13759 	ire_t		*new_ire;
13760 	ill_t		*ire_ill;
13761 	uint_t		ifindex;
13762 	ip_stack_t	*ipst = ill->ill_ipst;
13763 	boolean_t	strict_check = B_FALSE;
13764 
13765 	/*
13766 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13767 	 * issue (e.g. packet received on an underlying interface matched an
13768 	 * IRE_LOCAL on its associated group interface).
13769 	 */
13770 	if (ire->ire_rfq != NULL &&
13771 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13772 		return (ire);
13773 	}
13774 
13775 	/*
13776 	 * Do another ire lookup here, using the ingress ill, to see if the
13777 	 * interface is in a usesrc group.
13778 	 * As long as the ills belong to the same group, we don't consider
13779 	 * them to be arriving on the wrong interface. Thus, if the switch
13780 	 * is doing inbound load spreading, we won't drop packets when the
13781 	 * ip*_strict_dst_multihoming switch is on.
13782 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13783 	 * where the local address may not be unique. In this case we were
13784 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13785 	 * actually returned. The new lookup, which is more specific, should
13786 	 * only find the IRE_LOCAL associated with the ingress ill if one
13787 	 * exists.
13788 	 */
13789 
13790 	if (ire->ire_ipversion == IPV4_VERSION) {
13791 		if (ipst->ips_ip_strict_dst_multihoming)
13792 			strict_check = B_TRUE;
13793 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13794 		    ill->ill_ipif, ALL_ZONES, NULL,
13795 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13796 	} else {
13797 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13798 		if (ipst->ips_ipv6_strict_dst_multihoming)
13799 			strict_check = B_TRUE;
13800 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13801 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13802 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13803 	}
13804 	/*
13805 	 * If the same ire that was returned in ip_input() is found then this
13806 	 * is an indication that usesrc groups are in use. The packet
13807 	 * arrived on a different ill in the group than the one associated with
13808 	 * the destination address.  If a different ire was found then the same
13809 	 * IP address must be hosted on multiple ills. This is possible with
13810 	 * unnumbered point2point interfaces. We switch to use this new ire in
13811 	 * order to have accurate interface statistics.
13812 	 */
13813 	if (new_ire != NULL) {
13814 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13815 			ire_refrele(ire);
13816 			ire = new_ire;
13817 		} else {
13818 			ire_refrele(new_ire);
13819 		}
13820 		return (ire);
13821 	} else if ((ire->ire_rfq == NULL) &&
13822 	    (ire->ire_ipversion == IPV4_VERSION)) {
13823 		/*
13824 		 * The best match could have been the original ire which
13825 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13826 		 * the strict multihoming checks are irrelevant as we consider
13827 		 * local addresses hosted on lo0 to be interface agnostic. We
13828 		 * only expect a null ire_rfq on IREs which are associated with
13829 		 * lo0 hence we can return now.
13830 		 */
13831 		return (ire);
13832 	}
13833 
13834 	/*
13835 	 * Chase pointers once and store locally.
13836 	 */
13837 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13838 	    (ill_t *)(ire->ire_rfq->q_ptr);
13839 	ifindex = ill->ill_usesrc_ifindex;
13840 
13841 	/*
13842 	 * Check if it's a legal address on the 'usesrc' interface.
13843 	 */
13844 	if ((ifindex != 0) && (ire_ill != NULL) &&
13845 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13846 		return (ire);
13847 	}
13848 
13849 	/*
13850 	 * If the ip*_strict_dst_multihoming switch is on then we can
13851 	 * only accept this packet if the interface is marked as routing.
13852 	 */
13853 	if (!(strict_check))
13854 		return (ire);
13855 
13856 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13857 	    ILLF_ROUTER) != 0) {
13858 		return (ire);
13859 	}
13860 
13861 	ire_refrele(ire);
13862 	return (NULL);
13863 }
13864 
13865 /*
13866  *
13867  * This is the fast forward path. If we are here, we dont need to
13868  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13869  * needed to find the nexthop in this case is much simpler
13870  */
13871 ire_t *
13872 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13873 {
13874 	ipha_t	*ipha;
13875 	ire_t	*src_ire;
13876 	ill_t	*stq_ill;
13877 	uint_t	hlen;
13878 	uint_t	pkt_len;
13879 	uint32_t sum;
13880 	queue_t	*dev_q;
13881 	ip_stack_t *ipst = ill->ill_ipst;
13882 	mblk_t *fpmp;
13883 	enum	ire_forward_action ret_action;
13884 
13885 	ipha = (ipha_t *)mp->b_rptr;
13886 
13887 	if (ire != NULL &&
13888 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13889 	    ire->ire_zoneid != ALL_ZONES) {
13890 		/*
13891 		 * Should only use IREs that are visible to the global
13892 		 * zone for forwarding.
13893 		 */
13894 		ire_refrele(ire);
13895 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13896 		/*
13897 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13898 		 * transient cases. In such case, just drop the packet
13899 		 */
13900 		if (ire->ire_type != IRE_CACHE)
13901 			goto drop;
13902 	}
13903 
13904 	/*
13905 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13906 	 * The loopback address check for both src and dst has already
13907 	 * been checked in ip_input
13908 	 */
13909 
13910 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13911 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13912 		goto drop;
13913 	}
13914 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13915 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13916 
13917 	if (src_ire != NULL) {
13918 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13919 		ire_refrele(src_ire);
13920 		goto drop;
13921 	}
13922 
13923 	/* No ire cache of nexthop. So first create one  */
13924 	if (ire == NULL) {
13925 
13926 		ire = ire_forward_simple(dst, &ret_action, ipst);
13927 
13928 		/*
13929 		 * We only come to ip_fast_forward if ip_cgtp_filter
13930 		 * is not set. So ire_forward() should not return with
13931 		 * Forward_check_multirt as the next action.
13932 		 */
13933 		ASSERT(ret_action != Forward_check_multirt);
13934 		if (ire == NULL) {
13935 			/* An attempt was made to forward the packet */
13936 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13937 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13938 			mp->b_prev = mp->b_next = 0;
13939 			/* send icmp unreachable */
13940 			/* Sent by forwarding path, and router is global zone */
13941 			if (ret_action == Forward_ret_icmp_err) {
13942 				if (ip_source_routed(ipha, ipst)) {
13943 					icmp_unreachable(ill->ill_wq, mp,
13944 					    ICMP_SOURCE_ROUTE_FAILED,
13945 					    GLOBAL_ZONEID, ipst);
13946 				} else {
13947 					icmp_unreachable(ill->ill_wq, mp,
13948 					    ICMP_HOST_UNREACHABLE,
13949 					    GLOBAL_ZONEID, ipst);
13950 				}
13951 			} else {
13952 				freemsg(mp);
13953 			}
13954 			return (NULL);
13955 		}
13956 	}
13957 
13958 	/*
13959 	 * Forwarding fastpath exception case:
13960 	 * If any of the following are true, we take the slowpath:
13961 	 *	o forwarding is not enabled
13962 	 *	o incoming and outgoing interface are the same, or in the same
13963 	 *	  IPMP group.
13964 	 *	o corresponding ire is in incomplete state
13965 	 *	o packet needs fragmentation
13966 	 *	o ARP cache is not resolved
13967 	 *
13968 	 * The codeflow from here on is thus:
13969 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13970 	 */
13971 	pkt_len = ntohs(ipha->ipha_length);
13972 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13973 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13974 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13975 	    (ire->ire_nce == NULL) ||
13976 	    (pkt_len > ire->ire_max_frag) ||
13977 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13978 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13979 	    ipha->ipha_ttl <= 1) {
13980 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13981 		    ipha, ill, B_FALSE, B_TRUE);
13982 		return (ire);
13983 	}
13984 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13985 
13986 	DTRACE_PROBE4(ip4__forwarding__start,
13987 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13988 
13989 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13990 	    ipst->ips_ipv4firewall_forwarding,
13991 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13992 
13993 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13994 
13995 	if (mp == NULL)
13996 		goto drop;
13997 
13998 	mp->b_datap->db_struioun.cksum.flags = 0;
13999 	/* Adjust the checksum to reflect the ttl decrement. */
14000 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14001 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14002 	ipha->ipha_ttl--;
14003 
14004 	/*
14005 	 * Write the link layer header.  We can do this safely here,
14006 	 * because we have already tested to make sure that the IP
14007 	 * policy is not set, and that we have a fast path destination
14008 	 * header.
14009 	 */
14010 	mp->b_rptr -= hlen;
14011 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14012 
14013 	UPDATE_IB_PKT_COUNT(ire);
14014 	ire->ire_last_used_time = lbolt;
14015 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14016 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14017 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14018 
14019 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14020 		dev_q = ire->ire_stq->q_next;
14021 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14022 			goto indiscard;
14023 	}
14024 
14025 	DTRACE_PROBE4(ip4__physical__out__start,
14026 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14027 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14028 	    ipst->ips_ipv4firewall_physical_out,
14029 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14030 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14031 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14032 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14033 	    ip6_t *, NULL, int, 0);
14034 
14035 	if (mp != NULL) {
14036 		if (ipst->ips_ipobs_enabled) {
14037 			zoneid_t szone;
14038 
14039 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14040 			    ipst, ALL_ZONES);
14041 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14042 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14043 		}
14044 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14045 	}
14046 	return (ire);
14047 
14048 indiscard:
14049 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14050 drop:
14051 	if (mp != NULL)
14052 		freemsg(mp);
14053 	return (ire);
14054 
14055 }
14056 
14057 /*
14058  * This function is called in the forwarding slowpath, when
14059  * either the ire lacks the link-layer address, or the packet needs
14060  * further processing(eg. fragmentation), before transmission.
14061  */
14062 
14063 static void
14064 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14065     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14066 {
14067 	queue_t		*dev_q;
14068 	ire_t		*src_ire;
14069 	ip_stack_t	*ipst = ill->ill_ipst;
14070 	boolean_t	same_illgrp = B_FALSE;
14071 
14072 	ASSERT(ire->ire_stq != NULL);
14073 
14074 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14075 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14076 
14077 	/*
14078 	 * If the caller of this function is ip_fast_forward() skip the
14079 	 * next three checks as it does not apply.
14080 	 */
14081 	if (from_ip_fast_forward)
14082 		goto skip;
14083 
14084 	if (ll_multicast != 0) {
14085 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14086 		goto drop_pkt;
14087 	}
14088 
14089 	/*
14090 	 * check if ipha_src is a broadcast address. Note that this
14091 	 * check is redundant when we get here from ip_fast_forward()
14092 	 * which has already done this check. However, since we can
14093 	 * also get here from ip_rput_process_broadcast() or, for
14094 	 * for the slow path through ip_fast_forward(), we perform
14095 	 * the check again for code-reusability
14096 	 */
14097 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14098 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14099 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14100 		if (src_ire != NULL)
14101 			ire_refrele(src_ire);
14102 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14103 		ip2dbg(("ip_rput_process_forward: Received packet with"
14104 		    " bad src/dst address on %s\n", ill->ill_name));
14105 		goto drop_pkt;
14106 	}
14107 
14108 	/*
14109 	 * Check if we want to forward this one at this time.
14110 	 * We allow source routed packets on a host provided that
14111 	 * they go out the same ill or illgrp as they came in on.
14112 	 *
14113 	 * XXX To be quicker, we may wish to not chase pointers to
14114 	 * get the ILLF_ROUTER flag and instead store the
14115 	 * forwarding policy in the ire.  An unfortunate
14116 	 * side-effect of that would be requiring an ire flush
14117 	 * whenever the ILLF_ROUTER flag changes.
14118 	 */
14119 skip:
14120 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14121 
14122 	if (((ill->ill_flags &
14123 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14124 	    !(ip_source_routed(ipha, ipst) &&
14125 	    (ire->ire_rfq == q || same_illgrp))) {
14126 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14127 		if (ip_source_routed(ipha, ipst)) {
14128 			q = WR(q);
14129 			/*
14130 			 * Clear the indication that this may have
14131 			 * hardware checksum as we are not using it.
14132 			 */
14133 			DB_CKSUMFLAGS(mp) = 0;
14134 			/* Sent by forwarding path, and router is global zone */
14135 			icmp_unreachable(q, mp,
14136 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14137 			return;
14138 		}
14139 		goto drop_pkt;
14140 	}
14141 
14142 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14143 
14144 	/* Packet is being forwarded. Turning off hwcksum flag. */
14145 	DB_CKSUMFLAGS(mp) = 0;
14146 	if (ipst->ips_ip_g_send_redirects) {
14147 		/*
14148 		 * Check whether the incoming interface and outgoing
14149 		 * interface is part of the same group. If so,
14150 		 * send redirects.
14151 		 *
14152 		 * Check the source address to see if it originated
14153 		 * on the same logical subnet it is going back out on.
14154 		 * If so, we should be able to send it a redirect.
14155 		 * Avoid sending a redirect if the destination
14156 		 * is directly connected (i.e., ipha_dst is the same
14157 		 * as ire_gateway_addr or the ire_addr of the
14158 		 * nexthop IRE_CACHE ), or if the packet was source
14159 		 * routed out this interface.
14160 		 */
14161 		ipaddr_t src, nhop;
14162 		mblk_t	*mp1;
14163 		ire_t	*nhop_ire = NULL;
14164 
14165 		/*
14166 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14167 		 * If so, send redirects.
14168 		 */
14169 		if ((ire->ire_rfq == q || same_illgrp) &&
14170 		    !ip_source_routed(ipha, ipst)) {
14171 
14172 			nhop = (ire->ire_gateway_addr != 0 ?
14173 			    ire->ire_gateway_addr : ire->ire_addr);
14174 
14175 			if (ipha->ipha_dst == nhop) {
14176 				/*
14177 				 * We avoid sending a redirect if the
14178 				 * destination is directly connected
14179 				 * because it is possible that multiple
14180 				 * IP subnets may have been configured on
14181 				 * the link, and the source may not
14182 				 * be on the same subnet as ip destination,
14183 				 * even though they are on the same
14184 				 * physical link.
14185 				 */
14186 				goto sendit;
14187 			}
14188 
14189 			src = ipha->ipha_src;
14190 
14191 			/*
14192 			 * We look up the interface ire for the nexthop,
14193 			 * to see if ipha_src is in the same subnet
14194 			 * as the nexthop.
14195 			 *
14196 			 * Note that, if, in the future, IRE_CACHE entries
14197 			 * are obsoleted,  this lookup will not be needed,
14198 			 * as the ire passed to this function will be the
14199 			 * same as the nhop_ire computed below.
14200 			 */
14201 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14202 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14203 			    0, NULL, MATCH_IRE_TYPE, ipst);
14204 
14205 			if (nhop_ire != NULL) {
14206 				if ((src & nhop_ire->ire_mask) ==
14207 				    (nhop & nhop_ire->ire_mask)) {
14208 					/*
14209 					 * The source is directly connected.
14210 					 * Just copy the ip header (which is
14211 					 * in the first mblk)
14212 					 */
14213 					mp1 = copyb(mp);
14214 					if (mp1 != NULL) {
14215 						icmp_send_redirect(WR(q), mp1,
14216 						    nhop, ipst);
14217 					}
14218 				}
14219 				ire_refrele(nhop_ire);
14220 			}
14221 		}
14222 	}
14223 sendit:
14224 	dev_q = ire->ire_stq->q_next;
14225 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14226 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14227 		freemsg(mp);
14228 		return;
14229 	}
14230 
14231 	ip_rput_forward(ire, ipha, mp, ill);
14232 	return;
14233 
14234 drop_pkt:
14235 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14236 	freemsg(mp);
14237 }
14238 
14239 ire_t *
14240 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14241     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14242 {
14243 	queue_t		*q;
14244 	uint16_t	hcksumflags;
14245 	ip_stack_t	*ipst = ill->ill_ipst;
14246 
14247 	q = *qp;
14248 
14249 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14250 
14251 	/*
14252 	 * Clear the indication that this may have hardware
14253 	 * checksum as we are not using it for forwarding.
14254 	 */
14255 	hcksumflags = DB_CKSUMFLAGS(mp);
14256 	DB_CKSUMFLAGS(mp) = 0;
14257 
14258 	/*
14259 	 * Directed broadcast forwarding: if the packet came in over a
14260 	 * different interface then it is routed out over we can forward it.
14261 	 */
14262 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14263 		ire_refrele(ire);
14264 		freemsg(mp);
14265 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14266 		return (NULL);
14267 	}
14268 	/*
14269 	 * For multicast we have set dst to be INADDR_BROADCAST
14270 	 * for delivering to all STREAMS.
14271 	 */
14272 	if (!CLASSD(ipha->ipha_dst)) {
14273 		ire_t *new_ire;
14274 		ipif_t *ipif;
14275 
14276 		ipif = ipif_get_next_ipif(NULL, ill);
14277 		if (ipif == NULL) {
14278 discard:		ire_refrele(ire);
14279 			freemsg(mp);
14280 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14281 			return (NULL);
14282 		}
14283 		new_ire = ire_ctable_lookup(dst, 0, 0,
14284 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14285 		ipif_refrele(ipif);
14286 
14287 		if (new_ire != NULL) {
14288 			/*
14289 			 * If the matching IRE_BROADCAST is part of an IPMP
14290 			 * group, then drop the packet unless our ill has been
14291 			 * nominated to receive for the group.
14292 			 */
14293 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14294 			    new_ire->ire_rfq != q) {
14295 				ire_refrele(new_ire);
14296 				goto discard;
14297 			}
14298 
14299 			/*
14300 			 * In the special case of multirouted broadcast
14301 			 * packets, we unconditionally need to "gateway"
14302 			 * them to the appropriate interface here.
14303 			 * In the normal case, this cannot happen, because
14304 			 * there is no broadcast IRE tagged with the
14305 			 * RTF_MULTIRT flag.
14306 			 */
14307 			if (new_ire->ire_flags & RTF_MULTIRT) {
14308 				ire_refrele(new_ire);
14309 				if (ire->ire_rfq != NULL) {
14310 					q = ire->ire_rfq;
14311 					*qp = q;
14312 				}
14313 			} else {
14314 				ire_refrele(ire);
14315 				ire = new_ire;
14316 			}
14317 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14318 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14319 				/*
14320 				 * Free the message if
14321 				 * ip_g_forward_directed_bcast is turned
14322 				 * off for non-local broadcast.
14323 				 */
14324 				ire_refrele(ire);
14325 				freemsg(mp);
14326 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14327 				return (NULL);
14328 			}
14329 		} else {
14330 			/*
14331 			 * This CGTP packet successfully passed the
14332 			 * CGTP filter, but the related CGTP
14333 			 * broadcast IRE has not been found,
14334 			 * meaning that the redundant ipif is
14335 			 * probably down. However, if we discarded
14336 			 * this packet, its duplicate would be
14337 			 * filtered out by the CGTP filter so none
14338 			 * of them would get through. So we keep
14339 			 * going with this one.
14340 			 */
14341 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14342 			if (ire->ire_rfq != NULL) {
14343 				q = ire->ire_rfq;
14344 				*qp = q;
14345 			}
14346 		}
14347 	}
14348 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14349 		/*
14350 		 * Verify that there are not more then one
14351 		 * IRE_BROADCAST with this broadcast address which
14352 		 * has ire_stq set.
14353 		 * TODO: simplify, loop over all IRE's
14354 		 */
14355 		ire_t	*ire1;
14356 		int	num_stq = 0;
14357 		mblk_t	*mp1;
14358 
14359 		/* Find the first one with ire_stq set */
14360 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14361 		for (ire1 = ire; ire1 &&
14362 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14363 		    ire1 = ire1->ire_next)
14364 			;
14365 		if (ire1) {
14366 			ire_refrele(ire);
14367 			ire = ire1;
14368 			IRE_REFHOLD(ire);
14369 		}
14370 
14371 		/* Check if there are additional ones with stq set */
14372 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14373 			if (ire->ire_addr != ire1->ire_addr)
14374 				break;
14375 			if (ire1->ire_stq) {
14376 				num_stq++;
14377 				break;
14378 			}
14379 		}
14380 		rw_exit(&ire->ire_bucket->irb_lock);
14381 		if (num_stq == 1 && ire->ire_stq != NULL) {
14382 			ip1dbg(("ip_rput_process_broadcast: directed "
14383 			    "broadcast to 0x%x\n",
14384 			    ntohl(ire->ire_addr)));
14385 			mp1 = copymsg(mp);
14386 			if (mp1) {
14387 				switch (ipha->ipha_protocol) {
14388 				case IPPROTO_UDP:
14389 					ip_udp_input(q, mp1, ipha, ire, ill);
14390 					break;
14391 				default:
14392 					ip_proto_input(q, mp1, ipha, ire, ill,
14393 					    0);
14394 					break;
14395 				}
14396 			}
14397 			/*
14398 			 * Adjust ttl to 2 (1+1 - the forward engine
14399 			 * will decrement it by one.
14400 			 */
14401 			if (ip_csum_hdr(ipha)) {
14402 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14403 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14404 				freemsg(mp);
14405 				ire_refrele(ire);
14406 				return (NULL);
14407 			}
14408 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14409 			ipha->ipha_hdr_checksum = 0;
14410 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14411 			ip_rput_process_forward(q, mp, ire, ipha,
14412 			    ill, ll_multicast, B_FALSE);
14413 			ire_refrele(ire);
14414 			return (NULL);
14415 		}
14416 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14417 		    ntohl(ire->ire_addr)));
14418 	}
14419 
14420 	/* Restore any hardware checksum flags */
14421 	DB_CKSUMFLAGS(mp) = hcksumflags;
14422 	return (ire);
14423 }
14424 
14425 /* ARGSUSED */
14426 static boolean_t
14427 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14428     int *ll_multicast, ipaddr_t *dstp)
14429 {
14430 	ip_stack_t	*ipst = ill->ill_ipst;
14431 
14432 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14433 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14434 	    ntohs(ipha->ipha_length));
14435 
14436 	/*
14437 	 * So that we don't end up with dups, only one ill in an IPMP group is
14438 	 * nominated to receive multicast traffic.
14439 	 */
14440 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14441 		goto drop_pkt;
14442 
14443 	/*
14444 	 * Forward packets only if we have joined the allmulti
14445 	 * group on this interface.
14446 	 */
14447 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14448 		int retval;
14449 
14450 		/*
14451 		 * Clear the indication that this may have hardware
14452 		 * checksum as we are not using it.
14453 		 */
14454 		DB_CKSUMFLAGS(mp) = 0;
14455 		retval = ip_mforward(ill, ipha, mp);
14456 		/* ip_mforward updates mib variables if needed */
14457 		/* clear b_prev - used by ip_mroute_decap */
14458 		mp->b_prev = NULL;
14459 
14460 		switch (retval) {
14461 		case 0:
14462 			/*
14463 			 * pkt is okay and arrived on phyint.
14464 			 *
14465 			 * If we are running as a multicast router
14466 			 * we need to see all IGMP and/or PIM packets.
14467 			 */
14468 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14469 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14470 				goto done;
14471 			}
14472 			break;
14473 		case -1:
14474 			/* pkt is mal-formed, toss it */
14475 			goto drop_pkt;
14476 		case 1:
14477 			/* pkt is okay and arrived on a tunnel */
14478 			/*
14479 			 * If we are running a multicast router
14480 			 *  we need to see all igmp packets.
14481 			 */
14482 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14483 				*dstp = INADDR_BROADCAST;
14484 				*ll_multicast = 1;
14485 				return (B_FALSE);
14486 			}
14487 
14488 			goto drop_pkt;
14489 		}
14490 	}
14491 
14492 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14493 		/*
14494 		 * This might just be caused by the fact that
14495 		 * multiple IP Multicast addresses map to the same
14496 		 * link layer multicast - no need to increment counter!
14497 		 */
14498 		freemsg(mp);
14499 		return (B_TRUE);
14500 	}
14501 done:
14502 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14503 	/*
14504 	 * This assumes the we deliver to all streams for multicast
14505 	 * and broadcast packets.
14506 	 */
14507 	*dstp = INADDR_BROADCAST;
14508 	*ll_multicast = 1;
14509 	return (B_FALSE);
14510 drop_pkt:
14511 	ip2dbg(("ip_rput: drop pkt\n"));
14512 	freemsg(mp);
14513 	return (B_TRUE);
14514 }
14515 
14516 /*
14517  * This function is used to both return an indication of whether or not
14518  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14519  * and in doing so, determine whether or not it is broadcast vs multicast.
14520  * For it to be a broadcast packet, we must have the appropriate mblk_t
14521  * hanging off the ill_t.  If this is either not present or doesn't match
14522  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14523  * to be multicast.  Thus NICs that have no broadcast address (or no
14524  * capability for one, such as point to point links) cannot return as
14525  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14526  * the return values simplifies the current use of the return value of this
14527  * function, which is to pass through the multicast/broadcast characteristic
14528  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14529  * changing the return value to some other symbol demands the appropriate
14530  * "translation" when hpe_flags is set prior to calling hook_run() for
14531  * packet events.
14532  */
14533 int
14534 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14535 {
14536 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14537 	mblk_t *bmp;
14538 
14539 	if (ind->dl_group_address) {
14540 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14541 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14542 		    MBLKL(mb) &&
14543 		    (bmp = ill->ill_bcast_mp) != NULL) {
14544 			dl_unitdata_req_t *dlur;
14545 			uint8_t *bphys_addr;
14546 
14547 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14548 			if (ill->ill_sap_length < 0)
14549 				bphys_addr = (uchar_t *)dlur +
14550 				    dlur->dl_dest_addr_offset;
14551 			else
14552 				bphys_addr = (uchar_t *)dlur +
14553 				    dlur->dl_dest_addr_offset +
14554 				    ill->ill_sap_length;
14555 
14556 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14557 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14558 				return (HPE_BROADCAST);
14559 			}
14560 			return (HPE_MULTICAST);
14561 		}
14562 		return (HPE_MULTICAST);
14563 	}
14564 	return (0);
14565 }
14566 
14567 static boolean_t
14568 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14569     int *ll_multicast, mblk_t **mpp)
14570 {
14571 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14572 	boolean_t must_copy = B_FALSE;
14573 	struct iocblk   *iocp;
14574 	ipha_t		*ipha;
14575 	ip_stack_t	*ipst = ill->ill_ipst;
14576 
14577 #define	rptr    ((uchar_t *)ipha)
14578 
14579 	first_mp = *first_mpp;
14580 	mp = *mpp;
14581 
14582 	ASSERT(first_mp == mp);
14583 
14584 	/*
14585 	 * if db_ref > 1 then copymsg and free original. Packet may be
14586 	 * changed and do not want other entity who has a reference to this
14587 	 * message to trip over the changes. This is a blind change because
14588 	 * trying to catch all places that might change packet is too
14589 	 * difficult (since it may be a module above this one)
14590 	 *
14591 	 * This corresponds to the non-fast path case. We walk down the full
14592 	 * chain in this case, and check the db_ref count of all the dblks,
14593 	 * and do a copymsg if required. It is possible that the db_ref counts
14594 	 * of the data blocks in the mblk chain can be different.
14595 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14596 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14597 	 * 'snoop' is running.
14598 	 */
14599 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14600 		if (mp1->b_datap->db_ref > 1) {
14601 			must_copy = B_TRUE;
14602 			break;
14603 		}
14604 	}
14605 
14606 	if (must_copy) {
14607 		mp1 = copymsg(mp);
14608 		if (mp1 == NULL) {
14609 			for (mp1 = mp; mp1 != NULL;
14610 			    mp1 = mp1->b_cont) {
14611 				mp1->b_next = NULL;
14612 				mp1->b_prev = NULL;
14613 			}
14614 			freemsg(mp);
14615 			if (ill != NULL) {
14616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14617 			} else {
14618 				BUMP_MIB(&ipst->ips_ip_mib,
14619 				    ipIfStatsInDiscards);
14620 			}
14621 			return (B_TRUE);
14622 		}
14623 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14624 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14625 			/* Copy b_prev - used by ip_mroute_decap */
14626 			to_mp->b_prev = from_mp->b_prev;
14627 			from_mp->b_prev = NULL;
14628 		}
14629 		*first_mpp = first_mp = mp1;
14630 		freemsg(mp);
14631 		mp = mp1;
14632 		*mpp = mp1;
14633 	}
14634 
14635 	ipha = (ipha_t *)mp->b_rptr;
14636 
14637 	/*
14638 	 * previous code has a case for M_DATA.
14639 	 * We want to check how that happens.
14640 	 */
14641 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14642 	switch (first_mp->b_datap->db_type) {
14643 	case M_PROTO:
14644 	case M_PCPROTO:
14645 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14646 		    DL_UNITDATA_IND) {
14647 			/* Go handle anything other than data elsewhere. */
14648 			ip_rput_dlpi(q, mp);
14649 			return (B_TRUE);
14650 		}
14651 
14652 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14653 		/* Ditch the DLPI header. */
14654 		mp1 = mp->b_cont;
14655 		ASSERT(first_mp == mp);
14656 		*first_mpp = mp1;
14657 		freeb(mp);
14658 		*mpp = mp1;
14659 		return (B_FALSE);
14660 	case M_IOCACK:
14661 		ip1dbg(("got iocack "));
14662 		iocp = (struct iocblk *)mp->b_rptr;
14663 		switch (iocp->ioc_cmd) {
14664 		case DL_IOC_HDR_INFO:
14665 			ill = (ill_t *)q->q_ptr;
14666 			ill_fastpath_ack(ill, mp);
14667 			return (B_TRUE);
14668 		case SIOCSTUNPARAM:
14669 		case OSIOCSTUNPARAM:
14670 			/* Go through qwriter_ip */
14671 			break;
14672 		case SIOCGTUNPARAM:
14673 		case OSIOCGTUNPARAM:
14674 			ip_rput_other(NULL, q, mp, NULL);
14675 			return (B_TRUE);
14676 		default:
14677 			putnext(q, mp);
14678 			return (B_TRUE);
14679 		}
14680 		/* FALLTHRU */
14681 	case M_ERROR:
14682 	case M_HANGUP:
14683 		/*
14684 		 * Since this is on the ill stream we unconditionally
14685 		 * bump up the refcount
14686 		 */
14687 		ill_refhold(ill);
14688 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14689 		return (B_TRUE);
14690 	case M_CTL:
14691 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14692 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14693 		    IPHADA_M_CTL)) {
14694 			/*
14695 			 * It's an IPsec accelerated packet.
14696 			 * Make sure that the ill from which we received the
14697 			 * packet has enabled IPsec hardware acceleration.
14698 			 */
14699 			if (!(ill->ill_capabilities &
14700 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14701 				/* IPsec kstats: bean counter */
14702 				freemsg(mp);
14703 				return (B_TRUE);
14704 			}
14705 
14706 			/*
14707 			 * Make mp point to the mblk following the M_CTL,
14708 			 * then process according to type of mp.
14709 			 * After this processing, first_mp will point to
14710 			 * the data-attributes and mp to the pkt following
14711 			 * the M_CTL.
14712 			 */
14713 			mp = first_mp->b_cont;
14714 			if (mp == NULL) {
14715 				freemsg(first_mp);
14716 				return (B_TRUE);
14717 			}
14718 			/*
14719 			 * A Hardware Accelerated packet can only be M_DATA
14720 			 * ESP or AH packet.
14721 			 */
14722 			if (mp->b_datap->db_type != M_DATA) {
14723 				/* non-M_DATA IPsec accelerated packet */
14724 				IPSECHW_DEBUG(IPSECHW_PKT,
14725 				    ("non-M_DATA IPsec accelerated pkt\n"));
14726 				freemsg(first_mp);
14727 				return (B_TRUE);
14728 			}
14729 			ipha = (ipha_t *)mp->b_rptr;
14730 			if (ipha->ipha_protocol != IPPROTO_AH &&
14731 			    ipha->ipha_protocol != IPPROTO_ESP) {
14732 				IPSECHW_DEBUG(IPSECHW_PKT,
14733 				    ("non-M_DATA IPsec accelerated pkt\n"));
14734 				freemsg(first_mp);
14735 				return (B_TRUE);
14736 			}
14737 			*mpp = mp;
14738 			return (B_FALSE);
14739 		}
14740 		putnext(q, mp);
14741 		return (B_TRUE);
14742 	case M_IOCNAK:
14743 		ip1dbg(("got iocnak "));
14744 		iocp = (struct iocblk *)mp->b_rptr;
14745 		switch (iocp->ioc_cmd) {
14746 		case SIOCSTUNPARAM:
14747 		case OSIOCSTUNPARAM:
14748 			/*
14749 			 * Since this is on the ill stream we unconditionally
14750 			 * bump up the refcount
14751 			 */
14752 			ill_refhold(ill);
14753 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14754 			return (B_TRUE);
14755 		case DL_IOC_HDR_INFO:
14756 		case SIOCGTUNPARAM:
14757 		case OSIOCGTUNPARAM:
14758 			ip_rput_other(NULL, q, mp, NULL);
14759 			return (B_TRUE);
14760 		default:
14761 			break;
14762 		}
14763 		/* FALLTHRU */
14764 	default:
14765 		putnext(q, mp);
14766 		return (B_TRUE);
14767 	}
14768 }
14769 
14770 /* Read side put procedure.  Packets coming from the wire arrive here. */
14771 void
14772 ip_rput(queue_t *q, mblk_t *mp)
14773 {
14774 	ill_t	*ill;
14775 	union DL_primitives *dl;
14776 
14777 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14778 
14779 	ill = (ill_t *)q->q_ptr;
14780 
14781 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14782 		/*
14783 		 * If things are opening or closing, only accept high-priority
14784 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14785 		 * created; on close, things hanging off the ill may have been
14786 		 * freed already.)
14787 		 */
14788 		dl = (union DL_primitives *)mp->b_rptr;
14789 		if (DB_TYPE(mp) != M_PCPROTO ||
14790 		    dl->dl_primitive == DL_UNITDATA_IND) {
14791 			/*
14792 			 * SIOC[GS]TUNPARAM ioctls can come here.
14793 			 */
14794 			inet_freemsg(mp);
14795 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14796 			    "ip_rput_end: q %p (%S)", q, "uninit");
14797 			return;
14798 		}
14799 	}
14800 
14801 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14802 	    "ip_rput_end: q %p (%S)", q, "end");
14803 
14804 	ip_input(ill, NULL, mp, NULL);
14805 }
14806 
14807 static mblk_t *
14808 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14809 {
14810 	mblk_t *mp1;
14811 	boolean_t adjusted = B_FALSE;
14812 	ip_stack_t *ipst = ill->ill_ipst;
14813 
14814 	IP_STAT(ipst, ip_db_ref);
14815 	/*
14816 	 * The IP_RECVSLLA option depends on having the
14817 	 * link layer header. First check that:
14818 	 * a> the underlying device is of type ether,
14819 	 * since this option is currently supported only
14820 	 * over ethernet.
14821 	 * b> there is enough room to copy over the link
14822 	 * layer header.
14823 	 *
14824 	 * Once the checks are done, adjust rptr so that
14825 	 * the link layer header will be copied via
14826 	 * copymsg. Note that, IFT_ETHER may be returned
14827 	 * by some non-ethernet drivers but in this case
14828 	 * the second check will fail.
14829 	 */
14830 	if (ill->ill_type == IFT_ETHER &&
14831 	    (mp->b_rptr - mp->b_datap->db_base) >=
14832 	    sizeof (struct ether_header)) {
14833 		mp->b_rptr -= sizeof (struct ether_header);
14834 		adjusted = B_TRUE;
14835 	}
14836 	mp1 = copymsg(mp);
14837 
14838 	if (mp1 == NULL) {
14839 		mp->b_next = NULL;
14840 		/* clear b_prev - used by ip_mroute_decap */
14841 		mp->b_prev = NULL;
14842 		freemsg(mp);
14843 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14844 		return (NULL);
14845 	}
14846 
14847 	if (adjusted) {
14848 		/*
14849 		 * Copy is done. Restore the pointer in
14850 		 * the _new_ mblk
14851 		 */
14852 		mp1->b_rptr += sizeof (struct ether_header);
14853 	}
14854 
14855 	/* Copy b_prev - used by ip_mroute_decap */
14856 	mp1->b_prev = mp->b_prev;
14857 	mp->b_prev = NULL;
14858 
14859 	/* preserve the hardware checksum flags and data, if present */
14860 	if (DB_CKSUMFLAGS(mp) != 0) {
14861 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14862 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14863 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14864 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14865 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14866 	}
14867 
14868 	freemsg(mp);
14869 	return (mp1);
14870 }
14871 
14872 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14873 	if (tail != NULL)					\
14874 		tail->b_next = mp;				\
14875 	else							\
14876 		head = mp;					\
14877 	tail = mp;						\
14878 	cnt++;							\
14879 }
14880 
14881 /*
14882  * Direct read side procedure capable of dealing with chains. GLDv3 based
14883  * drivers call this function directly with mblk chains while STREAMS
14884  * read side procedure ip_rput() calls this for single packet with ip_ring
14885  * set to NULL to process one packet at a time.
14886  *
14887  * The ill will always be valid if this function is called directly from
14888  * the driver.
14889  *
14890  * If ip_input() is called from GLDv3:
14891  *
14892  *   - This must be a non-VLAN IP stream.
14893  *   - 'mp' is either an untagged or a special priority-tagged packet.
14894  *   - Any VLAN tag that was in the MAC header has been stripped.
14895  *
14896  * If the IP header in packet is not 32-bit aligned, every message in the
14897  * chain will be aligned before further operations. This is required on SPARC
14898  * platform.
14899  */
14900 /* ARGSUSED */
14901 void
14902 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14903     struct mac_header_info_s *mhip)
14904 {
14905 	ipaddr_t		dst = NULL;
14906 	ipaddr_t		prev_dst;
14907 	ire_t			*ire = NULL;
14908 	ipha_t			*ipha;
14909 	uint_t			pkt_len;
14910 	ssize_t			len;
14911 	uint_t			opt_len;
14912 	int			ll_multicast;
14913 	int			cgtp_flt_pkt;
14914 	queue_t			*q = ill->ill_rq;
14915 	squeue_t		*curr_sqp = NULL;
14916 	mblk_t 			*head = NULL;
14917 	mblk_t			*tail = NULL;
14918 	mblk_t			*first_mp;
14919 	int			cnt = 0;
14920 	ip_stack_t		*ipst = ill->ill_ipst;
14921 	mblk_t			*mp;
14922 	mblk_t			*dmp;
14923 	uint8_t			tag;
14924 
14925 	ASSERT(mp_chain != NULL);
14926 	ASSERT(ill != NULL);
14927 
14928 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14929 
14930 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14931 
14932 #define	rptr	((uchar_t *)ipha)
14933 
14934 	while (mp_chain != NULL) {
14935 		mp = mp_chain;
14936 		mp_chain = mp_chain->b_next;
14937 		mp->b_next = NULL;
14938 		ll_multicast = 0;
14939 
14940 		/*
14941 		 * We do ire caching from one iteration to
14942 		 * another. In the event the packet chain contains
14943 		 * all packets from the same dst, this caching saves
14944 		 * an ire_cache_lookup for each of the succeeding
14945 		 * packets in a packet chain.
14946 		 */
14947 		prev_dst = dst;
14948 
14949 		/*
14950 		 * if db_ref > 1 then copymsg and free original. Packet
14951 		 * may be changed and we do not want the other entity
14952 		 * who has a reference to this message to trip over the
14953 		 * changes. This is a blind change because trying to
14954 		 * catch all places that might change the packet is too
14955 		 * difficult.
14956 		 *
14957 		 * This corresponds to the fast path case, where we have
14958 		 * a chain of M_DATA mblks.  We check the db_ref count
14959 		 * of only the 1st data block in the mblk chain. There
14960 		 * doesn't seem to be a reason why a device driver would
14961 		 * send up data with varying db_ref counts in the mblk
14962 		 * chain. In any case the Fast path is a private
14963 		 * interface, and our drivers don't do such a thing.
14964 		 * Given the above assumption, there is no need to walk
14965 		 * down the entire mblk chain (which could have a
14966 		 * potential performance problem)
14967 		 *
14968 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14969 		 * to here because of exclusive ip stacks and vnics.
14970 		 * Packets transmitted from exclusive stack over vnic
14971 		 * can have db_ref > 1 and when it gets looped back to
14972 		 * another vnic in a different zone, you have ip_input()
14973 		 * getting dblks with db_ref > 1. So if someone
14974 		 * complains of TCP performance under this scenario,
14975 		 * take a serious look here on the impact of copymsg().
14976 		 */
14977 
14978 		if (DB_REF(mp) > 1) {
14979 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14980 				continue;
14981 		}
14982 
14983 		/*
14984 		 * Check and align the IP header.
14985 		 */
14986 		first_mp = mp;
14987 		if (DB_TYPE(mp) == M_DATA) {
14988 			dmp = mp;
14989 		} else if (DB_TYPE(mp) == M_PROTO &&
14990 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14991 			dmp = mp->b_cont;
14992 		} else {
14993 			dmp = NULL;
14994 		}
14995 		if (dmp != NULL) {
14996 			/*
14997 			 * IP header ptr not aligned?
14998 			 * OR IP header not complete in first mblk
14999 			 */
15000 			if (!OK_32PTR(dmp->b_rptr) ||
15001 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15002 				if (!ip_check_and_align_header(q, dmp, ipst))
15003 					continue;
15004 			}
15005 		}
15006 
15007 		/*
15008 		 * ip_input fast path
15009 		 */
15010 
15011 		/* mblk type is not M_DATA */
15012 		if (DB_TYPE(mp) != M_DATA) {
15013 			if (ip_rput_process_notdata(q, &first_mp, ill,
15014 			    &ll_multicast, &mp))
15015 				continue;
15016 
15017 			/*
15018 			 * The only way we can get here is if we had a
15019 			 * packet that was either a DL_UNITDATA_IND or
15020 			 * an M_CTL for an IPsec accelerated packet.
15021 			 *
15022 			 * In either case, the first_mp will point to
15023 			 * the leading M_PROTO or M_CTL.
15024 			 */
15025 			ASSERT(first_mp != NULL);
15026 		} else if (mhip != NULL) {
15027 			/*
15028 			 * ll_multicast is set here so that it is ready
15029 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15030 			 * manipulates ll_multicast in the same fashion when
15031 			 * called from ip_rput_process_notdata.
15032 			 */
15033 			switch (mhip->mhi_dsttype) {
15034 			case MAC_ADDRTYPE_MULTICAST :
15035 				ll_multicast = HPE_MULTICAST;
15036 				break;
15037 			case MAC_ADDRTYPE_BROADCAST :
15038 				ll_multicast = HPE_BROADCAST;
15039 				break;
15040 			default :
15041 				break;
15042 			}
15043 		}
15044 
15045 		/* Only M_DATA can come here and it is always aligned */
15046 		ASSERT(DB_TYPE(mp) == M_DATA);
15047 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15048 
15049 		ipha = (ipha_t *)mp->b_rptr;
15050 		len = mp->b_wptr - rptr;
15051 		pkt_len = ntohs(ipha->ipha_length);
15052 
15053 		/*
15054 		 * We must count all incoming packets, even if they end
15055 		 * up being dropped later on.
15056 		 */
15057 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15058 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15059 
15060 		/* multiple mblk or too short */
15061 		len -= pkt_len;
15062 		if (len != 0) {
15063 			/*
15064 			 * Make sure we have data length consistent
15065 			 * with the IP header.
15066 			 */
15067 			if (mp->b_cont == NULL) {
15068 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15069 					BUMP_MIB(ill->ill_ip_mib,
15070 					    ipIfStatsInHdrErrors);
15071 					ip2dbg(("ip_input: drop pkt\n"));
15072 					freemsg(mp);
15073 					continue;
15074 				}
15075 				mp->b_wptr = rptr + pkt_len;
15076 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15077 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15078 					BUMP_MIB(ill->ill_ip_mib,
15079 					    ipIfStatsInHdrErrors);
15080 					ip2dbg(("ip_input: drop pkt\n"));
15081 					freemsg(mp);
15082 					continue;
15083 				}
15084 				(void) adjmsg(mp, -len);
15085 				IP_STAT(ipst, ip_multimblk3);
15086 			}
15087 		}
15088 
15089 		/* Obtain the dst of the current packet */
15090 		dst = ipha->ipha_dst;
15091 
15092 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15093 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15094 		    ipha, ip6_t *, NULL, int, 0);
15095 
15096 		/*
15097 		 * The following test for loopback is faster than
15098 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15099 		 * operations.
15100 		 * Note that these addresses are always in network byte order
15101 		 */
15102 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15103 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15104 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15105 			freemsg(mp);
15106 			continue;
15107 		}
15108 
15109 		/*
15110 		 * The event for packets being received from a 'physical'
15111 		 * interface is placed after validation of the source and/or
15112 		 * destination address as being local so that packets can be
15113 		 * redirected to loopback addresses using ipnat.
15114 		 */
15115 		DTRACE_PROBE4(ip4__physical__in__start,
15116 		    ill_t *, ill, ill_t *, NULL,
15117 		    ipha_t *, ipha, mblk_t *, first_mp);
15118 
15119 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15120 		    ipst->ips_ipv4firewall_physical_in,
15121 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15122 
15123 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15124 
15125 		if (first_mp == NULL) {
15126 			continue;
15127 		}
15128 		dst = ipha->ipha_dst;
15129 		/*
15130 		 * Attach any necessary label information to
15131 		 * this packet
15132 		 */
15133 		if (is_system_labeled() &&
15134 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15135 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15136 			freemsg(mp);
15137 			continue;
15138 		}
15139 
15140 		if (ipst->ips_ipobs_enabled) {
15141 			zoneid_t dzone;
15142 
15143 			/*
15144 			 * On the inbound path the src zone will be unknown as
15145 			 * this packet has come from the wire.
15146 			 */
15147 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15148 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15149 			    ill, IPV4_VERSION, 0, ipst);
15150 		}
15151 
15152 		/*
15153 		 * Reuse the cached ire only if the ipha_dst of the previous
15154 		 * packet is the same as the current packet AND it is not
15155 		 * INADDR_ANY.
15156 		 */
15157 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15158 		    (ire != NULL)) {
15159 			ire_refrele(ire);
15160 			ire = NULL;
15161 		}
15162 
15163 		opt_len = ipha->ipha_version_and_hdr_length -
15164 		    IP_SIMPLE_HDR_VERSION;
15165 
15166 		/*
15167 		 * Check to see if we can take the fastpath.
15168 		 * That is possible if the following conditions are met
15169 		 *	o Tsol disabled
15170 		 *	o CGTP disabled
15171 		 *	o ipp_action_count is 0
15172 		 *	o no options in the packet
15173 		 *	o not a RSVP packet
15174 		 * 	o not a multicast packet
15175 		 *	o ill not in IP_DHCPINIT_IF mode
15176 		 */
15177 		if (!is_system_labeled() &&
15178 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15179 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15180 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15181 			if (ire == NULL)
15182 				ire = ire_cache_lookup_simple(dst, ipst);
15183 			/*
15184 			 * Unless forwarding is enabled, dont call
15185 			 * ip_fast_forward(). Incoming packet is for forwarding
15186 			 */
15187 			if ((ill->ill_flags & ILLF_ROUTER) &&
15188 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15189 				ire = ip_fast_forward(ire, dst, ill, mp);
15190 				continue;
15191 			}
15192 			/* incoming packet is for local consumption */
15193 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15194 				goto local;
15195 		}
15196 
15197 		/*
15198 		 * Disable ire caching for anything more complex
15199 		 * than the simple fast path case we checked for above.
15200 		 */
15201 		if (ire != NULL) {
15202 			ire_refrele(ire);
15203 			ire = NULL;
15204 		}
15205 
15206 		/*
15207 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15208 		 * server to unicast DHCP packets to a DHCP client using the
15209 		 * IP address it is offering to the client.  This can be
15210 		 * disabled through the "broadcast bit", but not all DHCP
15211 		 * servers honor that bit.  Therefore, to interoperate with as
15212 		 * many DHCP servers as possible, the DHCP client allows the
15213 		 * server to unicast, but we treat those packets as broadcast
15214 		 * here.  Note that we don't rewrite the packet itself since
15215 		 * (a) that would mess up the checksums and (b) the DHCP
15216 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15217 		 * hand it the packet regardless.
15218 		 */
15219 		if (ill->ill_dhcpinit != 0 &&
15220 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15221 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15222 			udpha_t *udpha;
15223 
15224 			/*
15225 			 * Reload ipha since pullupmsg() can change b_rptr.
15226 			 */
15227 			ipha = (ipha_t *)mp->b_rptr;
15228 			udpha = (udpha_t *)&ipha[1];
15229 
15230 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15231 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15232 				    mblk_t *, mp);
15233 				dst = INADDR_BROADCAST;
15234 			}
15235 		}
15236 
15237 		/* Full-blown slow path */
15238 		if (opt_len != 0) {
15239 			if (len != 0)
15240 				IP_STAT(ipst, ip_multimblk4);
15241 			else
15242 				IP_STAT(ipst, ip_ipoptions);
15243 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15244 			    &dst, ipst))
15245 				continue;
15246 		}
15247 
15248 		/*
15249 		 * Invoke the CGTP (multirouting) filtering module to process
15250 		 * the incoming packet. Packets identified as duplicates
15251 		 * must be discarded. Filtering is active only if the
15252 		 * the ip_cgtp_filter ndd variable is non-zero.
15253 		 */
15254 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15255 		if (ipst->ips_ip_cgtp_filter &&
15256 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15257 			netstackid_t stackid;
15258 
15259 			stackid = ipst->ips_netstack->netstack_stackid;
15260 			cgtp_flt_pkt =
15261 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15262 			    ill->ill_phyint->phyint_ifindex, mp);
15263 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15264 				freemsg(first_mp);
15265 				continue;
15266 			}
15267 		}
15268 
15269 		/*
15270 		 * If rsvpd is running, let RSVP daemon handle its processing
15271 		 * and forwarding of RSVP multicast/unicast packets.
15272 		 * If rsvpd is not running but mrouted is running, RSVP
15273 		 * multicast packets are forwarded as multicast traffic
15274 		 * and RSVP unicast packets are forwarded by unicast router.
15275 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15276 		 * packets are not forwarded, but the unicast packets are
15277 		 * forwarded like unicast traffic.
15278 		 */
15279 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15280 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15281 		    NULL) {
15282 			/* RSVP packet and rsvpd running. Treat as ours */
15283 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15284 			/*
15285 			 * This assumes that we deliver to all streams for
15286 			 * multicast and broadcast packets.
15287 			 * We have to force ll_multicast to 1 to handle the
15288 			 * M_DATA messages passed in from ip_mroute_decap.
15289 			 */
15290 			dst = INADDR_BROADCAST;
15291 			ll_multicast = 1;
15292 		} else if (CLASSD(dst)) {
15293 			/* packet is multicast */
15294 			mp->b_next = NULL;
15295 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15296 			    &ll_multicast, &dst))
15297 				continue;
15298 		}
15299 
15300 		if (ire == NULL) {
15301 			ire = ire_cache_lookup(dst, ALL_ZONES,
15302 			    msg_getlabel(mp), ipst);
15303 		}
15304 
15305 		if (ire != NULL && ire->ire_stq != NULL &&
15306 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15307 		    ire->ire_zoneid != ALL_ZONES) {
15308 			/*
15309 			 * Should only use IREs that are visible from the
15310 			 * global zone for forwarding.
15311 			 */
15312 			ire_refrele(ire);
15313 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15314 			    msg_getlabel(mp), ipst);
15315 		}
15316 
15317 		if (ire == NULL) {
15318 			/*
15319 			 * No IRE for this destination, so it can't be for us.
15320 			 * Unless we are forwarding, drop the packet.
15321 			 * We have to let source routed packets through
15322 			 * since we don't yet know if they are 'ping -l'
15323 			 * packets i.e. if they will go out over the
15324 			 * same interface as they came in on.
15325 			 */
15326 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15327 			if (ire == NULL)
15328 				continue;
15329 		}
15330 
15331 		/*
15332 		 * Broadcast IRE may indicate either broadcast or
15333 		 * multicast packet
15334 		 */
15335 		if (ire->ire_type == IRE_BROADCAST) {
15336 			/*
15337 			 * Skip broadcast checks if packet is UDP multicast;
15338 			 * we'd rather not enter ip_rput_process_broadcast()
15339 			 * unless the packet is broadcast for real, since
15340 			 * that routine is a no-op for multicast.
15341 			 */
15342 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15343 			    !CLASSD(ipha->ipha_dst)) {
15344 				ire = ip_rput_process_broadcast(&q, mp,
15345 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15346 				    ll_multicast);
15347 				if (ire == NULL)
15348 					continue;
15349 			}
15350 		} else if (ire->ire_stq != NULL) {
15351 			/* fowarding? */
15352 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15353 			    ll_multicast, B_FALSE);
15354 			/* ip_rput_process_forward consumed the packet */
15355 			continue;
15356 		}
15357 
15358 local:
15359 		/*
15360 		 * If the queue in the ire is different to the ingress queue
15361 		 * then we need to check to see if we can accept the packet.
15362 		 * Note that for multicast packets and broadcast packets sent
15363 		 * to a broadcast address which is shared between multiple
15364 		 * interfaces we should not do this since we just got a random
15365 		 * broadcast ire.
15366 		 */
15367 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15368 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15369 			if (ire == NULL) {
15370 				/* Drop packet */
15371 				BUMP_MIB(ill->ill_ip_mib,
15372 				    ipIfStatsForwProhibits);
15373 				freemsg(mp);
15374 				continue;
15375 			}
15376 			if (ire->ire_rfq != NULL)
15377 				q = ire->ire_rfq;
15378 		}
15379 
15380 		switch (ipha->ipha_protocol) {
15381 		case IPPROTO_TCP:
15382 			ASSERT(first_mp == mp);
15383 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15384 			    mp, 0, q, ip_ring)) != NULL) {
15385 				if (curr_sqp == NULL) {
15386 					curr_sqp = GET_SQUEUE(mp);
15387 					ASSERT(cnt == 0);
15388 					cnt++;
15389 					head = tail = mp;
15390 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15391 					ASSERT(tail != NULL);
15392 					cnt++;
15393 					tail->b_next = mp;
15394 					tail = mp;
15395 				} else {
15396 					/*
15397 					 * A different squeue. Send the
15398 					 * chain for the previous squeue on
15399 					 * its way. This shouldn't happen
15400 					 * often unless interrupt binding
15401 					 * changes.
15402 					 */
15403 					IP_STAT(ipst, ip_input_multi_squeue);
15404 					SQUEUE_ENTER(curr_sqp, head,
15405 					    tail, cnt, SQ_PROCESS, tag);
15406 					curr_sqp = GET_SQUEUE(mp);
15407 					head = mp;
15408 					tail = mp;
15409 					cnt = 1;
15410 				}
15411 			}
15412 			continue;
15413 		case IPPROTO_UDP:
15414 			ASSERT(first_mp == mp);
15415 			ip_udp_input(q, mp, ipha, ire, ill);
15416 			continue;
15417 		case IPPROTO_SCTP:
15418 			ASSERT(first_mp == mp);
15419 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15420 			    q, dst);
15421 			/* ire has been released by ip_sctp_input */
15422 			ire = NULL;
15423 			continue;
15424 		default:
15425 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15426 			continue;
15427 		}
15428 	}
15429 
15430 	if (ire != NULL)
15431 		ire_refrele(ire);
15432 
15433 	if (head != NULL)
15434 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15435 
15436 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15437 	    "ip_input_end: q %p (%S)", q, "end");
15438 #undef  rptr
15439 }
15440 
15441 /*
15442  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15443  * a chain of packets in the poll mode. The packets have gone through the
15444  * data link processing but not IP processing. For performance and latency
15445  * reasons, the squeue wants to process the chain in line instead of feeding
15446  * it back via ip_input path.
15447  *
15448  * So this is a light weight function which checks to see if the packets
15449  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15450  * but we still do the paranoid check) meant for local machine and we don't
15451  * have labels etc enabled. Packets that meet the criterion are returned to
15452  * the squeue and processed inline while the rest go via ip_input path.
15453  */
15454 /*ARGSUSED*/
15455 mblk_t *
15456 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15457     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15458 {
15459 	mblk_t 		*mp;
15460 	ipaddr_t	dst = NULL;
15461 	ipaddr_t	prev_dst;
15462 	ire_t		*ire = NULL;
15463 	ipha_t		*ipha;
15464 	uint_t		pkt_len;
15465 	ssize_t		len;
15466 	uint_t		opt_len;
15467 	queue_t		*q = ill->ill_rq;
15468 	squeue_t	*curr_sqp;
15469 	mblk_t 		*ahead = NULL;	/* Accepted head */
15470 	mblk_t		*atail = NULL;	/* Accepted tail */
15471 	uint_t		acnt = 0;	/* Accepted count */
15472 	mblk_t		*utail = NULL;	/* Unaccepted head */
15473 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15474 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15475 	ip_stack_t	*ipst = ill->ill_ipst;
15476 
15477 	*cnt = 0;
15478 
15479 	ASSERT(ill != NULL);
15480 	ASSERT(ip_ring != NULL);
15481 
15482 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15483 
15484 #define	rptr	((uchar_t *)ipha)
15485 
15486 	while (mp_chain != NULL) {
15487 		mp = mp_chain;
15488 		mp_chain = mp_chain->b_next;
15489 		mp->b_next = NULL;
15490 
15491 		/*
15492 		 * We do ire caching from one iteration to
15493 		 * another. In the event the packet chain contains
15494 		 * all packets from the same dst, this caching saves
15495 		 * an ire_cache_lookup for each of the succeeding
15496 		 * packets in a packet chain.
15497 		 */
15498 		prev_dst = dst;
15499 
15500 		ipha = (ipha_t *)mp->b_rptr;
15501 		len = mp->b_wptr - rptr;
15502 
15503 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15504 
15505 		/*
15506 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15507 		 * or doesn't have min len, reject.
15508 		 */
15509 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15510 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15511 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15512 			continue;
15513 		}
15514 
15515 		pkt_len = ntohs(ipha->ipha_length);
15516 		if (len != pkt_len) {
15517 			if (len > pkt_len) {
15518 				mp->b_wptr = rptr + pkt_len;
15519 			} else {
15520 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15521 				continue;
15522 			}
15523 		}
15524 
15525 		opt_len = ipha->ipha_version_and_hdr_length -
15526 		    IP_SIMPLE_HDR_VERSION;
15527 		dst = ipha->ipha_dst;
15528 
15529 		/* IP version bad or there are IP options */
15530 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15531 		    mp, &ipha, &dst, ipst)))
15532 			continue;
15533 
15534 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15535 		    (ipst->ips_ip_cgtp_filter &&
15536 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15537 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15538 			continue;
15539 		}
15540 
15541 		/*
15542 		 * Reuse the cached ire only if the ipha_dst of the previous
15543 		 * packet is the same as the current packet AND it is not
15544 		 * INADDR_ANY.
15545 		 */
15546 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15547 		    (ire != NULL)) {
15548 			ire_refrele(ire);
15549 			ire = NULL;
15550 		}
15551 
15552 		if (ire == NULL)
15553 			ire = ire_cache_lookup_simple(dst, ipst);
15554 
15555 		/*
15556 		 * Unless forwarding is enabled, dont call
15557 		 * ip_fast_forward(). Incoming packet is for forwarding
15558 		 */
15559 		if ((ill->ill_flags & ILLF_ROUTER) &&
15560 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15561 
15562 			DTRACE_PROBE4(ip4__physical__in__start,
15563 			    ill_t *, ill, ill_t *, NULL,
15564 			    ipha_t *, ipha, mblk_t *, mp);
15565 
15566 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15567 			    ipst->ips_ipv4firewall_physical_in,
15568 			    ill, NULL, ipha, mp, mp, 0, ipst);
15569 
15570 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15571 
15572 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15573 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15574 			    pkt_len);
15575 
15576 			if (mp != NULL)
15577 				ire = ip_fast_forward(ire, dst, ill, mp);
15578 			continue;
15579 		}
15580 
15581 		/* incoming packet is for local consumption */
15582 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15583 			goto local_accept;
15584 
15585 		/*
15586 		 * Disable ire caching for anything more complex
15587 		 * than the simple fast path case we checked for above.
15588 		 */
15589 		if (ire != NULL) {
15590 			ire_refrele(ire);
15591 			ire = NULL;
15592 		}
15593 
15594 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15595 		    ipst);
15596 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15597 		    ire->ire_stq != NULL) {
15598 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15599 			if (ire != NULL) {
15600 				ire_refrele(ire);
15601 				ire = NULL;
15602 			}
15603 			continue;
15604 		}
15605 
15606 local_accept:
15607 
15608 		if (ire->ire_rfq != q) {
15609 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15610 			if (ire != NULL) {
15611 				ire_refrele(ire);
15612 				ire = NULL;
15613 			}
15614 			continue;
15615 		}
15616 
15617 		/*
15618 		 * The event for packets being received from a 'physical'
15619 		 * interface is placed after validation of the source and/or
15620 		 * destination address as being local so that packets can be
15621 		 * redirected to loopback addresses using ipnat.
15622 		 */
15623 		DTRACE_PROBE4(ip4__physical__in__start,
15624 		    ill_t *, ill, ill_t *, NULL,
15625 		    ipha_t *, ipha, mblk_t *, mp);
15626 
15627 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15628 		    ipst->ips_ipv4firewall_physical_in,
15629 		    ill, NULL, ipha, mp, mp, 0, ipst);
15630 
15631 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15632 
15633 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15634 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15635 
15636 		if (mp != NULL &&
15637 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15638 		    0, q, ip_ring)) != NULL) {
15639 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15640 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15641 			} else {
15642 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15643 				    SQ_FILL, SQTAG_IP_INPUT);
15644 			}
15645 		}
15646 	}
15647 
15648 	if (ire != NULL)
15649 		ire_refrele(ire);
15650 
15651 	if (uhead != NULL)
15652 		ip_input(ill, ip_ring, uhead, NULL);
15653 
15654 	if (ahead != NULL) {
15655 		*last = atail;
15656 		*cnt = acnt;
15657 		return (ahead);
15658 	}
15659 
15660 	return (NULL);
15661 #undef  rptr
15662 }
15663 
15664 static void
15665 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15666     t_uscalar_t err)
15667 {
15668 	if (dl_err == DL_SYSERR) {
15669 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15670 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15671 		    ill->ill_name, dl_primstr(prim), err);
15672 		return;
15673 	}
15674 
15675 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15676 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15677 	    dl_errstr(dl_err));
15678 }
15679 
15680 /*
15681  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15682  * than DL_UNITDATA_IND messages. If we need to process this message
15683  * exclusively, we call qwriter_ip, in which case we also need to call
15684  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15685  */
15686 void
15687 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15688 {
15689 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15690 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15691 	ill_t		*ill = q->q_ptr;
15692 	t_uscalar_t	prim = dloa->dl_primitive;
15693 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15694 
15695 	ip1dbg(("ip_rput_dlpi"));
15696 
15697 	/*
15698 	 * If we received an ACK but didn't send a request for it, then it
15699 	 * can't be part of any pending operation; discard up-front.
15700 	 */
15701 	switch (prim) {
15702 	case DL_ERROR_ACK:
15703 		reqprim = dlea->dl_error_primitive;
15704 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15705 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15706 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15707 		    dlea->dl_unix_errno));
15708 		break;
15709 	case DL_OK_ACK:
15710 		reqprim = dloa->dl_correct_primitive;
15711 		break;
15712 	case DL_INFO_ACK:
15713 		reqprim = DL_INFO_REQ;
15714 		break;
15715 	case DL_BIND_ACK:
15716 		reqprim = DL_BIND_REQ;
15717 		break;
15718 	case DL_PHYS_ADDR_ACK:
15719 		reqprim = DL_PHYS_ADDR_REQ;
15720 		break;
15721 	case DL_NOTIFY_ACK:
15722 		reqprim = DL_NOTIFY_REQ;
15723 		break;
15724 	case DL_CONTROL_ACK:
15725 		reqprim = DL_CONTROL_REQ;
15726 		break;
15727 	case DL_CAPABILITY_ACK:
15728 		reqprim = DL_CAPABILITY_REQ;
15729 		break;
15730 	}
15731 
15732 	if (prim != DL_NOTIFY_IND) {
15733 		if (reqprim == DL_PRIM_INVAL ||
15734 		    !ill_dlpi_pending(ill, reqprim)) {
15735 			/* Not a DLPI message we support or expected */
15736 			freemsg(mp);
15737 			return;
15738 		}
15739 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15740 		    dl_primstr(reqprim)));
15741 	}
15742 
15743 	switch (reqprim) {
15744 	case DL_UNBIND_REQ:
15745 		/*
15746 		 * NOTE: we mark the unbind as complete even if we got a
15747 		 * DL_ERROR_ACK, since there's not much else we can do.
15748 		 */
15749 		mutex_enter(&ill->ill_lock);
15750 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15751 		cv_signal(&ill->ill_cv);
15752 		mutex_exit(&ill->ill_lock);
15753 		break;
15754 
15755 	case DL_ENABMULTI_REQ:
15756 		if (prim == DL_OK_ACK) {
15757 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15758 				ill->ill_dlpi_multicast_state = IDS_OK;
15759 		}
15760 		break;
15761 	}
15762 
15763 	/*
15764 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15765 	 * need to become writer to continue to process it.  Because an
15766 	 * exclusive operation doesn't complete until replies to all queued
15767 	 * DLPI messages have been received, we know we're in the middle of an
15768 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15769 	 *
15770 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15771 	 * Since this is on the ill stream we unconditionally bump up the
15772 	 * refcount without doing ILL_CAN_LOOKUP().
15773 	 */
15774 	ill_refhold(ill);
15775 	if (prim == DL_NOTIFY_IND)
15776 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15777 	else
15778 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15779 }
15780 
15781 /*
15782  * Handling of DLPI messages that require exclusive access to the ipsq.
15783  *
15784  * Need to do ill_pending_mp_release on ioctl completion, which could
15785  * happen here. (along with mi_copy_done)
15786  */
15787 /* ARGSUSED */
15788 static void
15789 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15790 {
15791 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15792 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15793 	int		err = 0;
15794 	ill_t		*ill;
15795 	ipif_t		*ipif = NULL;
15796 	mblk_t		*mp1 = NULL;
15797 	conn_t		*connp = NULL;
15798 	t_uscalar_t	paddrreq;
15799 	mblk_t		*mp_hw;
15800 	boolean_t	success;
15801 	boolean_t	ioctl_aborted = B_FALSE;
15802 	boolean_t	log = B_TRUE;
15803 	ip_stack_t		*ipst;
15804 
15805 	ip1dbg(("ip_rput_dlpi_writer .."));
15806 	ill = (ill_t *)q->q_ptr;
15807 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15808 	ASSERT(IAM_WRITER_ILL(ill));
15809 
15810 	ipst = ill->ill_ipst;
15811 
15812 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15813 	/*
15814 	 * The current ioctl could have been aborted by the user and a new
15815 	 * ioctl to bring up another ill could have started. We could still
15816 	 * get a response from the driver later.
15817 	 */
15818 	if (ipif != NULL && ipif->ipif_ill != ill)
15819 		ioctl_aborted = B_TRUE;
15820 
15821 	switch (dloa->dl_primitive) {
15822 	case DL_ERROR_ACK:
15823 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15824 		    dl_primstr(dlea->dl_error_primitive)));
15825 
15826 		switch (dlea->dl_error_primitive) {
15827 		case DL_DISABMULTI_REQ:
15828 			if (!ill->ill_isv6)
15829 				ipsq_current_finish(ipsq);
15830 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15831 			break;
15832 		case DL_PROMISCON_REQ:
15833 		case DL_PROMISCOFF_REQ:
15834 		case DL_UNBIND_REQ:
15835 		case DL_ATTACH_REQ:
15836 		case DL_INFO_REQ:
15837 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15838 			break;
15839 		case DL_NOTIFY_REQ:
15840 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15841 			log = B_FALSE;
15842 			break;
15843 		case DL_PHYS_ADDR_REQ:
15844 			/*
15845 			 * For IPv6 only, there are two additional
15846 			 * phys_addr_req's sent to the driver to get the
15847 			 * IPv6 token and lla. This allows IP to acquire
15848 			 * the hardware address format for a given interface
15849 			 * without having built in knowledge of the hardware
15850 			 * address. ill_phys_addr_pend keeps track of the last
15851 			 * DL_PAR sent so we know which response we are
15852 			 * dealing with. ill_dlpi_done will update
15853 			 * ill_phys_addr_pend when it sends the next req.
15854 			 * We don't complete the IOCTL until all three DL_PARs
15855 			 * have been attempted, so set *_len to 0 and break.
15856 			 */
15857 			paddrreq = ill->ill_phys_addr_pend;
15858 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15859 			if (paddrreq == DL_IPV6_TOKEN) {
15860 				ill->ill_token_length = 0;
15861 				log = B_FALSE;
15862 				break;
15863 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15864 				ill->ill_nd_lla_len = 0;
15865 				log = B_FALSE;
15866 				break;
15867 			}
15868 			/*
15869 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15870 			 * We presumably have an IOCTL hanging out waiting
15871 			 * for completion. Find it and complete the IOCTL
15872 			 * with the error noted.
15873 			 * However, ill_dl_phys was called on an ill queue
15874 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15875 			 * set. But the ioctl is known to be pending on ill_wq.
15876 			 */
15877 			if (!ill->ill_ifname_pending)
15878 				break;
15879 			ill->ill_ifname_pending = 0;
15880 			if (!ioctl_aborted)
15881 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15882 			if (mp1 != NULL) {
15883 				/*
15884 				 * This operation (SIOCSLIFNAME) must have
15885 				 * happened on the ill. Assert there is no conn
15886 				 */
15887 				ASSERT(connp == NULL);
15888 				q = ill->ill_wq;
15889 			}
15890 			break;
15891 		case DL_BIND_REQ:
15892 			ill_dlpi_done(ill, DL_BIND_REQ);
15893 			if (ill->ill_ifname_pending)
15894 				break;
15895 			/*
15896 			 * Something went wrong with the bind.  We presumably
15897 			 * have an IOCTL hanging out waiting for completion.
15898 			 * Find it, take down the interface that was coming
15899 			 * up, and complete the IOCTL with the error noted.
15900 			 */
15901 			if (!ioctl_aborted)
15902 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15903 			if (mp1 != NULL) {
15904 				/*
15905 				 * This operation (SIOCSLIFFLAGS) must have
15906 				 * happened from a conn.
15907 				 */
15908 				ASSERT(connp != NULL);
15909 				q = CONNP_TO_WQ(connp);
15910 				(void) ipif_down(ipif, NULL, NULL);
15911 				/* error is set below the switch */
15912 			}
15913 			break;
15914 		case DL_ENABMULTI_REQ:
15915 			if (!ill->ill_isv6)
15916 				ipsq_current_finish(ipsq);
15917 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15918 
15919 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15920 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15921 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15922 				ipif_t *ipif;
15923 
15924 				printf("ip: joining multicasts failed (%d)"
15925 				    " on %s - will use link layer "
15926 				    "broadcasts for multicast\n",
15927 				    dlea->dl_errno, ill->ill_name);
15928 
15929 				/*
15930 				 * Set up the multicast mapping alone.
15931 				 * writer, so ok to access ill->ill_ipif
15932 				 * without any lock.
15933 				 */
15934 				ipif = ill->ill_ipif;
15935 				mutex_enter(&ill->ill_phyint->phyint_lock);
15936 				ill->ill_phyint->phyint_flags |=
15937 				    PHYI_MULTI_BCAST;
15938 				mutex_exit(&ill->ill_phyint->phyint_lock);
15939 
15940 				if (!ill->ill_isv6) {
15941 					(void) ipif_arp_setup_multicast(ipif,
15942 					    NULL);
15943 				} else {
15944 					(void) ipif_ndp_setup_multicast(ipif,
15945 					    NULL);
15946 				}
15947 			}
15948 			freemsg(mp);	/* Don't want to pass this up */
15949 			return;
15950 		case DL_CONTROL_REQ:
15951 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15952 			    "DL_CONTROL_REQ\n"));
15953 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15954 			freemsg(mp);
15955 			return;
15956 		case DL_CAPABILITY_REQ:
15957 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15958 			    "DL_CAPABILITY REQ\n"));
15959 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15960 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15961 			ill_capability_done(ill);
15962 			freemsg(mp);
15963 			return;
15964 		}
15965 		/*
15966 		 * Note the error for IOCTL completion (mp1 is set when
15967 		 * ready to complete ioctl). If ill_ifname_pending_err is
15968 		 * set, an error occured during plumbing (ill_ifname_pending),
15969 		 * so we want to report that error.
15970 		 *
15971 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15972 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15973 		 * expected to get errack'd if the driver doesn't support
15974 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15975 		 * if these error conditions are encountered.
15976 		 */
15977 		if (mp1 != NULL) {
15978 			if (ill->ill_ifname_pending_err != 0)  {
15979 				err = ill->ill_ifname_pending_err;
15980 				ill->ill_ifname_pending_err = 0;
15981 			} else {
15982 				err = dlea->dl_unix_errno ?
15983 				    dlea->dl_unix_errno : ENXIO;
15984 			}
15985 		/*
15986 		 * If we're plumbing an interface and an error hasn't already
15987 		 * been saved, set ill_ifname_pending_err to the error passed
15988 		 * up. Ignore the error if log is B_FALSE (see comment above).
15989 		 */
15990 		} else if (log && ill->ill_ifname_pending &&
15991 		    ill->ill_ifname_pending_err == 0) {
15992 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15993 			    dlea->dl_unix_errno : ENXIO;
15994 		}
15995 
15996 		if (log)
15997 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15998 			    dlea->dl_errno, dlea->dl_unix_errno);
15999 		break;
16000 	case DL_CAPABILITY_ACK:
16001 		ill_capability_ack(ill, mp);
16002 		/*
16003 		 * The message has been handed off to ill_capability_ack
16004 		 * and must not be freed below
16005 		 */
16006 		mp = NULL;
16007 		break;
16008 
16009 	case DL_CONTROL_ACK:
16010 		/* We treat all of these as "fire and forget" */
16011 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16012 		break;
16013 	case DL_INFO_ACK:
16014 		/* Call a routine to handle this one. */
16015 		ill_dlpi_done(ill, DL_INFO_REQ);
16016 		ip_ll_subnet_defaults(ill, mp);
16017 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16018 		return;
16019 	case DL_BIND_ACK:
16020 		/*
16021 		 * We should have an IOCTL waiting on this unless
16022 		 * sent by ill_dl_phys, in which case just return
16023 		 */
16024 		ill_dlpi_done(ill, DL_BIND_REQ);
16025 		if (ill->ill_ifname_pending)
16026 			break;
16027 
16028 		if (!ioctl_aborted)
16029 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16030 		if (mp1 == NULL)
16031 			break;
16032 		/*
16033 		 * Because mp1 was added by ill_dl_up(), and it always
16034 		 * passes a valid connp, connp must be valid here.
16035 		 */
16036 		ASSERT(connp != NULL);
16037 		q = CONNP_TO_WQ(connp);
16038 
16039 		/*
16040 		 * We are exclusive. So nothing can change even after
16041 		 * we get the pending mp. If need be we can put it back
16042 		 * and restart, as in calling ipif_arp_up()  below.
16043 		 */
16044 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16045 
16046 		mutex_enter(&ill->ill_lock);
16047 		ill->ill_dl_up = 1;
16048 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16049 		mutex_exit(&ill->ill_lock);
16050 
16051 		/*
16052 		 * Now bring up the resolver; when that is complete, we'll
16053 		 * create IREs.  Note that we intentionally mirror what
16054 		 * ipif_up() would have done, because we got here by way of
16055 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16056 		 */
16057 		if (ill->ill_isv6) {
16058 			if (ill->ill_flags & ILLF_XRESOLV) {
16059 				mutex_enter(&connp->conn_lock);
16060 				mutex_enter(&ill->ill_lock);
16061 				success = ipsq_pending_mp_add(connp, ipif, q,
16062 				    mp1, 0);
16063 				mutex_exit(&ill->ill_lock);
16064 				mutex_exit(&connp->conn_lock);
16065 				if (success) {
16066 					err = ipif_resolver_up(ipif,
16067 					    Res_act_initial);
16068 					if (err == EINPROGRESS) {
16069 						freemsg(mp);
16070 						return;
16071 					}
16072 					ASSERT(err != 0);
16073 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16074 					ASSERT(mp1 != NULL);
16075 				} else {
16076 					/* conn has started closing */
16077 					err = EINTR;
16078 				}
16079 			} else { /* Non XRESOLV interface */
16080 				(void) ipif_resolver_up(ipif, Res_act_initial);
16081 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16082 					err = ipif_up_done_v6(ipif);
16083 			}
16084 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16085 			/*
16086 			 * ARP and other v4 external resolvers.
16087 			 * Leave the pending mblk intact so that
16088 			 * the ioctl completes in ip_rput().
16089 			 */
16090 			mutex_enter(&connp->conn_lock);
16091 			mutex_enter(&ill->ill_lock);
16092 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16093 			mutex_exit(&ill->ill_lock);
16094 			mutex_exit(&connp->conn_lock);
16095 			if (success) {
16096 				err = ipif_resolver_up(ipif, Res_act_initial);
16097 				if (err == EINPROGRESS) {
16098 					freemsg(mp);
16099 					return;
16100 				}
16101 				ASSERT(err != 0);
16102 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16103 			} else {
16104 				/* The conn has started closing */
16105 				err = EINTR;
16106 			}
16107 		} else {
16108 			/*
16109 			 * This one is complete. Reply to pending ioctl.
16110 			 */
16111 			(void) ipif_resolver_up(ipif, Res_act_initial);
16112 			err = ipif_up_done(ipif);
16113 		}
16114 
16115 		if ((err == 0) && (ill->ill_up_ipifs)) {
16116 			err = ill_up_ipifs(ill, q, mp1);
16117 			if (err == EINPROGRESS) {
16118 				freemsg(mp);
16119 				return;
16120 			}
16121 		}
16122 
16123 		/*
16124 		 * If we have a moved ipif to bring up, and everything has
16125 		 * succeeded to this point, bring it up on the IPMP ill.
16126 		 * Otherwise, leave it down -- the admin can try to bring it
16127 		 * up by hand if need be.
16128 		 */
16129 		if (ill->ill_move_ipif != NULL) {
16130 			if (err != 0) {
16131 				ill->ill_move_ipif = NULL;
16132 			} else {
16133 				ipif = ill->ill_move_ipif;
16134 				ill->ill_move_ipif = NULL;
16135 				err = ipif_up(ipif, q, mp1);
16136 				if (err == EINPROGRESS) {
16137 					freemsg(mp);
16138 					return;
16139 				}
16140 			}
16141 		}
16142 		break;
16143 
16144 	case DL_NOTIFY_IND: {
16145 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16146 		ire_t *ire;
16147 		uint_t orig_mtu;
16148 		boolean_t need_ire_walk_v4 = B_FALSE;
16149 		boolean_t need_ire_walk_v6 = B_FALSE;
16150 
16151 		switch (notify->dl_notification) {
16152 		case DL_NOTE_PHYS_ADDR:
16153 			err = ill_set_phys_addr(ill, mp);
16154 			break;
16155 
16156 		case DL_NOTE_FASTPATH_FLUSH:
16157 			ill_fastpath_flush(ill);
16158 			break;
16159 
16160 		case DL_NOTE_SDU_SIZE:
16161 			/*
16162 			 * Change the MTU size of the interface, of all
16163 			 * attached ipif's, and of all relevant ire's.  The
16164 			 * new value's a uint32_t at notify->dl_data.
16165 			 * Mtu change Vs. new ire creation - protocol below.
16166 			 *
16167 			 * a Mark the ipif as IPIF_CHANGING.
16168 			 * b Set the new mtu in the ipif.
16169 			 * c Change the ire_max_frag on all affected ires
16170 			 * d Unmark the IPIF_CHANGING
16171 			 *
16172 			 * To see how the protocol works, assume an interface
16173 			 * route is also being added simultaneously by
16174 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16175 			 * the ire. If the ire is created before step a,
16176 			 * it will be cleaned up by step c. If the ire is
16177 			 * created after step d, it will see the new value of
16178 			 * ipif_mtu. Any attempt to create the ire between
16179 			 * steps a to d will fail because of the IPIF_CHANGING
16180 			 * flag. Note that ire_create() is passed a pointer to
16181 			 * the ipif_mtu, and not the value. During ire_add
16182 			 * under the bucket lock, the ire_max_frag of the
16183 			 * new ire being created is set from the ipif/ire from
16184 			 * which it is being derived.
16185 			 */
16186 			mutex_enter(&ill->ill_lock);
16187 
16188 			orig_mtu = ill->ill_max_mtu;
16189 			ill->ill_max_frag = (uint_t)notify->dl_data;
16190 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16191 
16192 			/*
16193 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16194 			 * clamp ill_max_mtu at it.
16195 			 */
16196 			if (ill->ill_user_mtu != 0 &&
16197 			    ill->ill_user_mtu < ill->ill_max_mtu)
16198 				ill->ill_max_mtu = ill->ill_user_mtu;
16199 
16200 			/*
16201 			 * If the MTU is unchanged, we're done.
16202 			 */
16203 			if (orig_mtu == ill->ill_max_mtu) {
16204 				mutex_exit(&ill->ill_lock);
16205 				break;
16206 			}
16207 
16208 			if (ill->ill_isv6) {
16209 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16210 					ill->ill_max_mtu = IPV6_MIN_MTU;
16211 			} else {
16212 				if (ill->ill_max_mtu < IP_MIN_MTU)
16213 					ill->ill_max_mtu = IP_MIN_MTU;
16214 			}
16215 			for (ipif = ill->ill_ipif; ipif != NULL;
16216 			    ipif = ipif->ipif_next) {
16217 				/*
16218 				 * Don't override the mtu if the user
16219 				 * has explicitly set it.
16220 				 */
16221 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16222 					continue;
16223 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16224 				if (ipif->ipif_isv6)
16225 					ire = ipif_to_ire_v6(ipif);
16226 				else
16227 					ire = ipif_to_ire(ipif);
16228 				if (ire != NULL) {
16229 					ire->ire_max_frag = ipif->ipif_mtu;
16230 					ire_refrele(ire);
16231 				}
16232 				if (ipif->ipif_flags & IPIF_UP) {
16233 					if (ill->ill_isv6)
16234 						need_ire_walk_v6 = B_TRUE;
16235 					else
16236 						need_ire_walk_v4 = B_TRUE;
16237 				}
16238 			}
16239 			mutex_exit(&ill->ill_lock);
16240 			if (need_ire_walk_v4)
16241 				ire_walk_v4(ill_mtu_change, (char *)ill,
16242 				    ALL_ZONES, ipst);
16243 			if (need_ire_walk_v6)
16244 				ire_walk_v6(ill_mtu_change, (char *)ill,
16245 				    ALL_ZONES, ipst);
16246 
16247 			/*
16248 			 * Refresh IPMP meta-interface MTU if necessary.
16249 			 */
16250 			if (IS_UNDER_IPMP(ill))
16251 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16252 			break;
16253 
16254 		case DL_NOTE_LINK_UP:
16255 		case DL_NOTE_LINK_DOWN: {
16256 			/*
16257 			 * We are writer. ill / phyint / ipsq assocs stable.
16258 			 * The RUNNING flag reflects the state of the link.
16259 			 */
16260 			phyint_t *phyint = ill->ill_phyint;
16261 			uint64_t new_phyint_flags;
16262 			boolean_t changed = B_FALSE;
16263 			boolean_t went_up;
16264 
16265 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16266 			mutex_enter(&phyint->phyint_lock);
16267 
16268 			new_phyint_flags = went_up ?
16269 			    phyint->phyint_flags | PHYI_RUNNING :
16270 			    phyint->phyint_flags & ~PHYI_RUNNING;
16271 
16272 			if (IS_IPMP(ill)) {
16273 				new_phyint_flags = went_up ?
16274 				    new_phyint_flags & ~PHYI_FAILED :
16275 				    new_phyint_flags | PHYI_FAILED;
16276 			}
16277 
16278 			if (new_phyint_flags != phyint->phyint_flags) {
16279 				phyint->phyint_flags = new_phyint_flags;
16280 				changed = B_TRUE;
16281 			}
16282 			mutex_exit(&phyint->phyint_lock);
16283 			/*
16284 			 * ill_restart_dad handles the DAD restart and routing
16285 			 * socket notification logic.
16286 			 */
16287 			if (changed) {
16288 				ill_restart_dad(phyint->phyint_illv4, went_up);
16289 				ill_restart_dad(phyint->phyint_illv6, went_up);
16290 			}
16291 			break;
16292 		}
16293 		case DL_NOTE_PROMISC_ON_PHYS:
16294 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16295 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16296 			mutex_enter(&ill->ill_lock);
16297 			ill->ill_promisc_on_phys = B_TRUE;
16298 			mutex_exit(&ill->ill_lock);
16299 			break;
16300 		case DL_NOTE_PROMISC_OFF_PHYS:
16301 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16302 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16303 			mutex_enter(&ill->ill_lock);
16304 			ill->ill_promisc_on_phys = B_FALSE;
16305 			mutex_exit(&ill->ill_lock);
16306 			break;
16307 		case DL_NOTE_CAPAB_RENEG:
16308 			/*
16309 			 * Something changed on the driver side.
16310 			 * It wants us to renegotiate the capabilities
16311 			 * on this ill. One possible cause is the aggregation
16312 			 * interface under us where a port got added or
16313 			 * went away.
16314 			 *
16315 			 * If the capability negotiation is already done
16316 			 * or is in progress, reset the capabilities and
16317 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16318 			 * so that when the ack comes back, we can start
16319 			 * the renegotiation process.
16320 			 *
16321 			 * Note that if ill_capab_reneg is already B_TRUE
16322 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16323 			 * the capability resetting request has been sent
16324 			 * and the renegotiation has not been started yet;
16325 			 * nothing needs to be done in this case.
16326 			 */
16327 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16328 			ill_capability_reset(ill, B_TRUE);
16329 			ipsq_current_finish(ipsq);
16330 			break;
16331 		default:
16332 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16333 			    "type 0x%x for DL_NOTIFY_IND\n",
16334 			    notify->dl_notification));
16335 			break;
16336 		}
16337 
16338 		/*
16339 		 * As this is an asynchronous operation, we
16340 		 * should not call ill_dlpi_done
16341 		 */
16342 		break;
16343 	}
16344 	case DL_NOTIFY_ACK: {
16345 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16346 
16347 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16348 			ill->ill_note_link = 1;
16349 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16350 		break;
16351 	}
16352 	case DL_PHYS_ADDR_ACK: {
16353 		/*
16354 		 * As part of plumbing the interface via SIOCSLIFNAME,
16355 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16356 		 * whose answers we receive here.  As each answer is received,
16357 		 * we call ill_dlpi_done() to dispatch the next request as
16358 		 * we're processing the current one.  Once all answers have
16359 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16360 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16361 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16362 		 * available, but we know the ioctl is pending on ill_wq.)
16363 		 */
16364 		uint_t	paddrlen, paddroff;
16365 
16366 		paddrreq = ill->ill_phys_addr_pend;
16367 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16368 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16369 
16370 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16371 		if (paddrreq == DL_IPV6_TOKEN) {
16372 			/*
16373 			 * bcopy to low-order bits of ill_token
16374 			 *
16375 			 * XXX Temporary hack - currently, all known tokens
16376 			 * are 64 bits, so I'll cheat for the moment.
16377 			 */
16378 			bcopy(mp->b_rptr + paddroff,
16379 			    &ill->ill_token.s6_addr32[2], paddrlen);
16380 			ill->ill_token_length = paddrlen;
16381 			break;
16382 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16383 			ASSERT(ill->ill_nd_lla_mp == NULL);
16384 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16385 			mp = NULL;
16386 			break;
16387 		}
16388 
16389 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16390 		ASSERT(ill->ill_phys_addr_mp == NULL);
16391 		if (!ill->ill_ifname_pending)
16392 			break;
16393 		ill->ill_ifname_pending = 0;
16394 		if (!ioctl_aborted)
16395 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16396 		if (mp1 != NULL) {
16397 			ASSERT(connp == NULL);
16398 			q = ill->ill_wq;
16399 		}
16400 		/*
16401 		 * If any error acks received during the plumbing sequence,
16402 		 * ill_ifname_pending_err will be set. Break out and send up
16403 		 * the error to the pending ioctl.
16404 		 */
16405 		if (ill->ill_ifname_pending_err != 0) {
16406 			err = ill->ill_ifname_pending_err;
16407 			ill->ill_ifname_pending_err = 0;
16408 			break;
16409 		}
16410 
16411 		ill->ill_phys_addr_mp = mp;
16412 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16413 		mp = NULL;
16414 
16415 		/*
16416 		 * If paddrlen is zero, the DLPI provider doesn't support
16417 		 * physical addresses.  The other two tests were historical
16418 		 * workarounds for bugs in our former PPP implementation, but
16419 		 * now other things have grown dependencies on them -- e.g.,
16420 		 * the tun module specifies a dl_addr_length of zero in its
16421 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16422 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16423 		 * but only after careful testing ensures that all dependent
16424 		 * broken DLPI providers have been fixed.
16425 		 */
16426 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16427 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16428 			ill->ill_phys_addr = NULL;
16429 		} else if (paddrlen != ill->ill_phys_addr_length) {
16430 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16431 			    paddrlen, ill->ill_phys_addr_length));
16432 			err = EINVAL;
16433 			break;
16434 		}
16435 
16436 		if (ill->ill_nd_lla_mp == NULL) {
16437 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16438 				err = ENOMEM;
16439 				break;
16440 			}
16441 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16442 		}
16443 
16444 		/*
16445 		 * Set the interface token.  If the zeroth interface address
16446 		 * is unspecified, then set it to the link local address.
16447 		 */
16448 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16449 			(void) ill_setdefaulttoken(ill);
16450 
16451 		ASSERT(ill->ill_ipif->ipif_id == 0);
16452 		if (ipif != NULL &&
16453 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16454 			(void) ipif_setlinklocal(ipif);
16455 		}
16456 		break;
16457 	}
16458 	case DL_OK_ACK:
16459 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16460 		    dl_primstr((int)dloa->dl_correct_primitive),
16461 		    dloa->dl_correct_primitive));
16462 		switch (dloa->dl_correct_primitive) {
16463 		case DL_ENABMULTI_REQ:
16464 		case DL_DISABMULTI_REQ:
16465 			if (!ill->ill_isv6)
16466 				ipsq_current_finish(ipsq);
16467 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16468 			break;
16469 		case DL_PROMISCON_REQ:
16470 		case DL_PROMISCOFF_REQ:
16471 		case DL_UNBIND_REQ:
16472 		case DL_ATTACH_REQ:
16473 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16474 			break;
16475 		}
16476 		break;
16477 	default:
16478 		break;
16479 	}
16480 
16481 	freemsg(mp);
16482 	if (mp1 == NULL)
16483 		return;
16484 
16485 	/*
16486 	 * The operation must complete without EINPROGRESS since
16487 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16488 	 * the operation will be stuck forever inside the IPSQ.
16489 	 */
16490 	ASSERT(err != EINPROGRESS);
16491 
16492 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16493 	case 0:
16494 		ipsq_current_finish(ipsq);
16495 		break;
16496 
16497 	case SIOCSLIFNAME:
16498 	case IF_UNITSEL: {
16499 		ill_t *ill_other = ILL_OTHER(ill);
16500 
16501 		/*
16502 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16503 		 * ill has a peer which is in an IPMP group, then place ill
16504 		 * into the same group.  One catch: although ifconfig plumbs
16505 		 * the appropriate IPMP meta-interface prior to plumbing this
16506 		 * ill, it is possible for multiple ifconfig applications to
16507 		 * race (or for another application to adjust plumbing), in
16508 		 * which case the IPMP meta-interface we need will be missing.
16509 		 * If so, kick the phyint out of the group.
16510 		 */
16511 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16512 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16513 			ipmp_illgrp_t	*illg;
16514 
16515 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16516 			if (illg == NULL)
16517 				ipmp_phyint_leave_grp(ill->ill_phyint);
16518 			else
16519 				ipmp_ill_join_illgrp(ill, illg);
16520 		}
16521 
16522 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16523 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16524 		else
16525 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16526 		break;
16527 	}
16528 	case SIOCLIFADDIF:
16529 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16530 		break;
16531 
16532 	default:
16533 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16534 		break;
16535 	}
16536 }
16537 
16538 /*
16539  * ip_rput_other is called by ip_rput to handle messages modifying the global
16540  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16541  */
16542 /* ARGSUSED */
16543 void
16544 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16545 {
16546 	ill_t		*ill = q->q_ptr;
16547 	struct iocblk	*iocp;
16548 	mblk_t		*mp1;
16549 	conn_t		*connp = NULL;
16550 
16551 	ip1dbg(("ip_rput_other "));
16552 	if (ipsq != NULL) {
16553 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16554 		ASSERT(ipsq->ipsq_xop ==
16555 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16556 	}
16557 
16558 	switch (mp->b_datap->db_type) {
16559 	case M_ERROR:
16560 	case M_HANGUP:
16561 		/*
16562 		 * The device has a problem.  We force the ILL down.  It can
16563 		 * be brought up again manually using SIOCSIFFLAGS (via
16564 		 * ifconfig or equivalent).
16565 		 */
16566 		ASSERT(ipsq != NULL);
16567 		if (mp->b_rptr < mp->b_wptr)
16568 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16569 		if (ill->ill_error == 0)
16570 			ill->ill_error = ENXIO;
16571 		if (!ill_down_start(q, mp))
16572 			return;
16573 		ipif_all_down_tail(ipsq, q, mp, NULL);
16574 		break;
16575 	case M_IOCACK:
16576 		iocp = (struct iocblk *)mp->b_rptr;
16577 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16578 		switch (iocp->ioc_cmd) {
16579 		case SIOCSTUNPARAM:
16580 		case OSIOCSTUNPARAM:
16581 			ASSERT(ipsq != NULL);
16582 			/*
16583 			 * Finish socket ioctl passed through to tun.
16584 			 * We should have an IOCTL waiting on this.
16585 			 */
16586 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16587 			if (ill->ill_isv6) {
16588 				struct iftun_req *ta;
16589 
16590 				/*
16591 				 * if a source or destination is
16592 				 * being set, try and set the link
16593 				 * local address for the tunnel
16594 				 */
16595 				ta = (struct iftun_req *)mp->b_cont->
16596 				    b_cont->b_rptr;
16597 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16598 					ipif_set_tun_llink(ill, ta);
16599 				}
16600 
16601 			}
16602 			if (mp1 != NULL) {
16603 				/*
16604 				 * Now copy back the b_next/b_prev used by
16605 				 * mi code for the mi_copy* functions.
16606 				 * See ip_sioctl_tunparam() for the reason.
16607 				 * Also protect against missing b_cont.
16608 				 */
16609 				if (mp->b_cont != NULL) {
16610 					mp->b_cont->b_next =
16611 					    mp1->b_cont->b_next;
16612 					mp->b_cont->b_prev =
16613 					    mp1->b_cont->b_prev;
16614 				}
16615 				inet_freemsg(mp1);
16616 				ASSERT(connp != NULL);
16617 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16618 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16619 			} else {
16620 				ASSERT(connp == NULL);
16621 				putnext(q, mp);
16622 			}
16623 			break;
16624 		case SIOCGTUNPARAM:
16625 		case OSIOCGTUNPARAM:
16626 			/*
16627 			 * This is really M_IOCDATA from the tunnel driver.
16628 			 * convert back and complete the ioctl.
16629 			 * We should have an IOCTL waiting on this.
16630 			 */
16631 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16632 			if (mp1) {
16633 				/*
16634 				 * Now copy back the b_next/b_prev used by
16635 				 * mi code for the mi_copy* functions.
16636 				 * See ip_sioctl_tunparam() for the reason.
16637 				 * Also protect against missing b_cont.
16638 				 */
16639 				if (mp->b_cont != NULL) {
16640 					mp->b_cont->b_next =
16641 					    mp1->b_cont->b_next;
16642 					mp->b_cont->b_prev =
16643 					    mp1->b_cont->b_prev;
16644 				}
16645 				inet_freemsg(mp1);
16646 				if (iocp->ioc_error == 0)
16647 					mp->b_datap->db_type = M_IOCDATA;
16648 				ASSERT(connp != NULL);
16649 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16650 				    iocp->ioc_error, COPYOUT, NULL);
16651 			} else {
16652 				ASSERT(connp == NULL);
16653 				putnext(q, mp);
16654 			}
16655 			break;
16656 		default:
16657 			break;
16658 		}
16659 		break;
16660 	case M_IOCNAK:
16661 		iocp = (struct iocblk *)mp->b_rptr;
16662 
16663 		switch (iocp->ioc_cmd) {
16664 			int mode;
16665 
16666 		case DL_IOC_HDR_INFO:
16667 			/*
16668 			 * If this was the first attempt, turn off the
16669 			 * fastpath probing.
16670 			 */
16671 			mutex_enter(&ill->ill_lock);
16672 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16673 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16674 				mutex_exit(&ill->ill_lock);
16675 				ill_fastpath_nack(ill);
16676 				ip1dbg(("ip_rput: DLPI fastpath off on "
16677 				    "interface %s\n",
16678 				    ill->ill_name));
16679 			} else {
16680 				mutex_exit(&ill->ill_lock);
16681 			}
16682 			freemsg(mp);
16683 			break;
16684 			case SIOCSTUNPARAM:
16685 		case OSIOCSTUNPARAM:
16686 			ASSERT(ipsq != NULL);
16687 			/*
16688 			 * Finish socket ioctl passed through to tun
16689 			 * We should have an IOCTL waiting on this.
16690 			 */
16691 			/* FALLTHRU */
16692 		case SIOCGTUNPARAM:
16693 		case OSIOCGTUNPARAM:
16694 			/*
16695 			 * This is really M_IOCDATA from the tunnel driver.
16696 			 * convert back and complete the ioctl.
16697 			 * We should have an IOCTL waiting on this.
16698 			 */
16699 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16700 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16701 				mp1 = ill_pending_mp_get(ill, &connp,
16702 				    iocp->ioc_id);
16703 				mode = COPYOUT;
16704 				ipsq = NULL;
16705 			} else {
16706 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16707 				mode = NO_COPYOUT;
16708 			}
16709 			if (mp1 != NULL) {
16710 				/*
16711 				 * Now copy back the b_next/b_prev used by
16712 				 * mi code for the mi_copy* functions.
16713 				 * See ip_sioctl_tunparam() for the reason.
16714 				 * Also protect against missing b_cont.
16715 				 */
16716 				if (mp->b_cont != NULL) {
16717 					mp->b_cont->b_next =
16718 					    mp1->b_cont->b_next;
16719 					mp->b_cont->b_prev =
16720 					    mp1->b_cont->b_prev;
16721 				}
16722 				inet_freemsg(mp1);
16723 				if (iocp->ioc_error == 0)
16724 					iocp->ioc_error = EINVAL;
16725 				ASSERT(connp != NULL);
16726 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16727 				    iocp->ioc_error, mode, ipsq);
16728 			} else {
16729 				ASSERT(connp == NULL);
16730 				putnext(q, mp);
16731 			}
16732 			break;
16733 		default:
16734 			break;
16735 		}
16736 	default:
16737 		break;
16738 	}
16739 }
16740 
16741 /*
16742  * NOTE : This function does not ire_refrele the ire argument passed in.
16743  *
16744  * IPQoS notes
16745  * IP policy is invoked twice for a forwarded packet, once on the read side
16746  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16747  * enabled. An additional parameter, in_ill, has been added for this purpose.
16748  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16749  * because ip_mroute drops this information.
16750  *
16751  */
16752 void
16753 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16754 {
16755 	uint32_t	old_pkt_len;
16756 	uint32_t	pkt_len;
16757 	queue_t	*q;
16758 	uint32_t	sum;
16759 #define	rptr	((uchar_t *)ipha)
16760 	uint32_t	max_frag;
16761 	uint32_t	ill_index;
16762 	ill_t		*out_ill;
16763 	mib2_ipIfStatsEntry_t *mibptr;
16764 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16765 
16766 	/* Get the ill_index of the incoming ILL */
16767 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16768 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16769 
16770 	/* Initiate Read side IPPF processing */
16771 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16772 		ip_process(IPP_FWD_IN, &mp, ill_index);
16773 		if (mp == NULL) {
16774 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16775 			    "during IPPF processing\n"));
16776 			return;
16777 		}
16778 	}
16779 
16780 	/* Adjust the checksum to reflect the ttl decrement. */
16781 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16782 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16783 
16784 	if (ipha->ipha_ttl-- <= 1) {
16785 		if (ip_csum_hdr(ipha)) {
16786 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16787 			goto drop_pkt;
16788 		}
16789 		/*
16790 		 * Note: ire_stq this will be NULL for multicast
16791 		 * datagrams using the long path through arp (the IRE
16792 		 * is not an IRE_CACHE). This should not cause
16793 		 * problems since we don't generate ICMP errors for
16794 		 * multicast packets.
16795 		 */
16796 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16797 		q = ire->ire_stq;
16798 		if (q != NULL) {
16799 			/* Sent by forwarding path, and router is global zone */
16800 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16801 			    GLOBAL_ZONEID, ipst);
16802 		} else
16803 			freemsg(mp);
16804 		return;
16805 	}
16806 
16807 	/*
16808 	 * Don't forward if the interface is down
16809 	 */
16810 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16811 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16812 		ip2dbg(("ip_rput_forward:interface is down\n"));
16813 		goto drop_pkt;
16814 	}
16815 
16816 	/* Get the ill_index of the outgoing ILL */
16817 	out_ill = ire_to_ill(ire);
16818 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16819 
16820 	DTRACE_PROBE4(ip4__forwarding__start,
16821 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16822 
16823 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16824 	    ipst->ips_ipv4firewall_forwarding,
16825 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16826 
16827 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16828 
16829 	if (mp == NULL)
16830 		return;
16831 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16832 
16833 	if (is_system_labeled()) {
16834 		mblk_t *mp1;
16835 
16836 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16837 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16838 			goto drop_pkt;
16839 		}
16840 		/* Size may have changed */
16841 		mp = mp1;
16842 		ipha = (ipha_t *)mp->b_rptr;
16843 		pkt_len = ntohs(ipha->ipha_length);
16844 	}
16845 
16846 	/* Check if there are options to update */
16847 	if (!IS_SIMPLE_IPH(ipha)) {
16848 		if (ip_csum_hdr(ipha)) {
16849 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16850 			goto drop_pkt;
16851 		}
16852 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16853 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16854 			return;
16855 		}
16856 
16857 		ipha->ipha_hdr_checksum = 0;
16858 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16859 	}
16860 	max_frag = ire->ire_max_frag;
16861 	if (pkt_len > max_frag) {
16862 		/*
16863 		 * It needs fragging on its way out.  We haven't
16864 		 * verified the header checksum yet.  Since we
16865 		 * are going to put a surely good checksum in the
16866 		 * outgoing header, we have to make sure that it
16867 		 * was good coming in.
16868 		 */
16869 		if (ip_csum_hdr(ipha)) {
16870 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16871 			goto drop_pkt;
16872 		}
16873 		/* Initiate Write side IPPF processing */
16874 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16875 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16876 			if (mp == NULL) {
16877 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16878 				    " during IPPF processing\n"));
16879 				return;
16880 			}
16881 		}
16882 		/*
16883 		 * Handle labeled packet resizing.
16884 		 *
16885 		 * If we have added a label, inform ip_wput_frag() of its
16886 		 * effect on the MTU for ICMP messages.
16887 		 */
16888 		if (pkt_len > old_pkt_len) {
16889 			uint32_t secopt_size;
16890 
16891 			secopt_size = pkt_len - old_pkt_len;
16892 			if (secopt_size < max_frag)
16893 				max_frag -= secopt_size;
16894 		}
16895 
16896 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16897 		    GLOBAL_ZONEID, ipst, NULL);
16898 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16899 		return;
16900 	}
16901 
16902 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16903 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16904 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16905 	    ipst->ips_ipv4firewall_physical_out,
16906 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16907 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16908 	if (mp == NULL)
16909 		return;
16910 
16911 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16912 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16913 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16914 	/* ip_xmit_v4 always consumes the packet */
16915 	return;
16916 
16917 drop_pkt:;
16918 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16919 	freemsg(mp);
16920 #undef	rptr
16921 }
16922 
16923 void
16924 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16925 {
16926 	ire_t	*ire;
16927 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16928 
16929 	ASSERT(!ipif->ipif_isv6);
16930 	/*
16931 	 * Find an IRE which matches the destination and the outgoing
16932 	 * queue in the cache table. All we need is an IRE_CACHE which
16933 	 * is pointing at ipif->ipif_ill.
16934 	 */
16935 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16936 		dst = ipif->ipif_pp_dst_addr;
16937 
16938 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16939 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16940 	if (ire == NULL) {
16941 		/*
16942 		 * Mark this packet to make it be delivered to
16943 		 * ip_rput_forward after the new ire has been
16944 		 * created.
16945 		 */
16946 		mp->b_prev = NULL;
16947 		mp->b_next = mp;
16948 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16949 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16950 	} else {
16951 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16952 		IRE_REFRELE(ire);
16953 	}
16954 }
16955 
16956 /* Update any source route, record route or timestamp options */
16957 static int
16958 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16959 {
16960 	ipoptp_t	opts;
16961 	uchar_t		*opt;
16962 	uint8_t		optval;
16963 	uint8_t		optlen;
16964 	ipaddr_t	dst;
16965 	uint32_t	ts;
16966 	ire_t		*dst_ire = NULL;
16967 	ire_t		*tmp_ire = NULL;
16968 	timestruc_t	now;
16969 
16970 	ip2dbg(("ip_rput_forward_options\n"));
16971 	dst = ipha->ipha_dst;
16972 	for (optval = ipoptp_first(&opts, ipha);
16973 	    optval != IPOPT_EOL;
16974 	    optval = ipoptp_next(&opts)) {
16975 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16976 		opt = opts.ipoptp_cur;
16977 		optlen = opts.ipoptp_len;
16978 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16979 		    optval, opts.ipoptp_len));
16980 		switch (optval) {
16981 			uint32_t off;
16982 		case IPOPT_SSRR:
16983 		case IPOPT_LSRR:
16984 			/* Check if adminstratively disabled */
16985 			if (!ipst->ips_ip_forward_src_routed) {
16986 				if (ire->ire_stq != NULL) {
16987 					/*
16988 					 * Sent by forwarding path, and router
16989 					 * is global zone
16990 					 */
16991 					icmp_unreachable(ire->ire_stq, mp,
16992 					    ICMP_SOURCE_ROUTE_FAILED,
16993 					    GLOBAL_ZONEID, ipst);
16994 				} else {
16995 					ip0dbg(("ip_rput_forward_options: "
16996 					    "unable to send unreach\n"));
16997 					freemsg(mp);
16998 				}
16999 				return (-1);
17000 			}
17001 
17002 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17003 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17004 			if (dst_ire == NULL) {
17005 				/*
17006 				 * Must be partial since ip_rput_options
17007 				 * checked for strict.
17008 				 */
17009 				break;
17010 			}
17011 			off = opt[IPOPT_OFFSET];
17012 			off--;
17013 		redo_srr:
17014 			if (optlen < IP_ADDR_LEN ||
17015 			    off > optlen - IP_ADDR_LEN) {
17016 				/* End of source route */
17017 				ip1dbg((
17018 				    "ip_rput_forward_options: end of SR\n"));
17019 				ire_refrele(dst_ire);
17020 				break;
17021 			}
17022 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17023 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17024 			    IP_ADDR_LEN);
17025 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17026 			    ntohl(dst)));
17027 
17028 			/*
17029 			 * Check if our address is present more than
17030 			 * once as consecutive hops in source route.
17031 			 */
17032 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17033 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17034 			if (tmp_ire != NULL) {
17035 				ire_refrele(tmp_ire);
17036 				off += IP_ADDR_LEN;
17037 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17038 				goto redo_srr;
17039 			}
17040 			ipha->ipha_dst = dst;
17041 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17042 			ire_refrele(dst_ire);
17043 			break;
17044 		case IPOPT_RR:
17045 			off = opt[IPOPT_OFFSET];
17046 			off--;
17047 			if (optlen < IP_ADDR_LEN ||
17048 			    off > optlen - IP_ADDR_LEN) {
17049 				/* No more room - ignore */
17050 				ip1dbg((
17051 				    "ip_rput_forward_options: end of RR\n"));
17052 				break;
17053 			}
17054 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17055 			    IP_ADDR_LEN);
17056 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17057 			break;
17058 		case IPOPT_TS:
17059 			/* Insert timestamp if there is room */
17060 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17061 			case IPOPT_TS_TSONLY:
17062 				off = IPOPT_TS_TIMELEN;
17063 				break;
17064 			case IPOPT_TS_PRESPEC:
17065 			case IPOPT_TS_PRESPEC_RFC791:
17066 				/* Verify that the address matched */
17067 				off = opt[IPOPT_OFFSET] - 1;
17068 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17069 				dst_ire = ire_ctable_lookup(dst, 0,
17070 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17071 				    MATCH_IRE_TYPE, ipst);
17072 				if (dst_ire == NULL) {
17073 					/* Not for us */
17074 					break;
17075 				}
17076 				ire_refrele(dst_ire);
17077 				/* FALLTHRU */
17078 			case IPOPT_TS_TSANDADDR:
17079 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17080 				break;
17081 			default:
17082 				/*
17083 				 * ip_*put_options should have already
17084 				 * dropped this packet.
17085 				 */
17086 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17087 				    "unknown IT - bug in ip_rput_options?\n");
17088 				return (0);	/* Keep "lint" happy */
17089 			}
17090 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17091 				/* Increase overflow counter */
17092 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17093 				opt[IPOPT_POS_OV_FLG] =
17094 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17095 				    (off << 4));
17096 				break;
17097 			}
17098 			off = opt[IPOPT_OFFSET] - 1;
17099 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17100 			case IPOPT_TS_PRESPEC:
17101 			case IPOPT_TS_PRESPEC_RFC791:
17102 			case IPOPT_TS_TSANDADDR:
17103 				bcopy(&ire->ire_src_addr,
17104 				    (char *)opt + off, IP_ADDR_LEN);
17105 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17106 				/* FALLTHRU */
17107 			case IPOPT_TS_TSONLY:
17108 				off = opt[IPOPT_OFFSET] - 1;
17109 				/* Compute # of milliseconds since midnight */
17110 				gethrestime(&now);
17111 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17112 				    now.tv_nsec / (NANOSEC / MILLISEC);
17113 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17114 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17115 				break;
17116 			}
17117 			break;
17118 		}
17119 	}
17120 	return (0);
17121 }
17122 
17123 /*
17124  * This is called after processing at least one of AH/ESP headers.
17125  *
17126  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17127  * the actual, physical interface on which the packet was received,
17128  * but, when ip_strict_dst_multihoming is set to 1, could be the
17129  * interface which had the ipha_dst configured when the packet went
17130  * through ip_rput. The ill_index corresponding to the recv_ill
17131  * is saved in ipsec_in_rill_index
17132  *
17133  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17134  * cannot assume "ire" points to valid data for any IPv6 cases.
17135  */
17136 void
17137 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17138 {
17139 	mblk_t *mp;
17140 	ipaddr_t dst;
17141 	in6_addr_t *v6dstp;
17142 	ipha_t *ipha;
17143 	ip6_t *ip6h;
17144 	ipsec_in_t *ii;
17145 	boolean_t ill_need_rele = B_FALSE;
17146 	boolean_t rill_need_rele = B_FALSE;
17147 	boolean_t ire_need_rele = B_FALSE;
17148 	netstack_t	*ns;
17149 	ip_stack_t	*ipst;
17150 
17151 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17152 	ASSERT(ii->ipsec_in_ill_index != 0);
17153 	ns = ii->ipsec_in_ns;
17154 	ASSERT(ii->ipsec_in_ns != NULL);
17155 	ipst = ns->netstack_ip;
17156 
17157 	mp = ipsec_mp->b_cont;
17158 	ASSERT(mp != NULL);
17159 
17160 	if (ill == NULL) {
17161 		ASSERT(recv_ill == NULL);
17162 		/*
17163 		 * We need to get the original queue on which ip_rput_local
17164 		 * or ip_rput_data_v6 was called.
17165 		 */
17166 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17167 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17168 		ill_need_rele = B_TRUE;
17169 
17170 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17171 			recv_ill = ill_lookup_on_ifindex(
17172 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17173 			    NULL, NULL, NULL, NULL, ipst);
17174 			rill_need_rele = B_TRUE;
17175 		} else {
17176 			recv_ill = ill;
17177 		}
17178 
17179 		if ((ill == NULL) || (recv_ill == NULL)) {
17180 			ip0dbg(("ip_fanout_proto_again: interface "
17181 			    "disappeared\n"));
17182 			if (ill != NULL)
17183 				ill_refrele(ill);
17184 			if (recv_ill != NULL)
17185 				ill_refrele(recv_ill);
17186 			freemsg(ipsec_mp);
17187 			return;
17188 		}
17189 	}
17190 
17191 	ASSERT(ill != NULL && recv_ill != NULL);
17192 
17193 	if (mp->b_datap->db_type == M_CTL) {
17194 		/*
17195 		 * AH/ESP is returning the ICMP message after
17196 		 * removing their headers. Fanout again till
17197 		 * it gets to the right protocol.
17198 		 */
17199 		if (ii->ipsec_in_v4) {
17200 			icmph_t *icmph;
17201 			int iph_hdr_length;
17202 			int hdr_length;
17203 
17204 			ipha = (ipha_t *)mp->b_rptr;
17205 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17206 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17207 			ipha = (ipha_t *)&icmph[1];
17208 			hdr_length = IPH_HDR_LENGTH(ipha);
17209 			/*
17210 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17211 			 * Reset the type to M_DATA.
17212 			 */
17213 			mp->b_datap->db_type = M_DATA;
17214 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17215 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17216 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17217 		} else {
17218 			icmp6_t *icmp6;
17219 			int hdr_length;
17220 
17221 			ip6h = (ip6_t *)mp->b_rptr;
17222 			/* Don't call hdr_length_v6() unless you have to. */
17223 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17224 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17225 			else
17226 				hdr_length = IPV6_HDR_LEN;
17227 
17228 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17229 			/*
17230 			 * icmp_inbound_error_fanout_v6 may need to do
17231 			 * pullupmsg.  Reset the type to M_DATA.
17232 			 */
17233 			mp->b_datap->db_type = M_DATA;
17234 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17235 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17236 			    ii->ipsec_in_zoneid);
17237 		}
17238 		if (ill_need_rele)
17239 			ill_refrele(ill);
17240 		if (rill_need_rele)
17241 			ill_refrele(recv_ill);
17242 		return;
17243 	}
17244 
17245 	if (ii->ipsec_in_v4) {
17246 		ipha = (ipha_t *)mp->b_rptr;
17247 		dst = ipha->ipha_dst;
17248 		if (CLASSD(dst)) {
17249 			/*
17250 			 * Multicast has to be delivered to all streams.
17251 			 */
17252 			dst = INADDR_BROADCAST;
17253 		}
17254 
17255 		if (ire == NULL) {
17256 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17257 			    msg_getlabel(mp), ipst);
17258 			if (ire == NULL) {
17259 				if (ill_need_rele)
17260 					ill_refrele(ill);
17261 				if (rill_need_rele)
17262 					ill_refrele(recv_ill);
17263 				ip1dbg(("ip_fanout_proto_again: "
17264 				    "IRE not found"));
17265 				freemsg(ipsec_mp);
17266 				return;
17267 			}
17268 			ire_need_rele = B_TRUE;
17269 		}
17270 
17271 		switch (ipha->ipha_protocol) {
17272 		case IPPROTO_UDP:
17273 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17274 			    recv_ill);
17275 			if (ire_need_rele)
17276 				ire_refrele(ire);
17277 			break;
17278 		case IPPROTO_TCP:
17279 			if (!ire_need_rele)
17280 				IRE_REFHOLD(ire);
17281 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17282 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17283 			IRE_REFRELE(ire);
17284 			if (mp != NULL) {
17285 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17286 				    mp, 1, SQ_PROCESS,
17287 				    SQTAG_IP_PROTO_AGAIN);
17288 			}
17289 			break;
17290 		case IPPROTO_SCTP:
17291 			if (!ire_need_rele)
17292 				IRE_REFHOLD(ire);
17293 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17294 			    ipsec_mp, 0, ill->ill_rq, dst);
17295 			break;
17296 		default:
17297 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17298 			    recv_ill, 0);
17299 			if (ire_need_rele)
17300 				ire_refrele(ire);
17301 			break;
17302 		}
17303 	} else {
17304 		uint32_t rput_flags = 0;
17305 
17306 		ip6h = (ip6_t *)mp->b_rptr;
17307 		v6dstp = &ip6h->ip6_dst;
17308 		/*
17309 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17310 		 * address.
17311 		 *
17312 		 * Currently, we don't store that state in the IPSEC_IN
17313 		 * message, and we may need to.
17314 		 */
17315 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17316 		    IP6_IN_LLMCAST : 0);
17317 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17318 		    NULL, NULL);
17319 	}
17320 	if (ill_need_rele)
17321 		ill_refrele(ill);
17322 	if (rill_need_rele)
17323 		ill_refrele(recv_ill);
17324 }
17325 
17326 /*
17327  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17328  * returns 'true' if there are still fragments left on the queue, in
17329  * which case we restart the timer.
17330  */
17331 void
17332 ill_frag_timer(void *arg)
17333 {
17334 	ill_t	*ill = (ill_t *)arg;
17335 	boolean_t frag_pending;
17336 	ip_stack_t	*ipst = ill->ill_ipst;
17337 
17338 	mutex_enter(&ill->ill_lock);
17339 	ASSERT(!ill->ill_fragtimer_executing);
17340 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17341 		ill->ill_frag_timer_id = 0;
17342 		mutex_exit(&ill->ill_lock);
17343 		return;
17344 	}
17345 	ill->ill_fragtimer_executing = 1;
17346 	mutex_exit(&ill->ill_lock);
17347 
17348 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17349 
17350 	/*
17351 	 * Restart the timer, if we have fragments pending or if someone
17352 	 * wanted us to be scheduled again.
17353 	 */
17354 	mutex_enter(&ill->ill_lock);
17355 	ill->ill_fragtimer_executing = 0;
17356 	ill->ill_frag_timer_id = 0;
17357 	if (frag_pending || ill->ill_fragtimer_needrestart)
17358 		ill_frag_timer_start(ill);
17359 	mutex_exit(&ill->ill_lock);
17360 }
17361 
17362 void
17363 ill_frag_timer_start(ill_t *ill)
17364 {
17365 	ip_stack_t	*ipst = ill->ill_ipst;
17366 
17367 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17368 
17369 	/* If the ill is closing or opening don't proceed */
17370 	if (ill->ill_state_flags & ILL_CONDEMNED)
17371 		return;
17372 
17373 	if (ill->ill_fragtimer_executing) {
17374 		/*
17375 		 * ill_frag_timer is currently executing. Just record the
17376 		 * the fact that we want the timer to be restarted.
17377 		 * ill_frag_timer will post a timeout before it returns,
17378 		 * ensuring it will be called again.
17379 		 */
17380 		ill->ill_fragtimer_needrestart = 1;
17381 		return;
17382 	}
17383 
17384 	if (ill->ill_frag_timer_id == 0) {
17385 		/*
17386 		 * The timer is neither running nor is the timeout handler
17387 		 * executing. Post a timeout so that ill_frag_timer will be
17388 		 * called
17389 		 */
17390 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17391 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17392 		ill->ill_fragtimer_needrestart = 0;
17393 	}
17394 }
17395 
17396 /*
17397  * This routine is needed for loopback when forwarding multicasts.
17398  *
17399  * IPQoS Notes:
17400  * IPPF processing is done in fanout routines.
17401  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17402  * processing for IPsec packets is done when it comes back in clear.
17403  * NOTE : The callers of this function need to do the ire_refrele for the
17404  *	  ire that is being passed in.
17405  */
17406 void
17407 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17408     ill_t *recv_ill, uint32_t esp_udp_ports)
17409 {
17410 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17411 	ill_t	*ill = (ill_t *)q->q_ptr;
17412 	uint32_t	sum;
17413 	uint32_t	u1;
17414 	uint32_t	u2;
17415 	int		hdr_length;
17416 	boolean_t	mctl_present;
17417 	mblk_t		*first_mp = mp;
17418 	mblk_t		*hada_mp = NULL;
17419 	ipha_t		*inner_ipha;
17420 	ip_stack_t	*ipst;
17421 
17422 	ASSERT(recv_ill != NULL);
17423 	ipst = recv_ill->ill_ipst;
17424 
17425 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17426 	    "ip_rput_locl_start: q %p", q);
17427 
17428 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17429 	ASSERT(ill != NULL);
17430 
17431 #define	rptr	((uchar_t *)ipha)
17432 #define	iphs	((uint16_t *)ipha)
17433 
17434 	/*
17435 	 * no UDP or TCP packet should come here anymore.
17436 	 */
17437 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17438 	    ipha->ipha_protocol != IPPROTO_UDP);
17439 
17440 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17441 	if (mctl_present &&
17442 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17443 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17444 
17445 		/*
17446 		 * It's an IPsec accelerated packet.
17447 		 * Keep a pointer to the data attributes around until
17448 		 * we allocate the ipsec_info_t.
17449 		 */
17450 		IPSECHW_DEBUG(IPSECHW_PKT,
17451 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17452 		hada_mp = first_mp;
17453 		hada_mp->b_cont = NULL;
17454 		/*
17455 		 * Since it is accelerated, it comes directly from
17456 		 * the ill and the data attributes is followed by
17457 		 * the packet data.
17458 		 */
17459 		ASSERT(mp->b_datap->db_type != M_CTL);
17460 		first_mp = mp;
17461 		mctl_present = B_FALSE;
17462 	}
17463 
17464 	/*
17465 	 * IF M_CTL is not present, then ipsec_in_is_secure
17466 	 * should return B_TRUE. There is a case where loopback
17467 	 * packets has an M_CTL in the front with all the
17468 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17469 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17470 	 * packets never comes here, it is safe to ASSERT the
17471 	 * following.
17472 	 */
17473 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17474 
17475 	/*
17476 	 * Also, we should never have an mctl_present if this is an
17477 	 * ESP-in-UDP packet.
17478 	 */
17479 	ASSERT(!mctl_present || !esp_in_udp_packet);
17480 
17481 	/* u1 is # words of IP options */
17482 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17483 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17484 
17485 	/*
17486 	 * Don't verify header checksum if we just removed UDP header or
17487 	 * packet is coming back from AH/ESP.
17488 	 */
17489 	if (!esp_in_udp_packet && !mctl_present) {
17490 		if (u1) {
17491 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17492 				if (hada_mp != NULL)
17493 					freemsg(hada_mp);
17494 				return;
17495 			}
17496 		} else {
17497 			/* Check the IP header checksum.  */
17498 #define	uph	((uint16_t *)ipha)
17499 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17500 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17501 #undef  uph
17502 			/* finish doing IP checksum */
17503 			sum = (sum & 0xFFFF) + (sum >> 16);
17504 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17505 			if (sum && sum != 0xFFFF) {
17506 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17507 				goto drop_pkt;
17508 			}
17509 		}
17510 	}
17511 
17512 	/*
17513 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17514 	 * might be called more than once for secure packets, count only
17515 	 * the first time.
17516 	 */
17517 	if (!mctl_present) {
17518 		UPDATE_IB_PKT_COUNT(ire);
17519 		ire->ire_last_used_time = lbolt;
17520 	}
17521 
17522 	/* Check for fragmentation offset. */
17523 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17524 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17525 	if (u1) {
17526 		/*
17527 		 * We re-assemble fragments before we do the AH/ESP
17528 		 * processing. Thus, M_CTL should not be present
17529 		 * while we are re-assembling.
17530 		 */
17531 		ASSERT(!mctl_present);
17532 		ASSERT(first_mp == mp);
17533 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17534 			return;
17535 
17536 		/*
17537 		 * Make sure that first_mp points back to mp as
17538 		 * the mp we came in with could have changed in
17539 		 * ip_rput_fragment().
17540 		 */
17541 		ipha = (ipha_t *)mp->b_rptr;
17542 		first_mp = mp;
17543 	}
17544 
17545 	/*
17546 	 * Clear hardware checksumming flag as it is currently only
17547 	 * used by TCP and UDP.
17548 	 */
17549 	DB_CKSUMFLAGS(mp) = 0;
17550 
17551 	/* Now we have a complete datagram, destined for this machine. */
17552 	u1 = IPH_HDR_LENGTH(ipha);
17553 	switch (ipha->ipha_protocol) {
17554 	case IPPROTO_ICMP: {
17555 		ire_t		*ire_zone;
17556 		ilm_t		*ilm;
17557 		mblk_t		*mp1;
17558 		zoneid_t	last_zoneid;
17559 		ilm_walker_t	ilw;
17560 
17561 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17562 			ASSERT(ire->ire_type == IRE_BROADCAST);
17563 
17564 			/*
17565 			 * In the multicast case, applications may have joined
17566 			 * the group from different zones, so we need to deliver
17567 			 * the packet to each of them. Loop through the
17568 			 * multicast memberships structures (ilm) on the receive
17569 			 * ill and send a copy of the packet up each matching
17570 			 * one. However, we don't do this for multicasts sent on
17571 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17572 			 * they must stay in the sender's zone.
17573 			 *
17574 			 * ilm_add_v6() ensures that ilms in the same zone are
17575 			 * contiguous in the ill_ilm list. We use this property
17576 			 * to avoid sending duplicates needed when two
17577 			 * applications in the same zone join the same group on
17578 			 * different logical interfaces: we ignore the ilm if
17579 			 * its zoneid is the same as the last matching one.
17580 			 * In addition, the sending of the packet for
17581 			 * ire_zoneid is delayed until all of the other ilms
17582 			 * have been exhausted.
17583 			 */
17584 			last_zoneid = -1;
17585 			ilm = ilm_walker_start(&ilw, recv_ill);
17586 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17587 				if (ipha->ipha_dst != ilm->ilm_addr ||
17588 				    ilm->ilm_zoneid == last_zoneid ||
17589 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17590 				    ilm->ilm_zoneid == ALL_ZONES ||
17591 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17592 					continue;
17593 				mp1 = ip_copymsg(first_mp);
17594 				if (mp1 == NULL)
17595 					continue;
17596 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17597 				    0, sum, mctl_present, B_TRUE,
17598 				    recv_ill, ilm->ilm_zoneid);
17599 				last_zoneid = ilm->ilm_zoneid;
17600 			}
17601 			ilm_walker_finish(&ilw);
17602 		} else if (ire->ire_type == IRE_BROADCAST) {
17603 			/*
17604 			 * In the broadcast case, there may be many zones
17605 			 * which need a copy of the packet delivered to them.
17606 			 * There is one IRE_BROADCAST per broadcast address
17607 			 * and per zone; we walk those using a helper function.
17608 			 * In addition, the sending of the packet for ire is
17609 			 * delayed until all of the other ires have been
17610 			 * processed.
17611 			 */
17612 			IRB_REFHOLD(ire->ire_bucket);
17613 			ire_zone = NULL;
17614 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17615 			    ire)) != NULL) {
17616 				mp1 = ip_copymsg(first_mp);
17617 				if (mp1 == NULL)
17618 					continue;
17619 
17620 				UPDATE_IB_PKT_COUNT(ire_zone);
17621 				ire_zone->ire_last_used_time = lbolt;
17622 				icmp_inbound(q, mp1, B_TRUE, ill,
17623 				    0, sum, mctl_present, B_TRUE,
17624 				    recv_ill, ire_zone->ire_zoneid);
17625 			}
17626 			IRB_REFRELE(ire->ire_bucket);
17627 		}
17628 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17629 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17630 		    ire->ire_zoneid);
17631 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17632 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17633 		return;
17634 	}
17635 	case IPPROTO_IGMP:
17636 		/*
17637 		 * If we are not willing to accept IGMP packets in clear,
17638 		 * then check with global policy.
17639 		 */
17640 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17641 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17642 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17643 			if (first_mp == NULL)
17644 				return;
17645 		}
17646 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17647 			freemsg(first_mp);
17648 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17649 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17650 			return;
17651 		}
17652 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17653 			/* Bad packet - discarded by igmp_input */
17654 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17655 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17656 			if (mctl_present)
17657 				freeb(first_mp);
17658 			return;
17659 		}
17660 		/*
17661 		 * igmp_input() may have returned the pulled up message.
17662 		 * So first_mp and ipha need to be reinitialized.
17663 		 */
17664 		ipha = (ipha_t *)mp->b_rptr;
17665 		if (mctl_present)
17666 			first_mp->b_cont = mp;
17667 		else
17668 			first_mp = mp;
17669 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17670 		    connf_head != NULL) {
17671 			/* No user-level listener for IGMP packets */
17672 			goto drop_pkt;
17673 		}
17674 		/* deliver to local raw users */
17675 		break;
17676 	case IPPROTO_PIM:
17677 		/*
17678 		 * If we are not willing to accept PIM packets in clear,
17679 		 * then check with global policy.
17680 		 */
17681 		if (ipst->ips_pim_accept_clear_messages == 0) {
17682 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17683 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17684 			if (first_mp == NULL)
17685 				return;
17686 		}
17687 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17688 			freemsg(first_mp);
17689 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17690 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17691 			return;
17692 		}
17693 		if (pim_input(q, mp, ill) != 0) {
17694 			/* Bad packet - discarded by pim_input */
17695 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17696 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17697 			if (mctl_present)
17698 				freeb(first_mp);
17699 			return;
17700 		}
17701 
17702 		/*
17703 		 * pim_input() may have pulled up the message so ipha needs to
17704 		 * be reinitialized.
17705 		 */
17706 		ipha = (ipha_t *)mp->b_rptr;
17707 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17708 		    connf_head != NULL) {
17709 			/* No user-level listener for PIM packets */
17710 			goto drop_pkt;
17711 		}
17712 		/* deliver to local raw users */
17713 		break;
17714 	case IPPROTO_ENCAP:
17715 		/*
17716 		 * Handle self-encapsulated packets (IP-in-IP where
17717 		 * the inner addresses == the outer addresses).
17718 		 */
17719 		hdr_length = IPH_HDR_LENGTH(ipha);
17720 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17721 		    mp->b_wptr) {
17722 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17723 			    sizeof (ipha_t) - mp->b_rptr)) {
17724 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17725 				freemsg(first_mp);
17726 				return;
17727 			}
17728 			ipha = (ipha_t *)mp->b_rptr;
17729 		}
17730 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17731 		/*
17732 		 * Check the sanity of the inner IP header.
17733 		 */
17734 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17735 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17736 			freemsg(first_mp);
17737 			return;
17738 		}
17739 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17740 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17741 			freemsg(first_mp);
17742 			return;
17743 		}
17744 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17745 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17746 			ipsec_in_t *ii;
17747 
17748 			/*
17749 			 * Self-encapsulated tunnel packet. Remove
17750 			 * the outer IP header and fanout again.
17751 			 * We also need to make sure that the inner
17752 			 * header is pulled up until options.
17753 			 */
17754 			mp->b_rptr = (uchar_t *)inner_ipha;
17755 			ipha = inner_ipha;
17756 			hdr_length = IPH_HDR_LENGTH(ipha);
17757 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17758 				if (!pullupmsg(mp, (uchar_t *)ipha +
17759 				    + hdr_length - mp->b_rptr)) {
17760 					freemsg(first_mp);
17761 					return;
17762 				}
17763 				ipha = (ipha_t *)mp->b_rptr;
17764 			}
17765 			if (hdr_length > sizeof (ipha_t)) {
17766 				/* We got options on the inner packet. */
17767 				ipaddr_t dst = ipha->ipha_dst;
17768 
17769 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17770 				    -1) {
17771 					/* Bad options! */
17772 					return;
17773 				}
17774 				if (dst != ipha->ipha_dst) {
17775 					/*
17776 					 * Someone put a source-route in
17777 					 * the inside header of a self-
17778 					 * encapsulated packet.  Drop it
17779 					 * with extreme prejudice and let
17780 					 * the sender know.
17781 					 */
17782 					icmp_unreachable(q, first_mp,
17783 					    ICMP_SOURCE_ROUTE_FAILED,
17784 					    recv_ill->ill_zoneid, ipst);
17785 					return;
17786 				}
17787 			}
17788 			if (!mctl_present) {
17789 				ASSERT(first_mp == mp);
17790 				/*
17791 				 * This means that somebody is sending
17792 				 * Self-encapsualted packets without AH/ESP.
17793 				 * If AH/ESP was present, we would have already
17794 				 * allocated the first_mp.
17795 				 *
17796 				 * Send this packet to find a tunnel endpoint.
17797 				 * if I can't find one, an ICMP
17798 				 * PROTOCOL_UNREACHABLE will get sent.
17799 				 */
17800 				goto fanout;
17801 			}
17802 			/*
17803 			 * We generally store the ill_index if we need to
17804 			 * do IPsec processing as we lose the ill queue when
17805 			 * we come back. But in this case, we never should
17806 			 * have to store the ill_index here as it should have
17807 			 * been stored previously when we processed the
17808 			 * AH/ESP header in this routine or for non-ipsec
17809 			 * cases, we still have the queue. But for some bad
17810 			 * packets from the wire, we can get to IPsec after
17811 			 * this and we better store the index for that case.
17812 			 */
17813 			ill = (ill_t *)q->q_ptr;
17814 			ii = (ipsec_in_t *)first_mp->b_rptr;
17815 			ii->ipsec_in_ill_index =
17816 			    ill->ill_phyint->phyint_ifindex;
17817 			ii->ipsec_in_rill_index =
17818 			    recv_ill->ill_phyint->phyint_ifindex;
17819 			if (ii->ipsec_in_decaps) {
17820 				/*
17821 				 * This packet is self-encapsulated multiple
17822 				 * times. We don't want to recurse infinitely.
17823 				 * To keep it simple, drop the packet.
17824 				 */
17825 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17826 				freemsg(first_mp);
17827 				return;
17828 			}
17829 			ii->ipsec_in_decaps = B_TRUE;
17830 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17831 			    ire);
17832 			return;
17833 		}
17834 		break;
17835 	case IPPROTO_AH:
17836 	case IPPROTO_ESP: {
17837 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17838 
17839 		/*
17840 		 * Fast path for AH/ESP. If this is the first time
17841 		 * we are sending a datagram to AH/ESP, allocate
17842 		 * a IPSEC_IN message and prepend it. Otherwise,
17843 		 * just fanout.
17844 		 */
17845 
17846 		int ipsec_rc;
17847 		ipsec_in_t *ii;
17848 		netstack_t *ns = ipst->ips_netstack;
17849 
17850 		IP_STAT(ipst, ipsec_proto_ahesp);
17851 		if (!mctl_present) {
17852 			ASSERT(first_mp == mp);
17853 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17854 			if (first_mp == NULL) {
17855 				ip1dbg(("ip_proto_input: IPSEC_IN "
17856 				    "allocation failure.\n"));
17857 				freemsg(hada_mp); /* okay ifnull */
17858 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17859 				freemsg(mp);
17860 				return;
17861 			}
17862 			/*
17863 			 * Store the ill_index so that when we come back
17864 			 * from IPsec we ride on the same queue.
17865 			 */
17866 			ill = (ill_t *)q->q_ptr;
17867 			ii = (ipsec_in_t *)first_mp->b_rptr;
17868 			ii->ipsec_in_ill_index =
17869 			    ill->ill_phyint->phyint_ifindex;
17870 			ii->ipsec_in_rill_index =
17871 			    recv_ill->ill_phyint->phyint_ifindex;
17872 			first_mp->b_cont = mp;
17873 			/*
17874 			 * Cache hardware acceleration info.
17875 			 */
17876 			if (hada_mp != NULL) {
17877 				IPSECHW_DEBUG(IPSECHW_PKT,
17878 				    ("ip_rput_local: caching data attr.\n"));
17879 				ii->ipsec_in_accelerated = B_TRUE;
17880 				ii->ipsec_in_da = hada_mp;
17881 				hada_mp = NULL;
17882 			}
17883 		} else {
17884 			ii = (ipsec_in_t *)first_mp->b_rptr;
17885 		}
17886 
17887 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17888 
17889 		if (!ipsec_loaded(ipss)) {
17890 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17891 			    ire->ire_zoneid, ipst);
17892 			return;
17893 		}
17894 
17895 		ns = ipst->ips_netstack;
17896 		/* select inbound SA and have IPsec process the pkt */
17897 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17898 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17899 			boolean_t esp_in_udp_sa;
17900 			if (esph == NULL)
17901 				return;
17902 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17903 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17904 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17905 			    IPSA_F_NATT) != 0);
17906 			/*
17907 			 * The following is a fancy, but quick, way of saying:
17908 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17909 			 *    OR
17910 			 * ESP SA and ESP-in-UDP packet --> drop
17911 			 */
17912 			if (esp_in_udp_sa != esp_in_udp_packet) {
17913 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17914 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17915 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17916 				    &ns->netstack_ipsec->ipsec_dropper);
17917 				return;
17918 			}
17919 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17920 			    first_mp, esph);
17921 		} else {
17922 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17923 			if (ah == NULL)
17924 				return;
17925 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17926 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17927 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17928 			    first_mp, ah);
17929 		}
17930 
17931 		switch (ipsec_rc) {
17932 		case IPSEC_STATUS_SUCCESS:
17933 			break;
17934 		case IPSEC_STATUS_FAILED:
17935 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17936 			/* FALLTHRU */
17937 		case IPSEC_STATUS_PENDING:
17938 			return;
17939 		}
17940 		/* we're done with IPsec processing, send it up */
17941 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17942 		return;
17943 	}
17944 	default:
17945 		break;
17946 	}
17947 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17948 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17949 		    ire->ire_zoneid));
17950 		goto drop_pkt;
17951 	}
17952 	/*
17953 	 * Handle protocols with which IP is less intimate.  There
17954 	 * can be more than one stream bound to a particular
17955 	 * protocol.  When this is the case, each one gets a copy
17956 	 * of any incoming packets.
17957 	 */
17958 fanout:
17959 	ip_fanout_proto(q, first_mp, ill, ipha,
17960 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17961 	    B_TRUE, recv_ill, ire->ire_zoneid);
17962 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17963 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17964 	return;
17965 
17966 drop_pkt:
17967 	freemsg(first_mp);
17968 	if (hada_mp != NULL)
17969 		freeb(hada_mp);
17970 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17971 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17972 #undef	rptr
17973 #undef  iphs
17974 
17975 }
17976 
17977 /*
17978  * Update any source route, record route or timestamp options.
17979  * Check that we are at end of strict source route.
17980  * The options have already been checked for sanity in ip_rput_options().
17981  */
17982 static boolean_t
17983 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17984     ip_stack_t *ipst)
17985 {
17986 	ipoptp_t	opts;
17987 	uchar_t		*opt;
17988 	uint8_t		optval;
17989 	uint8_t		optlen;
17990 	ipaddr_t	dst;
17991 	uint32_t	ts;
17992 	ire_t		*dst_ire;
17993 	timestruc_t	now;
17994 	zoneid_t	zoneid;
17995 	ill_t		*ill;
17996 
17997 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17998 
17999 	ip2dbg(("ip_rput_local_options\n"));
18000 
18001 	for (optval = ipoptp_first(&opts, ipha);
18002 	    optval != IPOPT_EOL;
18003 	    optval = ipoptp_next(&opts)) {
18004 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18005 		opt = opts.ipoptp_cur;
18006 		optlen = opts.ipoptp_len;
18007 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18008 		    optval, optlen));
18009 		switch (optval) {
18010 			uint32_t off;
18011 		case IPOPT_SSRR:
18012 		case IPOPT_LSRR:
18013 			off = opt[IPOPT_OFFSET];
18014 			off--;
18015 			if (optlen < IP_ADDR_LEN ||
18016 			    off > optlen - IP_ADDR_LEN) {
18017 				/* End of source route */
18018 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18019 				break;
18020 			}
18021 			/*
18022 			 * This will only happen if two consecutive entries
18023 			 * in the source route contains our address or if
18024 			 * it is a packet with a loose source route which
18025 			 * reaches us before consuming the whole source route
18026 			 */
18027 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18028 			if (optval == IPOPT_SSRR) {
18029 				goto bad_src_route;
18030 			}
18031 			/*
18032 			 * Hack: instead of dropping the packet truncate the
18033 			 * source route to what has been used by filling the
18034 			 * rest with IPOPT_NOP.
18035 			 */
18036 			opt[IPOPT_OLEN] = (uint8_t)off;
18037 			while (off < optlen) {
18038 				opt[off++] = IPOPT_NOP;
18039 			}
18040 			break;
18041 		case IPOPT_RR:
18042 			off = opt[IPOPT_OFFSET];
18043 			off--;
18044 			if (optlen < IP_ADDR_LEN ||
18045 			    off > optlen - IP_ADDR_LEN) {
18046 				/* No more room - ignore */
18047 				ip1dbg((
18048 				    "ip_rput_local_options: end of RR\n"));
18049 				break;
18050 			}
18051 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18052 			    IP_ADDR_LEN);
18053 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18054 			break;
18055 		case IPOPT_TS:
18056 			/* Insert timestamp if there is romm */
18057 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18058 			case IPOPT_TS_TSONLY:
18059 				off = IPOPT_TS_TIMELEN;
18060 				break;
18061 			case IPOPT_TS_PRESPEC:
18062 			case IPOPT_TS_PRESPEC_RFC791:
18063 				/* Verify that the address matched */
18064 				off = opt[IPOPT_OFFSET] - 1;
18065 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18066 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18067 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18068 				    ipst);
18069 				if (dst_ire == NULL) {
18070 					/* Not for us */
18071 					break;
18072 				}
18073 				ire_refrele(dst_ire);
18074 				/* FALLTHRU */
18075 			case IPOPT_TS_TSANDADDR:
18076 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18077 				break;
18078 			default:
18079 				/*
18080 				 * ip_*put_options should have already
18081 				 * dropped this packet.
18082 				 */
18083 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18084 				    "unknown IT - bug in ip_rput_options?\n");
18085 				return (B_TRUE);	/* Keep "lint" happy */
18086 			}
18087 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18088 				/* Increase overflow counter */
18089 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18090 				opt[IPOPT_POS_OV_FLG] =
18091 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18092 				    (off << 4));
18093 				break;
18094 			}
18095 			off = opt[IPOPT_OFFSET] - 1;
18096 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18097 			case IPOPT_TS_PRESPEC:
18098 			case IPOPT_TS_PRESPEC_RFC791:
18099 			case IPOPT_TS_TSANDADDR:
18100 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18101 				    IP_ADDR_LEN);
18102 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18103 				/* FALLTHRU */
18104 			case IPOPT_TS_TSONLY:
18105 				off = opt[IPOPT_OFFSET] - 1;
18106 				/* Compute # of milliseconds since midnight */
18107 				gethrestime(&now);
18108 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18109 				    now.tv_nsec / (NANOSEC / MILLISEC);
18110 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18111 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18112 				break;
18113 			}
18114 			break;
18115 		}
18116 	}
18117 	return (B_TRUE);
18118 
18119 bad_src_route:
18120 	q = WR(q);
18121 	if (q->q_next != NULL)
18122 		ill = q->q_ptr;
18123 	else
18124 		ill = NULL;
18125 
18126 	/* make sure we clear any indication of a hardware checksum */
18127 	DB_CKSUMFLAGS(mp) = 0;
18128 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18129 	if (zoneid == ALL_ZONES)
18130 		freemsg(mp);
18131 	else
18132 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18133 	return (B_FALSE);
18134 
18135 }
18136 
18137 /*
18138  * Process IP options in an inbound packet.  If an option affects the
18139  * effective destination address, return the next hop address via dstp.
18140  * Returns -1 if something fails in which case an ICMP error has been sent
18141  * and mp freed.
18142  */
18143 static int
18144 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18145     ip_stack_t *ipst)
18146 {
18147 	ipoptp_t	opts;
18148 	uchar_t		*opt;
18149 	uint8_t		optval;
18150 	uint8_t		optlen;
18151 	ipaddr_t	dst;
18152 	intptr_t	code = 0;
18153 	ire_t		*ire = NULL;
18154 	zoneid_t	zoneid;
18155 	ill_t		*ill;
18156 
18157 	ip2dbg(("ip_rput_options\n"));
18158 	dst = ipha->ipha_dst;
18159 	for (optval = ipoptp_first(&opts, ipha);
18160 	    optval != IPOPT_EOL;
18161 	    optval = ipoptp_next(&opts)) {
18162 		opt = opts.ipoptp_cur;
18163 		optlen = opts.ipoptp_len;
18164 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18165 		    optval, optlen));
18166 		/*
18167 		 * Note: we need to verify the checksum before we
18168 		 * modify anything thus this routine only extracts the next
18169 		 * hop dst from any source route.
18170 		 */
18171 		switch (optval) {
18172 			uint32_t off;
18173 		case IPOPT_SSRR:
18174 		case IPOPT_LSRR:
18175 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18176 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18177 			if (ire == NULL) {
18178 				if (optval == IPOPT_SSRR) {
18179 					ip1dbg(("ip_rput_options: not next"
18180 					    " strict source route 0x%x\n",
18181 					    ntohl(dst)));
18182 					code = (char *)&ipha->ipha_dst -
18183 					    (char *)ipha;
18184 					goto param_prob; /* RouterReq's */
18185 				}
18186 				ip2dbg(("ip_rput_options: "
18187 				    "not next source route 0x%x\n",
18188 				    ntohl(dst)));
18189 				break;
18190 			}
18191 			ire_refrele(ire);
18192 
18193 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18194 				ip1dbg((
18195 				    "ip_rput_options: bad option offset\n"));
18196 				code = (char *)&opt[IPOPT_OLEN] -
18197 				    (char *)ipha;
18198 				goto param_prob;
18199 			}
18200 			off = opt[IPOPT_OFFSET];
18201 			off--;
18202 		redo_srr:
18203 			if (optlen < IP_ADDR_LEN ||
18204 			    off > optlen - IP_ADDR_LEN) {
18205 				/* End of source route */
18206 				ip1dbg(("ip_rput_options: end of SR\n"));
18207 				break;
18208 			}
18209 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18210 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18211 			    ntohl(dst)));
18212 
18213 			/*
18214 			 * Check if our address is present more than
18215 			 * once as consecutive hops in source route.
18216 			 * XXX verify per-interface ip_forwarding
18217 			 * for source route?
18218 			 */
18219 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18220 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18221 
18222 			if (ire != NULL) {
18223 				ire_refrele(ire);
18224 				off += IP_ADDR_LEN;
18225 				goto redo_srr;
18226 			}
18227 
18228 			if (dst == htonl(INADDR_LOOPBACK)) {
18229 				ip1dbg(("ip_rput_options: loopback addr in "
18230 				    "source route!\n"));
18231 				goto bad_src_route;
18232 			}
18233 			/*
18234 			 * For strict: verify that dst is directly
18235 			 * reachable.
18236 			 */
18237 			if (optval == IPOPT_SSRR) {
18238 				ire = ire_ftable_lookup(dst, 0, 0,
18239 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18240 				    msg_getlabel(mp),
18241 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18242 				if (ire == NULL) {
18243 					ip1dbg(("ip_rput_options: SSRR not "
18244 					    "directly reachable: 0x%x\n",
18245 					    ntohl(dst)));
18246 					goto bad_src_route;
18247 				}
18248 				ire_refrele(ire);
18249 			}
18250 			/*
18251 			 * Defer update of the offset and the record route
18252 			 * until the packet is forwarded.
18253 			 */
18254 			break;
18255 		case IPOPT_RR:
18256 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18257 				ip1dbg((
18258 				    "ip_rput_options: bad option offset\n"));
18259 				code = (char *)&opt[IPOPT_OLEN] -
18260 				    (char *)ipha;
18261 				goto param_prob;
18262 			}
18263 			break;
18264 		case IPOPT_TS:
18265 			/*
18266 			 * Verify that length >= 5 and that there is either
18267 			 * room for another timestamp or that the overflow
18268 			 * counter is not maxed out.
18269 			 */
18270 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18271 			if (optlen < IPOPT_MINLEN_IT) {
18272 				goto param_prob;
18273 			}
18274 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18275 				ip1dbg((
18276 				    "ip_rput_options: bad option offset\n"));
18277 				code = (char *)&opt[IPOPT_OFFSET] -
18278 				    (char *)ipha;
18279 				goto param_prob;
18280 			}
18281 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18282 			case IPOPT_TS_TSONLY:
18283 				off = IPOPT_TS_TIMELEN;
18284 				break;
18285 			case IPOPT_TS_TSANDADDR:
18286 			case IPOPT_TS_PRESPEC:
18287 			case IPOPT_TS_PRESPEC_RFC791:
18288 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18289 				break;
18290 			default:
18291 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18292 				    (char *)ipha;
18293 				goto param_prob;
18294 			}
18295 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18296 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18297 				/*
18298 				 * No room and the overflow counter is 15
18299 				 * already.
18300 				 */
18301 				goto param_prob;
18302 			}
18303 			break;
18304 		}
18305 	}
18306 
18307 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18308 		*dstp = dst;
18309 		return (0);
18310 	}
18311 
18312 	ip1dbg(("ip_rput_options: error processing IP options."));
18313 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18314 
18315 param_prob:
18316 	q = WR(q);
18317 	if (q->q_next != NULL)
18318 		ill = q->q_ptr;
18319 	else
18320 		ill = NULL;
18321 
18322 	/* make sure we clear any indication of a hardware checksum */
18323 	DB_CKSUMFLAGS(mp) = 0;
18324 	/* Don't know whether this is for non-global or global/forwarding */
18325 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18326 	if (zoneid == ALL_ZONES)
18327 		freemsg(mp);
18328 	else
18329 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18330 	return (-1);
18331 
18332 bad_src_route:
18333 	q = WR(q);
18334 	if (q->q_next != NULL)
18335 		ill = q->q_ptr;
18336 	else
18337 		ill = NULL;
18338 
18339 	/* make sure we clear any indication of a hardware checksum */
18340 	DB_CKSUMFLAGS(mp) = 0;
18341 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18342 	if (zoneid == ALL_ZONES)
18343 		freemsg(mp);
18344 	else
18345 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18346 	return (-1);
18347 }
18348 
18349 /*
18350  * IP & ICMP info in >=14 msg's ...
18351  *  - ip fixed part (mib2_ip_t)
18352  *  - icmp fixed part (mib2_icmp_t)
18353  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18354  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18355  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18356  *  - ipRouteAttributeTable (ip 102)	labeled routes
18357  *  - ip multicast membership (ip_member_t)
18358  *  - ip multicast source filtering (ip_grpsrc_t)
18359  *  - igmp fixed part (struct igmpstat)
18360  *  - multicast routing stats (struct mrtstat)
18361  *  - multicast routing vifs (array of struct vifctl)
18362  *  - multicast routing routes (array of struct mfcctl)
18363  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18364  *					One per ill plus one generic
18365  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18366  *					One per ill plus one generic
18367  *  - ipv6RouteEntry			all IPv6 IREs
18368  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18369  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18370  *  - ipv6AddrEntry			all IPv6 ipifs
18371  *  - ipv6 multicast membership (ipv6_member_t)
18372  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18373  *
18374  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18375  *
18376  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18377  * already filled in by the caller.
18378  * Return value of 0 indicates that no messages were sent and caller
18379  * should free mpctl.
18380  */
18381 int
18382 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18383 {
18384 	ip_stack_t *ipst;
18385 	sctp_stack_t *sctps;
18386 
18387 	if (q->q_next != NULL) {
18388 		ipst = ILLQ_TO_IPST(q);
18389 	} else {
18390 		ipst = CONNQ_TO_IPST(q);
18391 	}
18392 	ASSERT(ipst != NULL);
18393 	sctps = ipst->ips_netstack->netstack_sctp;
18394 
18395 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18396 		return (0);
18397 	}
18398 
18399 	/*
18400 	 * For the purposes of the (broken) packet shell use
18401 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18402 	 * to make TCP and UDP appear first in the list of mib items.
18403 	 * TBD: We could expand this and use it in netstat so that
18404 	 * the kernel doesn't have to produce large tables (connections,
18405 	 * routes, etc) when netstat only wants the statistics or a particular
18406 	 * table.
18407 	 */
18408 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18409 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18410 			return (1);
18411 		}
18412 	}
18413 
18414 	if (level != MIB2_TCP) {
18415 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18416 			return (1);
18417 		}
18418 	}
18419 
18420 	if (level != MIB2_UDP) {
18421 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18422 			return (1);
18423 		}
18424 	}
18425 
18426 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18427 	    ipst)) == NULL) {
18428 		return (1);
18429 	}
18430 
18431 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18432 		return (1);
18433 	}
18434 
18435 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18436 		return (1);
18437 	}
18438 
18439 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18440 		return (1);
18441 	}
18442 
18443 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18444 		return (1);
18445 	}
18446 
18447 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18448 		return (1);
18449 	}
18450 
18451 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18452 		return (1);
18453 	}
18454 
18455 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18456 		return (1);
18457 	}
18458 
18459 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18460 		return (1);
18461 	}
18462 
18463 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18464 		return (1);
18465 	}
18466 
18467 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18468 		return (1);
18469 	}
18470 
18471 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18472 		return (1);
18473 	}
18474 
18475 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18476 		return (1);
18477 	}
18478 
18479 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18480 		return (1);
18481 	}
18482 
18483 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18484 	if (mpctl == NULL)
18485 		return (1);
18486 
18487 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18488 	if (mpctl == NULL)
18489 		return (1);
18490 
18491 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18492 		return (1);
18493 	}
18494 	freemsg(mpctl);
18495 	return (1);
18496 }
18497 
18498 /* Get global (legacy) IPv4 statistics */
18499 static mblk_t *
18500 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18501     ip_stack_t *ipst)
18502 {
18503 	mib2_ip_t		old_ip_mib;
18504 	struct opthdr		*optp;
18505 	mblk_t			*mp2ctl;
18506 
18507 	/*
18508 	 * make a copy of the original message
18509 	 */
18510 	mp2ctl = copymsg(mpctl);
18511 
18512 	/* fixed length IP structure... */
18513 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18514 	optp->level = MIB2_IP;
18515 	optp->name = 0;
18516 	SET_MIB(old_ip_mib.ipForwarding,
18517 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18518 	SET_MIB(old_ip_mib.ipDefaultTTL,
18519 	    (uint32_t)ipst->ips_ip_def_ttl);
18520 	SET_MIB(old_ip_mib.ipReasmTimeout,
18521 	    ipst->ips_ip_g_frag_timeout);
18522 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18523 	    sizeof (mib2_ipAddrEntry_t));
18524 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18525 	    sizeof (mib2_ipRouteEntry_t));
18526 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18527 	    sizeof (mib2_ipNetToMediaEntry_t));
18528 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18529 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18530 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18531 	    sizeof (mib2_ipAttributeEntry_t));
18532 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18533 
18534 	/*
18535 	 * Grab the statistics from the new IP MIB
18536 	 */
18537 	SET_MIB(old_ip_mib.ipInReceives,
18538 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18539 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18540 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18541 	SET_MIB(old_ip_mib.ipForwDatagrams,
18542 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18543 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18544 	    ipmib->ipIfStatsInUnknownProtos);
18545 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18546 	SET_MIB(old_ip_mib.ipInDelivers,
18547 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18548 	SET_MIB(old_ip_mib.ipOutRequests,
18549 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18550 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18551 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18552 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18553 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18554 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18555 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18556 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18557 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18558 
18559 	/* ipRoutingDiscards is not being used */
18560 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18561 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18562 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18563 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18564 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18565 	    ipmib->ipIfStatsReasmDuplicates);
18566 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18567 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18568 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18569 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18570 	SET_MIB(old_ip_mib.rawipInOverflows,
18571 	    ipmib->rawipIfStatsInOverflows);
18572 
18573 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18574 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18575 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18576 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18577 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18578 	    ipmib->ipIfStatsOutSwitchIPVersion);
18579 
18580 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18581 	    (int)sizeof (old_ip_mib))) {
18582 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18583 		    (uint_t)sizeof (old_ip_mib)));
18584 	}
18585 
18586 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18587 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18588 	    (int)optp->level, (int)optp->name, (int)optp->len));
18589 	qreply(q, mpctl);
18590 	return (mp2ctl);
18591 }
18592 
18593 /* Per interface IPv4 statistics */
18594 static mblk_t *
18595 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18596 {
18597 	struct opthdr		*optp;
18598 	mblk_t			*mp2ctl;
18599 	ill_t			*ill;
18600 	ill_walk_context_t	ctx;
18601 	mblk_t			*mp_tail = NULL;
18602 	mib2_ipIfStatsEntry_t	global_ip_mib;
18603 
18604 	/*
18605 	 * Make a copy of the original message
18606 	 */
18607 	mp2ctl = copymsg(mpctl);
18608 
18609 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18610 	optp->level = MIB2_IP;
18611 	optp->name = MIB2_IP_TRAFFIC_STATS;
18612 	/* Include "unknown interface" ip_mib */
18613 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18614 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18615 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18616 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18617 	    (ipst->ips_ip_g_forward ? 1 : 2));
18618 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18619 	    (uint32_t)ipst->ips_ip_def_ttl);
18620 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18621 	    sizeof (mib2_ipIfStatsEntry_t));
18622 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18623 	    sizeof (mib2_ipAddrEntry_t));
18624 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18625 	    sizeof (mib2_ipRouteEntry_t));
18626 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18627 	    sizeof (mib2_ipNetToMediaEntry_t));
18628 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18629 	    sizeof (ip_member_t));
18630 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18631 	    sizeof (ip_grpsrc_t));
18632 
18633 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18634 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18635 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18636 		    "failed to allocate %u bytes\n",
18637 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18638 	}
18639 
18640 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18641 
18642 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18643 	ill = ILL_START_WALK_V4(&ctx, ipst);
18644 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18645 		ill->ill_ip_mib->ipIfStatsIfIndex =
18646 		    ill->ill_phyint->phyint_ifindex;
18647 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18648 		    (ipst->ips_ip_g_forward ? 1 : 2));
18649 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18650 		    (uint32_t)ipst->ips_ip_def_ttl);
18651 
18652 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18653 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18654 		    (char *)ill->ill_ip_mib,
18655 		    (int)sizeof (*ill->ill_ip_mib))) {
18656 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18657 			    "failed to allocate %u bytes\n",
18658 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18659 		}
18660 	}
18661 	rw_exit(&ipst->ips_ill_g_lock);
18662 
18663 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18664 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18665 	    "level %d, name %d, len %d\n",
18666 	    (int)optp->level, (int)optp->name, (int)optp->len));
18667 	qreply(q, mpctl);
18668 
18669 	if (mp2ctl == NULL)
18670 		return (NULL);
18671 
18672 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18673 }
18674 
18675 /* Global IPv4 ICMP statistics */
18676 static mblk_t *
18677 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18678 {
18679 	struct opthdr		*optp;
18680 	mblk_t			*mp2ctl;
18681 
18682 	/*
18683 	 * Make a copy of the original message
18684 	 */
18685 	mp2ctl = copymsg(mpctl);
18686 
18687 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18688 	optp->level = MIB2_ICMP;
18689 	optp->name = 0;
18690 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18691 	    (int)sizeof (ipst->ips_icmp_mib))) {
18692 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18693 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18694 	}
18695 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18696 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18697 	    (int)optp->level, (int)optp->name, (int)optp->len));
18698 	qreply(q, mpctl);
18699 	return (mp2ctl);
18700 }
18701 
18702 /* Global IPv4 IGMP statistics */
18703 static mblk_t *
18704 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18705 {
18706 	struct opthdr		*optp;
18707 	mblk_t			*mp2ctl;
18708 
18709 	/*
18710 	 * make a copy of the original message
18711 	 */
18712 	mp2ctl = copymsg(mpctl);
18713 
18714 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18715 	optp->level = EXPER_IGMP;
18716 	optp->name = 0;
18717 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18718 	    (int)sizeof (ipst->ips_igmpstat))) {
18719 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18720 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18721 	}
18722 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18723 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18724 	    (int)optp->level, (int)optp->name, (int)optp->len));
18725 	qreply(q, mpctl);
18726 	return (mp2ctl);
18727 }
18728 
18729 /* Global IPv4 Multicast Routing statistics */
18730 static mblk_t *
18731 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18732 {
18733 	struct opthdr		*optp;
18734 	mblk_t			*mp2ctl;
18735 
18736 	/*
18737 	 * make a copy of the original message
18738 	 */
18739 	mp2ctl = copymsg(mpctl);
18740 
18741 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18742 	optp->level = EXPER_DVMRP;
18743 	optp->name = 0;
18744 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18745 		ip0dbg(("ip_mroute_stats: failed\n"));
18746 	}
18747 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18748 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18749 	    (int)optp->level, (int)optp->name, (int)optp->len));
18750 	qreply(q, mpctl);
18751 	return (mp2ctl);
18752 }
18753 
18754 /* IPv4 address information */
18755 static mblk_t *
18756 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18757 {
18758 	struct opthdr		*optp;
18759 	mblk_t			*mp2ctl;
18760 	mblk_t			*mp_tail = NULL;
18761 	ill_t			*ill;
18762 	ipif_t			*ipif;
18763 	uint_t			bitval;
18764 	mib2_ipAddrEntry_t	mae;
18765 	zoneid_t		zoneid;
18766 	ill_walk_context_t ctx;
18767 
18768 	/*
18769 	 * make a copy of the original message
18770 	 */
18771 	mp2ctl = copymsg(mpctl);
18772 
18773 	/* ipAddrEntryTable */
18774 
18775 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18776 	optp->level = MIB2_IP;
18777 	optp->name = MIB2_IP_ADDR;
18778 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18779 
18780 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18781 	ill = ILL_START_WALK_V4(&ctx, ipst);
18782 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18783 		for (ipif = ill->ill_ipif; ipif != NULL;
18784 		    ipif = ipif->ipif_next) {
18785 			if (ipif->ipif_zoneid != zoneid &&
18786 			    ipif->ipif_zoneid != ALL_ZONES)
18787 				continue;
18788 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18789 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18790 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18791 
18792 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18793 			    OCTET_LENGTH);
18794 			mae.ipAdEntIfIndex.o_length =
18795 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18796 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18797 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18798 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18799 			mae.ipAdEntInfo.ae_subnet_len =
18800 			    ip_mask_to_plen(ipif->ipif_net_mask);
18801 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18802 			for (bitval = 1;
18803 			    bitval &&
18804 			    !(bitval & ipif->ipif_brd_addr);
18805 			    bitval <<= 1)
18806 				noop;
18807 			mae.ipAdEntBcastAddr = bitval;
18808 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18809 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18810 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18811 			mae.ipAdEntInfo.ae_broadcast_addr =
18812 			    ipif->ipif_brd_addr;
18813 			mae.ipAdEntInfo.ae_pp_dst_addr =
18814 			    ipif->ipif_pp_dst_addr;
18815 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18816 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18817 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18818 
18819 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18820 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18821 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18822 				    "allocate %u bytes\n",
18823 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18824 			}
18825 		}
18826 	}
18827 	rw_exit(&ipst->ips_ill_g_lock);
18828 
18829 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18830 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18831 	    (int)optp->level, (int)optp->name, (int)optp->len));
18832 	qreply(q, mpctl);
18833 	return (mp2ctl);
18834 }
18835 
18836 /* IPv6 address information */
18837 static mblk_t *
18838 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18839 {
18840 	struct opthdr		*optp;
18841 	mblk_t			*mp2ctl;
18842 	mblk_t			*mp_tail = NULL;
18843 	ill_t			*ill;
18844 	ipif_t			*ipif;
18845 	mib2_ipv6AddrEntry_t	mae6;
18846 	zoneid_t		zoneid;
18847 	ill_walk_context_t	ctx;
18848 
18849 	/*
18850 	 * make a copy of the original message
18851 	 */
18852 	mp2ctl = copymsg(mpctl);
18853 
18854 	/* ipv6AddrEntryTable */
18855 
18856 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18857 	optp->level = MIB2_IP6;
18858 	optp->name = MIB2_IP6_ADDR;
18859 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18860 
18861 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18862 	ill = ILL_START_WALK_V6(&ctx, ipst);
18863 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18864 		for (ipif = ill->ill_ipif; ipif != NULL;
18865 		    ipif = ipif->ipif_next) {
18866 			if (ipif->ipif_zoneid != zoneid &&
18867 			    ipif->ipif_zoneid != ALL_ZONES)
18868 				continue;
18869 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18870 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18871 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18872 
18873 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18874 			    OCTET_LENGTH);
18875 			mae6.ipv6AddrIfIndex.o_length =
18876 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18877 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18878 			mae6.ipv6AddrPfxLength =
18879 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18880 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18881 			mae6.ipv6AddrInfo.ae_subnet_len =
18882 			    mae6.ipv6AddrPfxLength;
18883 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18884 
18885 			/* Type: stateless(1), stateful(2), unknown(3) */
18886 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18887 				mae6.ipv6AddrType = 1;
18888 			else
18889 				mae6.ipv6AddrType = 2;
18890 			/* Anycast: true(1), false(2) */
18891 			if (ipif->ipif_flags & IPIF_ANYCAST)
18892 				mae6.ipv6AddrAnycastFlag = 1;
18893 			else
18894 				mae6.ipv6AddrAnycastFlag = 2;
18895 
18896 			/*
18897 			 * Address status: preferred(1), deprecated(2),
18898 			 * invalid(3), inaccessible(4), unknown(5)
18899 			 */
18900 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18901 				mae6.ipv6AddrStatus = 3;
18902 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18903 				mae6.ipv6AddrStatus = 2;
18904 			else
18905 				mae6.ipv6AddrStatus = 1;
18906 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18907 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18908 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18909 			    ipif->ipif_v6pp_dst_addr;
18910 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18911 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18912 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18913 			mae6.ipv6AddrIdentifier = ill->ill_token;
18914 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18915 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18916 			mae6.ipv6AddrRetransmitTime =
18917 			    ill->ill_reachable_retrans_time;
18918 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18919 			    (char *)&mae6,
18920 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18921 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18922 				    "allocate %u bytes\n",
18923 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18924 			}
18925 		}
18926 	}
18927 	rw_exit(&ipst->ips_ill_g_lock);
18928 
18929 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18930 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18931 	    (int)optp->level, (int)optp->name, (int)optp->len));
18932 	qreply(q, mpctl);
18933 	return (mp2ctl);
18934 }
18935 
18936 /* IPv4 multicast group membership. */
18937 static mblk_t *
18938 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18939 {
18940 	struct opthdr		*optp;
18941 	mblk_t			*mp2ctl;
18942 	ill_t			*ill;
18943 	ipif_t			*ipif;
18944 	ilm_t			*ilm;
18945 	ip_member_t		ipm;
18946 	mblk_t			*mp_tail = NULL;
18947 	ill_walk_context_t	ctx;
18948 	zoneid_t		zoneid;
18949 	ilm_walker_t		ilw;
18950 
18951 	/*
18952 	 * make a copy of the original message
18953 	 */
18954 	mp2ctl = copymsg(mpctl);
18955 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18956 
18957 	/* ipGroupMember table */
18958 	optp = (struct opthdr *)&mpctl->b_rptr[
18959 	    sizeof (struct T_optmgmt_ack)];
18960 	optp->level = MIB2_IP;
18961 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18962 
18963 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18964 	ill = ILL_START_WALK_V4(&ctx, ipst);
18965 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18966 		if (IS_UNDER_IPMP(ill))
18967 			continue;
18968 
18969 		ilm = ilm_walker_start(&ilw, ill);
18970 		for (ipif = ill->ill_ipif; ipif != NULL;
18971 		    ipif = ipif->ipif_next) {
18972 			if (ipif->ipif_zoneid != zoneid &&
18973 			    ipif->ipif_zoneid != ALL_ZONES)
18974 				continue;	/* not this zone */
18975 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18976 			    OCTET_LENGTH);
18977 			ipm.ipGroupMemberIfIndex.o_length =
18978 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18979 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18980 				ASSERT(ilm->ilm_ipif != NULL);
18981 				ASSERT(ilm->ilm_ill == NULL);
18982 				if (ilm->ilm_ipif != ipif)
18983 					continue;
18984 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18985 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18986 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18987 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18988 				    (char *)&ipm, (int)sizeof (ipm))) {
18989 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18990 					    "failed to allocate %u bytes\n",
18991 					    (uint_t)sizeof (ipm)));
18992 				}
18993 			}
18994 		}
18995 		ilm_walker_finish(&ilw);
18996 	}
18997 	rw_exit(&ipst->ips_ill_g_lock);
18998 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18999 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19000 	    (int)optp->level, (int)optp->name, (int)optp->len));
19001 	qreply(q, mpctl);
19002 	return (mp2ctl);
19003 }
19004 
19005 /* IPv6 multicast group membership. */
19006 static mblk_t *
19007 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19008 {
19009 	struct opthdr		*optp;
19010 	mblk_t			*mp2ctl;
19011 	ill_t			*ill;
19012 	ilm_t			*ilm;
19013 	ipv6_member_t		ipm6;
19014 	mblk_t			*mp_tail = NULL;
19015 	ill_walk_context_t	ctx;
19016 	zoneid_t		zoneid;
19017 	ilm_walker_t		ilw;
19018 
19019 	/*
19020 	 * make a copy of the original message
19021 	 */
19022 	mp2ctl = copymsg(mpctl);
19023 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19024 
19025 	/* ip6GroupMember table */
19026 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19027 	optp->level = MIB2_IP6;
19028 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19029 
19030 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19031 	ill = ILL_START_WALK_V6(&ctx, ipst);
19032 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19033 		if (IS_UNDER_IPMP(ill))
19034 			continue;
19035 
19036 		ilm = ilm_walker_start(&ilw, ill);
19037 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19038 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19039 			ASSERT(ilm->ilm_ipif == NULL);
19040 			ASSERT(ilm->ilm_ill != NULL);
19041 			if (ilm->ilm_zoneid != zoneid)
19042 				continue;	/* not this zone */
19043 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19044 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19045 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19046 			if (!snmp_append_data2(mpctl->b_cont,
19047 			    &mp_tail,
19048 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19049 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19050 				    "failed to allocate %u bytes\n",
19051 				    (uint_t)sizeof (ipm6)));
19052 			}
19053 		}
19054 		ilm_walker_finish(&ilw);
19055 	}
19056 	rw_exit(&ipst->ips_ill_g_lock);
19057 
19058 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19059 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19060 	    (int)optp->level, (int)optp->name, (int)optp->len));
19061 	qreply(q, mpctl);
19062 	return (mp2ctl);
19063 }
19064 
19065 /* IP multicast filtered sources */
19066 static mblk_t *
19067 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19068 {
19069 	struct opthdr		*optp;
19070 	mblk_t			*mp2ctl;
19071 	ill_t			*ill;
19072 	ipif_t			*ipif;
19073 	ilm_t			*ilm;
19074 	ip_grpsrc_t		ips;
19075 	mblk_t			*mp_tail = NULL;
19076 	ill_walk_context_t	ctx;
19077 	zoneid_t		zoneid;
19078 	int			i;
19079 	slist_t			*sl;
19080 	ilm_walker_t		ilw;
19081 
19082 	/*
19083 	 * make a copy of the original message
19084 	 */
19085 	mp2ctl = copymsg(mpctl);
19086 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19087 
19088 	/* ipGroupSource table */
19089 	optp = (struct opthdr *)&mpctl->b_rptr[
19090 	    sizeof (struct T_optmgmt_ack)];
19091 	optp->level = MIB2_IP;
19092 	optp->name = EXPER_IP_GROUP_SOURCES;
19093 
19094 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19095 	ill = ILL_START_WALK_V4(&ctx, ipst);
19096 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19097 		if (IS_UNDER_IPMP(ill))
19098 			continue;
19099 
19100 		ilm = ilm_walker_start(&ilw, ill);
19101 		for (ipif = ill->ill_ipif; ipif != NULL;
19102 		    ipif = ipif->ipif_next) {
19103 			if (ipif->ipif_zoneid != zoneid)
19104 				continue;	/* not this zone */
19105 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19106 			    OCTET_LENGTH);
19107 			ips.ipGroupSourceIfIndex.o_length =
19108 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19109 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19110 				ASSERT(ilm->ilm_ipif != NULL);
19111 				ASSERT(ilm->ilm_ill == NULL);
19112 				sl = ilm->ilm_filter;
19113 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19114 					continue;
19115 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19116 				for (i = 0; i < sl->sl_numsrc; i++) {
19117 					if (!IN6_IS_ADDR_V4MAPPED(
19118 					    &sl->sl_addr[i]))
19119 						continue;
19120 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19121 					    ips.ipGroupSourceAddress);
19122 					if (snmp_append_data2(mpctl->b_cont,
19123 					    &mp_tail, (char *)&ips,
19124 					    (int)sizeof (ips)) == 0) {
19125 						ip1dbg(("ip_snmp_get_mib2_"
19126 						    "ip_group_src: failed to "
19127 						    "allocate %u bytes\n",
19128 						    (uint_t)sizeof (ips)));
19129 					}
19130 				}
19131 			}
19132 		}
19133 		ilm_walker_finish(&ilw);
19134 	}
19135 	rw_exit(&ipst->ips_ill_g_lock);
19136 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19137 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19138 	    (int)optp->level, (int)optp->name, (int)optp->len));
19139 	qreply(q, mpctl);
19140 	return (mp2ctl);
19141 }
19142 
19143 /* IPv6 multicast filtered sources. */
19144 static mblk_t *
19145 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19146 {
19147 	struct opthdr		*optp;
19148 	mblk_t			*mp2ctl;
19149 	ill_t			*ill;
19150 	ilm_t			*ilm;
19151 	ipv6_grpsrc_t		ips6;
19152 	mblk_t			*mp_tail = NULL;
19153 	ill_walk_context_t	ctx;
19154 	zoneid_t		zoneid;
19155 	int			i;
19156 	slist_t			*sl;
19157 	ilm_walker_t		ilw;
19158 
19159 	/*
19160 	 * make a copy of the original message
19161 	 */
19162 	mp2ctl = copymsg(mpctl);
19163 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19164 
19165 	/* ip6GroupMember table */
19166 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19167 	optp->level = MIB2_IP6;
19168 	optp->name = EXPER_IP6_GROUP_SOURCES;
19169 
19170 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19171 	ill = ILL_START_WALK_V6(&ctx, ipst);
19172 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19173 		if (IS_UNDER_IPMP(ill))
19174 			continue;
19175 
19176 		ilm = ilm_walker_start(&ilw, ill);
19177 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19178 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19179 			ASSERT(ilm->ilm_ipif == NULL);
19180 			ASSERT(ilm->ilm_ill != NULL);
19181 			sl = ilm->ilm_filter;
19182 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19183 				continue;
19184 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19185 			for (i = 0; i < sl->sl_numsrc; i++) {
19186 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19187 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19188 				    (char *)&ips6, (int)sizeof (ips6))) {
19189 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19190 					    "group_src: failed to allocate "
19191 					    "%u bytes\n",
19192 					    (uint_t)sizeof (ips6)));
19193 				}
19194 			}
19195 		}
19196 		ilm_walker_finish(&ilw);
19197 	}
19198 	rw_exit(&ipst->ips_ill_g_lock);
19199 
19200 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19201 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19202 	    (int)optp->level, (int)optp->name, (int)optp->len));
19203 	qreply(q, mpctl);
19204 	return (mp2ctl);
19205 }
19206 
19207 /* Multicast routing virtual interface table. */
19208 static mblk_t *
19209 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19210 {
19211 	struct opthdr		*optp;
19212 	mblk_t			*mp2ctl;
19213 
19214 	/*
19215 	 * make a copy of the original message
19216 	 */
19217 	mp2ctl = copymsg(mpctl);
19218 
19219 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19220 	optp->level = EXPER_DVMRP;
19221 	optp->name = EXPER_DVMRP_VIF;
19222 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19223 		ip0dbg(("ip_mroute_vif: failed\n"));
19224 	}
19225 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19226 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19227 	    (int)optp->level, (int)optp->name, (int)optp->len));
19228 	qreply(q, mpctl);
19229 	return (mp2ctl);
19230 }
19231 
19232 /* Multicast routing table. */
19233 static mblk_t *
19234 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19235 {
19236 	struct opthdr		*optp;
19237 	mblk_t			*mp2ctl;
19238 
19239 	/*
19240 	 * make a copy of the original message
19241 	 */
19242 	mp2ctl = copymsg(mpctl);
19243 
19244 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19245 	optp->level = EXPER_DVMRP;
19246 	optp->name = EXPER_DVMRP_MRT;
19247 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19248 		ip0dbg(("ip_mroute_mrt: failed\n"));
19249 	}
19250 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19251 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19252 	    (int)optp->level, (int)optp->name, (int)optp->len));
19253 	qreply(q, mpctl);
19254 	return (mp2ctl);
19255 }
19256 
19257 /*
19258  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19259  * in one IRE walk.
19260  */
19261 static mblk_t *
19262 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19263     ip_stack_t *ipst)
19264 {
19265 	struct opthdr	*optp;
19266 	mblk_t		*mp2ctl;	/* Returned */
19267 	mblk_t		*mp3ctl;	/* nettomedia */
19268 	mblk_t		*mp4ctl;	/* routeattrs */
19269 	iproutedata_t	ird;
19270 	zoneid_t	zoneid;
19271 
19272 	/*
19273 	 * make copies of the original message
19274 	 *	- mp2ctl is returned unchanged to the caller for his use
19275 	 *	- mpctl is sent upstream as ipRouteEntryTable
19276 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19277 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19278 	 */
19279 	mp2ctl = copymsg(mpctl);
19280 	mp3ctl = copymsg(mpctl);
19281 	mp4ctl = copymsg(mpctl);
19282 	if (mp3ctl == NULL || mp4ctl == NULL) {
19283 		freemsg(mp4ctl);
19284 		freemsg(mp3ctl);
19285 		freemsg(mp2ctl);
19286 		freemsg(mpctl);
19287 		return (NULL);
19288 	}
19289 
19290 	bzero(&ird, sizeof (ird));
19291 
19292 	ird.ird_route.lp_head = mpctl->b_cont;
19293 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19294 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19295 	/*
19296 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19297 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19298 	 * intended a temporary solution until a proper MIB API is provided
19299 	 * that provides complete filtering/caller-opt-in.
19300 	 */
19301 	if (level == EXPER_IP_AND_TESTHIDDEN)
19302 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19303 
19304 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19305 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19306 
19307 	/* ipRouteEntryTable in mpctl */
19308 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19309 	optp->level = MIB2_IP;
19310 	optp->name = MIB2_IP_ROUTE;
19311 	optp->len = msgdsize(ird.ird_route.lp_head);
19312 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19313 	    (int)optp->level, (int)optp->name, (int)optp->len));
19314 	qreply(q, mpctl);
19315 
19316 	/* ipNetToMediaEntryTable in mp3ctl */
19317 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19318 	optp->level = MIB2_IP;
19319 	optp->name = MIB2_IP_MEDIA;
19320 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19321 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19322 	    (int)optp->level, (int)optp->name, (int)optp->len));
19323 	qreply(q, mp3ctl);
19324 
19325 	/* ipRouteAttributeTable in mp4ctl */
19326 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19327 	optp->level = MIB2_IP;
19328 	optp->name = EXPER_IP_RTATTR;
19329 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19330 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19331 	    (int)optp->level, (int)optp->name, (int)optp->len));
19332 	if (optp->len == 0)
19333 		freemsg(mp4ctl);
19334 	else
19335 		qreply(q, mp4ctl);
19336 
19337 	return (mp2ctl);
19338 }
19339 
19340 /*
19341  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19342  * ipv6NetToMediaEntryTable in an NDP walk.
19343  */
19344 static mblk_t *
19345 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19346     ip_stack_t *ipst)
19347 {
19348 	struct opthdr	*optp;
19349 	mblk_t		*mp2ctl;	/* Returned */
19350 	mblk_t		*mp3ctl;	/* nettomedia */
19351 	mblk_t		*mp4ctl;	/* routeattrs */
19352 	iproutedata_t	ird;
19353 	zoneid_t	zoneid;
19354 
19355 	/*
19356 	 * make copies of the original message
19357 	 *	- mp2ctl is returned unchanged to the caller for his use
19358 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19359 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19360 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19361 	 */
19362 	mp2ctl = copymsg(mpctl);
19363 	mp3ctl = copymsg(mpctl);
19364 	mp4ctl = copymsg(mpctl);
19365 	if (mp3ctl == NULL || mp4ctl == NULL) {
19366 		freemsg(mp4ctl);
19367 		freemsg(mp3ctl);
19368 		freemsg(mp2ctl);
19369 		freemsg(mpctl);
19370 		return (NULL);
19371 	}
19372 
19373 	bzero(&ird, sizeof (ird));
19374 
19375 	ird.ird_route.lp_head = mpctl->b_cont;
19376 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19377 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19378 	/*
19379 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19380 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19381 	 * intended a temporary solution until a proper MIB API is provided
19382 	 * that provides complete filtering/caller-opt-in.
19383 	 */
19384 	if (level == EXPER_IP_AND_TESTHIDDEN)
19385 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19386 
19387 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19388 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19389 
19390 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19391 	optp->level = MIB2_IP6;
19392 	optp->name = MIB2_IP6_ROUTE;
19393 	optp->len = msgdsize(ird.ird_route.lp_head);
19394 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19395 	    (int)optp->level, (int)optp->name, (int)optp->len));
19396 	qreply(q, mpctl);
19397 
19398 	/* ipv6NetToMediaEntryTable in mp3ctl */
19399 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19400 
19401 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19402 	optp->level = MIB2_IP6;
19403 	optp->name = MIB2_IP6_MEDIA;
19404 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19405 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19406 	    (int)optp->level, (int)optp->name, (int)optp->len));
19407 	qreply(q, mp3ctl);
19408 
19409 	/* ipv6RouteAttributeTable in mp4ctl */
19410 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19411 	optp->level = MIB2_IP6;
19412 	optp->name = EXPER_IP_RTATTR;
19413 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19414 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19415 	    (int)optp->level, (int)optp->name, (int)optp->len));
19416 	if (optp->len == 0)
19417 		freemsg(mp4ctl);
19418 	else
19419 		qreply(q, mp4ctl);
19420 
19421 	return (mp2ctl);
19422 }
19423 
19424 /*
19425  * IPv6 mib: One per ill
19426  */
19427 static mblk_t *
19428 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19429 {
19430 	struct opthdr		*optp;
19431 	mblk_t			*mp2ctl;
19432 	ill_t			*ill;
19433 	ill_walk_context_t	ctx;
19434 	mblk_t			*mp_tail = NULL;
19435 
19436 	/*
19437 	 * Make a copy of the original message
19438 	 */
19439 	mp2ctl = copymsg(mpctl);
19440 
19441 	/* fixed length IPv6 structure ... */
19442 
19443 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19444 	optp->level = MIB2_IP6;
19445 	optp->name = 0;
19446 	/* Include "unknown interface" ip6_mib */
19447 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19448 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19449 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19450 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19451 	    ipst->ips_ipv6_forward ? 1 : 2);
19452 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19453 	    ipst->ips_ipv6_def_hops);
19454 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19455 	    sizeof (mib2_ipIfStatsEntry_t));
19456 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19457 	    sizeof (mib2_ipv6AddrEntry_t));
19458 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19459 	    sizeof (mib2_ipv6RouteEntry_t));
19460 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19461 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19462 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19463 	    sizeof (ipv6_member_t));
19464 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19465 	    sizeof (ipv6_grpsrc_t));
19466 
19467 	/*
19468 	 * Synchronize 64- and 32-bit counters
19469 	 */
19470 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19471 	    ipIfStatsHCInReceives);
19472 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19473 	    ipIfStatsHCInDelivers);
19474 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19475 	    ipIfStatsHCOutRequests);
19476 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19477 	    ipIfStatsHCOutForwDatagrams);
19478 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19479 	    ipIfStatsHCOutMcastPkts);
19480 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19481 	    ipIfStatsHCInMcastPkts);
19482 
19483 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19484 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19485 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19486 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19487 	}
19488 
19489 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19490 	ill = ILL_START_WALK_V6(&ctx, ipst);
19491 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19492 		ill->ill_ip_mib->ipIfStatsIfIndex =
19493 		    ill->ill_phyint->phyint_ifindex;
19494 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19495 		    ipst->ips_ipv6_forward ? 1 : 2);
19496 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19497 		    ill->ill_max_hops);
19498 
19499 		/*
19500 		 * Synchronize 64- and 32-bit counters
19501 		 */
19502 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19503 		    ipIfStatsHCInReceives);
19504 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19505 		    ipIfStatsHCInDelivers);
19506 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19507 		    ipIfStatsHCOutRequests);
19508 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19509 		    ipIfStatsHCOutForwDatagrams);
19510 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19511 		    ipIfStatsHCOutMcastPkts);
19512 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19513 		    ipIfStatsHCInMcastPkts);
19514 
19515 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19516 		    (char *)ill->ill_ip_mib,
19517 		    (int)sizeof (*ill->ill_ip_mib))) {
19518 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19519 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19520 		}
19521 	}
19522 	rw_exit(&ipst->ips_ill_g_lock);
19523 
19524 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19525 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19526 	    (int)optp->level, (int)optp->name, (int)optp->len));
19527 	qreply(q, mpctl);
19528 	return (mp2ctl);
19529 }
19530 
19531 /*
19532  * ICMPv6 mib: One per ill
19533  */
19534 static mblk_t *
19535 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19536 {
19537 	struct opthdr		*optp;
19538 	mblk_t			*mp2ctl;
19539 	ill_t			*ill;
19540 	ill_walk_context_t	ctx;
19541 	mblk_t			*mp_tail = NULL;
19542 	/*
19543 	 * Make a copy of the original message
19544 	 */
19545 	mp2ctl = copymsg(mpctl);
19546 
19547 	/* fixed length ICMPv6 structure ... */
19548 
19549 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19550 	optp->level = MIB2_ICMP6;
19551 	optp->name = 0;
19552 	/* Include "unknown interface" icmp6_mib */
19553 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19554 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19555 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19556 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19557 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19558 	    (char *)&ipst->ips_icmp6_mib,
19559 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19560 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19561 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19562 	}
19563 
19564 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19565 	ill = ILL_START_WALK_V6(&ctx, ipst);
19566 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19567 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19568 		    ill->ill_phyint->phyint_ifindex;
19569 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19570 		    (char *)ill->ill_icmp6_mib,
19571 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19572 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19573 			    "%u bytes\n",
19574 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19575 		}
19576 	}
19577 	rw_exit(&ipst->ips_ill_g_lock);
19578 
19579 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19580 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19581 	    (int)optp->level, (int)optp->name, (int)optp->len));
19582 	qreply(q, mpctl);
19583 	return (mp2ctl);
19584 }
19585 
19586 /*
19587  * ire_walk routine to create both ipRouteEntryTable and
19588  * ipRouteAttributeTable in one IRE walk
19589  */
19590 static void
19591 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19592 {
19593 	ill_t				*ill;
19594 	ipif_t				*ipif;
19595 	mib2_ipRouteEntry_t		*re;
19596 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19597 	ipaddr_t			gw_addr;
19598 	tsol_ire_gw_secattr_t		*attrp;
19599 	tsol_gc_t			*gc = NULL;
19600 	tsol_gcgrp_t			*gcgrp = NULL;
19601 	uint_t				sacnt = 0;
19602 	int				i;
19603 
19604 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19605 
19606 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19607 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19608 		return;
19609 	}
19610 
19611 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19612 		return;
19613 
19614 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19615 		mutex_enter(&attrp->igsa_lock);
19616 		if ((gc = attrp->igsa_gc) != NULL) {
19617 			gcgrp = gc->gc_grp;
19618 			ASSERT(gcgrp != NULL);
19619 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19620 			sacnt = 1;
19621 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19622 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19623 			gc = gcgrp->gcgrp_head;
19624 			sacnt = gcgrp->gcgrp_count;
19625 		}
19626 		mutex_exit(&attrp->igsa_lock);
19627 
19628 		/* do nothing if there's no gc to report */
19629 		if (gc == NULL) {
19630 			ASSERT(sacnt == 0);
19631 			if (gcgrp != NULL) {
19632 				/* we might as well drop the lock now */
19633 				rw_exit(&gcgrp->gcgrp_rwlock);
19634 				gcgrp = NULL;
19635 			}
19636 			attrp = NULL;
19637 		}
19638 
19639 		ASSERT(gc == NULL || (gcgrp != NULL &&
19640 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19641 	}
19642 	ASSERT(sacnt == 0 || gc != NULL);
19643 
19644 	if (sacnt != 0 &&
19645 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19646 		kmem_free(re, sizeof (*re));
19647 		rw_exit(&gcgrp->gcgrp_rwlock);
19648 		return;
19649 	}
19650 
19651 	/*
19652 	 * Return all IRE types for route table... let caller pick and choose
19653 	 */
19654 	re->ipRouteDest = ire->ire_addr;
19655 	ipif = ire->ire_ipif;
19656 	re->ipRouteIfIndex.o_length = 0;
19657 	if (ire->ire_type == IRE_CACHE) {
19658 		ill = (ill_t *)ire->ire_stq->q_ptr;
19659 		re->ipRouteIfIndex.o_length =
19660 		    ill->ill_name_length == 0 ? 0 :
19661 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19662 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19663 		    re->ipRouteIfIndex.o_length);
19664 	} else if (ipif != NULL) {
19665 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19666 		re->ipRouteIfIndex.o_length =
19667 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19668 	}
19669 	re->ipRouteMetric1 = -1;
19670 	re->ipRouteMetric2 = -1;
19671 	re->ipRouteMetric3 = -1;
19672 	re->ipRouteMetric4 = -1;
19673 
19674 	gw_addr = ire->ire_gateway_addr;
19675 
19676 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19677 		re->ipRouteNextHop = ire->ire_src_addr;
19678 	else
19679 		re->ipRouteNextHop = gw_addr;
19680 	/* indirect(4), direct(3), or invalid(2) */
19681 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19682 		re->ipRouteType = 2;
19683 	else
19684 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19685 	re->ipRouteProto = -1;
19686 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19687 	re->ipRouteMask = ire->ire_mask;
19688 	re->ipRouteMetric5 = -1;
19689 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19690 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19691 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19692 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19693 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19694 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19695 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19696 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19697 
19698 	if (ire->ire_flags & RTF_DYNAMIC) {
19699 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19700 	} else {
19701 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19702 	}
19703 
19704 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19705 	    (char *)re, (int)sizeof (*re))) {
19706 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19707 		    (uint_t)sizeof (*re)));
19708 	}
19709 
19710 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19711 		iaeptr->iae_routeidx = ird->ird_idx;
19712 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19713 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19714 	}
19715 
19716 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19717 	    (char *)iae, sacnt * sizeof (*iae))) {
19718 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19719 		    (unsigned)(sacnt * sizeof (*iae))));
19720 	}
19721 
19722 	/* bump route index for next pass */
19723 	ird->ird_idx++;
19724 
19725 	kmem_free(re, sizeof (*re));
19726 	if (sacnt != 0)
19727 		kmem_free(iae, sacnt * sizeof (*iae));
19728 
19729 	if (gcgrp != NULL)
19730 		rw_exit(&gcgrp->gcgrp_rwlock);
19731 }
19732 
19733 /*
19734  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19735  */
19736 static void
19737 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19738 {
19739 	ill_t				*ill;
19740 	ipif_t				*ipif;
19741 	mib2_ipv6RouteEntry_t		*re;
19742 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19743 	in6_addr_t			gw_addr_v6;
19744 	tsol_ire_gw_secattr_t		*attrp;
19745 	tsol_gc_t			*gc = NULL;
19746 	tsol_gcgrp_t			*gcgrp = NULL;
19747 	uint_t				sacnt = 0;
19748 	int				i;
19749 
19750 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19751 
19752 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19753 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19754 		return;
19755 	}
19756 
19757 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19758 		return;
19759 
19760 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19761 		mutex_enter(&attrp->igsa_lock);
19762 		if ((gc = attrp->igsa_gc) != NULL) {
19763 			gcgrp = gc->gc_grp;
19764 			ASSERT(gcgrp != NULL);
19765 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19766 			sacnt = 1;
19767 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19768 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19769 			gc = gcgrp->gcgrp_head;
19770 			sacnt = gcgrp->gcgrp_count;
19771 		}
19772 		mutex_exit(&attrp->igsa_lock);
19773 
19774 		/* do nothing if there's no gc to report */
19775 		if (gc == NULL) {
19776 			ASSERT(sacnt == 0);
19777 			if (gcgrp != NULL) {
19778 				/* we might as well drop the lock now */
19779 				rw_exit(&gcgrp->gcgrp_rwlock);
19780 				gcgrp = NULL;
19781 			}
19782 			attrp = NULL;
19783 		}
19784 
19785 		ASSERT(gc == NULL || (gcgrp != NULL &&
19786 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19787 	}
19788 	ASSERT(sacnt == 0 || gc != NULL);
19789 
19790 	if (sacnt != 0 &&
19791 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19792 		kmem_free(re, sizeof (*re));
19793 		rw_exit(&gcgrp->gcgrp_rwlock);
19794 		return;
19795 	}
19796 
19797 	/*
19798 	 * Return all IRE types for route table... let caller pick and choose
19799 	 */
19800 	re->ipv6RouteDest = ire->ire_addr_v6;
19801 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19802 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19803 	re->ipv6RouteIfIndex.o_length = 0;
19804 	ipif = ire->ire_ipif;
19805 	if (ire->ire_type == IRE_CACHE) {
19806 		ill = (ill_t *)ire->ire_stq->q_ptr;
19807 		re->ipv6RouteIfIndex.o_length =
19808 		    ill->ill_name_length == 0 ? 0 :
19809 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19810 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19811 		    re->ipv6RouteIfIndex.o_length);
19812 	} else if (ipif != NULL) {
19813 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19814 		re->ipv6RouteIfIndex.o_length =
19815 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19816 	}
19817 
19818 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19819 
19820 	mutex_enter(&ire->ire_lock);
19821 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19822 	mutex_exit(&ire->ire_lock);
19823 
19824 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19825 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19826 	else
19827 		re->ipv6RouteNextHop = gw_addr_v6;
19828 
19829 	/* remote(4), local(3), or discard(2) */
19830 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19831 		re->ipv6RouteType = 2;
19832 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19833 		re->ipv6RouteType = 3;
19834 	else
19835 		re->ipv6RouteType = 4;
19836 
19837 	re->ipv6RouteProtocol	= -1;
19838 	re->ipv6RoutePolicy	= 0;
19839 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19840 	re->ipv6RouteNextHopRDI	= 0;
19841 	re->ipv6RouteWeight	= 0;
19842 	re->ipv6RouteMetric	= 0;
19843 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19844 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19845 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19846 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19847 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19848 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19849 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19850 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19851 
19852 	if (ire->ire_flags & RTF_DYNAMIC) {
19853 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19854 	} else {
19855 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19856 	}
19857 
19858 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19859 	    (char *)re, (int)sizeof (*re))) {
19860 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19861 		    (uint_t)sizeof (*re)));
19862 	}
19863 
19864 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19865 		iaeptr->iae_routeidx = ird->ird_idx;
19866 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19867 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19868 	}
19869 
19870 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19871 	    (char *)iae, sacnt * sizeof (*iae))) {
19872 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19873 		    (unsigned)(sacnt * sizeof (*iae))));
19874 	}
19875 
19876 	/* bump route index for next pass */
19877 	ird->ird_idx++;
19878 
19879 	kmem_free(re, sizeof (*re));
19880 	if (sacnt != 0)
19881 		kmem_free(iae, sacnt * sizeof (*iae));
19882 
19883 	if (gcgrp != NULL)
19884 		rw_exit(&gcgrp->gcgrp_rwlock);
19885 }
19886 
19887 /*
19888  * ndp_walk routine to create ipv6NetToMediaEntryTable
19889  */
19890 static int
19891 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19892 {
19893 	ill_t				*ill;
19894 	mib2_ipv6NetToMediaEntry_t	ntme;
19895 	dl_unitdata_req_t		*dl;
19896 
19897 	ill = nce->nce_ill;
19898 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19899 		return (0);
19900 
19901 	/*
19902 	 * Neighbor cache entry attached to IRE with on-link
19903 	 * destination.
19904 	 */
19905 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19906 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19907 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19908 	    (nce->nce_res_mp != NULL)) {
19909 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19910 		ntme.ipv6NetToMediaPhysAddress.o_length =
19911 		    dl->dl_dest_addr_length;
19912 	} else {
19913 		ntme.ipv6NetToMediaPhysAddress.o_length =
19914 		    ill->ill_phys_addr_length;
19915 	}
19916 	if (nce->nce_res_mp != NULL) {
19917 		bcopy((char *)nce->nce_res_mp->b_rptr +
19918 		    NCE_LL_ADDR_OFFSET(ill),
19919 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19920 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19921 	} else {
19922 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19923 		    ill->ill_phys_addr_length);
19924 	}
19925 	/*
19926 	 * Note: Returns ND_* states. Should be:
19927 	 * reachable(1), stale(2), delay(3), probe(4),
19928 	 * invalid(5), unknown(6)
19929 	 */
19930 	ntme.ipv6NetToMediaState = nce->nce_state;
19931 	ntme.ipv6NetToMediaLastUpdated = 0;
19932 
19933 	/* other(1), dynamic(2), static(3), local(4) */
19934 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19935 		ntme.ipv6NetToMediaType = 4;
19936 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19937 		ntme.ipv6NetToMediaType = 1;
19938 	} else {
19939 		ntme.ipv6NetToMediaType = 2;
19940 	}
19941 
19942 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19943 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19944 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19945 		    (uint_t)sizeof (ntme)));
19946 	}
19947 	return (0);
19948 }
19949 
19950 /*
19951  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19952  */
19953 /* ARGSUSED */
19954 int
19955 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19956 {
19957 	switch (level) {
19958 	case MIB2_IP:
19959 	case MIB2_ICMP:
19960 		switch (name) {
19961 		default:
19962 			break;
19963 		}
19964 		return (1);
19965 	default:
19966 		return (1);
19967 	}
19968 }
19969 
19970 /*
19971  * When there exists both a 64- and 32-bit counter of a particular type
19972  * (i.e., InReceives), only the 64-bit counters are added.
19973  */
19974 void
19975 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19976 {
19977 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19978 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19979 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19980 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19981 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19982 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19983 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19984 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19985 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19986 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19987 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19988 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19989 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19990 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19991 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19992 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19993 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19994 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19995 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19996 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19997 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19998 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19999 	    o2->ipIfStatsInWrongIPVersion);
20000 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20001 	    o2->ipIfStatsInWrongIPVersion);
20002 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20003 	    o2->ipIfStatsOutSwitchIPVersion);
20004 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20005 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20006 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20007 	    o2->ipIfStatsHCInForwDatagrams);
20008 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20009 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20010 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20011 	    o2->ipIfStatsHCOutForwDatagrams);
20012 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20013 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20014 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20015 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20016 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20017 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20018 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20019 	    o2->ipIfStatsHCOutMcastOctets);
20020 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20021 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20022 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20023 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20024 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20025 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20026 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20027 }
20028 
20029 void
20030 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20031 {
20032 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20033 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20034 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20035 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20036 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20037 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20038 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20039 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20040 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20041 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20042 	    o2->ipv6IfIcmpInRouterSolicits);
20043 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20044 	    o2->ipv6IfIcmpInRouterAdvertisements);
20045 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20046 	    o2->ipv6IfIcmpInNeighborSolicits);
20047 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20048 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20049 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20050 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20051 	    o2->ipv6IfIcmpInGroupMembQueries);
20052 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20053 	    o2->ipv6IfIcmpInGroupMembResponses);
20054 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20055 	    o2->ipv6IfIcmpInGroupMembReductions);
20056 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20057 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20058 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20059 	    o2->ipv6IfIcmpOutDestUnreachs);
20060 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20061 	    o2->ipv6IfIcmpOutAdminProhibs);
20062 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20063 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20064 	    o2->ipv6IfIcmpOutParmProblems);
20065 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20066 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20067 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20068 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20069 	    o2->ipv6IfIcmpOutRouterSolicits);
20070 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20071 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20072 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20073 	    o2->ipv6IfIcmpOutNeighborSolicits);
20074 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20075 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20076 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20077 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20078 	    o2->ipv6IfIcmpOutGroupMembQueries);
20079 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20080 	    o2->ipv6IfIcmpOutGroupMembResponses);
20081 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20082 	    o2->ipv6IfIcmpOutGroupMembReductions);
20083 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20084 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20085 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20086 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20087 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20088 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20089 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20090 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20091 	    o2->ipv6IfIcmpInGroupMembTotal);
20092 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20093 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20094 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20095 	    o2->ipv6IfIcmpInGroupMembBadReports);
20096 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20097 	    o2->ipv6IfIcmpInGroupMembOurReports);
20098 }
20099 
20100 /*
20101  * Called before the options are updated to check if this packet will
20102  * be source routed from here.
20103  * This routine assumes that the options are well formed i.e. that they
20104  * have already been checked.
20105  */
20106 static boolean_t
20107 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20108 {
20109 	ipoptp_t	opts;
20110 	uchar_t		*opt;
20111 	uint8_t		optval;
20112 	uint8_t		optlen;
20113 	ipaddr_t	dst;
20114 	ire_t		*ire;
20115 
20116 	if (IS_SIMPLE_IPH(ipha)) {
20117 		ip2dbg(("not source routed\n"));
20118 		return (B_FALSE);
20119 	}
20120 	dst = ipha->ipha_dst;
20121 	for (optval = ipoptp_first(&opts, ipha);
20122 	    optval != IPOPT_EOL;
20123 	    optval = ipoptp_next(&opts)) {
20124 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20125 		opt = opts.ipoptp_cur;
20126 		optlen = opts.ipoptp_len;
20127 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20128 		    optval, optlen));
20129 		switch (optval) {
20130 			uint32_t off;
20131 		case IPOPT_SSRR:
20132 		case IPOPT_LSRR:
20133 			/*
20134 			 * If dst is one of our addresses and there are some
20135 			 * entries left in the source route return (true).
20136 			 */
20137 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20138 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20139 			if (ire == NULL) {
20140 				ip2dbg(("ip_source_routed: not next"
20141 				    " source route 0x%x\n",
20142 				    ntohl(dst)));
20143 				return (B_FALSE);
20144 			}
20145 			ire_refrele(ire);
20146 			off = opt[IPOPT_OFFSET];
20147 			off--;
20148 			if (optlen < IP_ADDR_LEN ||
20149 			    off > optlen - IP_ADDR_LEN) {
20150 				/* End of source route */
20151 				ip1dbg(("ip_source_routed: end of SR\n"));
20152 				return (B_FALSE);
20153 			}
20154 			return (B_TRUE);
20155 		}
20156 	}
20157 	ip2dbg(("not source routed\n"));
20158 	return (B_FALSE);
20159 }
20160 
20161 /*
20162  * Check if the packet contains any source route.
20163  */
20164 static boolean_t
20165 ip_source_route_included(ipha_t *ipha)
20166 {
20167 	ipoptp_t	opts;
20168 	uint8_t		optval;
20169 
20170 	if (IS_SIMPLE_IPH(ipha))
20171 		return (B_FALSE);
20172 	for (optval = ipoptp_first(&opts, ipha);
20173 	    optval != IPOPT_EOL;
20174 	    optval = ipoptp_next(&opts)) {
20175 		switch (optval) {
20176 		case IPOPT_SSRR:
20177 		case IPOPT_LSRR:
20178 			return (B_TRUE);
20179 		}
20180 	}
20181 	return (B_FALSE);
20182 }
20183 
20184 /*
20185  * Called when the IRE expiration timer fires.
20186  */
20187 void
20188 ip_trash_timer_expire(void *args)
20189 {
20190 	int			flush_flag = 0;
20191 	ire_expire_arg_t	iea;
20192 	ip_stack_t		*ipst = (ip_stack_t *)args;
20193 
20194 	iea.iea_ipst = ipst;	/* No netstack_hold */
20195 
20196 	/*
20197 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20198 	 * This lock makes sure that a new invocation of this function
20199 	 * that occurs due to an almost immediate timer firing will not
20200 	 * progress beyond this point until the current invocation is done
20201 	 */
20202 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20203 	ipst->ips_ip_ire_expire_id = 0;
20204 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20205 
20206 	/* Periodic timer */
20207 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20208 	    ipst->ips_ip_ire_arp_interval) {
20209 		/*
20210 		 * Remove all IRE_CACHE entries since they might
20211 		 * contain arp information.
20212 		 */
20213 		flush_flag |= FLUSH_ARP_TIME;
20214 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20215 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20216 	}
20217 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20218 	    ipst->ips_ip_ire_redir_interval) {
20219 		/* Remove all redirects */
20220 		flush_flag |= FLUSH_REDIRECT_TIME;
20221 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20222 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20223 	}
20224 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20225 	    ipst->ips_ip_ire_pathmtu_interval) {
20226 		/* Increase path mtu */
20227 		flush_flag |= FLUSH_MTU_TIME;
20228 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20229 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20230 	}
20231 
20232 	/*
20233 	 * Optimize for the case when there are no redirects in the
20234 	 * ftable, that is, no need to walk the ftable in that case.
20235 	 */
20236 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20237 		iea.iea_flush_flag = flush_flag;
20238 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20239 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20240 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20241 		    NULL, ALL_ZONES, ipst);
20242 	}
20243 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20244 	    ipst->ips_ip_redirect_cnt > 0) {
20245 		iea.iea_flush_flag = flush_flag;
20246 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20247 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20248 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20249 	}
20250 	if (flush_flag & FLUSH_MTU_TIME) {
20251 		/*
20252 		 * Walk all IPv6 IRE's and update them
20253 		 * Note that ARP and redirect timers are not
20254 		 * needed since NUD handles stale entries.
20255 		 */
20256 		flush_flag = FLUSH_MTU_TIME;
20257 		iea.iea_flush_flag = flush_flag;
20258 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20259 		    ALL_ZONES, ipst);
20260 	}
20261 
20262 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20263 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20264 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20265 
20266 	/*
20267 	 * Hold the lock to serialize timeout calls and prevent
20268 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20269 	 * for the timer to fire and a new invocation of this function
20270 	 * to start before the return value of timeout has been stored
20271 	 * in ip_ire_expire_id by the current invocation.
20272 	 */
20273 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20274 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20275 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20276 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20277 }
20278 
20279 /*
20280  * Called by the memory allocator subsystem directly, when the system
20281  * is running low on memory.
20282  */
20283 /* ARGSUSED */
20284 void
20285 ip_trash_ire_reclaim(void *args)
20286 {
20287 	netstack_handle_t nh;
20288 	netstack_t *ns;
20289 
20290 	netstack_next_init(&nh);
20291 	while ((ns = netstack_next(&nh)) != NULL) {
20292 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20293 		netstack_rele(ns);
20294 	}
20295 	netstack_next_fini(&nh);
20296 }
20297 
20298 static void
20299 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20300 {
20301 	ire_cache_count_t icc;
20302 	ire_cache_reclaim_t icr;
20303 	ncc_cache_count_t ncc;
20304 	nce_cache_reclaim_t ncr;
20305 	uint_t delete_cnt;
20306 	/*
20307 	 * Memory reclaim call back.
20308 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20309 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20310 	 * entries, determine what fraction to free for
20311 	 * each category of IRE_CACHE entries giving absolute priority
20312 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20313 	 * entry will be freed unless all offlink entries are freed).
20314 	 */
20315 	icc.icc_total = 0;
20316 	icc.icc_unused = 0;
20317 	icc.icc_offlink = 0;
20318 	icc.icc_pmtu = 0;
20319 	icc.icc_onlink = 0;
20320 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20321 
20322 	/*
20323 	 * Free NCEs for IPv6 like the onlink ires.
20324 	 */
20325 	ncc.ncc_total = 0;
20326 	ncc.ncc_host = 0;
20327 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20328 
20329 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20330 	    icc.icc_pmtu + icc.icc_onlink);
20331 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20332 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20333 	if (delete_cnt == 0)
20334 		return;
20335 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20336 	/* Always delete all unused offlink entries */
20337 	icr.icr_ipst = ipst;
20338 	icr.icr_unused = 1;
20339 	if (delete_cnt <= icc.icc_unused) {
20340 		/*
20341 		 * Only need to free unused entries.  In other words,
20342 		 * there are enough unused entries to free to meet our
20343 		 * target number of freed ire cache entries.
20344 		 */
20345 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20346 		ncr.ncr_host = 0;
20347 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20348 		/*
20349 		 * Only need to free unused entries, plus a fraction of offlink
20350 		 * entries.  It follows from the first if statement that
20351 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20352 		 */
20353 		delete_cnt -= icc.icc_unused;
20354 		/* Round up # deleted by truncating fraction */
20355 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20356 		icr.icr_pmtu = icr.icr_onlink = 0;
20357 		ncr.ncr_host = 0;
20358 	} else if (delete_cnt <=
20359 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20360 		/*
20361 		 * Free all unused and offlink entries, plus a fraction of
20362 		 * pmtu entries.  It follows from the previous if statement
20363 		 * that icc_pmtu is non-zero, and that
20364 		 * delete_cnt != icc_unused + icc_offlink.
20365 		 */
20366 		icr.icr_offlink = 1;
20367 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20368 		/* Round up # deleted by truncating fraction */
20369 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20370 		icr.icr_onlink = 0;
20371 		ncr.ncr_host = 0;
20372 	} else {
20373 		/*
20374 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20375 		 * of onlink entries.  If we're here, then we know that
20376 		 * icc_onlink is non-zero, and that
20377 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20378 		 */
20379 		icr.icr_offlink = icr.icr_pmtu = 1;
20380 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20381 		    icc.icc_pmtu;
20382 		/* Round up # deleted by truncating fraction */
20383 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20384 		/* Using the same delete fraction as for onlink IREs */
20385 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20386 	}
20387 #ifdef DEBUG
20388 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20389 	    "fractions %d/%d/%d/%d\n",
20390 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20391 	    icc.icc_unused, icc.icc_offlink,
20392 	    icc.icc_pmtu, icc.icc_onlink,
20393 	    icr.icr_unused, icr.icr_offlink,
20394 	    icr.icr_pmtu, icr.icr_onlink));
20395 #endif
20396 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20397 	if (ncr.ncr_host != 0)
20398 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20399 		    (uchar_t *)&ncr, ipst);
20400 #ifdef DEBUG
20401 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20402 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20403 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20404 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20405 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20406 	    icc.icc_pmtu, icc.icc_onlink));
20407 #endif
20408 }
20409 
20410 /*
20411  * ip_unbind is called when a copy of an unbind request is received from the
20412  * upper level protocol.  We remove this conn from any fanout hash list it is
20413  * on, and zero out the bind information.  No reply is expected up above.
20414  */
20415 void
20416 ip_unbind(conn_t *connp)
20417 {
20418 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20419 
20420 	if (is_system_labeled() && connp->conn_anon_port) {
20421 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20422 		    connp->conn_mlp_type, connp->conn_ulp,
20423 		    ntohs(connp->conn_lport), B_FALSE);
20424 		connp->conn_anon_port = 0;
20425 	}
20426 	connp->conn_mlp_type = mlptSingle;
20427 
20428 	ipcl_hash_remove(connp);
20429 
20430 }
20431 
20432 /*
20433  * Write side put procedure.  Outbound data, IOCTLs, responses from
20434  * resolvers, etc, come down through here.
20435  *
20436  * arg2 is always a queue_t *.
20437  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20438  * the zoneid.
20439  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20440  */
20441 void
20442 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20443 {
20444 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20445 }
20446 
20447 void
20448 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20449     ip_opt_info_t *infop)
20450 {
20451 	conn_t		*connp = NULL;
20452 	queue_t		*q = (queue_t *)arg2;
20453 	ipha_t		*ipha;
20454 #define	rptr	((uchar_t *)ipha)
20455 	ire_t		*ire = NULL;
20456 	ire_t		*sctp_ire = NULL;
20457 	uint32_t	v_hlen_tos_len;
20458 	ipaddr_t	dst;
20459 	mblk_t		*first_mp = NULL;
20460 	boolean_t	mctl_present;
20461 	ipsec_out_t	*io;
20462 	int		match_flags;
20463 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20464 	ipif_t		*dst_ipif;
20465 	boolean_t	multirt_need_resolve = B_FALSE;
20466 	mblk_t		*copy_mp = NULL;
20467 	int		err;
20468 	zoneid_t	zoneid;
20469 	boolean_t	need_decref = B_FALSE;
20470 	boolean_t	ignore_dontroute = B_FALSE;
20471 	boolean_t	ignore_nexthop = B_FALSE;
20472 	boolean_t	ip_nexthop = B_FALSE;
20473 	ipaddr_t	nexthop_addr;
20474 	ip_stack_t	*ipst;
20475 
20476 #ifdef	_BIG_ENDIAN
20477 #define	V_HLEN	(v_hlen_tos_len >> 24)
20478 #else
20479 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20480 #endif
20481 
20482 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20483 	    "ip_wput_start: q %p", q);
20484 
20485 	/*
20486 	 * ip_wput fast path
20487 	 */
20488 
20489 	/* is packet from ARP ? */
20490 	if (q->q_next != NULL) {
20491 		zoneid = (zoneid_t)(uintptr_t)arg;
20492 		goto qnext;
20493 	}
20494 
20495 	connp = (conn_t *)arg;
20496 	ASSERT(connp != NULL);
20497 	zoneid = connp->conn_zoneid;
20498 	ipst = connp->conn_netstack->netstack_ip;
20499 	ASSERT(ipst != NULL);
20500 
20501 	/* is queue flow controlled? */
20502 	if ((q->q_first != NULL || connp->conn_draining) &&
20503 	    (caller == IP_WPUT)) {
20504 		ASSERT(!need_decref);
20505 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20506 		(void) putq(q, mp);
20507 		return;
20508 	}
20509 
20510 	/* Multidata transmit? */
20511 	if (DB_TYPE(mp) == M_MULTIDATA) {
20512 		/*
20513 		 * We should never get here, since all Multidata messages
20514 		 * originating from tcp should have been directed over to
20515 		 * tcp_multisend() in the first place.
20516 		 */
20517 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20518 		freemsg(mp);
20519 		return;
20520 	} else if (DB_TYPE(mp) != M_DATA)
20521 		goto notdata;
20522 
20523 	if (mp->b_flag & MSGHASREF) {
20524 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20525 		mp->b_flag &= ~MSGHASREF;
20526 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20527 		need_decref = B_TRUE;
20528 	}
20529 	ipha = (ipha_t *)mp->b_rptr;
20530 
20531 	/* is IP header non-aligned or mblk smaller than basic IP header */
20532 #ifndef SAFETY_BEFORE_SPEED
20533 	if (!OK_32PTR(rptr) ||
20534 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20535 		goto hdrtoosmall;
20536 #endif
20537 
20538 	ASSERT(OK_32PTR(ipha));
20539 
20540 	/*
20541 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20542 	 * wrong version, we'll catch it again in ip_output_v6.
20543 	 *
20544 	 * Note that this is *only* locally-generated output here, and never
20545 	 * forwarded data, and that we need to deal only with transports that
20546 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20547 	 * label.)
20548 	 */
20549 	if (is_system_labeled() &&
20550 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20551 	    !connp->conn_ulp_labeled) {
20552 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20553 		    connp->conn_mac_exempt, ipst);
20554 		ipha = (ipha_t *)mp->b_rptr;
20555 		if (err != 0) {
20556 			first_mp = mp;
20557 			if (err == EINVAL)
20558 				goto icmp_parameter_problem;
20559 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20560 			goto discard_pkt;
20561 		}
20562 	}
20563 
20564 	ASSERT(infop != NULL);
20565 
20566 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20567 		/*
20568 		 * IP_PKTINFO ancillary option is present.
20569 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20570 		 * allows using address of any zone as the source address.
20571 		 */
20572 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20573 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20574 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20575 		if (ire == NULL)
20576 			goto drop_pkt;
20577 		ire_refrele(ire);
20578 		ire = NULL;
20579 	}
20580 
20581 	/*
20582 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20583 	 */
20584 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20585 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20586 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20587 
20588 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20589 			goto drop_pkt;
20590 		/*
20591 		 * check that there is an ipif belonging
20592 		 * to our zone. IPCL_ZONEID is not used because
20593 		 * IP_ALLZONES option is valid only when the ill is
20594 		 * accessible from all zones i.e has a valid ipif in
20595 		 * all zones.
20596 		 */
20597 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20598 			goto drop_pkt;
20599 		}
20600 	}
20601 
20602 	/*
20603 	 * If there is a policy, try to attach an ipsec_out in
20604 	 * the front. At the end, first_mp either points to a
20605 	 * M_DATA message or IPSEC_OUT message linked to a
20606 	 * M_DATA message. We have to do it now as we might
20607 	 * lose the "conn" if we go through ip_newroute.
20608 	 */
20609 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20610 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20611 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20612 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20613 			if (need_decref)
20614 				CONN_DEC_REF(connp);
20615 			return;
20616 		} else {
20617 			ASSERT(mp->b_datap->db_type == M_CTL);
20618 			first_mp = mp;
20619 			mp = mp->b_cont;
20620 			mctl_present = B_TRUE;
20621 		}
20622 	} else {
20623 		first_mp = mp;
20624 		mctl_present = B_FALSE;
20625 	}
20626 
20627 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20628 
20629 	/* is wrong version or IP options present */
20630 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20631 		goto version_hdrlen_check;
20632 	dst = ipha->ipha_dst;
20633 
20634 	/* If IP_BOUND_IF has been set, use that ill. */
20635 	if (connp->conn_outgoing_ill != NULL) {
20636 		xmit_ill = conn_get_held_ill(connp,
20637 		    &connp->conn_outgoing_ill, &err);
20638 		if (err == ILL_LOOKUP_FAILED)
20639 			goto drop_pkt;
20640 
20641 		goto send_from_ill;
20642 	}
20643 
20644 	/* is packet multicast? */
20645 	if (CLASSD(dst))
20646 		goto multicast;
20647 
20648 	/*
20649 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20650 	 * takes precedence over conn_dontroute and conn_nexthop_set
20651 	 */
20652 	if (xmit_ill != NULL)
20653 		goto send_from_ill;
20654 
20655 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20656 		/*
20657 		 * If the destination is a broadcast, local, or loopback
20658 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20659 		 * standard path.
20660 		 */
20661 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20662 		if ((ire == NULL) || (ire->ire_type &
20663 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20664 			if (ire != NULL) {
20665 				ire_refrele(ire);
20666 				/* No more access to ire */
20667 				ire = NULL;
20668 			}
20669 			/*
20670 			 * bypass routing checks and go directly to interface.
20671 			 */
20672 			if (connp->conn_dontroute)
20673 				goto dontroute;
20674 
20675 			ASSERT(connp->conn_nexthop_set);
20676 			ip_nexthop = B_TRUE;
20677 			nexthop_addr = connp->conn_nexthop_v4;
20678 			goto send_from_ill;
20679 		}
20680 
20681 		/* Must be a broadcast, a loopback or a local ire */
20682 		ire_refrele(ire);
20683 		/* No more access to ire */
20684 		ire = NULL;
20685 	}
20686 
20687 	/*
20688 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20689 	 * this for the tcp global queue and listen end point
20690 	 * as it does not really have a real destination to
20691 	 * talk to.  This is also true for SCTP.
20692 	 */
20693 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20694 	    !connp->conn_fully_bound) {
20695 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20696 		if (ire == NULL)
20697 			goto noirefound;
20698 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20699 		    "ip_wput_end: q %p (%S)", q, "end");
20700 
20701 		/*
20702 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20703 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20704 		 */
20705 		if (ire->ire_flags & RTF_MULTIRT) {
20706 
20707 			/*
20708 			 * Force the TTL of multirouted packets if required.
20709 			 * The TTL of such packets is bounded by the
20710 			 * ip_multirt_ttl ndd variable.
20711 			 */
20712 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20713 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20714 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20715 				    "(was %d), dst 0x%08x\n",
20716 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20717 				    ntohl(ire->ire_addr)));
20718 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20719 			}
20720 			/*
20721 			 * We look at this point if there are pending
20722 			 * unresolved routes. ire_multirt_resolvable()
20723 			 * checks in O(n) that all IRE_OFFSUBNET ire
20724 			 * entries for the packet's destination and
20725 			 * flagged RTF_MULTIRT are currently resolved.
20726 			 * If some remain unresolved, we make a copy
20727 			 * of the current message. It will be used
20728 			 * to initiate additional route resolutions.
20729 			 */
20730 			multirt_need_resolve =
20731 			    ire_multirt_need_resolve(ire->ire_addr,
20732 			    msg_getlabel(first_mp), ipst);
20733 			ip2dbg(("ip_wput[TCP]: ire %p, "
20734 			    "multirt_need_resolve %d, first_mp %p\n",
20735 			    (void *)ire, multirt_need_resolve,
20736 			    (void *)first_mp));
20737 			if (multirt_need_resolve) {
20738 				copy_mp = copymsg(first_mp);
20739 				if (copy_mp != NULL) {
20740 					MULTIRT_DEBUG_TAG(copy_mp);
20741 				}
20742 			}
20743 		}
20744 
20745 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20746 
20747 		/*
20748 		 * Try to resolve another multiroute if
20749 		 * ire_multirt_need_resolve() deemed it necessary.
20750 		 */
20751 		if (copy_mp != NULL)
20752 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20753 		if (need_decref)
20754 			CONN_DEC_REF(connp);
20755 		return;
20756 	}
20757 
20758 	/*
20759 	 * Access to conn_ire_cache. (protected by conn_lock)
20760 	 *
20761 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20762 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20763 	 * send a packet or two with the IRE_CACHE that is going away.
20764 	 * Access to the ire requires an ire refhold on the ire prior to
20765 	 * its use since an interface unplumb thread may delete the cached
20766 	 * ire and release the refhold at any time.
20767 	 *
20768 	 * Caching an ire in the conn_ire_cache
20769 	 *
20770 	 * o Caching an ire pointer in the conn requires a strict check for
20771 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20772 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20773 	 * in the conn is done after making sure under the bucket lock that the
20774 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20775 	 * caching an ire after the unplumb thread has cleaned up the conn.
20776 	 * If the conn does not send a packet subsequently the unplumb thread
20777 	 * will be hanging waiting for the ire count to drop to zero.
20778 	 *
20779 	 * o We also need to atomically test for a null conn_ire_cache and
20780 	 * set the conn_ire_cache under the the protection of the conn_lock
20781 	 * to avoid races among concurrent threads trying to simultaneously
20782 	 * cache an ire in the conn_ire_cache.
20783 	 */
20784 	mutex_enter(&connp->conn_lock);
20785 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20786 
20787 	if (ire != NULL && ire->ire_addr == dst &&
20788 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20789 
20790 		IRE_REFHOLD(ire);
20791 		mutex_exit(&connp->conn_lock);
20792 
20793 	} else {
20794 		boolean_t cached = B_FALSE;
20795 		connp->conn_ire_cache = NULL;
20796 		mutex_exit(&connp->conn_lock);
20797 		/* Release the old ire */
20798 		if (ire != NULL && sctp_ire == NULL)
20799 			IRE_REFRELE_NOTR(ire);
20800 
20801 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20802 		if (ire == NULL)
20803 			goto noirefound;
20804 		IRE_REFHOLD_NOTR(ire);
20805 
20806 		mutex_enter(&connp->conn_lock);
20807 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20808 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20809 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20810 				if (connp->conn_ulp == IPPROTO_TCP)
20811 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20812 				connp->conn_ire_cache = ire;
20813 				cached = B_TRUE;
20814 			}
20815 			rw_exit(&ire->ire_bucket->irb_lock);
20816 		}
20817 		mutex_exit(&connp->conn_lock);
20818 
20819 		/*
20820 		 * We can continue to use the ire but since it was
20821 		 * not cached, we should drop the extra reference.
20822 		 */
20823 		if (!cached)
20824 			IRE_REFRELE_NOTR(ire);
20825 	}
20826 
20827 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20828 	    "ip_wput_end: q %p (%S)", q, "end");
20829 
20830 	/*
20831 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20832 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20833 	 */
20834 	if (ire->ire_flags & RTF_MULTIRT) {
20835 		/*
20836 		 * Force the TTL of multirouted packets if required.
20837 		 * The TTL of such packets is bounded by the
20838 		 * ip_multirt_ttl ndd variable.
20839 		 */
20840 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20841 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20842 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20843 			    "(was %d), dst 0x%08x\n",
20844 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20845 			    ntohl(ire->ire_addr)));
20846 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20847 		}
20848 
20849 		/*
20850 		 * At this point, we check to see if there are any pending
20851 		 * unresolved routes. ire_multirt_resolvable()
20852 		 * checks in O(n) that all IRE_OFFSUBNET ire
20853 		 * entries for the packet's destination and
20854 		 * flagged RTF_MULTIRT are currently resolved.
20855 		 * If some remain unresolved, we make a copy
20856 		 * of the current message. It will be used
20857 		 * to initiate additional route resolutions.
20858 		 */
20859 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20860 		    msg_getlabel(first_mp), ipst);
20861 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20862 		    "multirt_need_resolve %d, first_mp %p\n",
20863 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20864 		if (multirt_need_resolve) {
20865 			copy_mp = copymsg(first_mp);
20866 			if (copy_mp != NULL) {
20867 				MULTIRT_DEBUG_TAG(copy_mp);
20868 			}
20869 		}
20870 	}
20871 
20872 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20873 
20874 	/*
20875 	 * Try to resolve another multiroute if
20876 	 * ire_multirt_resolvable() deemed it necessary
20877 	 */
20878 	if (copy_mp != NULL)
20879 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20880 	if (need_decref)
20881 		CONN_DEC_REF(connp);
20882 	return;
20883 
20884 qnext:
20885 	/*
20886 	 * Upper Level Protocols pass down complete IP datagrams
20887 	 * as M_DATA messages.	Everything else is a sideshow.
20888 	 *
20889 	 * 1) We could be re-entering ip_wput because of ip_neworute
20890 	 *    in which case we could have a IPSEC_OUT message. We
20891 	 *    need to pass through ip_wput like other datagrams and
20892 	 *    hence cannot branch to ip_wput_nondata.
20893 	 *
20894 	 * 2) ARP, AH, ESP, and other clients who are on the module
20895 	 *    instance of IP stream, give us something to deal with.
20896 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20897 	 *
20898 	 * 3) ICMP replies also could come here.
20899 	 */
20900 	ipst = ILLQ_TO_IPST(q);
20901 
20902 	if (DB_TYPE(mp) != M_DATA) {
20903 notdata:
20904 		if (DB_TYPE(mp) == M_CTL) {
20905 			/*
20906 			 * M_CTL messages are used by ARP, AH and ESP to
20907 			 * communicate with IP. We deal with IPSEC_IN and
20908 			 * IPSEC_OUT here. ip_wput_nondata handles other
20909 			 * cases.
20910 			 */
20911 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20912 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20913 				first_mp = mp->b_cont;
20914 				first_mp->b_flag &= ~MSGHASREF;
20915 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20916 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20917 				CONN_DEC_REF(connp);
20918 				connp = NULL;
20919 			}
20920 			if (ii->ipsec_info_type == IPSEC_IN) {
20921 				/*
20922 				 * Either this message goes back to
20923 				 * IPsec for further processing or to
20924 				 * ULP after policy checks.
20925 				 */
20926 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20927 				return;
20928 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20929 				io = (ipsec_out_t *)ii;
20930 				if (io->ipsec_out_proc_begin) {
20931 					/*
20932 					 * IPsec processing has already started.
20933 					 * Complete it.
20934 					 * IPQoS notes: We don't care what is
20935 					 * in ipsec_out_ill_index since this
20936 					 * won't be processed for IPQoS policies
20937 					 * in ipsec_out_process.
20938 					 */
20939 					ipsec_out_process(q, mp, NULL,
20940 					    io->ipsec_out_ill_index);
20941 					return;
20942 				} else {
20943 					connp = (q->q_next != NULL) ?
20944 					    NULL : Q_TO_CONN(q);
20945 					first_mp = mp;
20946 					mp = mp->b_cont;
20947 					mctl_present = B_TRUE;
20948 				}
20949 				zoneid = io->ipsec_out_zoneid;
20950 				ASSERT(zoneid != ALL_ZONES);
20951 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20952 				/*
20953 				 * It's an IPsec control message requesting
20954 				 * an SADB update to be sent to the IPsec
20955 				 * hardware acceleration capable ills.
20956 				 */
20957 				ipsec_ctl_t *ipsec_ctl =
20958 				    (ipsec_ctl_t *)mp->b_rptr;
20959 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20960 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20961 				mblk_t *cmp = mp->b_cont;
20962 
20963 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20964 				ASSERT(cmp != NULL);
20965 
20966 				freeb(mp);
20967 				ill_ipsec_capab_send_all(satype, cmp, sa,
20968 				    ipst->ips_netstack);
20969 				return;
20970 			} else {
20971 				/*
20972 				 * This must be ARP or special TSOL signaling.
20973 				 */
20974 				ip_wput_nondata(NULL, q, mp, NULL);
20975 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20976 				    "ip_wput_end: q %p (%S)", q, "nondata");
20977 				return;
20978 			}
20979 		} else {
20980 			/*
20981 			 * This must be non-(ARP/AH/ESP) messages.
20982 			 */
20983 			ASSERT(!need_decref);
20984 			ip_wput_nondata(NULL, q, mp, NULL);
20985 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20986 			    "ip_wput_end: q %p (%S)", q, "nondata");
20987 			return;
20988 		}
20989 	} else {
20990 		first_mp = mp;
20991 		mctl_present = B_FALSE;
20992 	}
20993 
20994 	ASSERT(first_mp != NULL);
20995 
20996 	if (mctl_present) {
20997 		io = (ipsec_out_t *)first_mp->b_rptr;
20998 		if (io->ipsec_out_ip_nexthop) {
20999 			/*
21000 			 * We may have lost the conn context if we are
21001 			 * coming here from ip_newroute(). Copy the
21002 			 * nexthop information.
21003 			 */
21004 			ip_nexthop = B_TRUE;
21005 			nexthop_addr = io->ipsec_out_nexthop_addr;
21006 
21007 			ipha = (ipha_t *)mp->b_rptr;
21008 			dst = ipha->ipha_dst;
21009 			goto send_from_ill;
21010 		}
21011 	}
21012 
21013 	ASSERT(xmit_ill == NULL);
21014 
21015 	/* We have a complete IP datagram heading outbound. */
21016 	ipha = (ipha_t *)mp->b_rptr;
21017 
21018 #ifndef SPEED_BEFORE_SAFETY
21019 	/*
21020 	 * Make sure we have a full-word aligned message and that at least
21021 	 * a simple IP header is accessible in the first message.  If not,
21022 	 * try a pullup.  For labeled systems we need to always take this
21023 	 * path as M_CTLs are "notdata" but have trailing data to process.
21024 	 */
21025 	if (!OK_32PTR(rptr) ||
21026 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21027 hdrtoosmall:
21028 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21029 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21030 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21031 			if (first_mp == NULL)
21032 				first_mp = mp;
21033 			goto discard_pkt;
21034 		}
21035 
21036 		/* This function assumes that mp points to an IPv4 packet. */
21037 		if (is_system_labeled() && q->q_next == NULL &&
21038 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21039 		    !connp->conn_ulp_labeled) {
21040 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21041 			    connp->conn_mac_exempt, ipst);
21042 			ipha = (ipha_t *)mp->b_rptr;
21043 			if (first_mp != NULL)
21044 				first_mp->b_cont = mp;
21045 			if (err != 0) {
21046 				if (first_mp == NULL)
21047 					first_mp = mp;
21048 				if (err == EINVAL)
21049 					goto icmp_parameter_problem;
21050 				ip2dbg(("ip_wput: label check failed (%d)\n",
21051 				    err));
21052 				goto discard_pkt;
21053 			}
21054 		}
21055 
21056 		ipha = (ipha_t *)mp->b_rptr;
21057 		if (first_mp == NULL) {
21058 			ASSERT(xmit_ill == NULL);
21059 			/*
21060 			 * If we got here because of "goto hdrtoosmall"
21061 			 * We need to attach a IPSEC_OUT.
21062 			 */
21063 			if (connp->conn_out_enforce_policy) {
21064 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21065 				    NULL, ipha->ipha_protocol,
21066 				    ipst->ips_netstack)) == NULL)) {
21067 					BUMP_MIB(&ipst->ips_ip_mib,
21068 					    ipIfStatsOutDiscards);
21069 					if (need_decref)
21070 						CONN_DEC_REF(connp);
21071 					return;
21072 				} else {
21073 					ASSERT(mp->b_datap->db_type == M_CTL);
21074 					first_mp = mp;
21075 					mp = mp->b_cont;
21076 					mctl_present = B_TRUE;
21077 				}
21078 			} else {
21079 				first_mp = mp;
21080 				mctl_present = B_FALSE;
21081 			}
21082 		}
21083 	}
21084 #endif
21085 
21086 	/* Most of the code below is written for speed, not readability */
21087 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21088 
21089 	/*
21090 	 * If ip_newroute() fails, we're going to need a full
21091 	 * header for the icmp wraparound.
21092 	 */
21093 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21094 		uint_t	v_hlen;
21095 version_hdrlen_check:
21096 		ASSERT(first_mp != NULL);
21097 		v_hlen = V_HLEN;
21098 		/*
21099 		 * siphon off IPv6 packets coming down from transport
21100 		 * layer modules here.
21101 		 * Note: high-order bit carries NUD reachability confirmation
21102 		 */
21103 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21104 			/*
21105 			 * FIXME: assume that callers of ip_output* call
21106 			 * the right version?
21107 			 */
21108 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21109 			ASSERT(xmit_ill == NULL);
21110 			if (need_decref)
21111 				mp->b_flag |= MSGHASREF;
21112 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21113 			return;
21114 		}
21115 
21116 		if ((v_hlen >> 4) != IP_VERSION) {
21117 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21118 			    "ip_wput_end: q %p (%S)", q, "badvers");
21119 			goto discard_pkt;
21120 		}
21121 		/*
21122 		 * Is the header length at least 20 bytes?
21123 		 *
21124 		 * Are there enough bytes accessible in the header?  If
21125 		 * not, try a pullup.
21126 		 */
21127 		v_hlen &= 0xF;
21128 		v_hlen <<= 2;
21129 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21130 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21131 			    "ip_wput_end: q %p (%S)", q, "badlen");
21132 			goto discard_pkt;
21133 		}
21134 		if (v_hlen > (mp->b_wptr - rptr)) {
21135 			if (!pullupmsg(mp, v_hlen)) {
21136 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21137 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21138 				goto discard_pkt;
21139 			}
21140 			ipha = (ipha_t *)mp->b_rptr;
21141 		}
21142 		/*
21143 		 * Move first entry from any source route into ipha_dst and
21144 		 * verify the options
21145 		 */
21146 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21147 		    zoneid, ipst)) {
21148 			ASSERT(xmit_ill == NULL);
21149 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21150 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21151 			    "ip_wput_end: q %p (%S)", q, "badopts");
21152 			if (need_decref)
21153 				CONN_DEC_REF(connp);
21154 			return;
21155 		}
21156 	}
21157 	dst = ipha->ipha_dst;
21158 
21159 	/*
21160 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21161 	 * we have to run the packet through ip_newroute which will take
21162 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21163 	 * a resolver, or assigning a default gateway, etc.
21164 	 */
21165 	if (CLASSD(dst)) {
21166 		ipif_t	*ipif;
21167 		uint32_t setsrc = 0;
21168 
21169 multicast:
21170 		ASSERT(first_mp != NULL);
21171 		ip2dbg(("ip_wput: CLASSD\n"));
21172 		if (connp == NULL) {
21173 			/*
21174 			 * Use the first good ipif on the ill.
21175 			 * XXX Should this ever happen? (Appears
21176 			 * to show up with just ppp and no ethernet due
21177 			 * to in.rdisc.)
21178 			 * However, ire_send should be able to
21179 			 * call ip_wput_ire directly.
21180 			 *
21181 			 * XXX Also, this can happen for ICMP and other packets
21182 			 * with multicast source addresses.  Perhaps we should
21183 			 * fix things so that we drop the packet in question,
21184 			 * but for now, just run with it.
21185 			 */
21186 			ill_t *ill = (ill_t *)q->q_ptr;
21187 
21188 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21189 			if (ipif == NULL) {
21190 				if (need_decref)
21191 					CONN_DEC_REF(connp);
21192 				freemsg(first_mp);
21193 				return;
21194 			}
21195 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21196 			    ntohl(dst), ill->ill_name));
21197 		} else {
21198 			/*
21199 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21200 			 * and IP_MULTICAST_IF.  The block comment above this
21201 			 * function explains the locking mechanism used here.
21202 			 */
21203 			if (xmit_ill == NULL) {
21204 				xmit_ill = conn_get_held_ill(connp,
21205 				    &connp->conn_outgoing_ill, &err);
21206 				if (err == ILL_LOOKUP_FAILED) {
21207 					ip1dbg(("ip_wput: No ill for "
21208 					    "IP_BOUND_IF\n"));
21209 					BUMP_MIB(&ipst->ips_ip_mib,
21210 					    ipIfStatsOutNoRoutes);
21211 					goto drop_pkt;
21212 				}
21213 			}
21214 
21215 			if (xmit_ill == NULL) {
21216 				ipif = conn_get_held_ipif(connp,
21217 				    &connp->conn_multicast_ipif, &err);
21218 				if (err == IPIF_LOOKUP_FAILED) {
21219 					ip1dbg(("ip_wput: No ipif for "
21220 					    "multicast\n"));
21221 					BUMP_MIB(&ipst->ips_ip_mib,
21222 					    ipIfStatsOutNoRoutes);
21223 					goto drop_pkt;
21224 				}
21225 			}
21226 			if (xmit_ill != NULL) {
21227 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21228 				if (ipif == NULL) {
21229 					ip1dbg(("ip_wput: No ipif for "
21230 					    "xmit_ill\n"));
21231 					BUMP_MIB(&ipst->ips_ip_mib,
21232 					    ipIfStatsOutNoRoutes);
21233 					goto drop_pkt;
21234 				}
21235 			} else if (ipif == NULL || ipif->ipif_isv6) {
21236 				/*
21237 				 * We must do this ipif determination here
21238 				 * else we could pass through ip_newroute
21239 				 * and come back here without the conn context.
21240 				 *
21241 				 * Note: we do late binding i.e. we bind to
21242 				 * the interface when the first packet is sent.
21243 				 * For performance reasons we do not rebind on
21244 				 * each packet but keep the binding until the
21245 				 * next IP_MULTICAST_IF option.
21246 				 *
21247 				 * conn_multicast_{ipif,ill} are shared between
21248 				 * IPv4 and IPv6 and AF_INET6 sockets can
21249 				 * send both IPv4 and IPv6 packets. Hence
21250 				 * we have to check that "isv6" matches above.
21251 				 */
21252 				if (ipif != NULL)
21253 					ipif_refrele(ipif);
21254 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21255 				if (ipif == NULL) {
21256 					ip1dbg(("ip_wput: No ipif for "
21257 					    "multicast\n"));
21258 					BUMP_MIB(&ipst->ips_ip_mib,
21259 					    ipIfStatsOutNoRoutes);
21260 					goto drop_pkt;
21261 				}
21262 				err = conn_set_held_ipif(connp,
21263 				    &connp->conn_multicast_ipif, ipif);
21264 				if (err == IPIF_LOOKUP_FAILED) {
21265 					ipif_refrele(ipif);
21266 					ip1dbg(("ip_wput: No ipif for "
21267 					    "multicast\n"));
21268 					BUMP_MIB(&ipst->ips_ip_mib,
21269 					    ipIfStatsOutNoRoutes);
21270 					goto drop_pkt;
21271 				}
21272 			}
21273 		}
21274 		ASSERT(!ipif->ipif_isv6);
21275 		/*
21276 		 * As we may lose the conn by the time we reach ip_wput_ire,
21277 		 * we copy conn_multicast_loop and conn_dontroute on to an
21278 		 * ipsec_out. In case if this datagram goes out secure,
21279 		 * we need the ill_index also. Copy that also into the
21280 		 * ipsec_out.
21281 		 */
21282 		if (mctl_present) {
21283 			io = (ipsec_out_t *)first_mp->b_rptr;
21284 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21285 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21286 		} else {
21287 			ASSERT(mp == first_mp);
21288 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21289 			    BPRI_HI)) == NULL) {
21290 				ipif_refrele(ipif);
21291 				first_mp = mp;
21292 				goto discard_pkt;
21293 			}
21294 			first_mp->b_datap->db_type = M_CTL;
21295 			first_mp->b_wptr += sizeof (ipsec_info_t);
21296 			/* ipsec_out_secure is B_FALSE now */
21297 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21298 			io = (ipsec_out_t *)first_mp->b_rptr;
21299 			io->ipsec_out_type = IPSEC_OUT;
21300 			io->ipsec_out_len = sizeof (ipsec_out_t);
21301 			io->ipsec_out_use_global_policy = B_TRUE;
21302 			io->ipsec_out_ns = ipst->ips_netstack;
21303 			first_mp->b_cont = mp;
21304 			mctl_present = B_TRUE;
21305 		}
21306 
21307 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21308 		io->ipsec_out_ill_index =
21309 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21310 
21311 		if (connp != NULL) {
21312 			io->ipsec_out_multicast_loop =
21313 			    connp->conn_multicast_loop;
21314 			io->ipsec_out_dontroute = connp->conn_dontroute;
21315 			io->ipsec_out_zoneid = connp->conn_zoneid;
21316 		}
21317 		/*
21318 		 * If the application uses IP_MULTICAST_IF with
21319 		 * different logical addresses of the same ILL, we
21320 		 * need to make sure that the soruce address of
21321 		 * the packet matches the logical IP address used
21322 		 * in the option. We do it by initializing ipha_src
21323 		 * here. This should keep IPsec also happy as
21324 		 * when we return from IPsec processing, we don't
21325 		 * have to worry about getting the right address on
21326 		 * the packet. Thus it is sufficient to look for
21327 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21328 		 * MATCH_IRE_IPIF.
21329 		 *
21330 		 * NOTE : We need to do it for non-secure case also as
21331 		 * this might go out secure if there is a global policy
21332 		 * match in ip_wput_ire.
21333 		 *
21334 		 * As we do not have the ire yet, it is possible that
21335 		 * we set the source address here and then later discover
21336 		 * that the ire implies the source address to be assigned
21337 		 * through the RTF_SETSRC flag.
21338 		 * In that case, the setsrc variable will remind us
21339 		 * that overwritting the source address by the one
21340 		 * of the RTF_SETSRC-flagged ire is allowed.
21341 		 */
21342 		if (ipha->ipha_src == INADDR_ANY &&
21343 		    (connp == NULL || !connp->conn_unspec_src)) {
21344 			ipha->ipha_src = ipif->ipif_src_addr;
21345 			setsrc = RTF_SETSRC;
21346 		}
21347 		/*
21348 		 * Find an IRE which matches the destination and the outgoing
21349 		 * queue (i.e. the outgoing interface.)
21350 		 * For loopback use a unicast IP address for
21351 		 * the ire lookup.
21352 		 */
21353 		if (IS_LOOPBACK(ipif->ipif_ill))
21354 			dst = ipif->ipif_lcl_addr;
21355 
21356 		/*
21357 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21358 		 * We don't need to lookup ire in ctable as the packet
21359 		 * needs to be sent to the destination through the specified
21360 		 * ill irrespective of ires in the cache table.
21361 		 */
21362 		ire = NULL;
21363 		if (xmit_ill == NULL) {
21364 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21365 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21366 		}
21367 
21368 		if (ire == NULL) {
21369 			/*
21370 			 * Multicast loopback and multicast forwarding is
21371 			 * done in ip_wput_ire.
21372 			 *
21373 			 * Mark this packet to make it be delivered to
21374 			 * ip_wput_ire after the new ire has been
21375 			 * created.
21376 			 *
21377 			 * The call to ip_newroute_ipif takes into account
21378 			 * the setsrc reminder. In any case, we take care
21379 			 * of the RTF_MULTIRT flag.
21380 			 */
21381 			mp->b_prev = mp->b_next = NULL;
21382 			if (xmit_ill == NULL ||
21383 			    xmit_ill->ill_ipif_up_count > 0) {
21384 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21385 				    setsrc | RTF_MULTIRT, zoneid, infop);
21386 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21387 				    "ip_wput_end: q %p (%S)", q, "noire");
21388 			} else {
21389 				freemsg(first_mp);
21390 			}
21391 			ipif_refrele(ipif);
21392 			if (xmit_ill != NULL)
21393 				ill_refrele(xmit_ill);
21394 			if (need_decref)
21395 				CONN_DEC_REF(connp);
21396 			return;
21397 		}
21398 
21399 		ipif_refrele(ipif);
21400 		ipif = NULL;
21401 		ASSERT(xmit_ill == NULL);
21402 
21403 		/*
21404 		 * Honor the RTF_SETSRC flag for multicast packets,
21405 		 * if allowed by the setsrc reminder.
21406 		 */
21407 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21408 			ipha->ipha_src = ire->ire_src_addr;
21409 		}
21410 
21411 		/*
21412 		 * Unconditionally force the TTL to 1 for
21413 		 * multirouted multicast packets:
21414 		 * multirouted multicast should not cross
21415 		 * multicast routers.
21416 		 */
21417 		if (ire->ire_flags & RTF_MULTIRT) {
21418 			if (ipha->ipha_ttl > 1) {
21419 				ip2dbg(("ip_wput: forcing multicast "
21420 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21421 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21422 				ipha->ipha_ttl = 1;
21423 			}
21424 		}
21425 	} else {
21426 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21427 		if ((ire != NULL) && (ire->ire_type &
21428 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21429 			ignore_dontroute = B_TRUE;
21430 			ignore_nexthop = B_TRUE;
21431 		}
21432 		if (ire != NULL) {
21433 			ire_refrele(ire);
21434 			ire = NULL;
21435 		}
21436 		/*
21437 		 * Guard against coming in from arp in which case conn is NULL.
21438 		 * Also guard against non M_DATA with dontroute set but
21439 		 * destined to local, loopback or broadcast addresses.
21440 		 */
21441 		if (connp != NULL && connp->conn_dontroute &&
21442 		    !ignore_dontroute) {
21443 dontroute:
21444 			/*
21445 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21446 			 * routing protocols from seeing false direct
21447 			 * connectivity.
21448 			 */
21449 			ipha->ipha_ttl = 1;
21450 			/* If suitable ipif not found, drop packet */
21451 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21452 			if (dst_ipif == NULL) {
21453 noroute:
21454 				ip1dbg(("ip_wput: no route for dst using"
21455 				    " SO_DONTROUTE\n"));
21456 				BUMP_MIB(&ipst->ips_ip_mib,
21457 				    ipIfStatsOutNoRoutes);
21458 				mp->b_prev = mp->b_next = NULL;
21459 				if (first_mp == NULL)
21460 					first_mp = mp;
21461 				goto drop_pkt;
21462 			} else {
21463 				/*
21464 				 * If suitable ipif has been found, set
21465 				 * xmit_ill to the corresponding
21466 				 * ipif_ill because we'll be using the
21467 				 * send_from_ill logic below.
21468 				 */
21469 				ASSERT(xmit_ill == NULL);
21470 				xmit_ill = dst_ipif->ipif_ill;
21471 				mutex_enter(&xmit_ill->ill_lock);
21472 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21473 					mutex_exit(&xmit_ill->ill_lock);
21474 					xmit_ill = NULL;
21475 					ipif_refrele(dst_ipif);
21476 					goto noroute;
21477 				}
21478 				ill_refhold_locked(xmit_ill);
21479 				mutex_exit(&xmit_ill->ill_lock);
21480 				ipif_refrele(dst_ipif);
21481 			}
21482 		}
21483 
21484 send_from_ill:
21485 		if (xmit_ill != NULL) {
21486 			ipif_t *ipif;
21487 
21488 			/*
21489 			 * Mark this packet as originated locally
21490 			 */
21491 			mp->b_prev = mp->b_next = NULL;
21492 
21493 			/*
21494 			 * Could be SO_DONTROUTE case also.
21495 			 * Verify that at least one ipif is up on the ill.
21496 			 */
21497 			if (xmit_ill->ill_ipif_up_count == 0) {
21498 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21499 				    xmit_ill->ill_name));
21500 				goto drop_pkt;
21501 			}
21502 
21503 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21504 			if (ipif == NULL) {
21505 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21506 				    xmit_ill->ill_name));
21507 				goto drop_pkt;
21508 			}
21509 
21510 			match_flags = 0;
21511 			if (IS_UNDER_IPMP(xmit_ill))
21512 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21513 
21514 			/*
21515 			 * Look for a ire that is part of the group,
21516 			 * if found use it else call ip_newroute_ipif.
21517 			 * IPCL_ZONEID is not used for matching because
21518 			 * IP_ALLZONES option is valid only when the
21519 			 * ill is accessible from all zones i.e has a
21520 			 * valid ipif in all zones.
21521 			 */
21522 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21523 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21524 			    msg_getlabel(mp), match_flags, ipst);
21525 			/*
21526 			 * If an ire exists use it or else create
21527 			 * an ire but don't add it to the cache.
21528 			 * Adding an ire may cause issues with
21529 			 * asymmetric routing.
21530 			 * In case of multiroute always act as if
21531 			 * ire does not exist.
21532 			 */
21533 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21534 				if (ire != NULL)
21535 					ire_refrele(ire);
21536 				ip_newroute_ipif(q, first_mp, ipif,
21537 				    dst, connp, 0, zoneid, infop);
21538 				ipif_refrele(ipif);
21539 				ip1dbg(("ip_output: xmit_ill via %s\n",
21540 				    xmit_ill->ill_name));
21541 				ill_refrele(xmit_ill);
21542 				if (need_decref)
21543 					CONN_DEC_REF(connp);
21544 				return;
21545 			}
21546 			ipif_refrele(ipif);
21547 		} else if (ip_nexthop || (connp != NULL &&
21548 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21549 			if (!ip_nexthop) {
21550 				ip_nexthop = B_TRUE;
21551 				nexthop_addr = connp->conn_nexthop_v4;
21552 			}
21553 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21554 			    MATCH_IRE_GW;
21555 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21556 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21557 		} else {
21558 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21559 			    ipst);
21560 		}
21561 		if (!ire) {
21562 			if (ip_nexthop && !ignore_nexthop) {
21563 				if (mctl_present) {
21564 					io = (ipsec_out_t *)first_mp->b_rptr;
21565 					ASSERT(first_mp->b_datap->db_type ==
21566 					    M_CTL);
21567 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21568 				} else {
21569 					ASSERT(mp == first_mp);
21570 					first_mp = allocb(
21571 					    sizeof (ipsec_info_t), BPRI_HI);
21572 					if (first_mp == NULL) {
21573 						first_mp = mp;
21574 						goto discard_pkt;
21575 					}
21576 					first_mp->b_datap->db_type = M_CTL;
21577 					first_mp->b_wptr +=
21578 					    sizeof (ipsec_info_t);
21579 					/* ipsec_out_secure is B_FALSE now */
21580 					bzero(first_mp->b_rptr,
21581 					    sizeof (ipsec_info_t));
21582 					io = (ipsec_out_t *)first_mp->b_rptr;
21583 					io->ipsec_out_type = IPSEC_OUT;
21584 					io->ipsec_out_len =
21585 					    sizeof (ipsec_out_t);
21586 					io->ipsec_out_use_global_policy =
21587 					    B_TRUE;
21588 					io->ipsec_out_ns = ipst->ips_netstack;
21589 					first_mp->b_cont = mp;
21590 					mctl_present = B_TRUE;
21591 				}
21592 				io->ipsec_out_ip_nexthop = ip_nexthop;
21593 				io->ipsec_out_nexthop_addr = nexthop_addr;
21594 			}
21595 noirefound:
21596 			/*
21597 			 * Mark this packet as having originated on
21598 			 * this machine.  This will be noted in
21599 			 * ire_add_then_send, which needs to know
21600 			 * whether to run it back through ip_wput or
21601 			 * ip_rput following successful resolution.
21602 			 */
21603 			mp->b_prev = NULL;
21604 			mp->b_next = NULL;
21605 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21606 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21607 			    "ip_wput_end: q %p (%S)", q, "newroute");
21608 			if (xmit_ill != NULL)
21609 				ill_refrele(xmit_ill);
21610 			if (need_decref)
21611 				CONN_DEC_REF(connp);
21612 			return;
21613 		}
21614 	}
21615 
21616 	/* We now know where we are going with it. */
21617 
21618 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21619 	    "ip_wput_end: q %p (%S)", q, "end");
21620 
21621 	/*
21622 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21623 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21624 	 */
21625 	if (ire->ire_flags & RTF_MULTIRT) {
21626 		/*
21627 		 * Force the TTL of multirouted packets if required.
21628 		 * The TTL of such packets is bounded by the
21629 		 * ip_multirt_ttl ndd variable.
21630 		 */
21631 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21632 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21633 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21634 			    "(was %d), dst 0x%08x\n",
21635 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21636 			    ntohl(ire->ire_addr)));
21637 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21638 		}
21639 		/*
21640 		 * At this point, we check to see if there are any pending
21641 		 * unresolved routes. ire_multirt_resolvable()
21642 		 * checks in O(n) that all IRE_OFFSUBNET ire
21643 		 * entries for the packet's destination and
21644 		 * flagged RTF_MULTIRT are currently resolved.
21645 		 * If some remain unresolved, we make a copy
21646 		 * of the current message. It will be used
21647 		 * to initiate additional route resolutions.
21648 		 */
21649 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21650 		    msg_getlabel(first_mp), ipst);
21651 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21652 		    "multirt_need_resolve %d, first_mp %p\n",
21653 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21654 		if (multirt_need_resolve) {
21655 			copy_mp = copymsg(first_mp);
21656 			if (copy_mp != NULL) {
21657 				MULTIRT_DEBUG_TAG(copy_mp);
21658 			}
21659 		}
21660 	}
21661 
21662 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21663 	/*
21664 	 * Try to resolve another multiroute if
21665 	 * ire_multirt_resolvable() deemed it necessary.
21666 	 * At this point, we need to distinguish
21667 	 * multicasts from other packets. For multicasts,
21668 	 * we call ip_newroute_ipif() and request that both
21669 	 * multirouting and setsrc flags are checked.
21670 	 */
21671 	if (copy_mp != NULL) {
21672 		if (CLASSD(dst)) {
21673 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21674 			if (ipif) {
21675 				ASSERT(infop->ip_opt_ill_index == 0);
21676 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21677 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21678 				ipif_refrele(ipif);
21679 			} else {
21680 				MULTIRT_DEBUG_UNTAG(copy_mp);
21681 				freemsg(copy_mp);
21682 				copy_mp = NULL;
21683 			}
21684 		} else {
21685 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21686 		}
21687 	}
21688 	if (xmit_ill != NULL)
21689 		ill_refrele(xmit_ill);
21690 	if (need_decref)
21691 		CONN_DEC_REF(connp);
21692 	return;
21693 
21694 icmp_parameter_problem:
21695 	/* could not have originated externally */
21696 	ASSERT(mp->b_prev == NULL);
21697 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21698 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21699 		/* it's the IP header length that's in trouble */
21700 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21701 		first_mp = NULL;
21702 	}
21703 
21704 discard_pkt:
21705 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21706 drop_pkt:
21707 	ip1dbg(("ip_wput: dropped packet\n"));
21708 	if (ire != NULL)
21709 		ire_refrele(ire);
21710 	if (need_decref)
21711 		CONN_DEC_REF(connp);
21712 	freemsg(first_mp);
21713 	if (xmit_ill != NULL)
21714 		ill_refrele(xmit_ill);
21715 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21716 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21717 }
21718 
21719 /*
21720  * If this is a conn_t queue, then we pass in the conn. This includes the
21721  * zoneid.
21722  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21723  * in which case we use the global zoneid since those are all part of
21724  * the global zone.
21725  */
21726 void
21727 ip_wput(queue_t *q, mblk_t *mp)
21728 {
21729 	if (CONN_Q(q))
21730 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21731 	else
21732 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21733 }
21734 
21735 /*
21736  *
21737  * The following rules must be observed when accessing any ipif or ill
21738  * that has been cached in the conn. Typically conn_outgoing_ill,
21739  * conn_multicast_ipif and conn_multicast_ill.
21740  *
21741  * Access: The ipif or ill pointed to from the conn can be accessed under
21742  * the protection of the conn_lock or after it has been refheld under the
21743  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21744  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21745  * The reason for this is that a concurrent unplumb could actually be
21746  * cleaning up these cached pointers by walking the conns and might have
21747  * finished cleaning up the conn in question. The macros check that an
21748  * unplumb has not yet started on the ipif or ill.
21749  *
21750  * Caching: An ipif or ill pointer may be cached in the conn only after
21751  * making sure that an unplumb has not started. So the caching is done
21752  * while holding both the conn_lock and the ill_lock and after using the
21753  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21754  * flag before starting the cleanup of conns.
21755  *
21756  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21757  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21758  * or a reference to the ipif or a reference to an ire that references the
21759  * ipif. An ipif only changes its ill when migrating from an underlying ill
21760  * to an IPMP ill in ipif_up().
21761  */
21762 ipif_t *
21763 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21764 {
21765 	ipif_t	*ipif;
21766 	ill_t	*ill;
21767 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21768 
21769 	*err = 0;
21770 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21771 	mutex_enter(&connp->conn_lock);
21772 	ipif = *ipifp;
21773 	if (ipif != NULL) {
21774 		ill = ipif->ipif_ill;
21775 		mutex_enter(&ill->ill_lock);
21776 		if (IPIF_CAN_LOOKUP(ipif)) {
21777 			ipif_refhold_locked(ipif);
21778 			mutex_exit(&ill->ill_lock);
21779 			mutex_exit(&connp->conn_lock);
21780 			rw_exit(&ipst->ips_ill_g_lock);
21781 			return (ipif);
21782 		} else {
21783 			*err = IPIF_LOOKUP_FAILED;
21784 		}
21785 		mutex_exit(&ill->ill_lock);
21786 	}
21787 	mutex_exit(&connp->conn_lock);
21788 	rw_exit(&ipst->ips_ill_g_lock);
21789 	return (NULL);
21790 }
21791 
21792 ill_t *
21793 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21794 {
21795 	ill_t	*ill;
21796 
21797 	*err = 0;
21798 	mutex_enter(&connp->conn_lock);
21799 	ill = *illp;
21800 	if (ill != NULL) {
21801 		mutex_enter(&ill->ill_lock);
21802 		if (ILL_CAN_LOOKUP(ill)) {
21803 			ill_refhold_locked(ill);
21804 			mutex_exit(&ill->ill_lock);
21805 			mutex_exit(&connp->conn_lock);
21806 			return (ill);
21807 		} else {
21808 			*err = ILL_LOOKUP_FAILED;
21809 		}
21810 		mutex_exit(&ill->ill_lock);
21811 	}
21812 	mutex_exit(&connp->conn_lock);
21813 	return (NULL);
21814 }
21815 
21816 static int
21817 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21818 {
21819 	ill_t	*ill;
21820 
21821 	ill = ipif->ipif_ill;
21822 	mutex_enter(&connp->conn_lock);
21823 	mutex_enter(&ill->ill_lock);
21824 	if (IPIF_CAN_LOOKUP(ipif)) {
21825 		*ipifp = ipif;
21826 		mutex_exit(&ill->ill_lock);
21827 		mutex_exit(&connp->conn_lock);
21828 		return (0);
21829 	}
21830 	mutex_exit(&ill->ill_lock);
21831 	mutex_exit(&connp->conn_lock);
21832 	return (IPIF_LOOKUP_FAILED);
21833 }
21834 
21835 /*
21836  * This is called if the outbound datagram needs fragmentation.
21837  *
21838  * NOTE : This function does not ire_refrele the ire argument passed in.
21839  */
21840 static void
21841 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21842     ip_stack_t *ipst, conn_t *connp)
21843 {
21844 	ipha_t		*ipha;
21845 	mblk_t		*mp;
21846 	uint32_t	v_hlen_tos_len;
21847 	uint32_t	max_frag;
21848 	uint32_t	frag_flag;
21849 	boolean_t	dont_use;
21850 
21851 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21852 		mp = ipsec_mp->b_cont;
21853 	} else {
21854 		mp = ipsec_mp;
21855 	}
21856 
21857 	ipha = (ipha_t *)mp->b_rptr;
21858 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21859 
21860 #ifdef	_BIG_ENDIAN
21861 #define	V_HLEN	(v_hlen_tos_len >> 24)
21862 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21863 #else
21864 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21865 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21866 #endif
21867 
21868 #ifndef SPEED_BEFORE_SAFETY
21869 	/*
21870 	 * Check that ipha_length is consistent with
21871 	 * the mblk length
21872 	 */
21873 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21874 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21875 		    LENGTH, msgdsize(mp)));
21876 		freemsg(ipsec_mp);
21877 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21878 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21879 		    "packet length mismatch");
21880 		return;
21881 	}
21882 #endif
21883 	/*
21884 	 * Don't use frag_flag if pre-built packet or source
21885 	 * routed or if multicast (since multicast packets do not solicit
21886 	 * ICMP "packet too big" messages). Get the values of
21887 	 * max_frag and frag_flag atomically by acquiring the
21888 	 * ire_lock.
21889 	 */
21890 	mutex_enter(&ire->ire_lock);
21891 	max_frag = ire->ire_max_frag;
21892 	frag_flag = ire->ire_frag_flag;
21893 	mutex_exit(&ire->ire_lock);
21894 
21895 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21896 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21897 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21898 
21899 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21900 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21901 }
21902 
21903 /*
21904  * Used for deciding the MSS size for the upper layer. Thus
21905  * we need to check the outbound policy values in the conn.
21906  */
21907 int
21908 conn_ipsec_length(conn_t *connp)
21909 {
21910 	ipsec_latch_t *ipl;
21911 
21912 	ipl = connp->conn_latch;
21913 	if (ipl == NULL)
21914 		return (0);
21915 
21916 	if (ipl->ipl_out_policy == NULL)
21917 		return (0);
21918 
21919 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21920 }
21921 
21922 /*
21923  * Returns an estimate of the IPsec headers size. This is used if
21924  * we don't want to call into IPsec to get the exact size.
21925  */
21926 int
21927 ipsec_out_extra_length(mblk_t *ipsec_mp)
21928 {
21929 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21930 	ipsec_action_t *a;
21931 
21932 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21933 	if (!io->ipsec_out_secure)
21934 		return (0);
21935 
21936 	a = io->ipsec_out_act;
21937 
21938 	if (a == NULL) {
21939 		ASSERT(io->ipsec_out_policy != NULL);
21940 		a = io->ipsec_out_policy->ipsp_act;
21941 	}
21942 	ASSERT(a != NULL);
21943 
21944 	return (a->ipa_ovhd);
21945 }
21946 
21947 /*
21948  * Returns an estimate of the IPsec headers size. This is used if
21949  * we don't want to call into IPsec to get the exact size.
21950  */
21951 int
21952 ipsec_in_extra_length(mblk_t *ipsec_mp)
21953 {
21954 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21955 	ipsec_action_t *a;
21956 
21957 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21958 
21959 	a = ii->ipsec_in_action;
21960 	return (a == NULL ? 0 : a->ipa_ovhd);
21961 }
21962 
21963 /*
21964  * If there are any source route options, return the true final
21965  * destination. Otherwise, return the destination.
21966  */
21967 ipaddr_t
21968 ip_get_dst(ipha_t *ipha)
21969 {
21970 	ipoptp_t	opts;
21971 	uchar_t		*opt;
21972 	uint8_t		optval;
21973 	uint8_t		optlen;
21974 	ipaddr_t	dst;
21975 	uint32_t off;
21976 
21977 	dst = ipha->ipha_dst;
21978 
21979 	if (IS_SIMPLE_IPH(ipha))
21980 		return (dst);
21981 
21982 	for (optval = ipoptp_first(&opts, ipha);
21983 	    optval != IPOPT_EOL;
21984 	    optval = ipoptp_next(&opts)) {
21985 		opt = opts.ipoptp_cur;
21986 		optlen = opts.ipoptp_len;
21987 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21988 		switch (optval) {
21989 		case IPOPT_SSRR:
21990 		case IPOPT_LSRR:
21991 			off = opt[IPOPT_OFFSET];
21992 			/*
21993 			 * If one of the conditions is true, it means
21994 			 * end of options and dst already has the right
21995 			 * value.
21996 			 */
21997 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21998 				off = optlen - IP_ADDR_LEN;
21999 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22000 			}
22001 			return (dst);
22002 		default:
22003 			break;
22004 		}
22005 	}
22006 
22007 	return (dst);
22008 }
22009 
22010 mblk_t *
22011 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22012     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22013 {
22014 	ipsec_out_t	*io;
22015 	mblk_t		*first_mp;
22016 	boolean_t policy_present;
22017 	ip_stack_t	*ipst;
22018 	ipsec_stack_t	*ipss;
22019 
22020 	ASSERT(ire != NULL);
22021 	ipst = ire->ire_ipst;
22022 	ipss = ipst->ips_netstack->netstack_ipsec;
22023 
22024 	first_mp = mp;
22025 	if (mp->b_datap->db_type == M_CTL) {
22026 		io = (ipsec_out_t *)first_mp->b_rptr;
22027 		/*
22028 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22029 		 *
22030 		 * 1) There is per-socket policy (including cached global
22031 		 *    policy) or a policy on the IP-in-IP tunnel.
22032 		 * 2) There is no per-socket policy, but it is
22033 		 *    a multicast packet that needs to go out
22034 		 *    on a specific interface. This is the case
22035 		 *    where (ip_wput and ip_wput_multicast) attaches
22036 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22037 		 *
22038 		 * In case (2) we check with global policy to
22039 		 * see if there is a match and set the ill_index
22040 		 * appropriately so that we can lookup the ire
22041 		 * properly in ip_wput_ipsec_out.
22042 		 */
22043 
22044 		/*
22045 		 * ipsec_out_use_global_policy is set to B_FALSE
22046 		 * in ipsec_in_to_out(). Refer to that function for
22047 		 * details.
22048 		 */
22049 		if ((io->ipsec_out_latch == NULL) &&
22050 		    (io->ipsec_out_use_global_policy)) {
22051 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22052 			    ire, connp, unspec_src, zoneid));
22053 		}
22054 		if (!io->ipsec_out_secure) {
22055 			/*
22056 			 * If this is not a secure packet, drop
22057 			 * the IPSEC_OUT mp and treat it as a clear
22058 			 * packet. This happens when we are sending
22059 			 * a ICMP reply back to a clear packet. See
22060 			 * ipsec_in_to_out() for details.
22061 			 */
22062 			mp = first_mp->b_cont;
22063 			freeb(first_mp);
22064 		}
22065 		return (mp);
22066 	}
22067 	/*
22068 	 * See whether we need to attach a global policy here. We
22069 	 * don't depend on the conn (as it could be null) for deciding
22070 	 * what policy this datagram should go through because it
22071 	 * should have happened in ip_wput if there was some
22072 	 * policy. This normally happens for connections which are not
22073 	 * fully bound preventing us from caching policies in
22074 	 * ip_bind. Packets coming from the TCP listener/global queue
22075 	 * - which are non-hard_bound - could also be affected by
22076 	 * applying policy here.
22077 	 *
22078 	 * If this packet is coming from tcp global queue or listener,
22079 	 * we will be applying policy here.  This may not be *right*
22080 	 * if these packets are coming from the detached connection as
22081 	 * it could have gone in clear before. This happens only if a
22082 	 * TCP connection started when there is no policy and somebody
22083 	 * added policy before it became detached. Thus packets of the
22084 	 * detached connection could go out secure and the other end
22085 	 * would drop it because it will be expecting in clear. The
22086 	 * converse is not true i.e if somebody starts a TCP
22087 	 * connection and deletes the policy, all the packets will
22088 	 * still go out with the policy that existed before deleting
22089 	 * because ip_unbind sends up policy information which is used
22090 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22091 	 * TCP to attach a dummy IPSEC_OUT and set
22092 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22093 	 * affect performance for normal cases, we are not doing it.
22094 	 * Thus, set policy before starting any TCP connections.
22095 	 *
22096 	 * NOTE - We might apply policy even for a hard bound connection
22097 	 * - for which we cached policy in ip_bind - if somebody added
22098 	 * global policy after we inherited the policy in ip_bind.
22099 	 * This means that the packets that were going out in clear
22100 	 * previously would start going secure and hence get dropped
22101 	 * on the other side. To fix this, TCP attaches a dummy
22102 	 * ipsec_out and make sure that we don't apply global policy.
22103 	 */
22104 	if (ipha != NULL)
22105 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22106 	else
22107 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22108 	if (!policy_present)
22109 		return (mp);
22110 
22111 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22112 	    zoneid));
22113 }
22114 
22115 /*
22116  * This function does the ire_refrele of the ire passed in as the
22117  * argument. As this function looks up more ires i.e broadcast ires,
22118  * it needs to REFRELE them. Currently, for simplicity we don't
22119  * differentiate the one passed in and looked up here. We always
22120  * REFRELE.
22121  * IPQoS Notes:
22122  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22123  * IPsec packets are done in ipsec_out_process.
22124  */
22125 void
22126 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22127     zoneid_t zoneid)
22128 {
22129 	ipha_t		*ipha;
22130 #define	rptr	((uchar_t *)ipha)
22131 	queue_t		*stq;
22132 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22133 	uint32_t	v_hlen_tos_len;
22134 	uint32_t	ttl_protocol;
22135 	ipaddr_t	src;
22136 	ipaddr_t	dst;
22137 	uint32_t	cksum;
22138 	ipaddr_t	orig_src;
22139 	ire_t		*ire1;
22140 	mblk_t		*next_mp;
22141 	uint_t		hlen;
22142 	uint16_t	*up;
22143 	uint32_t	max_frag = ire->ire_max_frag;
22144 	ill_t		*ill = ire_to_ill(ire);
22145 	int		clusterwide;
22146 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22147 	int		ipsec_len;
22148 	mblk_t		*first_mp;
22149 	ipsec_out_t	*io;
22150 	boolean_t	conn_dontroute;		/* conn value for multicast */
22151 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22152 	boolean_t	multicast_forward;	/* Should we forward ? */
22153 	boolean_t	unspec_src;
22154 	ill_t		*conn_outgoing_ill = NULL;
22155 	ill_t		*ire_ill;
22156 	ill_t		*ire1_ill;
22157 	ill_t		*out_ill;
22158 	uint32_t 	ill_index = 0;
22159 	boolean_t	multirt_send = B_FALSE;
22160 	int		err;
22161 	ipxmit_state_t	pktxmit_state;
22162 	ip_stack_t	*ipst = ire->ire_ipst;
22163 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22164 
22165 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22166 	    "ip_wput_ire_start: q %p", q);
22167 
22168 	multicast_forward = B_FALSE;
22169 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22170 
22171 	if (ire->ire_flags & RTF_MULTIRT) {
22172 		/*
22173 		 * Multirouting case. The bucket where ire is stored
22174 		 * probably holds other RTF_MULTIRT flagged ire
22175 		 * to the destination. In this call to ip_wput_ire,
22176 		 * we attempt to send the packet through all
22177 		 * those ires. Thus, we first ensure that ire is the
22178 		 * first RTF_MULTIRT ire in the bucket,
22179 		 * before walking the ire list.
22180 		 */
22181 		ire_t *first_ire;
22182 		irb_t *irb = ire->ire_bucket;
22183 		ASSERT(irb != NULL);
22184 
22185 		/* Make sure we do not omit any multiroute ire. */
22186 		IRB_REFHOLD(irb);
22187 		for (first_ire = irb->irb_ire;
22188 		    first_ire != NULL;
22189 		    first_ire = first_ire->ire_next) {
22190 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22191 			    (first_ire->ire_addr == ire->ire_addr) &&
22192 			    !(first_ire->ire_marks &
22193 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22194 				break;
22195 		}
22196 
22197 		if ((first_ire != NULL) && (first_ire != ire)) {
22198 			IRE_REFHOLD(first_ire);
22199 			ire_refrele(ire);
22200 			ire = first_ire;
22201 			ill = ire_to_ill(ire);
22202 		}
22203 		IRB_REFRELE(irb);
22204 	}
22205 
22206 	/*
22207 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22208 	 * for performance we don't grab the mutexs in the fastpath
22209 	 */
22210 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22211 	    connp->conn_outgoing_ill != NULL) {
22212 		conn_outgoing_ill = conn_get_held_ill(connp,
22213 		    &connp->conn_outgoing_ill, &err);
22214 		if (err == ILL_LOOKUP_FAILED) {
22215 			ire_refrele(ire);
22216 			freemsg(mp);
22217 			return;
22218 		}
22219 	}
22220 
22221 	if (mp->b_datap->db_type != M_CTL) {
22222 		ipha = (ipha_t *)mp->b_rptr;
22223 	} else {
22224 		io = (ipsec_out_t *)mp->b_rptr;
22225 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22226 		ASSERT(zoneid == io->ipsec_out_zoneid);
22227 		ASSERT(zoneid != ALL_ZONES);
22228 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22229 		dst = ipha->ipha_dst;
22230 		/*
22231 		 * For the multicast case, ipsec_out carries conn_dontroute and
22232 		 * conn_multicast_loop as conn may not be available here. We
22233 		 * need this for multicast loopback and forwarding which is done
22234 		 * later in the code.
22235 		 */
22236 		if (CLASSD(dst)) {
22237 			conn_dontroute = io->ipsec_out_dontroute;
22238 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22239 			/*
22240 			 * If conn_dontroute is not set or conn_multicast_loop
22241 			 * is set, we need to do forwarding/loopback. For
22242 			 * datagrams from ip_wput_multicast, conn_dontroute is
22243 			 * set to B_TRUE and conn_multicast_loop is set to
22244 			 * B_FALSE so that we neither do forwarding nor
22245 			 * loopback.
22246 			 */
22247 			if (!conn_dontroute || conn_multicast_loop)
22248 				multicast_forward = B_TRUE;
22249 		}
22250 	}
22251 
22252 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22253 	    ire->ire_zoneid != ALL_ZONES) {
22254 		/*
22255 		 * When a zone sends a packet to another zone, we try to deliver
22256 		 * the packet under the same conditions as if the destination
22257 		 * was a real node on the network. To do so, we look for a
22258 		 * matching route in the forwarding table.
22259 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22260 		 * ip_newroute() does.
22261 		 * Note that IRE_LOCAL are special, since they are used
22262 		 * when the zoneid doesn't match in some cases. This means that
22263 		 * we need to handle ipha_src differently since ire_src_addr
22264 		 * belongs to the receiving zone instead of the sending zone.
22265 		 * When ip_restrict_interzone_loopback is set, then
22266 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22267 		 * for loopback between zones when the logical "Ethernet" would
22268 		 * have looped them back.
22269 		 */
22270 		ire_t *src_ire;
22271 
22272 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22273 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22274 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22275 		if (src_ire != NULL &&
22276 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22277 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22278 		    ire_local_same_lan(ire, src_ire))) {
22279 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22280 				ipha->ipha_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 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22287 			if (src_ire != NULL) {
22288 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22289 					ire_refrele(src_ire);
22290 					freemsg(mp);
22291 					return;
22292 				}
22293 				ire_refrele(src_ire);
22294 			}
22295 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22296 				/* Failed */
22297 				freemsg(mp);
22298 				return;
22299 			}
22300 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22301 			    ipst);
22302 			return;
22303 		}
22304 	}
22305 
22306 	if (mp->b_datap->db_type == M_CTL ||
22307 	    ipss->ipsec_outbound_v4_policy_present) {
22308 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22309 		    unspec_src, zoneid);
22310 		if (mp == NULL) {
22311 			ire_refrele(ire);
22312 			if (conn_outgoing_ill != NULL)
22313 				ill_refrele(conn_outgoing_ill);
22314 			return;
22315 		}
22316 		/*
22317 		 * Trusted Extensions supports all-zones interfaces, so
22318 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22319 		 * the global zone.
22320 		 */
22321 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22322 			io = (ipsec_out_t *)mp->b_rptr;
22323 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22324 			zoneid = io->ipsec_out_zoneid;
22325 		}
22326 	}
22327 
22328 	first_mp = mp;
22329 	ipsec_len = 0;
22330 
22331 	if (first_mp->b_datap->db_type == M_CTL) {
22332 		io = (ipsec_out_t *)first_mp->b_rptr;
22333 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22334 		mp = first_mp->b_cont;
22335 		ipsec_len = ipsec_out_extra_length(first_mp);
22336 		ASSERT(ipsec_len >= 0);
22337 		/* We already picked up the zoneid from the M_CTL above */
22338 		ASSERT(zoneid == io->ipsec_out_zoneid);
22339 		ASSERT(zoneid != ALL_ZONES);
22340 
22341 		/*
22342 		 * Drop M_CTL here if IPsec processing is not needed.
22343 		 * (Non-IPsec use of M_CTL extracted any information it
22344 		 * needed above).
22345 		 */
22346 		if (ipsec_len == 0) {
22347 			freeb(first_mp);
22348 			first_mp = mp;
22349 		}
22350 	}
22351 
22352 	/*
22353 	 * Fast path for ip_wput_ire
22354 	 */
22355 
22356 	ipha = (ipha_t *)mp->b_rptr;
22357 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22358 	dst = ipha->ipha_dst;
22359 
22360 	/*
22361 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22362 	 * if the socket is a SOCK_RAW type. The transport checksum should
22363 	 * be provided in the pre-built packet, so we don't need to compute it.
22364 	 * Also, other application set flags, like DF, should not be altered.
22365 	 * Other transport MUST pass down zero.
22366 	 */
22367 	ip_hdr_included = ipha->ipha_ident;
22368 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22369 
22370 	if (CLASSD(dst)) {
22371 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22372 		    ntohl(dst),
22373 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22374 		    ntohl(ire->ire_addr)));
22375 	}
22376 
22377 /* Macros to extract header fields from data already in registers */
22378 #ifdef	_BIG_ENDIAN
22379 #define	V_HLEN	(v_hlen_tos_len >> 24)
22380 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22381 #define	PROTO	(ttl_protocol & 0xFF)
22382 #else
22383 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22384 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22385 #define	PROTO	(ttl_protocol >> 8)
22386 #endif
22387 
22388 	orig_src = src = ipha->ipha_src;
22389 	/* (The loop back to "another" is explained down below.) */
22390 another:;
22391 	/*
22392 	 * Assign an ident value for this packet.  We assign idents on
22393 	 * a per destination basis out of the IRE.  There could be
22394 	 * other threads targeting the same destination, so we have to
22395 	 * arrange for a atomic increment.  Note that we use a 32-bit
22396 	 * atomic add because it has better performance than its
22397 	 * 16-bit sibling.
22398 	 *
22399 	 * If running in cluster mode and if the source address
22400 	 * belongs to a replicated service then vector through
22401 	 * cl_inet_ipident vector to allocate ip identifier
22402 	 * NOTE: This is a contract private interface with the
22403 	 * clustering group.
22404 	 */
22405 	clusterwide = 0;
22406 	if (cl_inet_ipident) {
22407 		ASSERT(cl_inet_isclusterwide);
22408 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22409 
22410 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22411 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22412 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22413 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22414 			    (uint8_t *)(uintptr_t)dst, NULL);
22415 			clusterwide = 1;
22416 		}
22417 	}
22418 	if (!clusterwide) {
22419 		ipha->ipha_ident =
22420 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22421 	}
22422 
22423 #ifndef _BIG_ENDIAN
22424 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22425 #endif
22426 
22427 	/*
22428 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22429 	 * This is needed to obey conn_unspec_src when packets go through
22430 	 * ip_newroute + arp.
22431 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22432 	 */
22433 	if (src == INADDR_ANY && !unspec_src) {
22434 		/*
22435 		 * Assign the appropriate source address from the IRE if none
22436 		 * was specified.
22437 		 */
22438 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22439 
22440 		src = ire->ire_src_addr;
22441 		if (connp == NULL) {
22442 			ip1dbg(("ip_wput_ire: no connp and no src "
22443 			    "address for dst 0x%x, using src 0x%x\n",
22444 			    ntohl(dst),
22445 			    ntohl(src)));
22446 		}
22447 		ipha->ipha_src = src;
22448 	}
22449 	stq = ire->ire_stq;
22450 
22451 	/*
22452 	 * We only allow ire chains for broadcasts since there will
22453 	 * be multiple IRE_CACHE entries for the same multicast
22454 	 * address (one per ipif).
22455 	 */
22456 	next_mp = NULL;
22457 
22458 	/* broadcast packet */
22459 	if (ire->ire_type == IRE_BROADCAST)
22460 		goto broadcast;
22461 
22462 	/* loopback ? */
22463 	if (stq == NULL)
22464 		goto nullstq;
22465 
22466 	/* The ill_index for outbound ILL */
22467 	ill_index = Q_TO_INDEX(stq);
22468 
22469 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22470 	ttl_protocol = ((uint16_t *)ipha)[4];
22471 
22472 	/* pseudo checksum (do it in parts for IP header checksum) */
22473 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22474 
22475 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22476 		queue_t *dev_q = stq->q_next;
22477 
22478 		/*
22479 		 * For DIRECT_CAPABLE, we do flow control at
22480 		 * the time of sending the packet. See
22481 		 * ILL_SEND_TX().
22482 		 */
22483 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22484 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22485 			goto blocked;
22486 
22487 		if ((PROTO == IPPROTO_UDP) &&
22488 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22489 			hlen = (V_HLEN & 0xF) << 2;
22490 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22491 			if (*up != 0) {
22492 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22493 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22494 				/* Software checksum? */
22495 				if (DB_CKSUMFLAGS(mp) == 0) {
22496 					IP_STAT(ipst, ip_out_sw_cksum);
22497 					IP_STAT_UPDATE(ipst,
22498 					    ip_udp_out_sw_cksum_bytes,
22499 					    LENGTH - hlen);
22500 				}
22501 			}
22502 		}
22503 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22504 		hlen = (V_HLEN & 0xF) << 2;
22505 		if (PROTO == IPPROTO_TCP) {
22506 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22507 			/*
22508 			 * The packet header is processed once and for all, even
22509 			 * in the multirouting case. We disable hardware
22510 			 * checksum if the packet is multirouted, as it will be
22511 			 * replicated via several interfaces, and not all of
22512 			 * them may have this capability.
22513 			 */
22514 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22515 			    LENGTH, max_frag, ipsec_len, cksum);
22516 			/* Software checksum? */
22517 			if (DB_CKSUMFLAGS(mp) == 0) {
22518 				IP_STAT(ipst, ip_out_sw_cksum);
22519 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22520 				    LENGTH - hlen);
22521 			}
22522 		} else {
22523 			sctp_hdr_t	*sctph;
22524 
22525 			ASSERT(PROTO == IPPROTO_SCTP);
22526 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22527 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22528 			/*
22529 			 * Zero out the checksum field to ensure proper
22530 			 * checksum calculation.
22531 			 */
22532 			sctph->sh_chksum = 0;
22533 #ifdef	DEBUG
22534 			if (!skip_sctp_cksum)
22535 #endif
22536 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22537 		}
22538 	}
22539 
22540 	/*
22541 	 * If this is a multicast packet and originated from ip_wput
22542 	 * we need to do loopback and forwarding checks. If it comes
22543 	 * from ip_wput_multicast, we SHOULD not do this.
22544 	 */
22545 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22546 
22547 	/* checksum */
22548 	cksum += ttl_protocol;
22549 
22550 	/* fragment the packet */
22551 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22552 		goto fragmentit;
22553 	/*
22554 	 * Don't use frag_flag if packet is pre-built or source
22555 	 * routed or if multicast (since multicast packets do
22556 	 * not solicit ICMP "packet too big" messages).
22557 	 */
22558 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22559 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22560 	    !ip_source_route_included(ipha)) &&
22561 	    !CLASSD(ipha->ipha_dst))
22562 		ipha->ipha_fragment_offset_and_flags |=
22563 		    htons(ire->ire_frag_flag);
22564 
22565 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22566 		/* calculate IP header checksum */
22567 		cksum += ipha->ipha_ident;
22568 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22569 		cksum += ipha->ipha_fragment_offset_and_flags;
22570 
22571 		/* IP options present */
22572 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22573 		if (hlen)
22574 			goto checksumoptions;
22575 
22576 		/* calculate hdr checksum */
22577 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22578 		cksum = ~(cksum + (cksum >> 16));
22579 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22580 	}
22581 	if (ipsec_len != 0) {
22582 		/*
22583 		 * We will do the rest of the processing after
22584 		 * we come back from IPsec in ip_wput_ipsec_out().
22585 		 */
22586 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22587 
22588 		io = (ipsec_out_t *)first_mp->b_rptr;
22589 		io->ipsec_out_ill_index =
22590 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22591 		ipsec_out_process(q, first_mp, ire, 0);
22592 		ire_refrele(ire);
22593 		if (conn_outgoing_ill != NULL)
22594 			ill_refrele(conn_outgoing_ill);
22595 		return;
22596 	}
22597 
22598 	/*
22599 	 * In most cases, the emission loop below is entered only
22600 	 * once. Only in the case where the ire holds the
22601 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22602 	 * flagged ires in the bucket, and send the packet
22603 	 * through all crossed RTF_MULTIRT routes.
22604 	 */
22605 	if (ire->ire_flags & RTF_MULTIRT) {
22606 		multirt_send = B_TRUE;
22607 	}
22608 	do {
22609 		if (multirt_send) {
22610 			irb_t *irb;
22611 			/*
22612 			 * We are in a multiple send case, need to get
22613 			 * the next ire and make a duplicate of the packet.
22614 			 * ire1 holds here the next ire to process in the
22615 			 * bucket. If multirouting is expected,
22616 			 * any non-RTF_MULTIRT ire that has the
22617 			 * right destination address is ignored.
22618 			 */
22619 			irb = ire->ire_bucket;
22620 			ASSERT(irb != NULL);
22621 
22622 			IRB_REFHOLD(irb);
22623 			for (ire1 = ire->ire_next;
22624 			    ire1 != NULL;
22625 			    ire1 = ire1->ire_next) {
22626 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22627 					continue;
22628 				if (ire1->ire_addr != ire->ire_addr)
22629 					continue;
22630 				if (ire1->ire_marks &
22631 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22632 					continue;
22633 
22634 				/* Got one */
22635 				IRE_REFHOLD(ire1);
22636 				break;
22637 			}
22638 			IRB_REFRELE(irb);
22639 
22640 			if (ire1 != NULL) {
22641 				next_mp = copyb(mp);
22642 				if ((next_mp == NULL) ||
22643 				    ((mp->b_cont != NULL) &&
22644 				    ((next_mp->b_cont =
22645 				    dupmsg(mp->b_cont)) == NULL))) {
22646 					freemsg(next_mp);
22647 					next_mp = NULL;
22648 					ire_refrele(ire1);
22649 					ire1 = NULL;
22650 				}
22651 			}
22652 
22653 			/* Last multiroute ire; don't loop anymore. */
22654 			if (ire1 == NULL) {
22655 				multirt_send = B_FALSE;
22656 			}
22657 		}
22658 
22659 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22660 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22661 		    mblk_t *, mp);
22662 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22663 		    ipst->ips_ipv4firewall_physical_out,
22664 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22665 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22666 
22667 		if (mp == NULL)
22668 			goto release_ire_and_ill;
22669 
22670 		if (ipst->ips_ipobs_enabled) {
22671 			zoneid_t szone;
22672 
22673 			/*
22674 			 * On the outbound path the destination zone will be
22675 			 * unknown as we're sending this packet out on the
22676 			 * wire.
22677 			 */
22678 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22679 			    ALL_ZONES);
22680 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22681 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22682 		}
22683 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22684 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22685 
22686 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22687 
22688 		if ((pktxmit_state == SEND_FAILED) ||
22689 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22690 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22691 			    "- packet dropped\n"));
22692 release_ire_and_ill:
22693 			ire_refrele(ire);
22694 			if (next_mp != NULL) {
22695 				freemsg(next_mp);
22696 				ire_refrele(ire1);
22697 			}
22698 			if (conn_outgoing_ill != NULL)
22699 				ill_refrele(conn_outgoing_ill);
22700 			return;
22701 		}
22702 
22703 		if (CLASSD(dst)) {
22704 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22705 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22706 			    LENGTH);
22707 		}
22708 
22709 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22710 		    "ip_wput_ire_end: q %p (%S)",
22711 		    q, "last copy out");
22712 		IRE_REFRELE(ire);
22713 
22714 		if (multirt_send) {
22715 			ASSERT(ire1);
22716 			/*
22717 			 * Proceed with the next RTF_MULTIRT ire,
22718 			 * Also set up the send-to queue accordingly.
22719 			 */
22720 			ire = ire1;
22721 			ire1 = NULL;
22722 			stq = ire->ire_stq;
22723 			mp = next_mp;
22724 			next_mp = NULL;
22725 			ipha = (ipha_t *)mp->b_rptr;
22726 			ill_index = Q_TO_INDEX(stq);
22727 			ill = (ill_t *)stq->q_ptr;
22728 		}
22729 	} while (multirt_send);
22730 	if (conn_outgoing_ill != NULL)
22731 		ill_refrele(conn_outgoing_ill);
22732 	return;
22733 
22734 	/*
22735 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22736 	 */
22737 broadcast:
22738 	{
22739 		/*
22740 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22741 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22742 		 * can be overridden stack-wide through the ip_broadcast_ttl
22743 		 * ndd tunable, or on a per-connection basis through the
22744 		 * IP_BROADCAST_TTL socket option.
22745 		 *
22746 		 * In the event that we are replying to incoming ICMP packets,
22747 		 * connp could be NULL.
22748 		 */
22749 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22750 		if (connp != NULL) {
22751 			if (connp->conn_dontroute)
22752 				ipha->ipha_ttl = 1;
22753 			else if (connp->conn_broadcast_ttl != 0)
22754 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22755 		}
22756 
22757 		/*
22758 		 * Note that we are not doing a IRB_REFHOLD here.
22759 		 * Actually we don't care if the list changes i.e
22760 		 * if somebody deletes an IRE from the list while
22761 		 * we drop the lock, the next time we come around
22762 		 * ire_next will be NULL and hence we won't send
22763 		 * out multiple copies which is fine.
22764 		 */
22765 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22766 		ire1 = ire->ire_next;
22767 		if (conn_outgoing_ill != NULL) {
22768 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22769 				ASSERT(ire1 == ire->ire_next);
22770 				if (ire1 != NULL && ire1->ire_addr == dst) {
22771 					ire_refrele(ire);
22772 					ire = ire1;
22773 					IRE_REFHOLD(ire);
22774 					ire1 = ire->ire_next;
22775 					continue;
22776 				}
22777 				rw_exit(&ire->ire_bucket->irb_lock);
22778 				/* Did not find a matching ill */
22779 				ip1dbg(("ip_wput_ire: broadcast with no "
22780 				    "matching IP_BOUND_IF ill %s dst %x\n",
22781 				    conn_outgoing_ill->ill_name, dst));
22782 				freemsg(first_mp);
22783 				if (ire != NULL)
22784 					ire_refrele(ire);
22785 				ill_refrele(conn_outgoing_ill);
22786 				return;
22787 			}
22788 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22789 			/*
22790 			 * If the next IRE has the same address and is not one
22791 			 * of the two copies that we need to send, try to see
22792 			 * whether this copy should be sent at all. This
22793 			 * assumes that we insert loopbacks first and then
22794 			 * non-loopbacks. This is acheived by inserting the
22795 			 * loopback always before non-loopback.
22796 			 * This is used to send a single copy of a broadcast
22797 			 * packet out all physical interfaces that have an
22798 			 * matching IRE_BROADCAST while also looping
22799 			 * back one copy (to ip_wput_local) for each
22800 			 * matching physical interface. However, we avoid
22801 			 * sending packets out different logical that match by
22802 			 * having ipif_up/ipif_down supress duplicate
22803 			 * IRE_BROADCASTS.
22804 			 *
22805 			 * This feature is currently used to get broadcasts
22806 			 * sent to multiple interfaces, when the broadcast
22807 			 * address being used applies to multiple interfaces.
22808 			 * For example, a whole net broadcast will be
22809 			 * replicated on every connected subnet of
22810 			 * the target net.
22811 			 *
22812 			 * Each zone has its own set of IRE_BROADCASTs, so that
22813 			 * we're able to distribute inbound packets to multiple
22814 			 * zones who share a broadcast address. We avoid looping
22815 			 * back outbound packets in different zones but on the
22816 			 * same ill, as the application would see duplicates.
22817 			 *
22818 			 * This logic assumes that ire_add_v4() groups the
22819 			 * IRE_BROADCAST entries so that those with the same
22820 			 * ire_addr are kept together.
22821 			 */
22822 			ire_ill = ire->ire_ipif->ipif_ill;
22823 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22824 				while (ire1 != NULL && ire1->ire_addr == dst) {
22825 					ire1_ill = ire1->ire_ipif->ipif_ill;
22826 					if (ire1_ill != ire_ill)
22827 						break;
22828 					ire1 = ire1->ire_next;
22829 				}
22830 			}
22831 		}
22832 		ASSERT(multirt_send == B_FALSE);
22833 		if (ire1 != NULL && ire1->ire_addr == dst) {
22834 			if ((ire->ire_flags & RTF_MULTIRT) &&
22835 			    (ire1->ire_flags & RTF_MULTIRT)) {
22836 				/*
22837 				 * We are in the multirouting case.
22838 				 * The message must be sent at least
22839 				 * on both ires. These ires have been
22840 				 * inserted AFTER the standard ones
22841 				 * in ip_rt_add(). There are thus no
22842 				 * other ire entries for the destination
22843 				 * address in the rest of the bucket
22844 				 * that do not have the RTF_MULTIRT
22845 				 * flag. We don't process a copy
22846 				 * of the message here. This will be
22847 				 * done in the final sending loop.
22848 				 */
22849 				multirt_send = B_TRUE;
22850 			} else {
22851 				next_mp = ip_copymsg(first_mp);
22852 				if (next_mp != NULL)
22853 					IRE_REFHOLD(ire1);
22854 			}
22855 		}
22856 		rw_exit(&ire->ire_bucket->irb_lock);
22857 	}
22858 
22859 	if (stq) {
22860 		/*
22861 		 * A non-NULL send-to queue means this packet is going
22862 		 * out of this machine.
22863 		 */
22864 		out_ill = (ill_t *)stq->q_ptr;
22865 
22866 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22867 		ttl_protocol = ((uint16_t *)ipha)[4];
22868 		/*
22869 		 * We accumulate the pseudo header checksum in cksum.
22870 		 * This is pretty hairy code, so watch close.  One
22871 		 * thing to keep in mind is that UDP and TCP have
22872 		 * stored their respective datagram lengths in their
22873 		 * checksum fields.  This lines things up real nice.
22874 		 */
22875 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22876 		    (src >> 16) + (src & 0xFFFF);
22877 		/*
22878 		 * We assume the udp checksum field contains the
22879 		 * length, so to compute the pseudo header checksum,
22880 		 * all we need is the protocol number and src/dst.
22881 		 */
22882 		/* Provide the checksums for UDP and TCP. */
22883 		if ((PROTO == IPPROTO_TCP) &&
22884 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22885 			/* hlen gets the number of uchar_ts in the IP header */
22886 			hlen = (V_HLEN & 0xF) << 2;
22887 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22888 			IP_STAT(ipst, ip_out_sw_cksum);
22889 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22890 			    LENGTH - hlen);
22891 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22892 		} else if (PROTO == IPPROTO_SCTP &&
22893 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22894 			sctp_hdr_t	*sctph;
22895 
22896 			hlen = (V_HLEN & 0xF) << 2;
22897 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22898 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22899 			sctph->sh_chksum = 0;
22900 #ifdef	DEBUG
22901 			if (!skip_sctp_cksum)
22902 #endif
22903 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22904 		} else {
22905 			queue_t	*dev_q = stq->q_next;
22906 
22907 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22908 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22909 blocked:
22910 				ipha->ipha_ident = ip_hdr_included;
22911 				/*
22912 				 * If we don't have a conn to apply
22913 				 * backpressure, free the message.
22914 				 * In the ire_send path, we don't know
22915 				 * the position to requeue the packet. Rather
22916 				 * than reorder packets, we just drop this
22917 				 * packet.
22918 				 */
22919 				if (ipst->ips_ip_output_queue &&
22920 				    connp != NULL &&
22921 				    caller != IRE_SEND) {
22922 					if (caller == IP_WSRV) {
22923 						idl_tx_list_t *idl_txl;
22924 
22925 						idl_txl =
22926 						    &ipst->ips_idl_tx_list[0];
22927 						connp->conn_did_putbq = 1;
22928 						(void) putbq(connp->conn_wq,
22929 						    first_mp);
22930 						conn_drain_insert(connp,
22931 						    idl_txl);
22932 						/*
22933 						 * This is the service thread,
22934 						 * and the queue is already
22935 						 * noenabled. The check for
22936 						 * canput and the putbq is not
22937 						 * atomic. So we need to check
22938 						 * again.
22939 						 */
22940 						if (canput(stq->q_next))
22941 							connp->conn_did_putbq
22942 							    = 0;
22943 						IP_STAT(ipst, ip_conn_flputbq);
22944 					} else {
22945 						/*
22946 						 * We are not the service proc.
22947 						 * ip_wsrv will be scheduled or
22948 						 * is already running.
22949 						 */
22950 
22951 						(void) putq(connp->conn_wq,
22952 						    first_mp);
22953 					}
22954 				} else {
22955 					out_ill = (ill_t *)stq->q_ptr;
22956 					BUMP_MIB(out_ill->ill_ip_mib,
22957 					    ipIfStatsOutDiscards);
22958 					freemsg(first_mp);
22959 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22960 					    "ip_wput_ire_end: q %p (%S)",
22961 					    q, "discard");
22962 				}
22963 				ire_refrele(ire);
22964 				if (next_mp) {
22965 					ire_refrele(ire1);
22966 					freemsg(next_mp);
22967 				}
22968 				if (conn_outgoing_ill != NULL)
22969 					ill_refrele(conn_outgoing_ill);
22970 				return;
22971 			}
22972 			if ((PROTO == IPPROTO_UDP) &&
22973 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22974 				/*
22975 				 * hlen gets the number of uchar_ts in the
22976 				 * IP header
22977 				 */
22978 				hlen = (V_HLEN & 0xF) << 2;
22979 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22980 				max_frag = ire->ire_max_frag;
22981 				if (*up != 0) {
22982 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22983 					    up, PROTO, hlen, LENGTH, max_frag,
22984 					    ipsec_len, cksum);
22985 					/* Software checksum? */
22986 					if (DB_CKSUMFLAGS(mp) == 0) {
22987 						IP_STAT(ipst, ip_out_sw_cksum);
22988 						IP_STAT_UPDATE(ipst,
22989 						    ip_udp_out_sw_cksum_bytes,
22990 						    LENGTH - hlen);
22991 					}
22992 				}
22993 			}
22994 		}
22995 		/*
22996 		 * Need to do this even when fragmenting. The local
22997 		 * loopback can be done without computing checksums
22998 		 * but forwarding out other interface must be done
22999 		 * after the IP checksum (and ULP checksums) have been
23000 		 * computed.
23001 		 *
23002 		 * NOTE : multicast_forward is set only if this packet
23003 		 * originated from ip_wput. For packets originating from
23004 		 * ip_wput_multicast, it is not set.
23005 		 */
23006 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23007 multi_loopback:
23008 			ip2dbg(("ip_wput: multicast, loop %d\n",
23009 			    conn_multicast_loop));
23010 
23011 			/*  Forget header checksum offload */
23012 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23013 
23014 			/*
23015 			 * Local loopback of multicasts?  Check the
23016 			 * ill.
23017 			 *
23018 			 * Note that the loopback function will not come
23019 			 * in through ip_rput - it will only do the
23020 			 * client fanout thus we need to do an mforward
23021 			 * as well.  The is different from the BSD
23022 			 * logic.
23023 			 */
23024 			if (ill != NULL) {
23025 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23026 				    ALL_ZONES) != NULL) {
23027 					/*
23028 					 * Pass along the virtual output q.
23029 					 * ip_wput_local() will distribute the
23030 					 * packet to all the matching zones,
23031 					 * except the sending zone when
23032 					 * IP_MULTICAST_LOOP is false.
23033 					 */
23034 					ip_multicast_loopback(q, ill, first_mp,
23035 					    conn_multicast_loop ? 0 :
23036 					    IP_FF_NO_MCAST_LOOP, zoneid);
23037 				}
23038 			}
23039 			if (ipha->ipha_ttl == 0) {
23040 				/*
23041 				 * 0 => only to this host i.e. we are
23042 				 * done. We are also done if this was the
23043 				 * loopback interface since it is sufficient
23044 				 * to loopback one copy of a multicast packet.
23045 				 */
23046 				freemsg(first_mp);
23047 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23048 				    "ip_wput_ire_end: q %p (%S)",
23049 				    q, "loopback");
23050 				ire_refrele(ire);
23051 				if (conn_outgoing_ill != NULL)
23052 					ill_refrele(conn_outgoing_ill);
23053 				return;
23054 			}
23055 			/*
23056 			 * ILLF_MULTICAST is checked in ip_newroute
23057 			 * i.e. we don't need to check it here since
23058 			 * all IRE_CACHEs come from ip_newroute.
23059 			 * For multicast traffic, SO_DONTROUTE is interpreted
23060 			 * to mean only send the packet out the interface
23061 			 * (optionally specified with IP_MULTICAST_IF)
23062 			 * and do not forward it out additional interfaces.
23063 			 * RSVP and the rsvp daemon is an example of a
23064 			 * protocol and user level process that
23065 			 * handles it's own routing. Hence, it uses the
23066 			 * SO_DONTROUTE option to accomplish this.
23067 			 */
23068 
23069 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23070 			    ill != NULL) {
23071 				/* Unconditionally redo the checksum */
23072 				ipha->ipha_hdr_checksum = 0;
23073 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23074 
23075 				/*
23076 				 * If this needs to go out secure, we need
23077 				 * to wait till we finish the IPsec
23078 				 * processing.
23079 				 */
23080 				if (ipsec_len == 0 &&
23081 				    ip_mforward(ill, ipha, mp)) {
23082 					freemsg(first_mp);
23083 					ip1dbg(("ip_wput: mforward failed\n"));
23084 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23085 					    "ip_wput_ire_end: q %p (%S)",
23086 					    q, "mforward failed");
23087 					ire_refrele(ire);
23088 					if (conn_outgoing_ill != NULL)
23089 						ill_refrele(conn_outgoing_ill);
23090 					return;
23091 				}
23092 			}
23093 		}
23094 		max_frag = ire->ire_max_frag;
23095 		cksum += ttl_protocol;
23096 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23097 			/* No fragmentation required for this one. */
23098 			/*
23099 			 * Don't use frag_flag if packet is pre-built or source
23100 			 * routed or if multicast (since multicast packets do
23101 			 * not solicit ICMP "packet too big" messages).
23102 			 */
23103 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23104 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23105 			    !ip_source_route_included(ipha)) &&
23106 			    !CLASSD(ipha->ipha_dst))
23107 				ipha->ipha_fragment_offset_and_flags |=
23108 				    htons(ire->ire_frag_flag);
23109 
23110 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23111 				/* Complete the IP header checksum. */
23112 				cksum += ipha->ipha_ident;
23113 				cksum += (v_hlen_tos_len >> 16)+
23114 				    (v_hlen_tos_len & 0xFFFF);
23115 				cksum += ipha->ipha_fragment_offset_and_flags;
23116 				hlen = (V_HLEN & 0xF) -
23117 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23118 				if (hlen) {
23119 checksumoptions:
23120 					/*
23121 					 * Account for the IP Options in the IP
23122 					 * header checksum.
23123 					 */
23124 					up = (uint16_t *)(rptr+
23125 					    IP_SIMPLE_HDR_LENGTH);
23126 					do {
23127 						cksum += up[0];
23128 						cksum += up[1];
23129 						up += 2;
23130 					} while (--hlen);
23131 				}
23132 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23133 				cksum = ~(cksum + (cksum >> 16));
23134 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23135 			}
23136 			if (ipsec_len != 0) {
23137 				ipsec_out_process(q, first_mp, ire, ill_index);
23138 				if (!next_mp) {
23139 					ire_refrele(ire);
23140 					if (conn_outgoing_ill != NULL)
23141 						ill_refrele(conn_outgoing_ill);
23142 					return;
23143 				}
23144 				goto next;
23145 			}
23146 
23147 			/*
23148 			 * multirt_send has already been handled
23149 			 * for broadcast, but not yet for multicast
23150 			 * or IP options.
23151 			 */
23152 			if (next_mp == NULL) {
23153 				if (ire->ire_flags & RTF_MULTIRT) {
23154 					multirt_send = B_TRUE;
23155 				}
23156 			}
23157 
23158 			/*
23159 			 * In most cases, the emission loop below is
23160 			 * entered only once. Only in the case where
23161 			 * the ire holds the RTF_MULTIRT flag, do we loop
23162 			 * to process all RTF_MULTIRT ires in the bucket,
23163 			 * and send the packet through all crossed
23164 			 * RTF_MULTIRT routes.
23165 			 */
23166 			do {
23167 				if (multirt_send) {
23168 					irb_t *irb;
23169 
23170 					irb = ire->ire_bucket;
23171 					ASSERT(irb != NULL);
23172 					/*
23173 					 * We are in a multiple send case,
23174 					 * need to get the next IRE and make
23175 					 * a duplicate of the packet.
23176 					 */
23177 					IRB_REFHOLD(irb);
23178 					for (ire1 = ire->ire_next;
23179 					    ire1 != NULL;
23180 					    ire1 = ire1->ire_next) {
23181 						if (!(ire1->ire_flags &
23182 						    RTF_MULTIRT))
23183 							continue;
23184 
23185 						if (ire1->ire_addr !=
23186 						    ire->ire_addr)
23187 							continue;
23188 
23189 						if (ire1->ire_marks &
23190 						    (IRE_MARK_CONDEMNED |
23191 						    IRE_MARK_TESTHIDDEN))
23192 							continue;
23193 
23194 						/* Got one */
23195 						IRE_REFHOLD(ire1);
23196 						break;
23197 					}
23198 					IRB_REFRELE(irb);
23199 
23200 					if (ire1 != NULL) {
23201 						next_mp = copyb(mp);
23202 						if ((next_mp == NULL) ||
23203 						    ((mp->b_cont != NULL) &&
23204 						    ((next_mp->b_cont =
23205 						    dupmsg(mp->b_cont))
23206 						    == NULL))) {
23207 							freemsg(next_mp);
23208 							next_mp = NULL;
23209 							ire_refrele(ire1);
23210 							ire1 = NULL;
23211 						}
23212 					}
23213 
23214 					/*
23215 					 * Last multiroute ire; don't loop
23216 					 * anymore. The emission is over
23217 					 * and next_mp is NULL.
23218 					 */
23219 					if (ire1 == NULL) {
23220 						multirt_send = B_FALSE;
23221 					}
23222 				}
23223 
23224 				out_ill = ire_to_ill(ire);
23225 				DTRACE_PROBE4(ip4__physical__out__start,
23226 				    ill_t *, NULL,
23227 				    ill_t *, out_ill,
23228 				    ipha_t *, ipha, mblk_t *, mp);
23229 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23230 				    ipst->ips_ipv4firewall_physical_out,
23231 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23232 				DTRACE_PROBE1(ip4__physical__out__end,
23233 				    mblk_t *, mp);
23234 				if (mp == NULL)
23235 					goto release_ire_and_ill_2;
23236 
23237 				ASSERT(ipsec_len == 0);
23238 				mp->b_prev =
23239 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23240 				DTRACE_PROBE2(ip__xmit__2,
23241 				    mblk_t *, mp, ire_t *, ire);
23242 				pktxmit_state = ip_xmit_v4(mp, ire,
23243 				    NULL, B_TRUE, connp);
23244 				if ((pktxmit_state == SEND_FAILED) ||
23245 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23246 release_ire_and_ill_2:
23247 					if (next_mp) {
23248 						freemsg(next_mp);
23249 						ire_refrele(ire1);
23250 					}
23251 					ire_refrele(ire);
23252 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23253 					    "ip_wput_ire_end: q %p (%S)",
23254 					    q, "discard MDATA");
23255 					if (conn_outgoing_ill != NULL)
23256 						ill_refrele(conn_outgoing_ill);
23257 					return;
23258 				}
23259 
23260 				if (CLASSD(dst)) {
23261 					BUMP_MIB(out_ill->ill_ip_mib,
23262 					    ipIfStatsHCOutMcastPkts);
23263 					UPDATE_MIB(out_ill->ill_ip_mib,
23264 					    ipIfStatsHCOutMcastOctets,
23265 					    LENGTH);
23266 				} else if (ire->ire_type == IRE_BROADCAST) {
23267 					BUMP_MIB(out_ill->ill_ip_mib,
23268 					    ipIfStatsHCOutBcastPkts);
23269 				}
23270 
23271 				if (multirt_send) {
23272 					/*
23273 					 * We are in a multiple send case,
23274 					 * need to re-enter the sending loop
23275 					 * using the next ire.
23276 					 */
23277 					ire_refrele(ire);
23278 					ire = ire1;
23279 					stq = ire->ire_stq;
23280 					mp = next_mp;
23281 					next_mp = NULL;
23282 					ipha = (ipha_t *)mp->b_rptr;
23283 					ill_index = Q_TO_INDEX(stq);
23284 				}
23285 			} while (multirt_send);
23286 
23287 			if (!next_mp) {
23288 				/*
23289 				 * Last copy going out (the ultra-common
23290 				 * case).  Note that we intentionally replicate
23291 				 * the putnext rather than calling it before
23292 				 * the next_mp check in hopes of a little
23293 				 * tail-call action out of the compiler.
23294 				 */
23295 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23296 				    "ip_wput_ire_end: q %p (%S)",
23297 				    q, "last copy out(1)");
23298 				ire_refrele(ire);
23299 				if (conn_outgoing_ill != NULL)
23300 					ill_refrele(conn_outgoing_ill);
23301 				return;
23302 			}
23303 			/* More copies going out below. */
23304 		} else {
23305 			int offset;
23306 fragmentit:
23307 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23308 			/*
23309 			 * If this would generate a icmp_frag_needed message,
23310 			 * we need to handle it before we do the IPsec
23311 			 * processing. Otherwise, we need to strip the IPsec
23312 			 * headers before we send up the message to the ULPs
23313 			 * which becomes messy and difficult.
23314 			 */
23315 			if (ipsec_len != 0) {
23316 				if ((max_frag < (unsigned int)(LENGTH +
23317 				    ipsec_len)) && (offset & IPH_DF)) {
23318 					out_ill = (ill_t *)stq->q_ptr;
23319 					BUMP_MIB(out_ill->ill_ip_mib,
23320 					    ipIfStatsOutFragFails);
23321 					BUMP_MIB(out_ill->ill_ip_mib,
23322 					    ipIfStatsOutFragReqds);
23323 					ipha->ipha_hdr_checksum = 0;
23324 					ipha->ipha_hdr_checksum =
23325 					    (uint16_t)ip_csum_hdr(ipha);
23326 					icmp_frag_needed(ire->ire_stq, first_mp,
23327 					    max_frag, zoneid, ipst);
23328 					if (!next_mp) {
23329 						ire_refrele(ire);
23330 						if (conn_outgoing_ill != NULL) {
23331 							ill_refrele(
23332 							    conn_outgoing_ill);
23333 						}
23334 						return;
23335 					}
23336 				} else {
23337 					/*
23338 					 * This won't cause a icmp_frag_needed
23339 					 * message. to be generated. Send it on
23340 					 * the wire. Note that this could still
23341 					 * cause fragmentation and all we
23342 					 * do is the generation of the message
23343 					 * to the ULP if needed before IPsec.
23344 					 */
23345 					if (!next_mp) {
23346 						ipsec_out_process(q, first_mp,
23347 						    ire, ill_index);
23348 						TRACE_2(TR_FAC_IP,
23349 						    TR_IP_WPUT_IRE_END,
23350 						    "ip_wput_ire_end: q %p "
23351 						    "(%S)", q,
23352 						    "last ipsec_out_process");
23353 						ire_refrele(ire);
23354 						if (conn_outgoing_ill != NULL) {
23355 							ill_refrele(
23356 							    conn_outgoing_ill);
23357 						}
23358 						return;
23359 					}
23360 					ipsec_out_process(q, first_mp,
23361 					    ire, ill_index);
23362 				}
23363 			} else {
23364 				/*
23365 				 * Initiate IPPF processing. For
23366 				 * fragmentable packets we finish
23367 				 * all QOS packet processing before
23368 				 * calling:
23369 				 * ip_wput_ire_fragmentit->ip_wput_frag
23370 				 */
23371 
23372 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23373 					ip_process(IPP_LOCAL_OUT, &mp,
23374 					    ill_index);
23375 					if (mp == NULL) {
23376 						out_ill = (ill_t *)stq->q_ptr;
23377 						BUMP_MIB(out_ill->ill_ip_mib,
23378 						    ipIfStatsOutDiscards);
23379 						if (next_mp != NULL) {
23380 							freemsg(next_mp);
23381 							ire_refrele(ire1);
23382 						}
23383 						ire_refrele(ire);
23384 						TRACE_2(TR_FAC_IP,
23385 						    TR_IP_WPUT_IRE_END,
23386 						    "ip_wput_ire: q %p (%S)",
23387 						    q, "discard MDATA");
23388 						if (conn_outgoing_ill != NULL) {
23389 							ill_refrele(
23390 							    conn_outgoing_ill);
23391 						}
23392 						return;
23393 					}
23394 				}
23395 				if (!next_mp) {
23396 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23397 					    "ip_wput_ire_end: q %p (%S)",
23398 					    q, "last fragmentation");
23399 					ip_wput_ire_fragmentit(mp, ire,
23400 					    zoneid, ipst, connp);
23401 					ire_refrele(ire);
23402 					if (conn_outgoing_ill != NULL)
23403 						ill_refrele(conn_outgoing_ill);
23404 					return;
23405 				}
23406 				ip_wput_ire_fragmentit(mp, ire,
23407 				    zoneid, ipst, connp);
23408 			}
23409 		}
23410 	} else {
23411 nullstq:
23412 		/* A NULL stq means the destination address is local. */
23413 		UPDATE_OB_PKT_COUNT(ire);
23414 		ire->ire_last_used_time = lbolt;
23415 		ASSERT(ire->ire_ipif != NULL);
23416 		if (!next_mp) {
23417 			/*
23418 			 * Is there an "in" and "out" for traffic local
23419 			 * to a host (loopback)?  The code in Solaris doesn't
23420 			 * explicitly draw a line in its code for in vs out,
23421 			 * so we've had to draw a line in the sand: ip_wput_ire
23422 			 * is considered to be the "output" side and
23423 			 * ip_wput_local to be the "input" side.
23424 			 */
23425 			out_ill = ire_to_ill(ire);
23426 
23427 			/*
23428 			 * DTrace this as ip:::send.  A blocked packet will
23429 			 * fire the send probe, but not the receive probe.
23430 			 */
23431 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23432 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23433 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23434 
23435 			DTRACE_PROBE4(ip4__loopback__out__start,
23436 			    ill_t *, NULL, ill_t *, out_ill,
23437 			    ipha_t *, ipha, mblk_t *, first_mp);
23438 
23439 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23440 			    ipst->ips_ipv4firewall_loopback_out,
23441 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23442 
23443 			DTRACE_PROBE1(ip4__loopback__out_end,
23444 			    mblk_t *, first_mp);
23445 
23446 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23447 			    "ip_wput_ire_end: q %p (%S)",
23448 			    q, "local address");
23449 
23450 			if (first_mp != NULL)
23451 				ip_wput_local(q, out_ill, ipha,
23452 				    first_mp, ire, 0, ire->ire_zoneid);
23453 			ire_refrele(ire);
23454 			if (conn_outgoing_ill != NULL)
23455 				ill_refrele(conn_outgoing_ill);
23456 			return;
23457 		}
23458 
23459 		out_ill = ire_to_ill(ire);
23460 
23461 		/*
23462 		 * DTrace this as ip:::send.  A blocked packet will fire the
23463 		 * send probe, but not the receive probe.
23464 		 */
23465 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23466 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23467 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23468 
23469 		DTRACE_PROBE4(ip4__loopback__out__start,
23470 		    ill_t *, NULL, ill_t *, out_ill,
23471 		    ipha_t *, ipha, mblk_t *, first_mp);
23472 
23473 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23474 		    ipst->ips_ipv4firewall_loopback_out,
23475 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23476 
23477 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23478 
23479 		if (first_mp != NULL)
23480 			ip_wput_local(q, out_ill, ipha,
23481 			    first_mp, ire, 0, ire->ire_zoneid);
23482 	}
23483 next:
23484 	/*
23485 	 * More copies going out to additional interfaces.
23486 	 * ire1 has already been held. We don't need the
23487 	 * "ire" anymore.
23488 	 */
23489 	ire_refrele(ire);
23490 	ire = ire1;
23491 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23492 	mp = next_mp;
23493 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23494 	ill = ire_to_ill(ire);
23495 	first_mp = mp;
23496 	if (ipsec_len != 0) {
23497 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23498 		mp = mp->b_cont;
23499 	}
23500 	dst = ire->ire_addr;
23501 	ipha = (ipha_t *)mp->b_rptr;
23502 	/*
23503 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23504 	 * Restore ipha_ident "no checksum" flag.
23505 	 */
23506 	src = orig_src;
23507 	ipha->ipha_ident = ip_hdr_included;
23508 	goto another;
23509 
23510 #undef	rptr
23511 #undef	Q_TO_INDEX
23512 }
23513 
23514 /*
23515  * Routine to allocate a message that is used to notify the ULP about MDT.
23516  * The caller may provide a pointer to the link-layer MDT capabilities,
23517  * or NULL if MDT is to be disabled on the stream.
23518  */
23519 mblk_t *
23520 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23521 {
23522 	mblk_t *mp;
23523 	ip_mdt_info_t *mdti;
23524 	ill_mdt_capab_t *idst;
23525 
23526 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23527 		DB_TYPE(mp) = M_CTL;
23528 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23529 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23530 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23531 		idst = &(mdti->mdt_capab);
23532 
23533 		/*
23534 		 * If the caller provides us with the capability, copy
23535 		 * it over into our notification message; otherwise
23536 		 * we zero out the capability portion.
23537 		 */
23538 		if (isrc != NULL)
23539 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23540 		else
23541 			bzero((caddr_t)idst, sizeof (*idst));
23542 	}
23543 	return (mp);
23544 }
23545 
23546 /*
23547  * Routine which determines whether MDT can be enabled on the destination
23548  * IRE and IPC combination, and if so, allocates and returns the MDT
23549  * notification mblk that may be used by ULP.  We also check if we need to
23550  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23551  * MDT usage in the past have been lifted.  This gets called during IP
23552  * and ULP binding.
23553  */
23554 mblk_t *
23555 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23556     ill_mdt_capab_t *mdt_cap)
23557 {
23558 	mblk_t *mp;
23559 	boolean_t rc = B_FALSE;
23560 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23561 
23562 	ASSERT(dst_ire != NULL);
23563 	ASSERT(connp != NULL);
23564 	ASSERT(mdt_cap != NULL);
23565 
23566 	/*
23567 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23568 	 * Multidata, which is handled in tcp_multisend().  This
23569 	 * is the reason why we do all these checks here, to ensure
23570 	 * that we don't enable Multidata for the cases which we
23571 	 * can't handle at the moment.
23572 	 */
23573 	do {
23574 		/* Only do TCP at the moment */
23575 		if (connp->conn_ulp != IPPROTO_TCP)
23576 			break;
23577 
23578 		/*
23579 		 * IPsec outbound policy present?  Note that we get here
23580 		 * after calling ipsec_conn_cache_policy() where the global
23581 		 * policy checking is performed.  conn_latch will be
23582 		 * non-NULL as long as there's a policy defined,
23583 		 * i.e. conn_out_enforce_policy may be NULL in such case
23584 		 * when the connection is non-secure, and hence we check
23585 		 * further if the latch refers to an outbound policy.
23586 		 */
23587 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23588 			break;
23589 
23590 		/* CGTP (multiroute) is enabled? */
23591 		if (dst_ire->ire_flags & RTF_MULTIRT)
23592 			break;
23593 
23594 		/* Outbound IPQoS enabled? */
23595 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23596 			/*
23597 			 * In this case, we disable MDT for this and all
23598 			 * future connections going over the interface.
23599 			 */
23600 			mdt_cap->ill_mdt_on = 0;
23601 			break;
23602 		}
23603 
23604 		/* socket option(s) present? */
23605 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23606 			break;
23607 
23608 		rc = B_TRUE;
23609 	/* CONSTCOND */
23610 	} while (0);
23611 
23612 	/* Remember the result */
23613 	connp->conn_mdt_ok = rc;
23614 
23615 	if (!rc)
23616 		return (NULL);
23617 	else if (!mdt_cap->ill_mdt_on) {
23618 		/*
23619 		 * If MDT has been previously turned off in the past, and we
23620 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23621 		 * then enable it for this interface.
23622 		 */
23623 		mdt_cap->ill_mdt_on = 1;
23624 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23625 		    "interface %s\n", ill_name));
23626 	}
23627 
23628 	/* Allocate the MDT info mblk */
23629 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23630 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23631 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23632 		return (NULL);
23633 	}
23634 	return (mp);
23635 }
23636 
23637 /*
23638  * Routine to allocate a message that is used to notify the ULP about LSO.
23639  * The caller may provide a pointer to the link-layer LSO capabilities,
23640  * or NULL if LSO is to be disabled on the stream.
23641  */
23642 mblk_t *
23643 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23644 {
23645 	mblk_t *mp;
23646 	ip_lso_info_t *lsoi;
23647 	ill_lso_capab_t *idst;
23648 
23649 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23650 		DB_TYPE(mp) = M_CTL;
23651 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23652 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23653 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23654 		idst = &(lsoi->lso_capab);
23655 
23656 		/*
23657 		 * If the caller provides us with the capability, copy
23658 		 * it over into our notification message; otherwise
23659 		 * we zero out the capability portion.
23660 		 */
23661 		if (isrc != NULL)
23662 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23663 		else
23664 			bzero((caddr_t)idst, sizeof (*idst));
23665 	}
23666 	return (mp);
23667 }
23668 
23669 /*
23670  * Routine which determines whether LSO can be enabled on the destination
23671  * IRE and IPC combination, and if so, allocates and returns the LSO
23672  * notification mblk that may be used by ULP.  We also check if we need to
23673  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23674  * LSO usage in the past have been lifted.  This gets called during IP
23675  * and ULP binding.
23676  */
23677 mblk_t *
23678 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23679     ill_lso_capab_t *lso_cap)
23680 {
23681 	mblk_t *mp;
23682 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23683 
23684 	ASSERT(dst_ire != NULL);
23685 	ASSERT(connp != NULL);
23686 	ASSERT(lso_cap != NULL);
23687 
23688 	connp->conn_lso_ok = B_TRUE;
23689 
23690 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23691 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23692 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23693 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23694 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23695 		connp->conn_lso_ok = B_FALSE;
23696 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23697 			/*
23698 			 * Disable LSO for this and all future connections going
23699 			 * over the interface.
23700 			 */
23701 			lso_cap->ill_lso_on = 0;
23702 		}
23703 	}
23704 
23705 	if (!connp->conn_lso_ok)
23706 		return (NULL);
23707 	else if (!lso_cap->ill_lso_on) {
23708 		/*
23709 		 * If LSO has been previously turned off in the past, and we
23710 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23711 		 * then enable it for this interface.
23712 		 */
23713 		lso_cap->ill_lso_on = 1;
23714 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23715 		    ill_name));
23716 	}
23717 
23718 	/* Allocate the LSO info mblk */
23719 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23720 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23721 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23722 
23723 	return (mp);
23724 }
23725 
23726 /*
23727  * Create destination address attribute, and fill it with the physical
23728  * destination address and SAP taken from the template DL_UNITDATA_REQ
23729  * message block.
23730  */
23731 boolean_t
23732 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23733 {
23734 	dl_unitdata_req_t *dlurp;
23735 	pattr_t *pa;
23736 	pattrinfo_t pa_info;
23737 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23738 	uint_t das_len, das_off;
23739 
23740 	ASSERT(dlmp != NULL);
23741 
23742 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23743 	das_len = dlurp->dl_dest_addr_length;
23744 	das_off = dlurp->dl_dest_addr_offset;
23745 
23746 	pa_info.type = PATTR_DSTADDRSAP;
23747 	pa_info.len = sizeof (**das) + das_len - 1;
23748 
23749 	/* create and associate the attribute */
23750 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23751 	if (pa != NULL) {
23752 		ASSERT(*das != NULL);
23753 		(*das)->addr_is_group = 0;
23754 		(*das)->addr_len = (uint8_t)das_len;
23755 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23756 	}
23757 
23758 	return (pa != NULL);
23759 }
23760 
23761 /*
23762  * Create hardware checksum attribute and fill it with the values passed.
23763  */
23764 boolean_t
23765 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23766     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23767 {
23768 	pattr_t *pa;
23769 	pattrinfo_t pa_info;
23770 
23771 	ASSERT(mmd != NULL);
23772 
23773 	pa_info.type = PATTR_HCKSUM;
23774 	pa_info.len = sizeof (pattr_hcksum_t);
23775 
23776 	/* create and associate the attribute */
23777 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23778 	if (pa != NULL) {
23779 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23780 
23781 		hck->hcksum_start_offset = start_offset;
23782 		hck->hcksum_stuff_offset = stuff_offset;
23783 		hck->hcksum_end_offset = end_offset;
23784 		hck->hcksum_flags = flags;
23785 	}
23786 	return (pa != NULL);
23787 }
23788 
23789 /*
23790  * Create zerocopy attribute and fill it with the specified flags
23791  */
23792 boolean_t
23793 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23794 {
23795 	pattr_t *pa;
23796 	pattrinfo_t pa_info;
23797 
23798 	ASSERT(mmd != NULL);
23799 	pa_info.type = PATTR_ZCOPY;
23800 	pa_info.len = sizeof (pattr_zcopy_t);
23801 
23802 	/* create and associate the attribute */
23803 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23804 	if (pa != NULL) {
23805 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23806 
23807 		zcopy->zcopy_flags = flags;
23808 	}
23809 	return (pa != NULL);
23810 }
23811 
23812 /*
23813  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23814  * block chain. We could rewrite to handle arbitrary message block chains but
23815  * that would make the code complicated and slow. Right now there three
23816  * restrictions:
23817  *
23818  *   1. The first message block must contain the complete IP header and
23819  *	at least 1 byte of payload data.
23820  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23821  *	so that we can use a single Multidata message.
23822  *   3. No frag must be distributed over two or more message blocks so
23823  *	that we don't need more than two packet descriptors per frag.
23824  *
23825  * The above restrictions allow us to support userland applications (which
23826  * will send down a single message block) and NFS over UDP (which will
23827  * send down a chain of at most three message blocks).
23828  *
23829  * We also don't use MDT for payloads with less than or equal to
23830  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23831  */
23832 boolean_t
23833 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23834 {
23835 	int	blocks;
23836 	ssize_t	total, missing, size;
23837 
23838 	ASSERT(mp != NULL);
23839 	ASSERT(hdr_len > 0);
23840 
23841 	size = MBLKL(mp) - hdr_len;
23842 	if (size <= 0)
23843 		return (B_FALSE);
23844 
23845 	/* The first mblk contains the header and some payload. */
23846 	blocks = 1;
23847 	total = size;
23848 	size %= len;
23849 	missing = (size == 0) ? 0 : (len - size);
23850 	mp = mp->b_cont;
23851 
23852 	while (mp != NULL) {
23853 		/*
23854 		 * Give up if we encounter a zero length message block.
23855 		 * In practice, this should rarely happen and therefore
23856 		 * not worth the trouble of freeing and re-linking the
23857 		 * mblk from the chain to handle such case.
23858 		 */
23859 		if ((size = MBLKL(mp)) == 0)
23860 			return (B_FALSE);
23861 
23862 		/* Too many payload buffers for a single Multidata message? */
23863 		if (++blocks > MULTIDATA_MAX_PBUFS)
23864 			return (B_FALSE);
23865 
23866 		total += size;
23867 		/* Is a frag distributed over two or more message blocks? */
23868 		if (missing > size)
23869 			return (B_FALSE);
23870 		size -= missing;
23871 
23872 		size %= len;
23873 		missing = (size == 0) ? 0 : (len - size);
23874 
23875 		mp = mp->b_cont;
23876 	}
23877 
23878 	return (total > ip_wput_frag_mdt_min);
23879 }
23880 
23881 /*
23882  * Outbound IPv4 fragmentation routine using MDT.
23883  */
23884 static void
23885 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23886     uint32_t frag_flag, int offset)
23887 {
23888 	ipha_t		*ipha_orig;
23889 	int		i1, ip_data_end;
23890 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23891 	mblk_t		*hdr_mp, *md_mp = NULL;
23892 	unsigned char	*hdr_ptr, *pld_ptr;
23893 	multidata_t	*mmd;
23894 	ip_pdescinfo_t	pdi;
23895 	ill_t		*ill;
23896 	ip_stack_t	*ipst = ire->ire_ipst;
23897 
23898 	ASSERT(DB_TYPE(mp) == M_DATA);
23899 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23900 
23901 	ill = ire_to_ill(ire);
23902 	ASSERT(ill != NULL);
23903 
23904 	ipha_orig = (ipha_t *)mp->b_rptr;
23905 	mp->b_rptr += sizeof (ipha_t);
23906 
23907 	/* Calculate how many packets we will send out */
23908 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23909 	pkts = (i1 + len - 1) / len;
23910 	ASSERT(pkts > 1);
23911 
23912 	/* Allocate a message block which will hold all the IP Headers. */
23913 	wroff = ipst->ips_ip_wroff_extra;
23914 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23915 
23916 	i1 = pkts * hdr_chunk_len;
23917 	/*
23918 	 * Create the header buffer, Multidata and destination address
23919 	 * and SAP attribute that should be associated with it.
23920 	 */
23921 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23922 	    ((hdr_mp->b_wptr += i1),
23923 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23924 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23925 		freemsg(mp);
23926 		if (md_mp == NULL) {
23927 			freemsg(hdr_mp);
23928 		} else {
23929 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23930 			freemsg(md_mp);
23931 		}
23932 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23933 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23934 		return;
23935 	}
23936 	IP_STAT(ipst, ip_frag_mdt_allocd);
23937 
23938 	/*
23939 	 * Add a payload buffer to the Multidata; this operation must not
23940 	 * fail, or otherwise our logic in this routine is broken.  There
23941 	 * is no memory allocation done by the routine, so any returned
23942 	 * failure simply tells us that we've done something wrong.
23943 	 *
23944 	 * A failure tells us that either we're adding the same payload
23945 	 * buffer more than once, or we're trying to add more buffers than
23946 	 * allowed.  None of the above cases should happen, and we panic
23947 	 * because either there's horrible heap corruption, and/or
23948 	 * programming mistake.
23949 	 */
23950 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23951 		goto pbuf_panic;
23952 
23953 	hdr_ptr = hdr_mp->b_rptr;
23954 	pld_ptr = mp->b_rptr;
23955 
23956 	/* Establish the ending byte offset, based on the starting offset. */
23957 	offset <<= 3;
23958 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23959 	    IP_SIMPLE_HDR_LENGTH;
23960 
23961 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23962 
23963 	while (pld_ptr < mp->b_wptr) {
23964 		ipha_t		*ipha;
23965 		uint16_t	offset_and_flags;
23966 		uint16_t	ip_len;
23967 		int		error;
23968 
23969 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23970 		ipha = (ipha_t *)(hdr_ptr + wroff);
23971 		ASSERT(OK_32PTR(ipha));
23972 		*ipha = *ipha_orig;
23973 
23974 		if (ip_data_end - offset > len) {
23975 			offset_and_flags = IPH_MF;
23976 		} else {
23977 			/*
23978 			 * Last frag. Set len to the length of this last piece.
23979 			 */
23980 			len = ip_data_end - offset;
23981 			/* A frag of a frag might have IPH_MF non-zero */
23982 			offset_and_flags =
23983 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23984 			    IPH_MF;
23985 		}
23986 		offset_and_flags |= (uint16_t)(offset >> 3);
23987 		offset_and_flags |= (uint16_t)frag_flag;
23988 		/* Store the offset and flags in the IP header. */
23989 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23990 
23991 		/* Store the length in the IP header. */
23992 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23993 		ipha->ipha_length = htons(ip_len);
23994 
23995 		/*
23996 		 * Set the IP header checksum.  Note that mp is just
23997 		 * the header, so this is easy to pass to ip_csum.
23998 		 */
23999 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24000 
24001 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24002 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24003 		    NULL, int, 0);
24004 
24005 		/*
24006 		 * Record offset and size of header and data of the next packet
24007 		 * in the multidata message.
24008 		 */
24009 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24010 		PDESC_PLD_INIT(&pdi);
24011 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24012 		ASSERT(i1 > 0);
24013 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24014 		if (i1 == len) {
24015 			pld_ptr += len;
24016 		} else {
24017 			i1 = len - i1;
24018 			mp = mp->b_cont;
24019 			ASSERT(mp != NULL);
24020 			ASSERT(MBLKL(mp) >= i1);
24021 			/*
24022 			 * Attach the next payload message block to the
24023 			 * multidata message.
24024 			 */
24025 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24026 				goto pbuf_panic;
24027 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24028 			pld_ptr = mp->b_rptr + i1;
24029 		}
24030 
24031 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24032 		    KM_NOSLEEP)) == NULL) {
24033 			/*
24034 			 * Any failure other than ENOMEM indicates that we
24035 			 * have passed in invalid pdesc info or parameters
24036 			 * to mmd_addpdesc, which must not happen.
24037 			 *
24038 			 * EINVAL is a result of failure on boundary checks
24039 			 * against the pdesc info contents.  It should not
24040 			 * happen, and we panic because either there's
24041 			 * horrible heap corruption, and/or programming
24042 			 * mistake.
24043 			 */
24044 			if (error != ENOMEM) {
24045 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24046 				    "pdesc logic error detected for "
24047 				    "mmd %p pinfo %p (%d)\n",
24048 				    (void *)mmd, (void *)&pdi, error);
24049 				/* NOTREACHED */
24050 			}
24051 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24052 			/* Free unattached payload message blocks as well */
24053 			md_mp->b_cont = mp->b_cont;
24054 			goto free_mmd;
24055 		}
24056 
24057 		/* Advance fragment offset. */
24058 		offset += len;
24059 
24060 		/* Advance to location for next header in the buffer. */
24061 		hdr_ptr += hdr_chunk_len;
24062 
24063 		/* Did we reach the next payload message block? */
24064 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24065 			mp = mp->b_cont;
24066 			/*
24067 			 * Attach the next message block with payload
24068 			 * data to the multidata message.
24069 			 */
24070 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24071 				goto pbuf_panic;
24072 			pld_ptr = mp->b_rptr;
24073 		}
24074 	}
24075 
24076 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24077 	ASSERT(mp->b_wptr == pld_ptr);
24078 
24079 	/* Update IP statistics */
24080 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24081 
24082 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24083 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24084 
24085 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24086 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24087 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24088 
24089 	if (pkt_type == OB_PKT) {
24090 		ire->ire_ob_pkt_count += pkts;
24091 		if (ire->ire_ipif != NULL)
24092 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24093 	} else {
24094 		/* The type is IB_PKT in the forwarding path. */
24095 		ire->ire_ib_pkt_count += pkts;
24096 		ASSERT(!IRE_IS_LOCAL(ire));
24097 		if (ire->ire_type & IRE_BROADCAST) {
24098 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24099 		} else {
24100 			UPDATE_MIB(ill->ill_ip_mib,
24101 			    ipIfStatsHCOutForwDatagrams, pkts);
24102 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24103 		}
24104 	}
24105 	ire->ire_last_used_time = lbolt;
24106 	/* Send it down */
24107 	putnext(ire->ire_stq, md_mp);
24108 	return;
24109 
24110 pbuf_panic:
24111 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24112 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24113 	    pbuf_idx);
24114 	/* NOTREACHED */
24115 }
24116 
24117 /*
24118  * Outbound IP fragmentation routine.
24119  *
24120  * NOTE : This routine does not ire_refrele the ire that is passed in
24121  * as the argument.
24122  */
24123 static void
24124 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24125     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24126 {
24127 	int		i1;
24128 	mblk_t		*ll_hdr_mp;
24129 	int 		ll_hdr_len;
24130 	int		hdr_len;
24131 	mblk_t		*hdr_mp;
24132 	ipha_t		*ipha;
24133 	int		ip_data_end;
24134 	int		len;
24135 	mblk_t		*mp = mp_orig, *mp1;
24136 	int		offset;
24137 	queue_t		*q;
24138 	uint32_t	v_hlen_tos_len;
24139 	mblk_t		*first_mp;
24140 	boolean_t	mctl_present;
24141 	ill_t		*ill;
24142 	ill_t		*out_ill;
24143 	mblk_t		*xmit_mp;
24144 	mblk_t		*carve_mp;
24145 	ire_t		*ire1 = NULL;
24146 	ire_t		*save_ire = NULL;
24147 	mblk_t  	*next_mp = NULL;
24148 	boolean_t	last_frag = B_FALSE;
24149 	boolean_t	multirt_send = B_FALSE;
24150 	ire_t		*first_ire = NULL;
24151 	irb_t		*irb = NULL;
24152 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24153 
24154 	ill = ire_to_ill(ire);
24155 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24156 
24157 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24158 
24159 	if (max_frag == 0) {
24160 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24161 		    " -  dropping packet\n"));
24162 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24163 		freemsg(mp);
24164 		return;
24165 	}
24166 
24167 	/*
24168 	 * IPsec does not allow hw accelerated packets to be fragmented
24169 	 * This check is made in ip_wput_ipsec_out prior to coming here
24170 	 * via ip_wput_ire_fragmentit.
24171 	 *
24172 	 * If at this point we have an ire whose ARP request has not
24173 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24174 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24175 	 * This packet and all fragmentable packets for this ire will
24176 	 * continue to get dropped while ire_nce->nce_state remains in
24177 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24178 	 * ND_REACHABLE, all subsquent large packets for this ire will
24179 	 * get fragemented and sent out by this function.
24180 	 */
24181 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24182 		/* If nce_state is ND_INITIAL, trigger ARP query */
24183 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24184 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24185 		    " -  dropping packet\n"));
24186 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24187 		freemsg(mp);
24188 		return;
24189 	}
24190 
24191 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24192 	    "ip_wput_frag_start:");
24193 
24194 	if (mp->b_datap->db_type == M_CTL) {
24195 		first_mp = mp;
24196 		mp_orig = mp = mp->b_cont;
24197 		mctl_present = B_TRUE;
24198 	} else {
24199 		first_mp = mp;
24200 		mctl_present = B_FALSE;
24201 	}
24202 
24203 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24204 	ipha = (ipha_t *)mp->b_rptr;
24205 
24206 	/*
24207 	 * If the Don't Fragment flag is on, generate an ICMP destination
24208 	 * unreachable, fragmentation needed.
24209 	 */
24210 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24211 	if (offset & IPH_DF) {
24212 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24213 		if (is_system_labeled()) {
24214 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24215 			    ire->ire_max_frag - max_frag, AF_INET);
24216 		}
24217 		/*
24218 		 * Need to compute hdr checksum if called from ip_wput_ire.
24219 		 * Note that ip_rput_forward verifies the checksum before
24220 		 * calling this routine so in that case this is a noop.
24221 		 */
24222 		ipha->ipha_hdr_checksum = 0;
24223 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24224 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24225 		    ipst);
24226 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24227 		    "ip_wput_frag_end:(%S)",
24228 		    "don't fragment");
24229 		return;
24230 	}
24231 	/*
24232 	 * Labeled systems adjust max_frag if they add a label
24233 	 * to send the correct path mtu.  We need the real mtu since we
24234 	 * are fragmenting the packet after label adjustment.
24235 	 */
24236 	if (is_system_labeled())
24237 		max_frag = ire->ire_max_frag;
24238 	if (mctl_present)
24239 		freeb(first_mp);
24240 	/*
24241 	 * Establish the starting offset.  May not be zero if we are fragging
24242 	 * a fragment that is being forwarded.
24243 	 */
24244 	offset = offset & IPH_OFFSET;
24245 
24246 	/* TODO why is this test needed? */
24247 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24248 	if (((max_frag - LENGTH) & ~7) < 8) {
24249 		/* TODO: notify ulp somehow */
24250 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24251 		freemsg(mp);
24252 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24253 		    "ip_wput_frag_end:(%S)",
24254 		    "len < 8");
24255 		return;
24256 	}
24257 
24258 	hdr_len = (V_HLEN & 0xF) << 2;
24259 
24260 	ipha->ipha_hdr_checksum = 0;
24261 
24262 	/*
24263 	 * Establish the number of bytes maximum per frag, after putting
24264 	 * in the header.
24265 	 */
24266 	len = (max_frag - hdr_len) & ~7;
24267 
24268 	/* Check if we can use MDT to send out the frags. */
24269 	ASSERT(!IRE_IS_LOCAL(ire));
24270 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24271 	    ipst->ips_ip_multidata_outbound &&
24272 	    !(ire->ire_flags & RTF_MULTIRT) &&
24273 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24274 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24275 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24276 		ASSERT(ill->ill_mdt_capab != NULL);
24277 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24278 			/*
24279 			 * If MDT has been previously turned off in the past,
24280 			 * and we currently can do MDT (due to IPQoS policy
24281 			 * removal, etc.) then enable it for this interface.
24282 			 */
24283 			ill->ill_mdt_capab->ill_mdt_on = 1;
24284 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24285 			    ill->ill_name));
24286 		}
24287 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24288 		    offset);
24289 		return;
24290 	}
24291 
24292 	/* Get a copy of the header for the trailing frags */
24293 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24294 	    mp);
24295 	if (!hdr_mp) {
24296 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24297 		freemsg(mp);
24298 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24299 		    "ip_wput_frag_end:(%S)",
24300 		    "couldn't copy hdr");
24301 		return;
24302 	}
24303 
24304 	/* Store the starting offset, with the MoreFrags flag. */
24305 	i1 = offset | IPH_MF | frag_flag;
24306 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24307 
24308 	/* Establish the ending byte offset, based on the starting offset. */
24309 	offset <<= 3;
24310 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24311 
24312 	/* Store the length of the first fragment in the IP header. */
24313 	i1 = len + hdr_len;
24314 	ASSERT(i1 <= IP_MAXPACKET);
24315 	ipha->ipha_length = htons((uint16_t)i1);
24316 
24317 	/*
24318 	 * Compute the IP header checksum for the first frag.  We have to
24319 	 * watch out that we stop at the end of the header.
24320 	 */
24321 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24322 
24323 	/*
24324 	 * Now carve off the first frag.  Note that this will include the
24325 	 * original IP header.
24326 	 */
24327 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24328 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24329 		freeb(hdr_mp);
24330 		freemsg(mp_orig);
24331 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24332 		    "ip_wput_frag_end:(%S)",
24333 		    "couldn't carve first");
24334 		return;
24335 	}
24336 
24337 	/*
24338 	 * Multirouting case. Each fragment is replicated
24339 	 * via all non-condemned RTF_MULTIRT routes
24340 	 * currently resolved.
24341 	 * We ensure that first_ire is the first RTF_MULTIRT
24342 	 * ire in the bucket.
24343 	 */
24344 	if (ire->ire_flags & RTF_MULTIRT) {
24345 		irb = ire->ire_bucket;
24346 		ASSERT(irb != NULL);
24347 
24348 		multirt_send = B_TRUE;
24349 
24350 		/* Make sure we do not omit any multiroute ire. */
24351 		IRB_REFHOLD(irb);
24352 		for (first_ire = irb->irb_ire;
24353 		    first_ire != NULL;
24354 		    first_ire = first_ire->ire_next) {
24355 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24356 			    (first_ire->ire_addr == ire->ire_addr) &&
24357 			    !(first_ire->ire_marks &
24358 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24359 				break;
24360 		}
24361 
24362 		if (first_ire != NULL) {
24363 			if (first_ire != ire) {
24364 				IRE_REFHOLD(first_ire);
24365 				/*
24366 				 * Do not release the ire passed in
24367 				 * as the argument.
24368 				 */
24369 				ire = first_ire;
24370 			} else {
24371 				first_ire = NULL;
24372 			}
24373 		}
24374 		IRB_REFRELE(irb);
24375 
24376 		/*
24377 		 * Save the first ire; we will need to restore it
24378 		 * for the trailing frags.
24379 		 * We REFHOLD save_ire, as each iterated ire will be
24380 		 * REFRELEd.
24381 		 */
24382 		save_ire = ire;
24383 		IRE_REFHOLD(save_ire);
24384 	}
24385 
24386 	/*
24387 	 * First fragment emission loop.
24388 	 * In most cases, the emission loop below is entered only
24389 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24390 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24391 	 * bucket, and send the fragment through all crossed
24392 	 * RTF_MULTIRT routes.
24393 	 */
24394 	do {
24395 		if (ire->ire_flags & RTF_MULTIRT) {
24396 			/*
24397 			 * We are in a multiple send case, need to get
24398 			 * the next ire and make a copy of the packet.
24399 			 * ire1 holds here the next ire to process in the
24400 			 * bucket. If multirouting is expected,
24401 			 * any non-RTF_MULTIRT ire that has the
24402 			 * right destination address is ignored.
24403 			 *
24404 			 * We have to take into account the MTU of
24405 			 * each walked ire. max_frag is set by the
24406 			 * the caller and generally refers to
24407 			 * the primary ire entry. Here we ensure that
24408 			 * no route with a lower MTU will be used, as
24409 			 * fragments are carved once for all ires,
24410 			 * then replicated.
24411 			 */
24412 			ASSERT(irb != NULL);
24413 			IRB_REFHOLD(irb);
24414 			for (ire1 = ire->ire_next;
24415 			    ire1 != NULL;
24416 			    ire1 = ire1->ire_next) {
24417 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24418 					continue;
24419 				if (ire1->ire_addr != ire->ire_addr)
24420 					continue;
24421 				if (ire1->ire_marks &
24422 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24423 					continue;
24424 				/*
24425 				 * Ensure we do not exceed the MTU
24426 				 * of the next route.
24427 				 */
24428 				if (ire1->ire_max_frag < max_frag) {
24429 					ip_multirt_bad_mtu(ire1, max_frag);
24430 					continue;
24431 				}
24432 
24433 				/* Got one. */
24434 				IRE_REFHOLD(ire1);
24435 				break;
24436 			}
24437 			IRB_REFRELE(irb);
24438 
24439 			if (ire1 != NULL) {
24440 				next_mp = copyb(mp);
24441 				if ((next_mp == NULL) ||
24442 				    ((mp->b_cont != NULL) &&
24443 				    ((next_mp->b_cont =
24444 				    dupmsg(mp->b_cont)) == NULL))) {
24445 					freemsg(next_mp);
24446 					next_mp = NULL;
24447 					ire_refrele(ire1);
24448 					ire1 = NULL;
24449 				}
24450 			}
24451 
24452 			/* Last multiroute ire; don't loop anymore. */
24453 			if (ire1 == NULL) {
24454 				multirt_send = B_FALSE;
24455 			}
24456 		}
24457 
24458 		ll_hdr_len = 0;
24459 		LOCK_IRE_FP_MP(ire);
24460 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24461 		if (ll_hdr_mp != NULL) {
24462 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24463 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24464 		} else {
24465 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24466 		}
24467 
24468 		/* If there is a transmit header, get a copy for this frag. */
24469 		/*
24470 		 * TODO: should check db_ref before calling ip_carve_mp since
24471 		 * it might give us a dup.
24472 		 */
24473 		if (!ll_hdr_mp) {
24474 			/* No xmit header. */
24475 			xmit_mp = mp;
24476 
24477 		/* We have a link-layer header that can fit in our mblk. */
24478 		} else if (mp->b_datap->db_ref == 1 &&
24479 		    ll_hdr_len != 0 &&
24480 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24481 			/* M_DATA fastpath */
24482 			mp->b_rptr -= ll_hdr_len;
24483 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24484 			xmit_mp = mp;
24485 
24486 		/* Corner case if copyb has failed */
24487 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24488 			UNLOCK_IRE_FP_MP(ire);
24489 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24490 			freeb(hdr_mp);
24491 			freemsg(mp);
24492 			freemsg(mp_orig);
24493 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24494 			    "ip_wput_frag_end:(%S)",
24495 			    "discard");
24496 
24497 			if (multirt_send) {
24498 				ASSERT(ire1);
24499 				ASSERT(next_mp);
24500 
24501 				freemsg(next_mp);
24502 				ire_refrele(ire1);
24503 			}
24504 			if (save_ire != NULL)
24505 				IRE_REFRELE(save_ire);
24506 
24507 			if (first_ire != NULL)
24508 				ire_refrele(first_ire);
24509 			return;
24510 
24511 		/*
24512 		 * Case of res_mp OR the fastpath mp can't fit
24513 		 * in the mblk
24514 		 */
24515 		} else {
24516 			xmit_mp->b_cont = mp;
24517 
24518 			/*
24519 			 * Get priority marking, if any.
24520 			 * We propagate the CoS marking from the
24521 			 * original packet that went to QoS processing
24522 			 * in ip_wput_ire to the newly carved mp.
24523 			 */
24524 			if (DB_TYPE(xmit_mp) == M_DATA)
24525 				xmit_mp->b_band = mp->b_band;
24526 		}
24527 		UNLOCK_IRE_FP_MP(ire);
24528 
24529 		q = ire->ire_stq;
24530 		out_ill = (ill_t *)q->q_ptr;
24531 
24532 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24533 
24534 		DTRACE_PROBE4(ip4__physical__out__start,
24535 		    ill_t *, NULL, ill_t *, out_ill,
24536 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24537 
24538 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24539 		    ipst->ips_ipv4firewall_physical_out,
24540 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24541 
24542 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24543 
24544 		if (xmit_mp != NULL) {
24545 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24546 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24547 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24548 
24549 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24550 
24551 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24552 			UPDATE_MIB(out_ill->ill_ip_mib,
24553 			    ipIfStatsHCOutOctets, i1);
24554 
24555 			if (pkt_type != OB_PKT) {
24556 				/*
24557 				 * Update the packet count and MIB stats
24558 				 * of trailing RTF_MULTIRT ires.
24559 				 */
24560 				UPDATE_OB_PKT_COUNT(ire);
24561 				BUMP_MIB(out_ill->ill_ip_mib,
24562 				    ipIfStatsOutFragReqds);
24563 			}
24564 		}
24565 
24566 		if (multirt_send) {
24567 			/*
24568 			 * We are in a multiple send case; look for
24569 			 * the next ire and re-enter the loop.
24570 			 */
24571 			ASSERT(ire1);
24572 			ASSERT(next_mp);
24573 			/* REFRELE the current ire before looping */
24574 			ire_refrele(ire);
24575 			ire = ire1;
24576 			ire1 = NULL;
24577 			mp = next_mp;
24578 			next_mp = NULL;
24579 		}
24580 	} while (multirt_send);
24581 
24582 	ASSERT(ire1 == NULL);
24583 
24584 	/* Restore the original ire; we need it for the trailing frags */
24585 	if (save_ire != NULL) {
24586 		/* REFRELE the last iterated ire */
24587 		ire_refrele(ire);
24588 		/* save_ire has been REFHOLDed */
24589 		ire = save_ire;
24590 		save_ire = NULL;
24591 		q = ire->ire_stq;
24592 	}
24593 
24594 	if (pkt_type == OB_PKT) {
24595 		UPDATE_OB_PKT_COUNT(ire);
24596 	} else {
24597 		out_ill = (ill_t *)q->q_ptr;
24598 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24599 		UPDATE_IB_PKT_COUNT(ire);
24600 	}
24601 
24602 	/* Advance the offset to the second frag starting point. */
24603 	offset += len;
24604 	/*
24605 	 * Update hdr_len from the copied header - there might be less options
24606 	 * in the later fragments.
24607 	 */
24608 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24609 	/* Loop until done. */
24610 	for (;;) {
24611 		uint16_t	offset_and_flags;
24612 		uint16_t	ip_len;
24613 
24614 		if (ip_data_end - offset > len) {
24615 			/*
24616 			 * Carve off the appropriate amount from the original
24617 			 * datagram.
24618 			 */
24619 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24620 				mp = NULL;
24621 				break;
24622 			}
24623 			/*
24624 			 * More frags after this one.  Get another copy
24625 			 * of the header.
24626 			 */
24627 			if (carve_mp->b_datap->db_ref == 1 &&
24628 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24629 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24630 				/* Inline IP header */
24631 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24632 				    hdr_mp->b_rptr;
24633 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24634 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24635 				mp = carve_mp;
24636 			} else {
24637 				if (!(mp = copyb(hdr_mp))) {
24638 					freemsg(carve_mp);
24639 					break;
24640 				}
24641 				/* Get priority marking, if any. */
24642 				mp->b_band = carve_mp->b_band;
24643 				mp->b_cont = carve_mp;
24644 			}
24645 			ipha = (ipha_t *)mp->b_rptr;
24646 			offset_and_flags = IPH_MF;
24647 		} else {
24648 			/*
24649 			 * Last frag.  Consume the header. Set len to
24650 			 * the length of this last piece.
24651 			 */
24652 			len = ip_data_end - offset;
24653 
24654 			/*
24655 			 * Carve off the appropriate amount from the original
24656 			 * datagram.
24657 			 */
24658 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24659 				mp = NULL;
24660 				break;
24661 			}
24662 			if (carve_mp->b_datap->db_ref == 1 &&
24663 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24664 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24665 				/* Inline IP header */
24666 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24667 				    hdr_mp->b_rptr;
24668 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24669 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24670 				mp = carve_mp;
24671 				freeb(hdr_mp);
24672 				hdr_mp = mp;
24673 			} else {
24674 				mp = hdr_mp;
24675 				/* Get priority marking, if any. */
24676 				mp->b_band = carve_mp->b_band;
24677 				mp->b_cont = carve_mp;
24678 			}
24679 			ipha = (ipha_t *)mp->b_rptr;
24680 			/* A frag of a frag might have IPH_MF non-zero */
24681 			offset_and_flags =
24682 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24683 			    IPH_MF;
24684 		}
24685 		offset_and_flags |= (uint16_t)(offset >> 3);
24686 		offset_and_flags |= (uint16_t)frag_flag;
24687 		/* Store the offset and flags in the IP header. */
24688 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24689 
24690 		/* Store the length in the IP header. */
24691 		ip_len = (uint16_t)(len + hdr_len);
24692 		ipha->ipha_length = htons(ip_len);
24693 
24694 		/*
24695 		 * Set the IP header checksum.	Note that mp is just
24696 		 * the header, so this is easy to pass to ip_csum.
24697 		 */
24698 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24699 
24700 		/* Attach a transmit header, if any, and ship it. */
24701 		if (pkt_type == OB_PKT) {
24702 			UPDATE_OB_PKT_COUNT(ire);
24703 		} else {
24704 			out_ill = (ill_t *)q->q_ptr;
24705 			BUMP_MIB(out_ill->ill_ip_mib,
24706 			    ipIfStatsHCOutForwDatagrams);
24707 			UPDATE_IB_PKT_COUNT(ire);
24708 		}
24709 
24710 		if (ire->ire_flags & RTF_MULTIRT) {
24711 			irb = ire->ire_bucket;
24712 			ASSERT(irb != NULL);
24713 
24714 			multirt_send = B_TRUE;
24715 
24716 			/*
24717 			 * Save the original ire; we will need to restore it
24718 			 * for the tailing frags.
24719 			 */
24720 			save_ire = ire;
24721 			IRE_REFHOLD(save_ire);
24722 		}
24723 		/*
24724 		 * Emission loop for this fragment, similar
24725 		 * to what is done for the first fragment.
24726 		 */
24727 		do {
24728 			if (multirt_send) {
24729 				/*
24730 				 * We are in a multiple send case, need to get
24731 				 * the next ire and make a copy of the packet.
24732 				 */
24733 				ASSERT(irb != NULL);
24734 				IRB_REFHOLD(irb);
24735 				for (ire1 = ire->ire_next;
24736 				    ire1 != NULL;
24737 				    ire1 = ire1->ire_next) {
24738 					if (!(ire1->ire_flags & RTF_MULTIRT))
24739 						continue;
24740 					if (ire1->ire_addr != ire->ire_addr)
24741 						continue;
24742 					if (ire1->ire_marks &
24743 					    (IRE_MARK_CONDEMNED |
24744 					    IRE_MARK_TESTHIDDEN))
24745 						continue;
24746 					/*
24747 					 * Ensure we do not exceed the MTU
24748 					 * of the next route.
24749 					 */
24750 					if (ire1->ire_max_frag < max_frag) {
24751 						ip_multirt_bad_mtu(ire1,
24752 						    max_frag);
24753 						continue;
24754 					}
24755 
24756 					/* Got one. */
24757 					IRE_REFHOLD(ire1);
24758 					break;
24759 				}
24760 				IRB_REFRELE(irb);
24761 
24762 				if (ire1 != NULL) {
24763 					next_mp = copyb(mp);
24764 					if ((next_mp == NULL) ||
24765 					    ((mp->b_cont != NULL) &&
24766 					    ((next_mp->b_cont =
24767 					    dupmsg(mp->b_cont)) == NULL))) {
24768 						freemsg(next_mp);
24769 						next_mp = NULL;
24770 						ire_refrele(ire1);
24771 						ire1 = NULL;
24772 					}
24773 				}
24774 
24775 				/* Last multiroute ire; don't loop anymore. */
24776 				if (ire1 == NULL) {
24777 					multirt_send = B_FALSE;
24778 				}
24779 			}
24780 
24781 			/* Update transmit header */
24782 			ll_hdr_len = 0;
24783 			LOCK_IRE_FP_MP(ire);
24784 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24785 			if (ll_hdr_mp != NULL) {
24786 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24787 				ll_hdr_len = MBLKL(ll_hdr_mp);
24788 			} else {
24789 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24790 			}
24791 
24792 			if (!ll_hdr_mp) {
24793 				xmit_mp = mp;
24794 
24795 			/*
24796 			 * We have link-layer header that can fit in
24797 			 * our mblk.
24798 			 */
24799 			} else if (mp->b_datap->db_ref == 1 &&
24800 			    ll_hdr_len != 0 &&
24801 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24802 				/* M_DATA fastpath */
24803 				mp->b_rptr -= ll_hdr_len;
24804 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24805 				    ll_hdr_len);
24806 				xmit_mp = mp;
24807 
24808 			/*
24809 			 * Case of res_mp OR the fastpath mp can't fit
24810 			 * in the mblk
24811 			 */
24812 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24813 				xmit_mp->b_cont = mp;
24814 				/* Get priority marking, if any. */
24815 				if (DB_TYPE(xmit_mp) == M_DATA)
24816 					xmit_mp->b_band = mp->b_band;
24817 
24818 			/* Corner case if copyb failed */
24819 			} else {
24820 				/*
24821 				 * Exit both the replication and
24822 				 * fragmentation loops.
24823 				 */
24824 				UNLOCK_IRE_FP_MP(ire);
24825 				goto drop_pkt;
24826 			}
24827 			UNLOCK_IRE_FP_MP(ire);
24828 
24829 			mp1 = mp;
24830 			out_ill = (ill_t *)q->q_ptr;
24831 
24832 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24833 
24834 			DTRACE_PROBE4(ip4__physical__out__start,
24835 			    ill_t *, NULL, ill_t *, out_ill,
24836 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24837 
24838 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24839 			    ipst->ips_ipv4firewall_physical_out,
24840 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24841 
24842 			DTRACE_PROBE1(ip4__physical__out__end,
24843 			    mblk_t *, xmit_mp);
24844 
24845 			if (mp != mp1 && hdr_mp == mp1)
24846 				hdr_mp = mp;
24847 			if (mp != mp1 && mp_orig == mp1)
24848 				mp_orig = mp;
24849 
24850 			if (xmit_mp != NULL) {
24851 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24852 				    NULL, void_ip_t *, ipha,
24853 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24854 				    ipha, ip6_t *, NULL, int, 0);
24855 
24856 				ILL_SEND_TX(out_ill, ire, connp,
24857 				    xmit_mp, 0, connp);
24858 
24859 				BUMP_MIB(out_ill->ill_ip_mib,
24860 				    ipIfStatsHCOutTransmits);
24861 				UPDATE_MIB(out_ill->ill_ip_mib,
24862 				    ipIfStatsHCOutOctets, ip_len);
24863 
24864 				if (pkt_type != OB_PKT) {
24865 					/*
24866 					 * Update the packet count of trailing
24867 					 * RTF_MULTIRT ires.
24868 					 */
24869 					UPDATE_OB_PKT_COUNT(ire);
24870 				}
24871 			}
24872 
24873 			/* All done if we just consumed the hdr_mp. */
24874 			if (mp == hdr_mp) {
24875 				last_frag = B_TRUE;
24876 				BUMP_MIB(out_ill->ill_ip_mib,
24877 				    ipIfStatsOutFragOKs);
24878 			}
24879 
24880 			if (multirt_send) {
24881 				/*
24882 				 * We are in a multiple send case; look for
24883 				 * the next ire and re-enter the loop.
24884 				 */
24885 				ASSERT(ire1);
24886 				ASSERT(next_mp);
24887 				/* REFRELE the current ire before looping */
24888 				ire_refrele(ire);
24889 				ire = ire1;
24890 				ire1 = NULL;
24891 				q = ire->ire_stq;
24892 				mp = next_mp;
24893 				next_mp = NULL;
24894 			}
24895 		} while (multirt_send);
24896 		/*
24897 		 * Restore the original ire; we need it for the
24898 		 * trailing frags
24899 		 */
24900 		if (save_ire != NULL) {
24901 			ASSERT(ire1 == NULL);
24902 			/* REFRELE the last iterated ire */
24903 			ire_refrele(ire);
24904 			/* save_ire has been REFHOLDed */
24905 			ire = save_ire;
24906 			q = ire->ire_stq;
24907 			save_ire = NULL;
24908 		}
24909 
24910 		if (last_frag) {
24911 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24912 			    "ip_wput_frag_end:(%S)",
24913 			    "consumed hdr_mp");
24914 
24915 			if (first_ire != NULL)
24916 				ire_refrele(first_ire);
24917 			return;
24918 		}
24919 		/* Otherwise, advance and loop. */
24920 		offset += len;
24921 	}
24922 
24923 drop_pkt:
24924 	/* Clean up following allocation failure. */
24925 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24926 	freemsg(mp);
24927 	if (mp != hdr_mp)
24928 		freeb(hdr_mp);
24929 	if (mp != mp_orig)
24930 		freemsg(mp_orig);
24931 
24932 	if (save_ire != NULL)
24933 		IRE_REFRELE(save_ire);
24934 	if (first_ire != NULL)
24935 		ire_refrele(first_ire);
24936 
24937 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24938 	    "ip_wput_frag_end:(%S)",
24939 	    "end--alloc failure");
24940 }
24941 
24942 /*
24943  * Copy the header plus those options which have the copy bit set
24944  * src is the template to make sure we preserve the cred for TX purposes.
24945  */
24946 static mblk_t *
24947 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24948     mblk_t *src)
24949 {
24950 	mblk_t	*mp;
24951 	uchar_t	*up;
24952 
24953 	/*
24954 	 * Quick check if we need to look for options without the copy bit
24955 	 * set
24956 	 */
24957 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24958 	if (!mp)
24959 		return (mp);
24960 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24961 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24962 		bcopy(rptr, mp->b_rptr, hdr_len);
24963 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24964 		return (mp);
24965 	}
24966 	up  = mp->b_rptr;
24967 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24968 	up += IP_SIMPLE_HDR_LENGTH;
24969 	rptr += IP_SIMPLE_HDR_LENGTH;
24970 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24971 	while (hdr_len > 0) {
24972 		uint32_t optval;
24973 		uint32_t optlen;
24974 
24975 		optval = *rptr;
24976 		if (optval == IPOPT_EOL)
24977 			break;
24978 		if (optval == IPOPT_NOP)
24979 			optlen = 1;
24980 		else
24981 			optlen = rptr[1];
24982 		if (optval & IPOPT_COPY) {
24983 			bcopy(rptr, up, optlen);
24984 			up += optlen;
24985 		}
24986 		rptr += optlen;
24987 		hdr_len -= optlen;
24988 	}
24989 	/*
24990 	 * Make sure that we drop an even number of words by filling
24991 	 * with EOL to the next word boundary.
24992 	 */
24993 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24994 	    hdr_len & 0x3; hdr_len++)
24995 		*up++ = IPOPT_EOL;
24996 	mp->b_wptr = up;
24997 	/* Update header length */
24998 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24999 	return (mp);
25000 }
25001 
25002 /*
25003  * Delivery to local recipients including fanout to multiple recipients.
25004  * Does not do checksumming of UDP/TCP.
25005  * Note: q should be the read side queue for either the ill or conn.
25006  * Note: rq should be the read side q for the lower (ill) stream.
25007  * We don't send packets to IPPF processing, thus the last argument
25008  * to all the fanout calls are B_FALSE.
25009  */
25010 void
25011 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25012     int fanout_flags, zoneid_t zoneid)
25013 {
25014 	uint32_t	protocol;
25015 	mblk_t		*first_mp;
25016 	boolean_t	mctl_present;
25017 	int		ire_type;
25018 #define	rptr	((uchar_t *)ipha)
25019 	ip_stack_t	*ipst = ill->ill_ipst;
25020 
25021 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25022 	    "ip_wput_local_start: q %p", q);
25023 
25024 	if (ire != NULL) {
25025 		ire_type = ire->ire_type;
25026 	} else {
25027 		/*
25028 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25029 		 * packet is not multicast, we can't tell the ire type.
25030 		 */
25031 		ASSERT(CLASSD(ipha->ipha_dst));
25032 		ire_type = IRE_BROADCAST;
25033 	}
25034 
25035 	first_mp = mp;
25036 	if (first_mp->b_datap->db_type == M_CTL) {
25037 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25038 		if (!io->ipsec_out_secure) {
25039 			/*
25040 			 * This ipsec_out_t was allocated in ip_wput
25041 			 * for multicast packets to store the ill_index.
25042 			 * As this is being delivered locally, we don't
25043 			 * need this anymore.
25044 			 */
25045 			mp = first_mp->b_cont;
25046 			freeb(first_mp);
25047 			first_mp = mp;
25048 			mctl_present = B_FALSE;
25049 		} else {
25050 			/*
25051 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25052 			 * security properties for the looped-back packet.
25053 			 */
25054 			mctl_present = B_TRUE;
25055 			mp = first_mp->b_cont;
25056 			ASSERT(mp != NULL);
25057 			ipsec_out_to_in(first_mp);
25058 		}
25059 	} else {
25060 		mctl_present = B_FALSE;
25061 	}
25062 
25063 	DTRACE_PROBE4(ip4__loopback__in__start,
25064 	    ill_t *, ill, ill_t *, NULL,
25065 	    ipha_t *, ipha, mblk_t *, first_mp);
25066 
25067 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25068 	    ipst->ips_ipv4firewall_loopback_in,
25069 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25070 
25071 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25072 
25073 	if (first_mp == NULL)
25074 		return;
25075 
25076 	if (ipst->ips_ipobs_enabled) {
25077 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25078 		zoneid_t stackzoneid = netstackid_to_zoneid(
25079 		    ipst->ips_netstack->netstack_stackid);
25080 
25081 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25082 		/*
25083 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25084 		 * address.  Restrict the lookup below to the destination zone.
25085 		 */
25086 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25087 			lookup_zoneid = zoneid;
25088 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25089 		    lookup_zoneid);
25090 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25091 		    IPV4_VERSION, 0, ipst);
25092 	}
25093 
25094 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25095 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25096 	    int, 1);
25097 
25098 	ipst->ips_loopback_packets++;
25099 
25100 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25101 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25102 	if (!IS_SIMPLE_IPH(ipha)) {
25103 		ip_wput_local_options(ipha, ipst);
25104 	}
25105 
25106 	protocol = ipha->ipha_protocol;
25107 	switch (protocol) {
25108 	case IPPROTO_ICMP: {
25109 		ire_t		*ire_zone;
25110 		ilm_t		*ilm;
25111 		mblk_t		*mp1;
25112 		zoneid_t	last_zoneid;
25113 		ilm_walker_t	ilw;
25114 
25115 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25116 			ASSERT(ire_type == IRE_BROADCAST);
25117 			/*
25118 			 * In the multicast case, applications may have joined
25119 			 * the group from different zones, so we need to deliver
25120 			 * the packet to each of them. Loop through the
25121 			 * multicast memberships structures (ilm) on the receive
25122 			 * ill and send a copy of the packet up each matching
25123 			 * one. However, we don't do this for multicasts sent on
25124 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25125 			 * they must stay in the sender's zone.
25126 			 *
25127 			 * ilm_add_v6() ensures that ilms in the same zone are
25128 			 * contiguous in the ill_ilm list. We use this property
25129 			 * to avoid sending duplicates needed when two
25130 			 * applications in the same zone join the same group on
25131 			 * different logical interfaces: we ignore the ilm if
25132 			 * it's zoneid is the same as the last matching one.
25133 			 * In addition, the sending of the packet for
25134 			 * ire_zoneid is delayed until all of the other ilms
25135 			 * have been exhausted.
25136 			 */
25137 			last_zoneid = -1;
25138 			ilm = ilm_walker_start(&ilw, ill);
25139 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25140 				if (ipha->ipha_dst != ilm->ilm_addr ||
25141 				    ilm->ilm_zoneid == last_zoneid ||
25142 				    ilm->ilm_zoneid == zoneid ||
25143 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25144 					continue;
25145 				mp1 = ip_copymsg(first_mp);
25146 				if (mp1 == NULL)
25147 					continue;
25148 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25149 				    0, 0, mctl_present, B_FALSE, ill,
25150 				    ilm->ilm_zoneid);
25151 				last_zoneid = ilm->ilm_zoneid;
25152 			}
25153 			ilm_walker_finish(&ilw);
25154 			/*
25155 			 * Loopback case: the sending endpoint has
25156 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25157 			 * dispatch the multicast packet to the sending zone.
25158 			 */
25159 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25160 				freemsg(first_mp);
25161 				return;
25162 			}
25163 		} else if (ire_type == IRE_BROADCAST) {
25164 			/*
25165 			 * In the broadcast case, there may be many zones
25166 			 * which need a copy of the packet delivered to them.
25167 			 * There is one IRE_BROADCAST per broadcast address
25168 			 * and per zone; we walk those using a helper function.
25169 			 * In addition, the sending of the packet for zoneid is
25170 			 * delayed until all of the other ires have been
25171 			 * processed.
25172 			 */
25173 			IRB_REFHOLD(ire->ire_bucket);
25174 			ire_zone = NULL;
25175 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25176 			    ire)) != NULL) {
25177 				mp1 = ip_copymsg(first_mp);
25178 				if (mp1 == NULL)
25179 					continue;
25180 
25181 				UPDATE_IB_PKT_COUNT(ire_zone);
25182 				ire_zone->ire_last_used_time = lbolt;
25183 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25184 				    mctl_present, B_FALSE, ill,
25185 				    ire_zone->ire_zoneid);
25186 			}
25187 			IRB_REFRELE(ire->ire_bucket);
25188 		}
25189 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25190 		    0, mctl_present, B_FALSE, ill, zoneid);
25191 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25192 		    "ip_wput_local_end: q %p (%S)",
25193 		    q, "icmp");
25194 		return;
25195 	}
25196 	case IPPROTO_IGMP:
25197 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25198 			/* Bad packet - discarded by igmp_input */
25199 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25200 			    "ip_wput_local_end: q %p (%S)",
25201 			    q, "igmp_input--bad packet");
25202 			if (mctl_present)
25203 				freeb(first_mp);
25204 			return;
25205 		}
25206 		/*
25207 		 * igmp_input() may have returned the pulled up message.
25208 		 * So first_mp and ipha need to be reinitialized.
25209 		 */
25210 		ipha = (ipha_t *)mp->b_rptr;
25211 		if (mctl_present)
25212 			first_mp->b_cont = mp;
25213 		else
25214 			first_mp = mp;
25215 		/* deliver to local raw users */
25216 		break;
25217 	case IPPROTO_ENCAP:
25218 		/*
25219 		 * This case is covered by either ip_fanout_proto, or by
25220 		 * the above security processing for self-tunneled packets.
25221 		 */
25222 		break;
25223 	case IPPROTO_UDP: {
25224 		uint16_t	*up;
25225 		uint32_t	ports;
25226 
25227 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25228 		    UDP_PORTS_OFFSET);
25229 		/* Force a 'valid' checksum. */
25230 		up[3] = 0;
25231 
25232 		ports = *(uint32_t *)up;
25233 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25234 		    (ire_type == IRE_BROADCAST),
25235 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25236 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25237 		    ill, zoneid);
25238 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25239 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25240 		return;
25241 	}
25242 	case IPPROTO_TCP: {
25243 
25244 		/*
25245 		 * For TCP, discard broadcast packets.
25246 		 */
25247 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25248 			freemsg(first_mp);
25249 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25250 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25251 			return;
25252 		}
25253 
25254 		if (mp->b_datap->db_type == M_DATA) {
25255 			/*
25256 			 * M_DATA mblk, so init mblk (chain) for no struio().
25257 			 */
25258 			mblk_t	*mp1 = mp;
25259 
25260 			do {
25261 				mp1->b_datap->db_struioflag = 0;
25262 			} while ((mp1 = mp1->b_cont) != NULL);
25263 		}
25264 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25265 		    <= mp->b_wptr);
25266 		ip_fanout_tcp(q, first_mp, ill, ipha,
25267 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25268 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25269 		    mctl_present, B_FALSE, zoneid);
25270 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25271 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25272 		return;
25273 	}
25274 	case IPPROTO_SCTP:
25275 	{
25276 		uint32_t	ports;
25277 
25278 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25279 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25280 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25281 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25282 		return;
25283 	}
25284 
25285 	default:
25286 		break;
25287 	}
25288 	/*
25289 	 * Find a client for some other protocol.  We give
25290 	 * copies to multiple clients, if more than one is
25291 	 * bound.
25292 	 */
25293 	ip_fanout_proto(q, first_mp, ill, ipha,
25294 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25295 	    mctl_present, B_FALSE, ill, zoneid);
25296 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25297 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25298 #undef	rptr
25299 }
25300 
25301 /*
25302  * Update any source route, record route, or timestamp options.
25303  * Check that we are at end of strict source route.
25304  * The options have been sanity checked by ip_wput_options().
25305  */
25306 static void
25307 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25308 {
25309 	ipoptp_t	opts;
25310 	uchar_t		*opt;
25311 	uint8_t		optval;
25312 	uint8_t		optlen;
25313 	ipaddr_t	dst;
25314 	uint32_t	ts;
25315 	ire_t		*ire;
25316 	timestruc_t	now;
25317 
25318 	ip2dbg(("ip_wput_local_options\n"));
25319 	for (optval = ipoptp_first(&opts, ipha);
25320 	    optval != IPOPT_EOL;
25321 	    optval = ipoptp_next(&opts)) {
25322 		opt = opts.ipoptp_cur;
25323 		optlen = opts.ipoptp_len;
25324 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25325 		switch (optval) {
25326 			uint32_t off;
25327 		case IPOPT_SSRR:
25328 		case IPOPT_LSRR:
25329 			off = opt[IPOPT_OFFSET];
25330 			off--;
25331 			if (optlen < IP_ADDR_LEN ||
25332 			    off > optlen - IP_ADDR_LEN) {
25333 				/* End of source route */
25334 				break;
25335 			}
25336 			/*
25337 			 * This will only happen if two consecutive entries
25338 			 * in the source route contains our address or if
25339 			 * it is a packet with a loose source route which
25340 			 * reaches us before consuming the whole source route
25341 			 */
25342 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25343 			if (optval == IPOPT_SSRR) {
25344 				return;
25345 			}
25346 			/*
25347 			 * Hack: instead of dropping the packet truncate the
25348 			 * source route to what has been used by filling the
25349 			 * rest with IPOPT_NOP.
25350 			 */
25351 			opt[IPOPT_OLEN] = (uint8_t)off;
25352 			while (off < optlen) {
25353 				opt[off++] = IPOPT_NOP;
25354 			}
25355 			break;
25356 		case IPOPT_RR:
25357 			off = opt[IPOPT_OFFSET];
25358 			off--;
25359 			if (optlen < IP_ADDR_LEN ||
25360 			    off > optlen - IP_ADDR_LEN) {
25361 				/* No more room - ignore */
25362 				ip1dbg((
25363 				    "ip_wput_forward_options: end of RR\n"));
25364 				break;
25365 			}
25366 			dst = htonl(INADDR_LOOPBACK);
25367 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25368 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25369 			break;
25370 		case IPOPT_TS:
25371 			/* Insert timestamp if there is romm */
25372 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25373 			case IPOPT_TS_TSONLY:
25374 				off = IPOPT_TS_TIMELEN;
25375 				break;
25376 			case IPOPT_TS_PRESPEC:
25377 			case IPOPT_TS_PRESPEC_RFC791:
25378 				/* Verify that the address matched */
25379 				off = opt[IPOPT_OFFSET] - 1;
25380 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25381 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25382 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25383 				    ipst);
25384 				if (ire == NULL) {
25385 					/* Not for us */
25386 					break;
25387 				}
25388 				ire_refrele(ire);
25389 				/* FALLTHRU */
25390 			case IPOPT_TS_TSANDADDR:
25391 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25392 				break;
25393 			default:
25394 				/*
25395 				 * ip_*put_options should have already
25396 				 * dropped this packet.
25397 				 */
25398 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25399 				    "unknown IT - bug in ip_wput_options?\n");
25400 				return;	/* Keep "lint" happy */
25401 			}
25402 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25403 				/* Increase overflow counter */
25404 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25405 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25406 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25407 				    (off << 4);
25408 				break;
25409 			}
25410 			off = opt[IPOPT_OFFSET] - 1;
25411 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25412 			case IPOPT_TS_PRESPEC:
25413 			case IPOPT_TS_PRESPEC_RFC791:
25414 			case IPOPT_TS_TSANDADDR:
25415 				dst = htonl(INADDR_LOOPBACK);
25416 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25417 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25418 				/* FALLTHRU */
25419 			case IPOPT_TS_TSONLY:
25420 				off = opt[IPOPT_OFFSET] - 1;
25421 				/* Compute # of milliseconds since midnight */
25422 				gethrestime(&now);
25423 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25424 				    now.tv_nsec / (NANOSEC / MILLISEC);
25425 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25426 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25427 				break;
25428 			}
25429 			break;
25430 		}
25431 	}
25432 }
25433 
25434 /*
25435  * Send out a multicast packet on interface ipif.
25436  * The sender does not have an conn.
25437  * Caller verifies that this isn't a PHYI_LOOPBACK.
25438  */
25439 void
25440 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25441 {
25442 	ipha_t	*ipha;
25443 	ire_t	*ire;
25444 	ipaddr_t	dst;
25445 	mblk_t		*first_mp;
25446 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25447 
25448 	/* igmp_sendpkt always allocates a ipsec_out_t */
25449 	ASSERT(mp->b_datap->db_type == M_CTL);
25450 	ASSERT(!ipif->ipif_isv6);
25451 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25452 
25453 	first_mp = mp;
25454 	mp = first_mp->b_cont;
25455 	ASSERT(mp->b_datap->db_type == M_DATA);
25456 	ipha = (ipha_t *)mp->b_rptr;
25457 
25458 	/*
25459 	 * Find an IRE which matches the destination and the outgoing
25460 	 * queue (i.e. the outgoing interface.)
25461 	 */
25462 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25463 		dst = ipif->ipif_pp_dst_addr;
25464 	else
25465 		dst = ipha->ipha_dst;
25466 	/*
25467 	 * The source address has already been initialized by the
25468 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25469 	 * be sufficient rather than MATCH_IRE_IPIF.
25470 	 *
25471 	 * This function is used for sending IGMP packets.  For IPMP,
25472 	 * we sidestep IGMP snooping issues by sending all multicast
25473 	 * traffic on a single interface in the IPMP group.
25474 	 */
25475 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25476 	    MATCH_IRE_ILL, ipst);
25477 	if (!ire) {
25478 		/*
25479 		 * Mark this packet to make it be delivered to
25480 		 * ip_wput_ire after the new ire has been
25481 		 * created.
25482 		 */
25483 		mp->b_prev = NULL;
25484 		mp->b_next = NULL;
25485 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25486 		    zoneid, &zero_info);
25487 		return;
25488 	}
25489 
25490 	/*
25491 	 * Honor the RTF_SETSRC flag; this is the only case
25492 	 * where we force this addr whatever the current src addr is,
25493 	 * because this address is set by igmp_sendpkt(), and
25494 	 * cannot be specified by any user.
25495 	 */
25496 	if (ire->ire_flags & RTF_SETSRC) {
25497 		ipha->ipha_src = ire->ire_src_addr;
25498 	}
25499 
25500 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25501 }
25502 
25503 /*
25504  * NOTE : This function does not ire_refrele the ire argument passed in.
25505  *
25506  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25507  * failure. The nce_fp_mp can vanish any time in the case of
25508  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25509  * the ire_lock to access the nce_fp_mp in this case.
25510  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25511  * prepending a fastpath message IPQoS processing must precede it, we also set
25512  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25513  * (IPQoS might have set the b_band for CoS marking).
25514  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25515  * must follow it so that IPQoS can mark the dl_priority field for CoS
25516  * marking, if needed.
25517  */
25518 static mblk_t *
25519 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25520     uint32_t ill_index, ipha_t **iphap)
25521 {
25522 	uint_t	hlen;
25523 	ipha_t *ipha;
25524 	mblk_t *mp1;
25525 	boolean_t qos_done = B_FALSE;
25526 	uchar_t	*ll_hdr;
25527 	ip_stack_t	*ipst = ire->ire_ipst;
25528 
25529 #define	rptr	((uchar_t *)ipha)
25530 
25531 	ipha = (ipha_t *)mp->b_rptr;
25532 	hlen = 0;
25533 	LOCK_IRE_FP_MP(ire);
25534 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25535 		ASSERT(DB_TYPE(mp1) == M_DATA);
25536 		/* Initiate IPPF processing */
25537 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25538 			UNLOCK_IRE_FP_MP(ire);
25539 			ip_process(proc, &mp, ill_index);
25540 			if (mp == NULL)
25541 				return (NULL);
25542 
25543 			ipha = (ipha_t *)mp->b_rptr;
25544 			LOCK_IRE_FP_MP(ire);
25545 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25546 				qos_done = B_TRUE;
25547 				goto no_fp_mp;
25548 			}
25549 			ASSERT(DB_TYPE(mp1) == M_DATA);
25550 		}
25551 		hlen = MBLKL(mp1);
25552 		/*
25553 		 * Check if we have enough room to prepend fastpath
25554 		 * header
25555 		 */
25556 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25557 			ll_hdr = rptr - hlen;
25558 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25559 			/*
25560 			 * Set the b_rptr to the start of the link layer
25561 			 * header
25562 			 */
25563 			mp->b_rptr = ll_hdr;
25564 			mp1 = mp;
25565 		} else {
25566 			mp1 = copyb(mp1);
25567 			if (mp1 == NULL)
25568 				goto unlock_err;
25569 			mp1->b_band = mp->b_band;
25570 			mp1->b_cont = mp;
25571 			/*
25572 			 * XXX disable ICK_VALID and compute checksum
25573 			 * here; can happen if nce_fp_mp changes and
25574 			 * it can't be copied now due to insufficient
25575 			 * space. (unlikely, fp mp can change, but it
25576 			 * does not increase in length)
25577 			 */
25578 		}
25579 		UNLOCK_IRE_FP_MP(ire);
25580 	} else {
25581 no_fp_mp:
25582 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25583 		if (mp1 == NULL) {
25584 unlock_err:
25585 			UNLOCK_IRE_FP_MP(ire);
25586 			freemsg(mp);
25587 			return (NULL);
25588 		}
25589 		UNLOCK_IRE_FP_MP(ire);
25590 		mp1->b_cont = mp;
25591 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25592 			ip_process(proc, &mp1, ill_index);
25593 			if (mp1 == NULL)
25594 				return (NULL);
25595 
25596 			if (mp1->b_cont == NULL)
25597 				ipha = NULL;
25598 			else
25599 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25600 		}
25601 	}
25602 
25603 	*iphap = ipha;
25604 	return (mp1);
25605 #undef rptr
25606 }
25607 
25608 /*
25609  * Finish the outbound IPsec processing for an IPv6 packet. This function
25610  * is called from ipsec_out_process() if the IPsec packet was processed
25611  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25612  * asynchronously.
25613  */
25614 void
25615 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25616     ire_t *ire_arg)
25617 {
25618 	in6_addr_t *v6dstp;
25619 	ire_t *ire;
25620 	mblk_t *mp;
25621 	ip6_t *ip6h1;
25622 	uint_t	ill_index;
25623 	ipsec_out_t *io;
25624 	boolean_t hwaccel;
25625 	uint32_t flags = IP6_NO_IPPOLICY;
25626 	int match_flags;
25627 	zoneid_t zoneid;
25628 	boolean_t ill_need_rele = B_FALSE;
25629 	boolean_t ire_need_rele = B_FALSE;
25630 	ip_stack_t	*ipst;
25631 
25632 	mp = ipsec_mp->b_cont;
25633 	ip6h1 = (ip6_t *)mp->b_rptr;
25634 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25635 	ASSERT(io->ipsec_out_ns != NULL);
25636 	ipst = io->ipsec_out_ns->netstack_ip;
25637 	ill_index = io->ipsec_out_ill_index;
25638 	if (io->ipsec_out_reachable) {
25639 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25640 	}
25641 	hwaccel = io->ipsec_out_accelerated;
25642 	zoneid = io->ipsec_out_zoneid;
25643 	ASSERT(zoneid != ALL_ZONES);
25644 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25645 	/* Multicast addresses should have non-zero ill_index. */
25646 	v6dstp = &ip6h->ip6_dst;
25647 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25648 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25649 
25650 	if (ill == NULL && ill_index != 0) {
25651 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25652 		/* Failure case frees things for us. */
25653 		if (ill == NULL)
25654 			return;
25655 
25656 		ill_need_rele = B_TRUE;
25657 	}
25658 	ASSERT(mp != NULL);
25659 
25660 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25661 		boolean_t unspec_src;
25662 		ipif_t	*ipif;
25663 
25664 		/*
25665 		 * Use the ill_index to get the right ill.
25666 		 */
25667 		unspec_src = io->ipsec_out_unspec_src;
25668 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25669 		if (ipif == NULL) {
25670 			if (ill_need_rele)
25671 				ill_refrele(ill);
25672 			freemsg(ipsec_mp);
25673 			return;
25674 		}
25675 
25676 		if (ire_arg != NULL) {
25677 			ire = ire_arg;
25678 		} else {
25679 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25680 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25681 			ire_need_rele = B_TRUE;
25682 		}
25683 		if (ire != NULL) {
25684 			ipif_refrele(ipif);
25685 			/*
25686 			 * XXX Do the multicast forwarding now, as the IPsec
25687 			 * processing has been done.
25688 			 */
25689 			goto send;
25690 		}
25691 
25692 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25693 		mp->b_prev = NULL;
25694 		mp->b_next = NULL;
25695 
25696 		/*
25697 		 * If the IPsec packet was processed asynchronously,
25698 		 * drop it now.
25699 		 */
25700 		if (q == NULL) {
25701 			if (ill_need_rele)
25702 				ill_refrele(ill);
25703 			freemsg(ipsec_mp);
25704 			return;
25705 		}
25706 
25707 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25708 		    unspec_src, zoneid);
25709 		ipif_refrele(ipif);
25710 	} else {
25711 		if (ire_arg != NULL) {
25712 			ire = ire_arg;
25713 		} else {
25714 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25715 			ire_need_rele = B_TRUE;
25716 		}
25717 		if (ire != NULL)
25718 			goto send;
25719 		/*
25720 		 * ire disappeared underneath.
25721 		 *
25722 		 * What we need to do here is the ip_newroute
25723 		 * logic to get the ire without doing the IPsec
25724 		 * processing. Follow the same old path. But this
25725 		 * time, ip_wput or ire_add_then_send will call us
25726 		 * directly as all the IPsec operations are done.
25727 		 */
25728 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25729 		mp->b_prev = NULL;
25730 		mp->b_next = NULL;
25731 
25732 		/*
25733 		 * If the IPsec packet was processed asynchronously,
25734 		 * drop it now.
25735 		 */
25736 		if (q == NULL) {
25737 			if (ill_need_rele)
25738 				ill_refrele(ill);
25739 			freemsg(ipsec_mp);
25740 			return;
25741 		}
25742 
25743 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25744 		    zoneid, ipst);
25745 	}
25746 	if (ill != NULL && ill_need_rele)
25747 		ill_refrele(ill);
25748 	return;
25749 send:
25750 	if (ill != NULL && ill_need_rele)
25751 		ill_refrele(ill);
25752 
25753 	/* Local delivery */
25754 	if (ire->ire_stq == NULL) {
25755 		ill_t	*out_ill;
25756 		ASSERT(q != NULL);
25757 
25758 		/* PFHooks: LOOPBACK_OUT */
25759 		out_ill = ire_to_ill(ire);
25760 
25761 		/*
25762 		 * DTrace this as ip:::send.  A blocked packet will fire the
25763 		 * send probe, but not the receive probe.
25764 		 */
25765 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25766 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25767 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25768 
25769 		DTRACE_PROBE4(ip6__loopback__out__start,
25770 		    ill_t *, NULL, ill_t *, out_ill,
25771 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25772 
25773 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25774 		    ipst->ips_ipv6firewall_loopback_out,
25775 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25776 
25777 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25778 
25779 		if (ipsec_mp != NULL) {
25780 			ip_wput_local_v6(RD(q), out_ill,
25781 			    ip6h, ipsec_mp, ire, 0, zoneid);
25782 		}
25783 		if (ire_need_rele)
25784 			ire_refrele(ire);
25785 		return;
25786 	}
25787 	/*
25788 	 * Everything is done. Send it out on the wire.
25789 	 * We force the insertion of a fragment header using the
25790 	 * IPH_FRAG_HDR flag in two cases:
25791 	 * - after reception of an ICMPv6 "packet too big" message
25792 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25793 	 * - for multirouted IPv6 packets, so that the receiver can
25794 	 *   discard duplicates according to their fragment identifier
25795 	 */
25796 	/* XXX fix flow control problems. */
25797 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25798 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25799 		if (hwaccel) {
25800 			/*
25801 			 * hardware acceleration does not handle these
25802 			 * "slow path" cases.
25803 			 */
25804 			/* IPsec KSTATS: should bump bean counter here. */
25805 			if (ire_need_rele)
25806 				ire_refrele(ire);
25807 			freemsg(ipsec_mp);
25808 			return;
25809 		}
25810 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25811 		    (mp->b_cont ? msgdsize(mp) :
25812 		    mp->b_wptr - (uchar_t *)ip6h)) {
25813 			/* IPsec KSTATS: should bump bean counter here. */
25814 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25815 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25816 			    msgdsize(mp)));
25817 			if (ire_need_rele)
25818 				ire_refrele(ire);
25819 			freemsg(ipsec_mp);
25820 			return;
25821 		}
25822 		ASSERT(mp->b_prev == NULL);
25823 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25824 		    ntohs(ip6h->ip6_plen) +
25825 		    IPV6_HDR_LEN, ire->ire_max_frag));
25826 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25827 		    ire->ire_max_frag);
25828 	} else {
25829 		UPDATE_OB_PKT_COUNT(ire);
25830 		ire->ire_last_used_time = lbolt;
25831 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25832 	}
25833 	if (ire_need_rele)
25834 		ire_refrele(ire);
25835 	freeb(ipsec_mp);
25836 }
25837 
25838 void
25839 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25840 {
25841 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25842 	da_ipsec_t *hada;	/* data attributes */
25843 	ill_t *ill = (ill_t *)q->q_ptr;
25844 
25845 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25846 
25847 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25848 		/* IPsec KSTATS: Bump lose counter here! */
25849 		freemsg(mp);
25850 		return;
25851 	}
25852 
25853 	/*
25854 	 * It's an IPsec packet that must be
25855 	 * accelerated by the Provider, and the
25856 	 * outbound ill is IPsec acceleration capable.
25857 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25858 	 * to the ill.
25859 	 * IPsec KSTATS: should bump packet counter here.
25860 	 */
25861 
25862 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25863 	if (hada_mp == NULL) {
25864 		/* IPsec KSTATS: should bump packet counter here. */
25865 		freemsg(mp);
25866 		return;
25867 	}
25868 
25869 	hada_mp->b_datap->db_type = M_CTL;
25870 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25871 	hada_mp->b_cont = mp;
25872 
25873 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25874 	bzero(hada, sizeof (da_ipsec_t));
25875 	hada->da_type = IPHADA_M_CTL;
25876 
25877 	putnext(q, hada_mp);
25878 }
25879 
25880 /*
25881  * Finish the outbound IPsec processing. This function is called from
25882  * ipsec_out_process() if the IPsec packet was processed
25883  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25884  * asynchronously.
25885  */
25886 void
25887 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25888     ire_t *ire_arg)
25889 {
25890 	uint32_t v_hlen_tos_len;
25891 	ipaddr_t	dst;
25892 	ipif_t	*ipif = NULL;
25893 	ire_t *ire;
25894 	ire_t *ire1 = NULL;
25895 	mblk_t *next_mp = NULL;
25896 	uint32_t max_frag;
25897 	boolean_t multirt_send = B_FALSE;
25898 	mblk_t *mp;
25899 	ipha_t *ipha1;
25900 	uint_t	ill_index;
25901 	ipsec_out_t *io;
25902 	int match_flags;
25903 	irb_t *irb = NULL;
25904 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25905 	zoneid_t zoneid;
25906 	ipxmit_state_t	pktxmit_state;
25907 	ip_stack_t	*ipst;
25908 
25909 #ifdef	_BIG_ENDIAN
25910 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25911 #else
25912 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25913 #endif
25914 
25915 	mp = ipsec_mp->b_cont;
25916 	ipha1 = (ipha_t *)mp->b_rptr;
25917 	ASSERT(mp != NULL);
25918 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25919 	dst = ipha->ipha_dst;
25920 
25921 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25922 	ill_index = io->ipsec_out_ill_index;
25923 	zoneid = io->ipsec_out_zoneid;
25924 	ASSERT(zoneid != ALL_ZONES);
25925 	ipst = io->ipsec_out_ns->netstack_ip;
25926 	ASSERT(io->ipsec_out_ns != NULL);
25927 
25928 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25929 	if (ill == NULL && ill_index != 0) {
25930 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25931 		/* Failure case frees things for us. */
25932 		if (ill == NULL)
25933 			return;
25934 
25935 		ill_need_rele = B_TRUE;
25936 	}
25937 
25938 	if (CLASSD(dst)) {
25939 		boolean_t conn_dontroute;
25940 		/*
25941 		 * Use the ill_index to get the right ipif.
25942 		 */
25943 		conn_dontroute = io->ipsec_out_dontroute;
25944 		if (ill_index == 0)
25945 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25946 		else
25947 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25948 		if (ipif == NULL) {
25949 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25950 			    " multicast\n"));
25951 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25952 			freemsg(ipsec_mp);
25953 			goto done;
25954 		}
25955 		/*
25956 		 * ipha_src has already been intialized with the
25957 		 * value of the ipif in ip_wput. All we need now is
25958 		 * an ire to send this downstream.
25959 		 */
25960 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25961 		    msg_getlabel(mp), match_flags, ipst);
25962 		if (ire != NULL) {
25963 			ill_t *ill1;
25964 			/*
25965 			 * Do the multicast forwarding now, as the IPsec
25966 			 * processing has been done.
25967 			 */
25968 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25969 			    (ill1 = ire_to_ill(ire))) {
25970 				if (ip_mforward(ill1, ipha, mp)) {
25971 					freemsg(ipsec_mp);
25972 					ip1dbg(("ip_wput_ipsec_out: mforward "
25973 					    "failed\n"));
25974 					ire_refrele(ire);
25975 					goto done;
25976 				}
25977 			}
25978 			goto send;
25979 		}
25980 
25981 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25982 		mp->b_prev = NULL;
25983 		mp->b_next = NULL;
25984 
25985 		/*
25986 		 * If the IPsec packet was processed asynchronously,
25987 		 * drop it now.
25988 		 */
25989 		if (q == NULL) {
25990 			freemsg(ipsec_mp);
25991 			goto done;
25992 		}
25993 
25994 		/*
25995 		 * We may be using a wrong ipif to create the ire.
25996 		 * But it is okay as the source address is assigned
25997 		 * for the packet already. Next outbound packet would
25998 		 * create the IRE with the right IPIF in ip_wput.
25999 		 *
26000 		 * Also handle RTF_MULTIRT routes.
26001 		 */
26002 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26003 		    zoneid, &zero_info);
26004 	} else {
26005 		if (ire_arg != NULL) {
26006 			ire = ire_arg;
26007 			ire_need_rele = B_FALSE;
26008 		} else {
26009 			ire = ire_cache_lookup(dst, zoneid,
26010 			    msg_getlabel(mp), ipst);
26011 		}
26012 		if (ire != NULL) {
26013 			goto send;
26014 		}
26015 
26016 		/*
26017 		 * ire disappeared underneath.
26018 		 *
26019 		 * What we need to do here is the ip_newroute
26020 		 * logic to get the ire without doing the IPsec
26021 		 * processing. Follow the same old path. But this
26022 		 * time, ip_wput or ire_add_then_put will call us
26023 		 * directly as all the IPsec operations are done.
26024 		 */
26025 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26026 		mp->b_prev = NULL;
26027 		mp->b_next = NULL;
26028 
26029 		/*
26030 		 * If the IPsec packet was processed asynchronously,
26031 		 * drop it now.
26032 		 */
26033 		if (q == NULL) {
26034 			freemsg(ipsec_mp);
26035 			goto done;
26036 		}
26037 
26038 		/*
26039 		 * Since we're going through ip_newroute() again, we
26040 		 * need to make sure we don't:
26041 		 *
26042 		 *	1.) Trigger the ASSERT() with the ipha_ident
26043 		 *	    overloading.
26044 		 *	2.) Redo transport-layer checksumming, since we've
26045 		 *	    already done all that to get this far.
26046 		 *
26047 		 * The easiest way not do either of the above is to set
26048 		 * the ipha_ident field to IP_HDR_INCLUDED.
26049 		 */
26050 		ipha->ipha_ident = IP_HDR_INCLUDED;
26051 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26052 		    zoneid, ipst);
26053 	}
26054 	goto done;
26055 send:
26056 	if (ire->ire_stq == NULL) {
26057 		ill_t	*out_ill;
26058 		/*
26059 		 * Loopbacks go through ip_wput_local except for one case.
26060 		 * We come here if we generate a icmp_frag_needed message
26061 		 * after IPsec processing is over. When this function calls
26062 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26063 		 * icmp_frag_needed. The message generated comes back here
26064 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26065 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26066 		 * source address as it is usually set in ip_wput_ire. As
26067 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26068 		 * and we end up here. We can't enter ip_wput_ire once the
26069 		 * IPsec processing is over and hence we need to do it here.
26070 		 */
26071 		ASSERT(q != NULL);
26072 		UPDATE_OB_PKT_COUNT(ire);
26073 		ire->ire_last_used_time = lbolt;
26074 		if (ipha->ipha_src == 0)
26075 			ipha->ipha_src = ire->ire_src_addr;
26076 
26077 		/* PFHooks: LOOPBACK_OUT */
26078 		out_ill = ire_to_ill(ire);
26079 
26080 		/*
26081 		 * DTrace this as ip:::send.  A blocked packet will fire the
26082 		 * send probe, but not the receive probe.
26083 		 */
26084 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26085 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26086 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26087 
26088 		DTRACE_PROBE4(ip4__loopback__out__start,
26089 		    ill_t *, NULL, ill_t *, out_ill,
26090 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26091 
26092 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26093 		    ipst->ips_ipv4firewall_loopback_out,
26094 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26095 
26096 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26097 
26098 		if (ipsec_mp != NULL)
26099 			ip_wput_local(RD(q), out_ill,
26100 			    ipha, ipsec_mp, ire, 0, zoneid);
26101 		if (ire_need_rele)
26102 			ire_refrele(ire);
26103 		goto done;
26104 	}
26105 
26106 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26107 		/*
26108 		 * We are through with IPsec processing.
26109 		 * Fragment this and send it on the wire.
26110 		 */
26111 		if (io->ipsec_out_accelerated) {
26112 			/*
26113 			 * The packet has been accelerated but must
26114 			 * be fragmented. This should not happen
26115 			 * since AH and ESP must not accelerate
26116 			 * packets that need fragmentation, however
26117 			 * the configuration could have changed
26118 			 * since the AH or ESP processing.
26119 			 * Drop packet.
26120 			 * IPsec KSTATS: bump bean counter here.
26121 			 */
26122 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26123 			    "fragmented accelerated packet!\n"));
26124 			freemsg(ipsec_mp);
26125 		} else {
26126 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26127 			    zoneid, ipst, NULL);
26128 		}
26129 		if (ire_need_rele)
26130 			ire_refrele(ire);
26131 		goto done;
26132 	}
26133 
26134 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26135 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26136 	    (void *)ire->ire_ipif, (void *)ipif));
26137 
26138 	/*
26139 	 * Multiroute the secured packet.
26140 	 */
26141 	if (ire->ire_flags & RTF_MULTIRT) {
26142 		ire_t *first_ire;
26143 		irb = ire->ire_bucket;
26144 		ASSERT(irb != NULL);
26145 		/*
26146 		 * This ire has been looked up as the one that
26147 		 * goes through the given ipif;
26148 		 * make sure we do not omit any other multiroute ire
26149 		 * that may be present in the bucket before this one.
26150 		 */
26151 		IRB_REFHOLD(irb);
26152 		for (first_ire = irb->irb_ire;
26153 		    first_ire != NULL;
26154 		    first_ire = first_ire->ire_next) {
26155 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26156 			    (first_ire->ire_addr == ire->ire_addr) &&
26157 			    !(first_ire->ire_marks &
26158 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26159 				break;
26160 		}
26161 
26162 		if ((first_ire != NULL) && (first_ire != ire)) {
26163 			/*
26164 			 * Don't change the ire if the packet must
26165 			 * be fragmented if sent via this new one.
26166 			 */
26167 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26168 				IRE_REFHOLD(first_ire);
26169 				if (ire_need_rele)
26170 					ire_refrele(ire);
26171 				else
26172 					ire_need_rele = B_TRUE;
26173 				ire = first_ire;
26174 			}
26175 		}
26176 		IRB_REFRELE(irb);
26177 
26178 		multirt_send = B_TRUE;
26179 		max_frag = ire->ire_max_frag;
26180 	}
26181 
26182 	/*
26183 	 * In most cases, the emission loop below is entered only once.
26184 	 * Only in the case where the ire holds the RTF_MULTIRT
26185 	 * flag, we loop to process all RTF_MULTIRT ires in the
26186 	 * bucket, and send the packet through all crossed
26187 	 * RTF_MULTIRT routes.
26188 	 */
26189 	do {
26190 		if (multirt_send) {
26191 			/*
26192 			 * ire1 holds here the next ire to process in the
26193 			 * bucket. If multirouting is expected,
26194 			 * any non-RTF_MULTIRT ire that has the
26195 			 * right destination address is ignored.
26196 			 */
26197 			ASSERT(irb != NULL);
26198 			IRB_REFHOLD(irb);
26199 			for (ire1 = ire->ire_next;
26200 			    ire1 != NULL;
26201 			    ire1 = ire1->ire_next) {
26202 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26203 					continue;
26204 				if (ire1->ire_addr != ire->ire_addr)
26205 					continue;
26206 				if (ire1->ire_marks &
26207 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26208 					continue;
26209 				/* No loopback here */
26210 				if (ire1->ire_stq == NULL)
26211 					continue;
26212 				/*
26213 				 * Ensure we do not exceed the MTU
26214 				 * of the next route.
26215 				 */
26216 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26217 					ip_multirt_bad_mtu(ire1, max_frag);
26218 					continue;
26219 				}
26220 
26221 				IRE_REFHOLD(ire1);
26222 				break;
26223 			}
26224 			IRB_REFRELE(irb);
26225 			if (ire1 != NULL) {
26226 				/*
26227 				 * We are in a multiple send case, need to
26228 				 * make a copy of the packet.
26229 				 */
26230 				next_mp = copymsg(ipsec_mp);
26231 				if (next_mp == NULL) {
26232 					ire_refrele(ire1);
26233 					ire1 = NULL;
26234 				}
26235 			}
26236 		}
26237 		/*
26238 		 * Everything is done. Send it out on the wire
26239 		 *
26240 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26241 		 * either send it on the wire or, in the case of
26242 		 * HW acceleration, call ipsec_hw_putnext.
26243 		 */
26244 		if (ire->ire_nce &&
26245 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26246 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26247 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26248 			/*
26249 			 * If ire's link-layer is unresolved (this
26250 			 * would only happen if the incomplete ire
26251 			 * was added to cachetable via forwarding path)
26252 			 * don't bother going to ip_xmit_v4. Just drop the
26253 			 * packet.
26254 			 * There is a slight risk here, in that, if we
26255 			 * have the forwarding path create an incomplete
26256 			 * IRE, then until the IRE is completed, any
26257 			 * transmitted IPsec packets will be dropped
26258 			 * instead of being queued waiting for resolution.
26259 			 *
26260 			 * But the likelihood of a forwarding packet and a wput
26261 			 * packet sending to the same dst at the same time
26262 			 * and there not yet be an ARP entry for it is small.
26263 			 * Furthermore, if this actually happens, it might
26264 			 * be likely that wput would generate multiple
26265 			 * packets (and forwarding would also have a train
26266 			 * of packets) for that destination. If this is
26267 			 * the case, some of them would have been dropped
26268 			 * anyway, since ARP only queues a few packets while
26269 			 * waiting for resolution
26270 			 *
26271 			 * NOTE: We should really call ip_xmit_v4,
26272 			 * and let it queue the packet and send the
26273 			 * ARP query and have ARP come back thus:
26274 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26275 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26276 			 * hw accel work. But it's too complex to get
26277 			 * the IPsec hw  acceleration approach to fit
26278 			 * well with ip_xmit_v4 doing ARP without
26279 			 * doing IPsec simplification. For now, we just
26280 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26281 			 * that we can continue with the send on the next
26282 			 * attempt.
26283 			 *
26284 			 * XXX THis should be revisited, when
26285 			 * the IPsec/IP interaction is cleaned up
26286 			 */
26287 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26288 			    " - dropping packet\n"));
26289 			freemsg(ipsec_mp);
26290 			/*
26291 			 * Call ip_xmit_v4() to trigger ARP query
26292 			 * in case the nce_state is ND_INITIAL
26293 			 */
26294 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26295 			goto drop_pkt;
26296 		}
26297 
26298 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26299 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26300 		    mblk_t *, ipsec_mp);
26301 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26302 		    ipst->ips_ipv4firewall_physical_out, NULL,
26303 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26304 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26305 		if (ipsec_mp == NULL)
26306 			goto drop_pkt;
26307 
26308 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26309 		pktxmit_state = ip_xmit_v4(mp, ire,
26310 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26311 
26312 		if ((pktxmit_state ==  SEND_FAILED) ||
26313 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26314 
26315 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26316 drop_pkt:
26317 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26318 			    ipIfStatsOutDiscards);
26319 			if (ire_need_rele)
26320 				ire_refrele(ire);
26321 			if (ire1 != NULL) {
26322 				ire_refrele(ire1);
26323 				freemsg(next_mp);
26324 			}
26325 			goto done;
26326 		}
26327 
26328 		freeb(ipsec_mp);
26329 		if (ire_need_rele)
26330 			ire_refrele(ire);
26331 
26332 		if (ire1 != NULL) {
26333 			ire = ire1;
26334 			ire_need_rele = B_TRUE;
26335 			ASSERT(next_mp);
26336 			ipsec_mp = next_mp;
26337 			mp = ipsec_mp->b_cont;
26338 			ire1 = NULL;
26339 			next_mp = NULL;
26340 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26341 		} else {
26342 			multirt_send = B_FALSE;
26343 		}
26344 	} while (multirt_send);
26345 done:
26346 	if (ill != NULL && ill_need_rele)
26347 		ill_refrele(ill);
26348 	if (ipif != NULL)
26349 		ipif_refrele(ipif);
26350 }
26351 
26352 /*
26353  * Get the ill corresponding to the specified ire, and compare its
26354  * capabilities with the protocol and algorithms specified by the
26355  * the SA obtained from ipsec_out. If they match, annotate the
26356  * ipsec_out structure to indicate that the packet needs acceleration.
26357  *
26358  *
26359  * A packet is eligible for outbound hardware acceleration if the
26360  * following conditions are satisfied:
26361  *
26362  * 1. the packet will not be fragmented
26363  * 2. the provider supports the algorithm
26364  * 3. there is no pending control message being exchanged
26365  * 4. snoop is not attached
26366  * 5. the destination address is not a broadcast or multicast address.
26367  *
26368  * Rationale:
26369  *	- Hardware drivers do not support fragmentation with
26370  *	  the current interface.
26371  *	- snoop, multicast, and broadcast may result in exposure of
26372  *	  a cleartext datagram.
26373  * We check all five of these conditions here.
26374  *
26375  * XXX would like to nuke "ire_t *" parameter here; problem is that
26376  * IRE is only way to figure out if a v4 address is a broadcast and
26377  * thus ineligible for acceleration...
26378  */
26379 static void
26380 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26381 {
26382 	ipsec_out_t *io;
26383 	mblk_t *data_mp;
26384 	uint_t plen, overhead;
26385 	ip_stack_t	*ipst;
26386 
26387 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26388 		return;
26389 
26390 	if (ill == NULL)
26391 		return;
26392 	ipst = ill->ill_ipst;
26393 	/*
26394 	 * Destination address is a broadcast or multicast.  Punt.
26395 	 */
26396 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26397 	    IRE_LOCAL)))
26398 		return;
26399 
26400 	data_mp = ipsec_mp->b_cont;
26401 
26402 	if (ill->ill_isv6) {
26403 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26404 
26405 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26406 			return;
26407 
26408 		plen = ip6h->ip6_plen;
26409 	} else {
26410 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26411 
26412 		if (CLASSD(ipha->ipha_dst))
26413 			return;
26414 
26415 		plen = ipha->ipha_length;
26416 	}
26417 	/*
26418 	 * Is there a pending DLPI control message being exchanged
26419 	 * between IP/IPsec and the DLS Provider? If there is, it
26420 	 * could be a SADB update, and the state of the DLS Provider
26421 	 * SADB might not be in sync with the SADB maintained by
26422 	 * IPsec. To avoid dropping packets or using the wrong keying
26423 	 * material, we do not accelerate this packet.
26424 	 */
26425 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26426 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26427 		    "ill_dlpi_pending! don't accelerate packet\n"));
26428 		return;
26429 	}
26430 
26431 	/*
26432 	 * Is the Provider in promiscous mode? If it does, we don't
26433 	 * accelerate the packet since it will bounce back up to the
26434 	 * listeners in the clear.
26435 	 */
26436 	if (ill->ill_promisc_on_phys) {
26437 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26438 		    "ill in promiscous mode, don't accelerate packet\n"));
26439 		return;
26440 	}
26441 
26442 	/*
26443 	 * Will the packet require fragmentation?
26444 	 */
26445 
26446 	/*
26447 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26448 	 * as is used elsewhere.
26449 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26450 	 *	+ 2-byte trailer
26451 	 */
26452 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26453 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26454 
26455 	if ((plen + overhead) > ill->ill_max_mtu)
26456 		return;
26457 
26458 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26459 
26460 	/*
26461 	 * Can the ill accelerate this IPsec protocol and algorithm
26462 	 * specified by the SA?
26463 	 */
26464 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26465 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26466 		return;
26467 	}
26468 
26469 	/*
26470 	 * Tell AH or ESP that the outbound ill is capable of
26471 	 * accelerating this packet.
26472 	 */
26473 	io->ipsec_out_is_capab_ill = B_TRUE;
26474 }
26475 
26476 /*
26477  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26478  *
26479  * If this function returns B_TRUE, the requested SA's have been filled
26480  * into the ipsec_out_*_sa pointers.
26481  *
26482  * If the function returns B_FALSE, the packet has been "consumed", most
26483  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26484  *
26485  * The SA references created by the protocol-specific "select"
26486  * function will be released when the ipsec_mp is freed, thanks to the
26487  * ipsec_out_free destructor -- see spd.c.
26488  */
26489 static boolean_t
26490 ipsec_out_select_sa(mblk_t *ipsec_mp)
26491 {
26492 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26493 	ipsec_out_t *io;
26494 	ipsec_policy_t *pp;
26495 	ipsec_action_t *ap;
26496 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26497 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26498 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26499 
26500 	if (!io->ipsec_out_secure) {
26501 		/*
26502 		 * We came here by mistake.
26503 		 * Don't bother with ipsec processing
26504 		 * We should "discourage" this path in the future.
26505 		 */
26506 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26507 		return (B_FALSE);
26508 	}
26509 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26510 	ASSERT((io->ipsec_out_policy != NULL) ||
26511 	    (io->ipsec_out_act != NULL));
26512 
26513 	ASSERT(io->ipsec_out_failed == B_FALSE);
26514 
26515 	/*
26516 	 * IPsec processing has started.
26517 	 */
26518 	io->ipsec_out_proc_begin = B_TRUE;
26519 	ap = io->ipsec_out_act;
26520 	if (ap == NULL) {
26521 		pp = io->ipsec_out_policy;
26522 		ASSERT(pp != NULL);
26523 		ap = pp->ipsp_act;
26524 		ASSERT(ap != NULL);
26525 	}
26526 
26527 	/*
26528 	 * We have an action.  now, let's select SA's.
26529 	 * (In the future, we can cache this in the conn_t..)
26530 	 */
26531 	if (ap->ipa_want_esp) {
26532 		if (io->ipsec_out_esp_sa == NULL) {
26533 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26534 			    IPPROTO_ESP);
26535 		}
26536 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26537 	}
26538 
26539 	if (ap->ipa_want_ah) {
26540 		if (io->ipsec_out_ah_sa == NULL) {
26541 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26542 			    IPPROTO_AH);
26543 		}
26544 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26545 		/*
26546 		 * The ESP and AH processing order needs to be preserved
26547 		 * when both protocols are required (ESP should be applied
26548 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26549 		 * when both ESP and AH are required, and an AH ACQUIRE
26550 		 * is needed.
26551 		 */
26552 		if (ap->ipa_want_esp && need_ah_acquire)
26553 			need_esp_acquire = B_TRUE;
26554 	}
26555 
26556 	/*
26557 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26558 	 * Release SAs that got referenced, but will not be used until we
26559 	 * acquire _all_ of the SAs we need.
26560 	 */
26561 	if (need_ah_acquire || need_esp_acquire) {
26562 		if (io->ipsec_out_ah_sa != NULL) {
26563 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26564 			io->ipsec_out_ah_sa = NULL;
26565 		}
26566 		if (io->ipsec_out_esp_sa != NULL) {
26567 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26568 			io->ipsec_out_esp_sa = NULL;
26569 		}
26570 
26571 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26572 		return (B_FALSE);
26573 	}
26574 
26575 	return (B_TRUE);
26576 }
26577 
26578 /*
26579  * Process an IPSEC_OUT message and see what you can
26580  * do with it.
26581  * IPQoS Notes:
26582  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26583  * IPsec.
26584  * XXX would like to nuke ire_t.
26585  * XXX ill_index better be "real"
26586  */
26587 void
26588 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26589 {
26590 	ipsec_out_t *io;
26591 	ipsec_policy_t *pp;
26592 	ipsec_action_t *ap;
26593 	ipha_t *ipha;
26594 	ip6_t *ip6h;
26595 	mblk_t *mp;
26596 	ill_t *ill;
26597 	zoneid_t zoneid;
26598 	ipsec_status_t ipsec_rc;
26599 	boolean_t ill_need_rele = B_FALSE;
26600 	ip_stack_t	*ipst;
26601 	ipsec_stack_t	*ipss;
26602 
26603 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26604 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26605 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26606 	ipst = io->ipsec_out_ns->netstack_ip;
26607 	mp = ipsec_mp->b_cont;
26608 
26609 	/*
26610 	 * Initiate IPPF processing. We do it here to account for packets
26611 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26612 	 * We can check for ipsec_out_proc_begin even for such packets, as
26613 	 * they will always be false (asserted below).
26614 	 */
26615 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26616 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26617 		    io->ipsec_out_ill_index : ill_index);
26618 		if (mp == NULL) {
26619 			ip2dbg(("ipsec_out_process: packet dropped "\
26620 			    "during IPPF processing\n"));
26621 			freeb(ipsec_mp);
26622 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26623 			return;
26624 		}
26625 	}
26626 
26627 	if (!io->ipsec_out_secure) {
26628 		/*
26629 		 * We came here by mistake.
26630 		 * Don't bother with ipsec processing
26631 		 * Should "discourage" this path in the future.
26632 		 */
26633 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26634 		goto done;
26635 	}
26636 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26637 	ASSERT((io->ipsec_out_policy != NULL) ||
26638 	    (io->ipsec_out_act != NULL));
26639 	ASSERT(io->ipsec_out_failed == B_FALSE);
26640 
26641 	ipss = ipst->ips_netstack->netstack_ipsec;
26642 	if (!ipsec_loaded(ipss)) {
26643 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26644 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26645 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26646 		} else {
26647 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26648 		}
26649 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26650 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26651 		    &ipss->ipsec_dropper);
26652 		return;
26653 	}
26654 
26655 	/*
26656 	 * IPsec processing has started.
26657 	 */
26658 	io->ipsec_out_proc_begin = B_TRUE;
26659 	ap = io->ipsec_out_act;
26660 	if (ap == NULL) {
26661 		pp = io->ipsec_out_policy;
26662 		ASSERT(pp != NULL);
26663 		ap = pp->ipsp_act;
26664 		ASSERT(ap != NULL);
26665 	}
26666 
26667 	/*
26668 	 * Save the outbound ill index. When the packet comes back
26669 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26670 	 * before sending it the accelerated packet.
26671 	 */
26672 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26673 		ill = ire_to_ill(ire);
26674 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26675 	}
26676 
26677 	/*
26678 	 * The order of processing is first insert a IP header if needed.
26679 	 * Then insert the ESP header and then the AH header.
26680 	 */
26681 	if ((io->ipsec_out_se_done == B_FALSE) &&
26682 	    (ap->ipa_want_se)) {
26683 		/*
26684 		 * First get the outer IP header before sending
26685 		 * it to ESP.
26686 		 */
26687 		ipha_t *oipha, *iipha;
26688 		mblk_t *outer_mp, *inner_mp;
26689 
26690 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26691 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26692 			    "ipsec_out_process: "
26693 			    "Self-Encapsulation failed: Out of memory\n");
26694 			freemsg(ipsec_mp);
26695 			if (ill != NULL) {
26696 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26697 			} else {
26698 				BUMP_MIB(&ipst->ips_ip_mib,
26699 				    ipIfStatsOutDiscards);
26700 			}
26701 			return;
26702 		}
26703 		inner_mp = ipsec_mp->b_cont;
26704 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26705 		oipha = (ipha_t *)outer_mp->b_rptr;
26706 		iipha = (ipha_t *)inner_mp->b_rptr;
26707 		*oipha = *iipha;
26708 		outer_mp->b_wptr += sizeof (ipha_t);
26709 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26710 		    sizeof (ipha_t));
26711 		oipha->ipha_protocol = IPPROTO_ENCAP;
26712 		oipha->ipha_version_and_hdr_length =
26713 		    IP_SIMPLE_HDR_VERSION;
26714 		oipha->ipha_hdr_checksum = 0;
26715 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26716 		outer_mp->b_cont = inner_mp;
26717 		ipsec_mp->b_cont = outer_mp;
26718 
26719 		io->ipsec_out_se_done = B_TRUE;
26720 		io->ipsec_out_tunnel = B_TRUE;
26721 	}
26722 
26723 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26724 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26725 	    !ipsec_out_select_sa(ipsec_mp))
26726 		return;
26727 
26728 	/*
26729 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26730 	 * to do the heavy lifting.
26731 	 */
26732 	zoneid = io->ipsec_out_zoneid;
26733 	ASSERT(zoneid != ALL_ZONES);
26734 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26735 		ASSERT(io->ipsec_out_esp_sa != NULL);
26736 		io->ipsec_out_esp_done = B_TRUE;
26737 		/*
26738 		 * Note that since hw accel can only apply one transform,
26739 		 * not two, we skip hw accel for ESP if we also have AH
26740 		 * This is an design limitation of the interface
26741 		 * which should be revisited.
26742 		 */
26743 		ASSERT(ire != NULL);
26744 		if (io->ipsec_out_ah_sa == NULL) {
26745 			ill = (ill_t *)ire->ire_stq->q_ptr;
26746 			ipsec_out_is_accelerated(ipsec_mp,
26747 			    io->ipsec_out_esp_sa, ill, ire);
26748 		}
26749 
26750 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26751 		switch (ipsec_rc) {
26752 		case IPSEC_STATUS_SUCCESS:
26753 			break;
26754 		case IPSEC_STATUS_FAILED:
26755 			if (ill != NULL) {
26756 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26757 			} else {
26758 				BUMP_MIB(&ipst->ips_ip_mib,
26759 				    ipIfStatsOutDiscards);
26760 			}
26761 			/* FALLTHRU */
26762 		case IPSEC_STATUS_PENDING:
26763 			return;
26764 		}
26765 	}
26766 
26767 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26768 		ASSERT(io->ipsec_out_ah_sa != NULL);
26769 		io->ipsec_out_ah_done = B_TRUE;
26770 		if (ire == NULL) {
26771 			int idx = io->ipsec_out_capab_ill_index;
26772 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26773 			    NULL, NULL, NULL, NULL, ipst);
26774 			ill_need_rele = B_TRUE;
26775 		} else {
26776 			ill = (ill_t *)ire->ire_stq->q_ptr;
26777 		}
26778 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26779 		    ire);
26780 
26781 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26782 		switch (ipsec_rc) {
26783 		case IPSEC_STATUS_SUCCESS:
26784 			break;
26785 		case IPSEC_STATUS_FAILED:
26786 			if (ill != NULL) {
26787 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26788 			} else {
26789 				BUMP_MIB(&ipst->ips_ip_mib,
26790 				    ipIfStatsOutDiscards);
26791 			}
26792 			/* FALLTHRU */
26793 		case IPSEC_STATUS_PENDING:
26794 			if (ill != NULL && ill_need_rele)
26795 				ill_refrele(ill);
26796 			return;
26797 		}
26798 	}
26799 	/*
26800 	 * We are done with IPsec processing. Send it over the wire.
26801 	 */
26802 done:
26803 	mp = ipsec_mp->b_cont;
26804 	ipha = (ipha_t *)mp->b_rptr;
26805 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26806 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26807 		    ire);
26808 	} else {
26809 		ip6h = (ip6_t *)ipha;
26810 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26811 		    ire);
26812 	}
26813 	if (ill != NULL && ill_need_rele)
26814 		ill_refrele(ill);
26815 }
26816 
26817 /* ARGSUSED */
26818 void
26819 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26820 {
26821 	opt_restart_t	*or;
26822 	int	err;
26823 	conn_t	*connp;
26824 	cred_t	*cr;
26825 
26826 	ASSERT(CONN_Q(q));
26827 	connp = Q_TO_CONN(q);
26828 
26829 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26830 	or = (opt_restart_t *)first_mp->b_rptr;
26831 	/*
26832 	 * We checked for a db_credp the first time svr4_optcom_req
26833 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26834 	 */
26835 	cr = msg_getcred(first_mp, NULL);
26836 	ASSERT(cr != NULL);
26837 
26838 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26839 		err = svr4_optcom_req(q, first_mp, cr,
26840 		    &ip_opt_obj, B_FALSE);
26841 	} else {
26842 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26843 		err = tpi_optcom_req(q, first_mp, cr,
26844 		    &ip_opt_obj, B_FALSE);
26845 	}
26846 	if (err != EINPROGRESS) {
26847 		/* operation is done */
26848 		CONN_OPER_PENDING_DONE(connp);
26849 	}
26850 }
26851 
26852 /*
26853  * ioctls that go through a down/up sequence may need to wait for the down
26854  * to complete. This involves waiting for the ire and ipif refcnts to go down
26855  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26856  */
26857 /* ARGSUSED */
26858 void
26859 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26860 {
26861 	struct iocblk *iocp;
26862 	mblk_t *mp1;
26863 	ip_ioctl_cmd_t *ipip;
26864 	int err;
26865 	sin_t	*sin;
26866 	struct lifreq *lifr;
26867 	struct ifreq *ifr;
26868 
26869 	iocp = (struct iocblk *)mp->b_rptr;
26870 	ASSERT(ipsq != NULL);
26871 	/* Existence of mp1 verified in ip_wput_nondata */
26872 	mp1 = mp->b_cont->b_cont;
26873 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26874 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26875 		/*
26876 		 * Special case where ipx_current_ipif is not set:
26877 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26878 		 * We are here as were not able to complete the operation in
26879 		 * ipif_set_values because we could not become exclusive on
26880 		 * the new ipsq.
26881 		 */
26882 		ill_t *ill = q->q_ptr;
26883 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26884 	}
26885 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26886 
26887 	if (ipip->ipi_cmd_type == IF_CMD) {
26888 		/* This a old style SIOC[GS]IF* command */
26889 		ifr = (struct ifreq *)mp1->b_rptr;
26890 		sin = (sin_t *)&ifr->ifr_addr;
26891 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26892 		/* This a new style SIOC[GS]LIF* command */
26893 		lifr = (struct lifreq *)mp1->b_rptr;
26894 		sin = (sin_t *)&lifr->lifr_addr;
26895 	} else {
26896 		sin = NULL;
26897 	}
26898 
26899 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26900 	    q, mp, ipip, mp1->b_rptr);
26901 
26902 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26903 }
26904 
26905 /*
26906  * ioctl processing
26907  *
26908  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26909  * the ioctl command in the ioctl tables, determines the copyin data size
26910  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26911  *
26912  * ioctl processing then continues when the M_IOCDATA makes its way down to
26913  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26914  * associated 'conn' is refheld till the end of the ioctl and the general
26915  * ioctl processing function ip_process_ioctl() is called to extract the
26916  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26917  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26918  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26919  * is used to extract the ioctl's arguments.
26920  *
26921  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26922  * so goes thru the serialization primitive ipsq_try_enter. Then the
26923  * appropriate function to handle the ioctl is called based on the entry in
26924  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26925  * which also refreleases the 'conn' that was refheld at the start of the
26926  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26927  *
26928  * Many exclusive ioctls go thru an internal down up sequence as part of
26929  * the operation. For example an attempt to change the IP address of an
26930  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26931  * does all the cleanup such as deleting all ires that use this address.
26932  * Then we need to wait till all references to the interface go away.
26933  */
26934 void
26935 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26936 {
26937 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26938 	ip_ioctl_cmd_t *ipip = arg;
26939 	ip_extract_func_t *extract_funcp;
26940 	cmd_info_t ci;
26941 	int err;
26942 	boolean_t entered_ipsq = B_FALSE;
26943 
26944 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26945 
26946 	if (ipip == NULL)
26947 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26948 
26949 	/*
26950 	 * SIOCLIFADDIF needs to go thru a special path since the
26951 	 * ill may not exist yet. This happens in the case of lo0
26952 	 * which is created using this ioctl.
26953 	 */
26954 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26955 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26956 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26957 		return;
26958 	}
26959 
26960 	ci.ci_ipif = NULL;
26961 	if (ipip->ipi_cmd_type == MISC_CMD) {
26962 		/*
26963 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26964 		 */
26965 		if (ipip->ipi_cmd == IF_UNITSEL) {
26966 			/* ioctl comes down the ill */
26967 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26968 			ipif_refhold(ci.ci_ipif);
26969 		}
26970 		err = 0;
26971 		ci.ci_sin = NULL;
26972 		ci.ci_sin6 = NULL;
26973 		ci.ci_lifr = NULL;
26974 	} else {
26975 		switch (ipip->ipi_cmd_type) {
26976 		case IF_CMD:
26977 		case LIF_CMD:
26978 			extract_funcp = ip_extract_lifreq;
26979 			break;
26980 
26981 		case ARP_CMD:
26982 		case XARP_CMD:
26983 			extract_funcp = ip_extract_arpreq;
26984 			break;
26985 
26986 		case TUN_CMD:
26987 			extract_funcp = ip_extract_tunreq;
26988 			break;
26989 
26990 		case MSFILT_CMD:
26991 			extract_funcp = ip_extract_msfilter;
26992 			break;
26993 
26994 		default:
26995 			ASSERT(0);
26996 		}
26997 
26998 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26999 		if (err != 0) {
27000 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27001 			return;
27002 		}
27003 
27004 		/*
27005 		 * All of the extraction functions return a refheld ipif.
27006 		 */
27007 		ASSERT(ci.ci_ipif != NULL);
27008 	}
27009 
27010 	if (!(ipip->ipi_flags & IPI_WR)) {
27011 		/*
27012 		 * A return value of EINPROGRESS means the ioctl is
27013 		 * either queued and waiting for some reason or has
27014 		 * already completed.
27015 		 */
27016 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27017 		    ci.ci_lifr);
27018 		if (ci.ci_ipif != NULL)
27019 			ipif_refrele(ci.ci_ipif);
27020 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27021 		return;
27022 	}
27023 
27024 	ASSERT(ci.ci_ipif != NULL);
27025 
27026 	/*
27027 	 * If ipsq is non-NULL, we are already being called exclusively.
27028 	 */
27029 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27030 	if (ipsq == NULL) {
27031 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27032 		    NEW_OP, B_TRUE);
27033 		if (ipsq == NULL) {
27034 			ipif_refrele(ci.ci_ipif);
27035 			return;
27036 		}
27037 		entered_ipsq = B_TRUE;
27038 	}
27039 
27040 	/*
27041 	 * Release the ipif so that ipif_down and friends that wait for
27042 	 * references to go away are not misled about the current ipif_refcnt
27043 	 * values. We are writer so we can access the ipif even after releasing
27044 	 * the ipif.
27045 	 */
27046 	ipif_refrele(ci.ci_ipif);
27047 
27048 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27049 
27050 	/*
27051 	 * For most set ioctls that come here, this serves as a single point
27052 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27053 	 * be any new references to the ipif. This helps functions that go
27054 	 * through this path and end up trying to wait for the refcnts
27055 	 * associated with the ipif to go down to zero.  The exception is
27056 	 * SIOCSLIFREMOVEIF, which sets IPIF_CONDEMNED internally after
27057 	 * identifying the right ipif to operate on.
27058 	 */
27059 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27060 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF)
27061 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27062 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27063 
27064 	/*
27065 	 * A return value of EINPROGRESS means the ioctl is
27066 	 * either queued and waiting for some reason or has
27067 	 * already completed.
27068 	 */
27069 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27070 
27071 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27072 
27073 	if (entered_ipsq)
27074 		ipsq_exit(ipsq);
27075 }
27076 
27077 /*
27078  * Complete the ioctl. Typically ioctls use the mi package and need to
27079  * do mi_copyout/mi_copy_done.
27080  */
27081 void
27082 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27083 {
27084 	conn_t	*connp = NULL;
27085 
27086 	if (err == EINPROGRESS)
27087 		return;
27088 
27089 	if (CONN_Q(q)) {
27090 		connp = Q_TO_CONN(q);
27091 		ASSERT(connp->conn_ref >= 2);
27092 	}
27093 
27094 	switch (mode) {
27095 	case COPYOUT:
27096 		if (err == 0)
27097 			mi_copyout(q, mp);
27098 		else
27099 			mi_copy_done(q, mp, err);
27100 		break;
27101 
27102 	case NO_COPYOUT:
27103 		mi_copy_done(q, mp, err);
27104 		break;
27105 
27106 	default:
27107 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27108 		break;
27109 	}
27110 
27111 	/*
27112 	 * The refhold placed at the start of the ioctl is released here.
27113 	 */
27114 	if (connp != NULL)
27115 		CONN_OPER_PENDING_DONE(connp);
27116 
27117 	if (ipsq != NULL)
27118 		ipsq_current_finish(ipsq);
27119 }
27120 
27121 /* Called from ip_wput for all non data messages */
27122 /* ARGSUSED */
27123 void
27124 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27125 {
27126 	mblk_t		*mp1;
27127 	ire_t		*ire, *fake_ire;
27128 	ill_t		*ill;
27129 	struct iocblk	*iocp;
27130 	ip_ioctl_cmd_t	*ipip;
27131 	cred_t		*cr;
27132 	conn_t		*connp;
27133 	int		err;
27134 	nce_t		*nce;
27135 	ipif_t		*ipif;
27136 	ip_stack_t	*ipst;
27137 	char		*proto_str;
27138 
27139 	if (CONN_Q(q)) {
27140 		connp = Q_TO_CONN(q);
27141 		ipst = connp->conn_netstack->netstack_ip;
27142 	} else {
27143 		connp = NULL;
27144 		ipst = ILLQ_TO_IPST(q);
27145 	}
27146 
27147 	switch (DB_TYPE(mp)) {
27148 	case M_IOCTL:
27149 		/*
27150 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27151 		 * will arrange to copy in associated control structures.
27152 		 */
27153 		ip_sioctl_copyin_setup(q, mp);
27154 		return;
27155 	case M_IOCDATA:
27156 		/*
27157 		 * Ensure that this is associated with one of our trans-
27158 		 * parent ioctls.  If it's not ours, discard it if we're
27159 		 * running as a driver, or pass it on if we're a module.
27160 		 */
27161 		iocp = (struct iocblk *)mp->b_rptr;
27162 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27163 		if (ipip == NULL) {
27164 			if (q->q_next == NULL) {
27165 				goto nak;
27166 			} else {
27167 				putnext(q, mp);
27168 			}
27169 			return;
27170 		}
27171 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27172 			/*
27173 			 * the ioctl is one we recognise, but is not
27174 			 * consumed by IP as a module, pass M_IOCDATA
27175 			 * for processing downstream, but only for
27176 			 * common Streams ioctls.
27177 			 */
27178 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27179 				putnext(q, mp);
27180 				return;
27181 			} else {
27182 				goto nak;
27183 			}
27184 		}
27185 
27186 		/* IOCTL continuation following copyin or copyout. */
27187 		if (mi_copy_state(q, mp, NULL) == -1) {
27188 			/*
27189 			 * The copy operation failed.  mi_copy_state already
27190 			 * cleaned up, so we're out of here.
27191 			 */
27192 			return;
27193 		}
27194 		/*
27195 		 * If we just completed a copy in, we become writer and
27196 		 * continue processing in ip_sioctl_copyin_done.  If it
27197 		 * was a copy out, we call mi_copyout again.  If there is
27198 		 * nothing more to copy out, it will complete the IOCTL.
27199 		 */
27200 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27201 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27202 				mi_copy_done(q, mp, EPROTO);
27203 				return;
27204 			}
27205 			/*
27206 			 * Check for cases that need more copying.  A return
27207 			 * value of 0 means a second copyin has been started,
27208 			 * so we return; a return value of 1 means no more
27209 			 * copying is needed, so we continue.
27210 			 */
27211 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27212 			    MI_COPY_COUNT(mp) == 1) {
27213 				if (ip_copyin_msfilter(q, mp) == 0)
27214 					return;
27215 			}
27216 			/*
27217 			 * Refhold the conn, till the ioctl completes. This is
27218 			 * needed in case the ioctl ends up in the pending mp
27219 			 * list. Every mp in the ill_pending_mp list and
27220 			 * the ipx_pending_mp must have a refhold on the conn
27221 			 * to resume processing. The refhold is released when
27222 			 * the ioctl completes. (normally or abnormally)
27223 			 * In all cases ip_ioctl_finish is called to finish
27224 			 * the ioctl.
27225 			 */
27226 			if (connp != NULL) {
27227 				/* This is not a reentry */
27228 				ASSERT(ipsq == NULL);
27229 				CONN_INC_REF(connp);
27230 			} else {
27231 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27232 					mi_copy_done(q, mp, EINVAL);
27233 					return;
27234 				}
27235 			}
27236 
27237 			ip_process_ioctl(ipsq, q, mp, ipip);
27238 
27239 		} else {
27240 			mi_copyout(q, mp);
27241 		}
27242 		return;
27243 nak:
27244 		iocp->ioc_error = EINVAL;
27245 		mp->b_datap->db_type = M_IOCNAK;
27246 		iocp->ioc_count = 0;
27247 		qreply(q, mp);
27248 		return;
27249 
27250 	case M_IOCNAK:
27251 		/*
27252 		 * The only way we could get here is if a resolver didn't like
27253 		 * an IOCTL we sent it.	 This shouldn't happen.
27254 		 */
27255 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27256 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27257 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27258 		freemsg(mp);
27259 		return;
27260 	case M_IOCACK:
27261 		/* /dev/ip shouldn't see this */
27262 		if (CONN_Q(q))
27263 			goto nak;
27264 
27265 		/*
27266 		 * Finish socket ioctls passed through to ARP.  We use the
27267 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27268 		 * we need to become writer before calling ip_sioctl_iocack().
27269 		 * Note that qwriter_ip() will release the refhold, and that a
27270 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27271 		 * ill stream.
27272 		 */
27273 		iocp = (struct iocblk *)mp->b_rptr;
27274 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27275 			ip_sioctl_iocack(NULL, q, mp, NULL);
27276 			return;
27277 		}
27278 
27279 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27280 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27281 		ill = q->q_ptr;
27282 		ill_refhold(ill);
27283 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27284 		return;
27285 	case M_FLUSH:
27286 		if (*mp->b_rptr & FLUSHW)
27287 			flushq(q, FLUSHALL);
27288 		if (q->q_next) {
27289 			putnext(q, mp);
27290 			return;
27291 		}
27292 		if (*mp->b_rptr & FLUSHR) {
27293 			*mp->b_rptr &= ~FLUSHW;
27294 			qreply(q, mp);
27295 			return;
27296 		}
27297 		freemsg(mp);
27298 		return;
27299 	case IRE_DB_REQ_TYPE:
27300 		if (connp == NULL) {
27301 			proto_str = "IRE_DB_REQ_TYPE";
27302 			goto protonak;
27303 		}
27304 		/* An Upper Level Protocol wants a copy of an IRE. */
27305 		ip_ire_req(q, mp);
27306 		return;
27307 	case M_CTL:
27308 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27309 			break;
27310 
27311 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27312 		    TUN_HELLO) {
27313 			ASSERT(connp != NULL);
27314 			connp->conn_flags |= IPCL_IPTUN;
27315 			freeb(mp);
27316 			return;
27317 		}
27318 
27319 		/* M_CTL messages are used by ARP to tell us things. */
27320 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27321 			break;
27322 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27323 		case AR_ENTRY_SQUERY:
27324 			ip_wput_ctl(q, mp);
27325 			return;
27326 		case AR_CLIENT_NOTIFY:
27327 			ip_arp_news(q, mp);
27328 			return;
27329 		case AR_DLPIOP_DONE:
27330 			ASSERT(q->q_next != NULL);
27331 			ill = (ill_t *)q->q_ptr;
27332 			/* qwriter_ip releases the refhold */
27333 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27334 			ill_refhold(ill);
27335 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27336 			return;
27337 		case AR_ARP_CLOSING:
27338 			/*
27339 			 * ARP (above us) is closing. If no ARP bringup is
27340 			 * currently pending, ack the message so that ARP
27341 			 * can complete its close. Also mark ill_arp_closing
27342 			 * so that new ARP bringups will fail. If any
27343 			 * ARP bringup is currently in progress, we will
27344 			 * ack this when the current ARP bringup completes.
27345 			 */
27346 			ASSERT(q->q_next != NULL);
27347 			ill = (ill_t *)q->q_ptr;
27348 			mutex_enter(&ill->ill_lock);
27349 			ill->ill_arp_closing = 1;
27350 			if (!ill->ill_arp_bringup_pending) {
27351 				mutex_exit(&ill->ill_lock);
27352 				qreply(q, mp);
27353 			} else {
27354 				mutex_exit(&ill->ill_lock);
27355 				freemsg(mp);
27356 			}
27357 			return;
27358 		case AR_ARP_EXTEND:
27359 			/*
27360 			 * The ARP module above us is capable of duplicate
27361 			 * address detection.  Old ATM drivers will not send
27362 			 * this message.
27363 			 */
27364 			ASSERT(q->q_next != NULL);
27365 			ill = (ill_t *)q->q_ptr;
27366 			ill->ill_arp_extend = B_TRUE;
27367 			freemsg(mp);
27368 			return;
27369 		default:
27370 			break;
27371 		}
27372 		break;
27373 	case M_PROTO:
27374 	case M_PCPROTO:
27375 		/*
27376 		 * The only PROTO messages we expect are copies of option
27377 		 * negotiation acknowledgements, AH and ESP bind requests
27378 		 * are also expected.
27379 		 */
27380 		switch (((union T_primitives *)mp->b_rptr)->type) {
27381 		case O_T_BIND_REQ:
27382 		case T_BIND_REQ: {
27383 			/* Request can get queued in bind */
27384 			if (connp == NULL) {
27385 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27386 				goto protonak;
27387 			}
27388 			/*
27389 			 * The transports except SCTP call ip_bind_{v4,v6}()
27390 			 * directly instead of a a putnext. SCTP doesn't
27391 			 * generate any T_BIND_REQ since it has its own
27392 			 * fanout data structures. However, ESP and AH
27393 			 * come in for regular binds; all other cases are
27394 			 * bind retries.
27395 			 */
27396 			ASSERT(!IPCL_IS_SCTP(connp));
27397 
27398 			/* Don't increment refcnt if this is a re-entry */
27399 			if (ipsq == NULL)
27400 				CONN_INC_REF(connp);
27401 
27402 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27403 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27404 			ASSERT(mp != NULL);
27405 
27406 			ASSERT(!IPCL_IS_TCP(connp));
27407 			ASSERT(!IPCL_IS_UDP(connp));
27408 			ASSERT(!IPCL_IS_RAWIP(connp));
27409 
27410 			/* The case of AH and ESP */
27411 			qreply(q, mp);
27412 			CONN_OPER_PENDING_DONE(connp);
27413 			return;
27414 		}
27415 		case T_SVR4_OPTMGMT_REQ:
27416 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27417 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27418 
27419 			if (connp == NULL) {
27420 				proto_str = "T_SVR4_OPTMGMT_REQ";
27421 				goto protonak;
27422 			}
27423 
27424 			/*
27425 			 * All Solaris components should pass a db_credp
27426 			 * for this TPI message, hence we ASSERT.
27427 			 * But in case there is some other M_PROTO that looks
27428 			 * like a TPI message sent by some other kernel
27429 			 * component, we check and return an error.
27430 			 */
27431 			cr = msg_getcred(mp, NULL);
27432 			ASSERT(cr != NULL);
27433 			if (cr == NULL) {
27434 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27435 				if (mp != NULL)
27436 					qreply(q, mp);
27437 				return;
27438 			}
27439 
27440 			if (!snmpcom_req(q, mp, ip_snmp_set,
27441 			    ip_snmp_get, cr)) {
27442 				/*
27443 				 * Call svr4_optcom_req so that it can
27444 				 * generate the ack. We don't come here
27445 				 * if this operation is being restarted.
27446 				 * ip_restart_optmgmt will drop the conn ref.
27447 				 * In the case of ipsec option after the ipsec
27448 				 * load is complete conn_restart_ipsec_waiter
27449 				 * drops the conn ref.
27450 				 */
27451 				ASSERT(ipsq == NULL);
27452 				CONN_INC_REF(connp);
27453 				if (ip_check_for_ipsec_opt(q, mp))
27454 					return;
27455 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27456 				    B_FALSE);
27457 				if (err != EINPROGRESS) {
27458 					/* Operation is done */
27459 					CONN_OPER_PENDING_DONE(connp);
27460 				}
27461 			}
27462 			return;
27463 		case T_OPTMGMT_REQ:
27464 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27465 			/*
27466 			 * Note: No snmpcom_req support through new
27467 			 * T_OPTMGMT_REQ.
27468 			 * Call tpi_optcom_req so that it can
27469 			 * generate the ack.
27470 			 */
27471 			if (connp == NULL) {
27472 				proto_str = "T_OPTMGMT_REQ";
27473 				goto protonak;
27474 			}
27475 
27476 			/*
27477 			 * All Solaris components should pass a db_credp
27478 			 * for this TPI message, hence we ASSERT.
27479 			 * But in case there is some other M_PROTO that looks
27480 			 * like a TPI message sent by some other kernel
27481 			 * component, we check and return an error.
27482 			 */
27483 			cr = msg_getcred(mp, NULL);
27484 			ASSERT(cr != NULL);
27485 			if (cr == NULL) {
27486 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27487 				if (mp != NULL)
27488 					qreply(q, mp);
27489 				return;
27490 			}
27491 			ASSERT(ipsq == NULL);
27492 			/*
27493 			 * We don't come here for restart. ip_restart_optmgmt
27494 			 * will drop the conn ref. In the case of ipsec option
27495 			 * after the ipsec load is complete
27496 			 * conn_restart_ipsec_waiter drops the conn ref.
27497 			 */
27498 			CONN_INC_REF(connp);
27499 			if (ip_check_for_ipsec_opt(q, mp))
27500 				return;
27501 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27502 			if (err != EINPROGRESS) {
27503 				/* Operation is done */
27504 				CONN_OPER_PENDING_DONE(connp);
27505 			}
27506 			return;
27507 		case T_UNBIND_REQ:
27508 			if (connp == NULL) {
27509 				proto_str = "T_UNBIND_REQ";
27510 				goto protonak;
27511 			}
27512 			ip_unbind(Q_TO_CONN(q));
27513 			mp = mi_tpi_ok_ack_alloc(mp);
27514 			qreply(q, mp);
27515 			return;
27516 		default:
27517 			/*
27518 			 * Have to drop any DLPI messages coming down from
27519 			 * arp (such as an info_req which would cause ip
27520 			 * to receive an extra info_ack if it was passed
27521 			 * through.
27522 			 */
27523 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27524 			    (int)*(uint_t *)mp->b_rptr));
27525 			freemsg(mp);
27526 			return;
27527 		}
27528 		/* NOTREACHED */
27529 	case IRE_DB_TYPE: {
27530 		nce_t		*nce;
27531 		ill_t		*ill;
27532 		in6_addr_t	gw_addr_v6;
27533 
27534 		/*
27535 		 * This is a response back from a resolver.  It
27536 		 * consists of a message chain containing:
27537 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27538 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27539 		 * The LL_HDR_MBLK is the DLPI header to use to get
27540 		 * the attached packet, and subsequent ones for the
27541 		 * same destination, transmitted.
27542 		 */
27543 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27544 			break;
27545 		/*
27546 		 * First, check to make sure the resolution succeeded.
27547 		 * If it failed, the second mblk will be empty.
27548 		 * If it is, free the chain, dropping the packet.
27549 		 * (We must ire_delete the ire; that frees the ire mblk)
27550 		 * We're doing this now to support PVCs for ATM; it's
27551 		 * a partial xresolv implementation. When we fully implement
27552 		 * xresolv interfaces, instead of freeing everything here
27553 		 * we'll initiate neighbor discovery.
27554 		 *
27555 		 * For v4 (ARP and other external resolvers) the resolver
27556 		 * frees the message, so no check is needed. This check
27557 		 * is required, though, for a full xresolve implementation.
27558 		 * Including this code here now both shows how external
27559 		 * resolvers can NACK a resolution request using an
27560 		 * existing design that has no specific provisions for NACKs,
27561 		 * and also takes into account that the current non-ARP
27562 		 * external resolver has been coded to use this method of
27563 		 * NACKing for all IPv6 (xresolv) cases,
27564 		 * whether our xresolv implementation is complete or not.
27565 		 *
27566 		 */
27567 		ire = (ire_t *)mp->b_rptr;
27568 		ill = ire_to_ill(ire);
27569 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27570 		if (mp1->b_rptr == mp1->b_wptr) {
27571 			if (ire->ire_ipversion == IPV6_VERSION) {
27572 				/*
27573 				 * XRESOLV interface.
27574 				 */
27575 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27576 				mutex_enter(&ire->ire_lock);
27577 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27578 				mutex_exit(&ire->ire_lock);
27579 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27580 					nce = ndp_lookup_v6(ill, B_FALSE,
27581 					    &ire->ire_addr_v6, B_FALSE);
27582 				} else {
27583 					nce = ndp_lookup_v6(ill, B_FALSE,
27584 					    &gw_addr_v6, B_FALSE);
27585 				}
27586 				if (nce != NULL) {
27587 					nce_resolv_failed(nce);
27588 					ndp_delete(nce);
27589 					NCE_REFRELE(nce);
27590 				}
27591 			}
27592 			mp->b_cont = NULL;
27593 			freemsg(mp1);		/* frees the pkt as well */
27594 			ASSERT(ire->ire_nce == NULL);
27595 			ire_delete((ire_t *)mp->b_rptr);
27596 			return;
27597 		}
27598 
27599 		/*
27600 		 * Split them into IRE_MBLK and pkt and feed it into
27601 		 * ire_add_then_send. Then in ire_add_then_send
27602 		 * the IRE will be added, and then the packet will be
27603 		 * run back through ip_wput. This time it will make
27604 		 * it to the wire.
27605 		 */
27606 		mp->b_cont = NULL;
27607 		mp = mp1->b_cont;		/* now, mp points to pkt */
27608 		mp1->b_cont = NULL;
27609 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27610 		if (ire->ire_ipversion == IPV6_VERSION) {
27611 			/*
27612 			 * XRESOLV interface. Find the nce and put a copy
27613 			 * of the dl_unitdata_req in nce_res_mp
27614 			 */
27615 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27616 			mutex_enter(&ire->ire_lock);
27617 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27618 			mutex_exit(&ire->ire_lock);
27619 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27620 				nce = ndp_lookup_v6(ill, B_FALSE,
27621 				    &ire->ire_addr_v6, B_FALSE);
27622 			} else {
27623 				nce = ndp_lookup_v6(ill, B_FALSE,
27624 				    &gw_addr_v6, B_FALSE);
27625 			}
27626 			if (nce != NULL) {
27627 				/*
27628 				 * We have to protect nce_res_mp here
27629 				 * from being accessed by other threads
27630 				 * while we change the mblk pointer.
27631 				 * Other functions will also lock the nce when
27632 				 * accessing nce_res_mp.
27633 				 *
27634 				 * The reason we change the mblk pointer
27635 				 * here rather than copying the resolved address
27636 				 * into the template is that, unlike with
27637 				 * ethernet, we have no guarantee that the
27638 				 * resolved address length will be
27639 				 * smaller than or equal to the lla length
27640 				 * with which the template was allocated,
27641 				 * (for ethernet, they're equal)
27642 				 * so we have to use the actual resolved
27643 				 * address mblk - which holds the real
27644 				 * dl_unitdata_req with the resolved address.
27645 				 *
27646 				 * Doing this is the same behavior as was
27647 				 * previously used in the v4 ARP case.
27648 				 */
27649 				mutex_enter(&nce->nce_lock);
27650 				if (nce->nce_res_mp != NULL)
27651 					freemsg(nce->nce_res_mp);
27652 				nce->nce_res_mp = mp1;
27653 				mutex_exit(&nce->nce_lock);
27654 				/*
27655 				 * We do a fastpath probe here because
27656 				 * we have resolved the address without
27657 				 * using Neighbor Discovery.
27658 				 * In the non-XRESOLV v6 case, the fastpath
27659 				 * probe is done right after neighbor
27660 				 * discovery completes.
27661 				 */
27662 				if (nce->nce_res_mp != NULL) {
27663 					int res;
27664 					nce_fastpath_list_add(nce);
27665 					res = ill_fastpath_probe(ill,
27666 					    nce->nce_res_mp);
27667 					if (res != 0 && res != EAGAIN)
27668 						nce_fastpath_list_delete(nce);
27669 				}
27670 
27671 				ire_add_then_send(q, ire, mp);
27672 				/*
27673 				 * Now we have to clean out any packets
27674 				 * that may have been queued on the nce
27675 				 * while it was waiting for address resolution
27676 				 * to complete.
27677 				 */
27678 				mutex_enter(&nce->nce_lock);
27679 				mp1 = nce->nce_qd_mp;
27680 				nce->nce_qd_mp = NULL;
27681 				mutex_exit(&nce->nce_lock);
27682 				while (mp1 != NULL) {
27683 					mblk_t *nxt_mp;
27684 					queue_t *fwdq = NULL;
27685 					ill_t   *inbound_ill;
27686 					uint_t ifindex;
27687 
27688 					nxt_mp = mp1->b_next;
27689 					mp1->b_next = NULL;
27690 					/*
27691 					 * Retrieve ifindex stored in
27692 					 * ip_rput_data_v6()
27693 					 */
27694 					ifindex =
27695 					    (uint_t)(uintptr_t)mp1->b_prev;
27696 					inbound_ill =
27697 					    ill_lookup_on_ifindex(ifindex,
27698 					    B_TRUE, NULL, NULL, NULL,
27699 					    NULL, ipst);
27700 					mp1->b_prev = NULL;
27701 					if (inbound_ill != NULL)
27702 						fwdq = inbound_ill->ill_rq;
27703 
27704 					if (fwdq != NULL) {
27705 						put(fwdq, mp1);
27706 						ill_refrele(inbound_ill);
27707 					} else
27708 						put(WR(ill->ill_rq), mp1);
27709 					mp1 = nxt_mp;
27710 				}
27711 				NCE_REFRELE(nce);
27712 			} else {	/* nce is NULL; clean up */
27713 				ire_delete(ire);
27714 				freemsg(mp);
27715 				freemsg(mp1);
27716 				return;
27717 			}
27718 		} else {
27719 			nce_t *arpce;
27720 			/*
27721 			 * Link layer resolution succeeded. Recompute the
27722 			 * ire_nce.
27723 			 */
27724 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27725 			if ((arpce = ndp_lookup_v4(ill,
27726 			    (ire->ire_gateway_addr != INADDR_ANY ?
27727 			    &ire->ire_gateway_addr : &ire->ire_addr),
27728 			    B_FALSE)) == NULL) {
27729 				freeb(ire->ire_mp);
27730 				freeb(mp1);
27731 				freemsg(mp);
27732 				return;
27733 			}
27734 			mutex_enter(&arpce->nce_lock);
27735 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27736 			if (arpce->nce_state == ND_REACHABLE) {
27737 				/*
27738 				 * Someone resolved this before us;
27739 				 * cleanup the res_mp. Since ire has
27740 				 * not been added yet, the call to ire_add_v4
27741 				 * from ire_add_then_send (when a dup is
27742 				 * detected) will clean up the ire.
27743 				 */
27744 				freeb(mp1);
27745 			} else {
27746 				ASSERT(arpce->nce_res_mp == NULL);
27747 				arpce->nce_res_mp = mp1;
27748 				arpce->nce_state = ND_REACHABLE;
27749 			}
27750 			mutex_exit(&arpce->nce_lock);
27751 			if (ire->ire_marks & IRE_MARK_NOADD) {
27752 				/*
27753 				 * this ire will not be added to the ire
27754 				 * cache table, so we can set the ire_nce
27755 				 * here, as there are no atomicity constraints.
27756 				 */
27757 				ire->ire_nce = arpce;
27758 				/*
27759 				 * We are associating this nce with the ire
27760 				 * so change the nce ref taken in
27761 				 * ndp_lookup_v4() from
27762 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27763 				 */
27764 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27765 			} else {
27766 				NCE_REFRELE(arpce);
27767 			}
27768 			ire_add_then_send(q, ire, mp);
27769 		}
27770 		return;	/* All is well, the packet has been sent. */
27771 	}
27772 	case IRE_ARPRESOLVE_TYPE: {
27773 
27774 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27775 			break;
27776 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27777 		mp->b_cont = NULL;
27778 		/*
27779 		 * First, check to make sure the resolution succeeded.
27780 		 * If it failed, the second mblk will be empty.
27781 		 */
27782 		if (mp1->b_rptr == mp1->b_wptr) {
27783 			/* cleanup  the incomplete ire, free queued packets */
27784 			freemsg(mp); /* fake ire */
27785 			freeb(mp1);  /* dl_unitdata response */
27786 			return;
27787 		}
27788 
27789 		/*
27790 		 * Update any incomplete nce_t found. We search the ctable
27791 		 * and find the nce from the ire->ire_nce because we need
27792 		 * to pass the ire to ip_xmit_v4 later, and can find both
27793 		 * ire and nce in one lookup.
27794 		 */
27795 		fake_ire = (ire_t *)mp->b_rptr;
27796 
27797 		/*
27798 		 * By the time we come back here from ARP the logical outgoing
27799 		 * interface of the incomplete ire we added in ire_forward()
27800 		 * could have disappeared, causing the incomplete ire to also
27801 		 * disappear.  So we need to retreive the proper ipif for the
27802 		 * ire before looking in ctable.  In the case of IPMP, the
27803 		 * ipif may be on the IPMP ill, so look it up based on the
27804 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27805 		 * Then, we can verify that ire_ipif_seqid still exists.
27806 		 */
27807 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27808 		    NULL, NULL, NULL, NULL, ipst);
27809 		if (ill == NULL) {
27810 			ip1dbg(("ill for incomplete ire vanished\n"));
27811 			freemsg(mp); /* fake ire */
27812 			freeb(mp1);  /* dl_unitdata response */
27813 			return;
27814 		}
27815 
27816 		/* Get the outgoing ipif */
27817 		mutex_enter(&ill->ill_lock);
27818 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27819 		if (ipif == NULL) {
27820 			mutex_exit(&ill->ill_lock);
27821 			ill_refrele(ill);
27822 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27823 			freemsg(mp); /* fake_ire */
27824 			freeb(mp1);  /* dl_unitdata response */
27825 			return;
27826 		}
27827 
27828 		ipif_refhold_locked(ipif);
27829 		mutex_exit(&ill->ill_lock);
27830 		ill_refrele(ill);
27831 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27832 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27833 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27834 		ipif_refrele(ipif);
27835 		if (ire == NULL) {
27836 			/*
27837 			 * no ire was found; check if there is an nce
27838 			 * for this lookup; if it has no ire's pointing at it
27839 			 * cleanup.
27840 			 */
27841 			if ((nce = ndp_lookup_v4(q->q_ptr,
27842 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27843 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27844 			    B_FALSE)) != NULL) {
27845 				/*
27846 				 * cleanup:
27847 				 * We check for refcnt 2 (one for the nce
27848 				 * hash list + 1 for the ref taken by
27849 				 * ndp_lookup_v4) to check that there are
27850 				 * no ire's pointing at the nce.
27851 				 */
27852 				if (nce->nce_refcnt == 2)
27853 					ndp_delete(nce);
27854 				NCE_REFRELE(nce);
27855 			}
27856 			freeb(mp1);  /* dl_unitdata response */
27857 			freemsg(mp); /* fake ire */
27858 			return;
27859 		}
27860 
27861 		nce = ire->ire_nce;
27862 		DTRACE_PROBE2(ire__arpresolve__type,
27863 		    ire_t *, ire, nce_t *, nce);
27864 		ASSERT(nce->nce_state != ND_INITIAL);
27865 		mutex_enter(&nce->nce_lock);
27866 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27867 		if (nce->nce_state == ND_REACHABLE) {
27868 			/*
27869 			 * Someone resolved this before us;
27870 			 * our response is not needed any more.
27871 			 */
27872 			mutex_exit(&nce->nce_lock);
27873 			freeb(mp1);  /* dl_unitdata response */
27874 		} else {
27875 			ASSERT(nce->nce_res_mp == NULL);
27876 			nce->nce_res_mp = mp1;
27877 			nce->nce_state = ND_REACHABLE;
27878 			mutex_exit(&nce->nce_lock);
27879 			nce_fastpath(nce);
27880 		}
27881 		/*
27882 		 * The cached nce_t has been updated to be reachable;
27883 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27884 		 */
27885 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27886 		freemsg(mp);
27887 		/*
27888 		 * send out queued packets.
27889 		 */
27890 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27891 
27892 		IRE_REFRELE(ire);
27893 		return;
27894 	}
27895 	default:
27896 		break;
27897 	}
27898 	if (q->q_next) {
27899 		putnext(q, mp);
27900 	} else
27901 		freemsg(mp);
27902 	return;
27903 
27904 protonak:
27905 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27906 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27907 		qreply(q, mp);
27908 }
27909 
27910 /*
27911  * Process IP options in an outbound packet.  Modify the destination if there
27912  * is a source route option.
27913  * Returns non-zero if something fails in which case an ICMP error has been
27914  * sent and mp freed.
27915  */
27916 static int
27917 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27918     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27919 {
27920 	ipoptp_t	opts;
27921 	uchar_t		*opt;
27922 	uint8_t		optval;
27923 	uint8_t		optlen;
27924 	ipaddr_t	dst;
27925 	intptr_t	code = 0;
27926 	mblk_t		*mp;
27927 	ire_t		*ire = NULL;
27928 
27929 	ip2dbg(("ip_wput_options\n"));
27930 	mp = ipsec_mp;
27931 	if (mctl_present) {
27932 		mp = ipsec_mp->b_cont;
27933 	}
27934 
27935 	dst = ipha->ipha_dst;
27936 	for (optval = ipoptp_first(&opts, ipha);
27937 	    optval != IPOPT_EOL;
27938 	    optval = ipoptp_next(&opts)) {
27939 		opt = opts.ipoptp_cur;
27940 		optlen = opts.ipoptp_len;
27941 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27942 		    optval, optlen));
27943 		switch (optval) {
27944 			uint32_t off;
27945 		case IPOPT_SSRR:
27946 		case IPOPT_LSRR:
27947 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27948 				ip1dbg((
27949 				    "ip_wput_options: bad option offset\n"));
27950 				code = (char *)&opt[IPOPT_OLEN] -
27951 				    (char *)ipha;
27952 				goto param_prob;
27953 			}
27954 			off = opt[IPOPT_OFFSET];
27955 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27956 			    ntohl(dst)));
27957 			/*
27958 			 * For strict: verify that dst is directly
27959 			 * reachable.
27960 			 */
27961 			if (optval == IPOPT_SSRR) {
27962 				ire = ire_ftable_lookup(dst, 0, 0,
27963 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27964 				    msg_getlabel(mp),
27965 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27966 				if (ire == NULL) {
27967 					ip1dbg(("ip_wput_options: SSRR not"
27968 					    " directly reachable: 0x%x\n",
27969 					    ntohl(dst)));
27970 					goto bad_src_route;
27971 				}
27972 				ire_refrele(ire);
27973 			}
27974 			break;
27975 		case IPOPT_RR:
27976 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27977 				ip1dbg((
27978 				    "ip_wput_options: bad option offset\n"));
27979 				code = (char *)&opt[IPOPT_OLEN] -
27980 				    (char *)ipha;
27981 				goto param_prob;
27982 			}
27983 			break;
27984 		case IPOPT_TS:
27985 			/*
27986 			 * Verify that length >=5 and that there is either
27987 			 * room for another timestamp or that the overflow
27988 			 * counter is not maxed out.
27989 			 */
27990 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27991 			if (optlen < IPOPT_MINLEN_IT) {
27992 				goto param_prob;
27993 			}
27994 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27995 				ip1dbg((
27996 				    "ip_wput_options: bad option offset\n"));
27997 				code = (char *)&opt[IPOPT_OFFSET] -
27998 				    (char *)ipha;
27999 				goto param_prob;
28000 			}
28001 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28002 			case IPOPT_TS_TSONLY:
28003 				off = IPOPT_TS_TIMELEN;
28004 				break;
28005 			case IPOPT_TS_TSANDADDR:
28006 			case IPOPT_TS_PRESPEC:
28007 			case IPOPT_TS_PRESPEC_RFC791:
28008 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28009 				break;
28010 			default:
28011 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28012 				    (char *)ipha;
28013 				goto param_prob;
28014 			}
28015 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28016 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28017 				/*
28018 				 * No room and the overflow counter is 15
28019 				 * already.
28020 				 */
28021 				goto param_prob;
28022 			}
28023 			break;
28024 		}
28025 	}
28026 
28027 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28028 		return (0);
28029 
28030 	ip1dbg(("ip_wput_options: error processing IP options."));
28031 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28032 
28033 param_prob:
28034 	/*
28035 	 * Since ip_wput() isn't close to finished, we fill
28036 	 * in enough of the header for credible error reporting.
28037 	 */
28038 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28039 		/* Failed */
28040 		freemsg(ipsec_mp);
28041 		return (-1);
28042 	}
28043 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28044 	return (-1);
28045 
28046 bad_src_route:
28047 	/*
28048 	 * Since ip_wput() isn't close to finished, we fill
28049 	 * in enough of the header for credible error reporting.
28050 	 */
28051 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28052 		/* Failed */
28053 		freemsg(ipsec_mp);
28054 		return (-1);
28055 	}
28056 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28057 	return (-1);
28058 }
28059 
28060 /*
28061  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28062  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28063  * thru /etc/system.
28064  */
28065 #define	CONN_MAXDRAINCNT	64
28066 
28067 static void
28068 conn_drain_init(ip_stack_t *ipst)
28069 {
28070 	int i, j;
28071 	idl_tx_list_t *itl_tx;
28072 
28073 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28074 
28075 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28076 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28077 		/*
28078 		 * Default value of the number of drainers is the
28079 		 * number of cpus, subject to maximum of 8 drainers.
28080 		 */
28081 		if (boot_max_ncpus != -1)
28082 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28083 		else
28084 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28085 	}
28086 
28087 	ipst->ips_idl_tx_list =
28088 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28089 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28090 		itl_tx =  &ipst->ips_idl_tx_list[i];
28091 		itl_tx->txl_drain_list =
28092 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28093 		    sizeof (idl_t), KM_SLEEP);
28094 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28095 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28096 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28097 			    MUTEX_DEFAULT, NULL);
28098 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28099 		}
28100 	}
28101 }
28102 
28103 static void
28104 conn_drain_fini(ip_stack_t *ipst)
28105 {
28106 	int i;
28107 	idl_tx_list_t *itl_tx;
28108 
28109 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28110 		itl_tx =  &ipst->ips_idl_tx_list[i];
28111 		kmem_free(itl_tx->txl_drain_list,
28112 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28113 	}
28114 	kmem_free(ipst->ips_idl_tx_list,
28115 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28116 	ipst->ips_idl_tx_list = NULL;
28117 }
28118 
28119 /*
28120  * Note: For an overview of how flowcontrol is handled in IP please see the
28121  * IP Flowcontrol notes at the top of this file.
28122  *
28123  * Flow control has blocked us from proceeding. Insert the given conn in one
28124  * of the conn drain lists. These conn wq's will be qenabled later on when
28125  * STREAMS flow control does a backenable. conn_walk_drain will enable
28126  * the first conn in each of these drain lists. Each of these qenabled conns
28127  * in turn enables the next in the list, after it runs, or when it closes,
28128  * thus sustaining the drain process.
28129  */
28130 void
28131 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28132 {
28133 	idl_t	*idl = tx_list->txl_drain_list;
28134 	uint_t	index;
28135 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28136 
28137 	mutex_enter(&connp->conn_lock);
28138 	if (connp->conn_state_flags & CONN_CLOSING) {
28139 		/*
28140 		 * The conn is closing as a result of which CONN_CLOSING
28141 		 * is set. Return.
28142 		 */
28143 		mutex_exit(&connp->conn_lock);
28144 		return;
28145 	} else if (connp->conn_idl == NULL) {
28146 		/*
28147 		 * Assign the next drain list round robin. We dont' use
28148 		 * a lock, and thus it may not be strictly round robin.
28149 		 * Atomicity of load/stores is enough to make sure that
28150 		 * conn_drain_list_index is always within bounds.
28151 		 */
28152 		index = tx_list->txl_drain_index;
28153 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28154 		connp->conn_idl = &tx_list->txl_drain_list[index];
28155 		index++;
28156 		if (index == ipst->ips_conn_drain_list_cnt)
28157 			index = 0;
28158 		tx_list->txl_drain_index = index;
28159 	}
28160 	mutex_exit(&connp->conn_lock);
28161 
28162 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28163 	if ((connp->conn_drain_prev != NULL) ||
28164 	    (connp->conn_state_flags & CONN_CLOSING)) {
28165 		/*
28166 		 * The conn is already in the drain list, OR
28167 		 * the conn is closing. We need to check again for
28168 		 * the closing case again since close can happen
28169 		 * after we drop the conn_lock, and before we
28170 		 * acquire the CONN_DRAIN_LIST_LOCK.
28171 		 */
28172 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28173 		return;
28174 	} else {
28175 		idl = connp->conn_idl;
28176 	}
28177 
28178 	/*
28179 	 * The conn is not in the drain list. Insert it at the
28180 	 * tail of the drain list. The drain list is circular
28181 	 * and doubly linked. idl_conn points to the 1st element
28182 	 * in the list.
28183 	 */
28184 	if (idl->idl_conn == NULL) {
28185 		idl->idl_conn = connp;
28186 		connp->conn_drain_next = connp;
28187 		connp->conn_drain_prev = connp;
28188 	} else {
28189 		conn_t *head = idl->idl_conn;
28190 
28191 		connp->conn_drain_next = head;
28192 		connp->conn_drain_prev = head->conn_drain_prev;
28193 		head->conn_drain_prev->conn_drain_next = connp;
28194 		head->conn_drain_prev = connp;
28195 	}
28196 	/*
28197 	 * For non streams based sockets assert flow control.
28198 	 */
28199 	if (IPCL_IS_NONSTR(connp)) {
28200 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28201 		(*connp->conn_upcalls->su_txq_full)
28202 		    (connp->conn_upper_handle, B_TRUE);
28203 	} else {
28204 		conn_setqfull(connp);
28205 		noenable(connp->conn_wq);
28206 	}
28207 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28208 }
28209 
28210 /*
28211  * This conn is closing, and we are called from ip_close. OR
28212  * This conn has been serviced by ip_wsrv, and we need to do the tail
28213  * processing.
28214  * If this conn is part of the drain list, we may need to sustain the drain
28215  * process by qenabling the next conn in the drain list. We may also need to
28216  * remove this conn from the list, if it is done.
28217  */
28218 static void
28219 conn_drain_tail(conn_t *connp, boolean_t closing)
28220 {
28221 	idl_t *idl;
28222 
28223 	/*
28224 	 * connp->conn_idl is stable at this point, and no lock is needed
28225 	 * to check it. If we are called from ip_close, close has already
28226 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28227 	 * called us only because conn_idl is non-null. If we are called thru
28228 	 * service, conn_idl could be null, but it cannot change because
28229 	 * service is single-threaded per queue, and there cannot be another
28230 	 * instance of service trying to call conn_drain_insert on this conn
28231 	 * now.
28232 	 */
28233 	ASSERT(!closing || (connp->conn_idl != NULL));
28234 
28235 	/*
28236 	 * If connp->conn_idl is null, the conn has not been inserted into any
28237 	 * drain list even once since creation of the conn. Just return.
28238 	 */
28239 	if (connp->conn_idl == NULL)
28240 		return;
28241 
28242 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28243 
28244 	if (connp->conn_drain_prev == NULL) {
28245 		/* This conn is currently not in the drain list.  */
28246 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28247 		return;
28248 	}
28249 	idl = connp->conn_idl;
28250 	if (idl->idl_conn_draining == connp) {
28251 		/*
28252 		 * This conn is the current drainer. If this is the last conn
28253 		 * in the drain list, we need to do more checks, in the 'if'
28254 		 * below. Otherwwise we need to just qenable the next conn,
28255 		 * to sustain the draining, and is handled in the 'else'
28256 		 * below.
28257 		 */
28258 		if (connp->conn_drain_next == idl->idl_conn) {
28259 			/*
28260 			 * This conn is the last in this list. This round
28261 			 * of draining is complete. If idl_repeat is set,
28262 			 * it means another flow enabling has happened from
28263 			 * the driver/streams and we need to another round
28264 			 * of draining.
28265 			 * If there are more than 2 conns in the drain list,
28266 			 * do a left rotate by 1, so that all conns except the
28267 			 * conn at the head move towards the head by 1, and the
28268 			 * the conn at the head goes to the tail. This attempts
28269 			 * a more even share for all queues that are being
28270 			 * drained.
28271 			 */
28272 			if ((connp->conn_drain_next != connp) &&
28273 			    (idl->idl_conn->conn_drain_next != connp)) {
28274 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28275 			}
28276 			if (idl->idl_repeat) {
28277 				qenable(idl->idl_conn->conn_wq);
28278 				idl->idl_conn_draining = idl->idl_conn;
28279 				idl->idl_repeat = 0;
28280 			} else {
28281 				idl->idl_conn_draining = NULL;
28282 			}
28283 		} else {
28284 			/*
28285 			 * If the next queue that we are now qenable'ing,
28286 			 * is closing, it will remove itself from this list
28287 			 * and qenable the subsequent queue in ip_close().
28288 			 * Serialization is acheived thru idl_lock.
28289 			 */
28290 			qenable(connp->conn_drain_next->conn_wq);
28291 			idl->idl_conn_draining = connp->conn_drain_next;
28292 		}
28293 	}
28294 	if (!connp->conn_did_putbq || closing) {
28295 		/*
28296 		 * Remove ourself from the drain list, if we did not do
28297 		 * a putbq, or if the conn is closing.
28298 		 * Note: It is possible that q->q_first is non-null. It means
28299 		 * that these messages landed after we did a enableok() in
28300 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28301 		 * service them.
28302 		 */
28303 		if (connp->conn_drain_next == connp) {
28304 			/* Singleton in the list */
28305 			ASSERT(connp->conn_drain_prev == connp);
28306 			idl->idl_conn = NULL;
28307 			idl->idl_conn_draining = NULL;
28308 		} else {
28309 			connp->conn_drain_prev->conn_drain_next =
28310 			    connp->conn_drain_next;
28311 			connp->conn_drain_next->conn_drain_prev =
28312 			    connp->conn_drain_prev;
28313 			if (idl->idl_conn == connp)
28314 				idl->idl_conn = connp->conn_drain_next;
28315 			ASSERT(idl->idl_conn_draining != connp);
28316 
28317 		}
28318 		connp->conn_drain_next = NULL;
28319 		connp->conn_drain_prev = NULL;
28320 
28321 		/*
28322 		 * For non streams based sockets open up flow control.
28323 		 */
28324 		if (IPCL_IS_NONSTR(connp)) {
28325 			(*connp->conn_upcalls->su_txq_full)
28326 			    (connp->conn_upper_handle, B_FALSE);
28327 		} else {
28328 			conn_clrqfull(connp);
28329 			enableok(connp->conn_wq);
28330 		}
28331 	}
28332 
28333 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28334 }
28335 
28336 /*
28337  * Write service routine. Shared perimeter entry point.
28338  * ip_wsrv can be called in any of the following ways.
28339  * 1. The device queue's messages has fallen below the low water mark
28340  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28341  *    the drain lists and backenable the first conn in each list.
28342  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28343  *    qenabled non-tcp upper layers. We start dequeing messages and call
28344  *    ip_wput for each message.
28345  */
28346 
28347 void
28348 ip_wsrv(queue_t *q)
28349 {
28350 	conn_t	*connp;
28351 	ill_t	*ill;
28352 	mblk_t	*mp;
28353 
28354 	if (q->q_next) {
28355 		ill = (ill_t *)q->q_ptr;
28356 		if (ill->ill_state_flags == 0) {
28357 			ip_stack_t *ipst = ill->ill_ipst;
28358 
28359 			/*
28360 			 * The device flow control has opened up.
28361 			 * Walk through conn drain lists and qenable the
28362 			 * first conn in each list. This makes sense only
28363 			 * if the stream is fully plumbed and setup.
28364 			 * Hence the if check above.
28365 			 */
28366 			ip1dbg(("ip_wsrv: walking\n"));
28367 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28368 		}
28369 		return;
28370 	}
28371 
28372 	connp = Q_TO_CONN(q);
28373 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28374 
28375 	/*
28376 	 * 1. Set conn_draining flag to signal that service is active.
28377 	 *
28378 	 * 2. ip_output determines whether it has been called from service,
28379 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28380 	 *    has been called from service.
28381 	 *
28382 	 * 3. Message ordering is preserved by the following logic.
28383 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28384 	 *    the message at the tail, if conn_draining is set (i.e. service
28385 	 *    is running) or if q->q_first is non-null.
28386 	 *
28387 	 *    ii. If ip_output is called from service, and if ip_output cannot
28388 	 *    putnext due to flow control, it does a putbq.
28389 	 *
28390 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28391 	 *    (causing an infinite loop).
28392 	 */
28393 	ASSERT(!connp->conn_did_putbq);
28394 
28395 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28396 		connp->conn_draining = 1;
28397 		noenable(q);
28398 		while ((mp = getq(q)) != NULL) {
28399 			ASSERT(CONN_Q(q));
28400 
28401 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28402 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28403 			if (connp->conn_did_putbq) {
28404 				/* ip_wput did a putbq */
28405 				break;
28406 			}
28407 		}
28408 		/*
28409 		 * At this point, a thread coming down from top, calling
28410 		 * ip_wput, may end up queueing the message. We have not yet
28411 		 * enabled the queue, so ip_wsrv won't be called again.
28412 		 * To avoid this race, check q->q_first again (in the loop)
28413 		 * If the other thread queued the message before we call
28414 		 * enableok(), we will catch it in the q->q_first check.
28415 		 * If the other thread queues the message after we call
28416 		 * enableok(), ip_wsrv will be called again by STREAMS.
28417 		 */
28418 		connp->conn_draining = 0;
28419 		enableok(q);
28420 	}
28421 
28422 	/* Enable the next conn for draining */
28423 	conn_drain_tail(connp, B_FALSE);
28424 
28425 	/*
28426 	 * conn_direct_blocked is used to indicate blocked
28427 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28428 	 * This is the only place where it is set without
28429 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28430 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28431 	 */
28432 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28433 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28434 		connp->conn_direct_blocked = B_FALSE;
28435 	}
28436 
28437 	connp->conn_did_putbq = 0;
28438 }
28439 
28440 /*
28441  * Callback to disable flow control in IP.
28442  *
28443  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28444  * is enabled.
28445  *
28446  * When MAC_TX() is not able to send any more packets, dld sets its queue
28447  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28448  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28449  * function and wakes up corresponding mac worker threads, which in turn
28450  * calls this callback function, and disables flow control.
28451  */
28452 void
28453 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28454 {
28455 	ill_t *ill = (ill_t *)arg;
28456 	ip_stack_t *ipst = ill->ill_ipst;
28457 	idl_tx_list_t *idl_txl;
28458 
28459 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28460 	mutex_enter(&idl_txl->txl_lock);
28461 	/* add code to to set a flag to indicate idl_txl is enabled */
28462 	conn_walk_drain(ipst, idl_txl);
28463 	mutex_exit(&idl_txl->txl_lock);
28464 }
28465 
28466 /*
28467  * Walk the list of all conn's calling the function provided with the
28468  * specified argument for each.	 Note that this only walks conn's that
28469  * have been bound.
28470  * Applies to both IPv4 and IPv6.
28471  */
28472 static void
28473 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28474 {
28475 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28476 	    ipst->ips_ipcl_udp_fanout_size,
28477 	    func, arg, zoneid);
28478 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28479 	    ipst->ips_ipcl_conn_fanout_size,
28480 	    func, arg, zoneid);
28481 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28482 	    ipst->ips_ipcl_bind_fanout_size,
28483 	    func, arg, zoneid);
28484 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28485 	    IPPROTO_MAX, func, arg, zoneid);
28486 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28487 	    IPPROTO_MAX, func, arg, zoneid);
28488 }
28489 
28490 /*
28491  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28492  * of conns that need to be drained, check if drain is already in progress.
28493  * If so set the idl_repeat bit, indicating that the last conn in the list
28494  * needs to reinitiate the drain once again, for the list. If drain is not
28495  * in progress for the list, initiate the draining, by qenabling the 1st
28496  * conn in the list. The drain is self-sustaining, each qenabled conn will
28497  * in turn qenable the next conn, when it is done/blocked/closing.
28498  */
28499 static void
28500 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28501 {
28502 	int i;
28503 	idl_t *idl;
28504 
28505 	IP_STAT(ipst, ip_conn_walk_drain);
28506 
28507 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28508 		idl = &tx_list->txl_drain_list[i];
28509 		mutex_enter(&idl->idl_lock);
28510 		if (idl->idl_conn == NULL) {
28511 			mutex_exit(&idl->idl_lock);
28512 			continue;
28513 		}
28514 		/*
28515 		 * If this list is not being drained currently by
28516 		 * an ip_wsrv thread, start the process.
28517 		 */
28518 		if (idl->idl_conn_draining == NULL) {
28519 			ASSERT(idl->idl_repeat == 0);
28520 			qenable(idl->idl_conn->conn_wq);
28521 			idl->idl_conn_draining = idl->idl_conn;
28522 		} else {
28523 			idl->idl_repeat = 1;
28524 		}
28525 		mutex_exit(&idl->idl_lock);
28526 	}
28527 }
28528 
28529 /*
28530  * Walk an conn hash table of `count' buckets, calling func for each entry.
28531  */
28532 static void
28533 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28534     zoneid_t zoneid)
28535 {
28536 	conn_t	*connp;
28537 
28538 	while (count-- > 0) {
28539 		mutex_enter(&connfp->connf_lock);
28540 		for (connp = connfp->connf_head; connp != NULL;
28541 		    connp = connp->conn_next) {
28542 			if (zoneid == GLOBAL_ZONEID ||
28543 			    zoneid == connp->conn_zoneid) {
28544 				CONN_INC_REF(connp);
28545 				mutex_exit(&connfp->connf_lock);
28546 				(*func)(connp, arg);
28547 				mutex_enter(&connfp->connf_lock);
28548 				CONN_DEC_REF(connp);
28549 			}
28550 		}
28551 		mutex_exit(&connfp->connf_lock);
28552 		connfp++;
28553 	}
28554 }
28555 
28556 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28557 static void
28558 conn_report1(conn_t *connp, void *mp)
28559 {
28560 	char	buf1[INET6_ADDRSTRLEN];
28561 	char	buf2[INET6_ADDRSTRLEN];
28562 	uint_t	print_len, buf_len;
28563 
28564 	ASSERT(connp != NULL);
28565 
28566 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28567 	if (buf_len <= 0)
28568 		return;
28569 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28570 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28571 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28572 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28573 	    "%5d %s/%05d %s/%05d\n",
28574 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28575 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28576 	    buf1, connp->conn_lport,
28577 	    buf2, connp->conn_fport);
28578 	if (print_len < buf_len) {
28579 		((mblk_t *)mp)->b_wptr += print_len;
28580 	} else {
28581 		((mblk_t *)mp)->b_wptr += buf_len;
28582 	}
28583 }
28584 
28585 /*
28586  * Named Dispatch routine to produce a formatted report on all conns
28587  * that are listed in one of the fanout tables.
28588  * This report is accessed by using the ndd utility to "get" ND variable
28589  * "ip_conn_status".
28590  */
28591 /* ARGSUSED */
28592 static int
28593 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28594 {
28595 	conn_t *connp = Q_TO_CONN(q);
28596 
28597 	(void) mi_mpprintf(mp,
28598 	    "CONN      " MI_COL_HDRPAD_STR
28599 	    "rfq      " MI_COL_HDRPAD_STR
28600 	    "stq      " MI_COL_HDRPAD_STR
28601 	    " zone local		 remote");
28602 
28603 	/*
28604 	 * Because of the ndd constraint, at most we can have 64K buffer
28605 	 * to put in all conn info.  So to be more efficient, just
28606 	 * allocate a 64K buffer here, assuming we need that large buffer.
28607 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28608 	 */
28609 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28610 		/* The following may work even if we cannot get a large buf. */
28611 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28612 		return (0);
28613 	}
28614 
28615 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28616 	    connp->conn_netstack->netstack_ip);
28617 	return (0);
28618 }
28619 
28620 /*
28621  * Determine if the ill and multicast aspects of that packets
28622  * "matches" the conn.
28623  */
28624 boolean_t
28625 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28626     zoneid_t zoneid)
28627 {
28628 	ill_t *bound_ill;
28629 	boolean_t found;
28630 	ipif_t *ipif;
28631 	ire_t *ire;
28632 	ipaddr_t dst, src;
28633 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28634 
28635 	dst = ipha->ipha_dst;
28636 	src = ipha->ipha_src;
28637 
28638 	/*
28639 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28640 	 * unicast, broadcast and multicast reception to
28641 	 * conn_incoming_ill. conn_wantpacket itself is called
28642 	 * only for BROADCAST and multicast.
28643 	 */
28644 	bound_ill = connp->conn_incoming_ill;
28645 	if (bound_ill != NULL) {
28646 		if (IS_IPMP(bound_ill)) {
28647 			if (bound_ill->ill_grp != ill->ill_grp)
28648 				return (B_FALSE);
28649 		} else {
28650 			if (bound_ill != ill)
28651 				return (B_FALSE);
28652 		}
28653 	}
28654 
28655 	if (!CLASSD(dst)) {
28656 		if (IPCL_ZONE_MATCH(connp, zoneid))
28657 			return (B_TRUE);
28658 		/*
28659 		 * The conn is in a different zone; we need to check that this
28660 		 * broadcast address is configured in the application's zone.
28661 		 */
28662 		ipif = ipif_get_next_ipif(NULL, ill);
28663 		if (ipif == NULL)
28664 			return (B_FALSE);
28665 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28666 		    connp->conn_zoneid, NULL,
28667 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28668 		ipif_refrele(ipif);
28669 		if (ire != NULL) {
28670 			ire_refrele(ire);
28671 			return (B_TRUE);
28672 		} else {
28673 			return (B_FALSE);
28674 		}
28675 	}
28676 
28677 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28678 	    connp->conn_zoneid == zoneid) {
28679 		/*
28680 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28681 		 * disabled, therefore we don't dispatch the multicast packet to
28682 		 * the sending zone.
28683 		 */
28684 		return (B_FALSE);
28685 	}
28686 
28687 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28688 		/*
28689 		 * Multicast packet on the loopback interface: we only match
28690 		 * conns who joined the group in the specified zone.
28691 		 */
28692 		return (B_FALSE);
28693 	}
28694 
28695 	if (connp->conn_multi_router) {
28696 		/* multicast packet and multicast router socket: send up */
28697 		return (B_TRUE);
28698 	}
28699 
28700 	mutex_enter(&connp->conn_lock);
28701 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28702 	mutex_exit(&connp->conn_lock);
28703 	return (found);
28704 }
28705 
28706 static void
28707 conn_setqfull(conn_t *connp)
28708 {
28709 	queue_t *q = connp->conn_wq;
28710 
28711 	if (!(q->q_flag & QFULL)) {
28712 		mutex_enter(QLOCK(q));
28713 		if (!(q->q_flag & QFULL)) {
28714 			/* still need to set QFULL */
28715 			q->q_flag |= QFULL;
28716 			mutex_exit(QLOCK(q));
28717 		} else {
28718 			mutex_exit(QLOCK(q));
28719 		}
28720 	}
28721 }
28722 
28723 static void
28724 conn_clrqfull(conn_t *connp)
28725 {
28726 	queue_t *q = connp->conn_wq;
28727 
28728 	if (q->q_flag & QFULL) {
28729 		mutex_enter(QLOCK(q));
28730 		if (q->q_flag & QFULL) {
28731 			q->q_flag &= ~QFULL;
28732 			mutex_exit(QLOCK(q));
28733 			if (q->q_flag & QWANTW)
28734 				qbackenable(q, 0);
28735 		} else {
28736 			mutex_exit(QLOCK(q));
28737 		}
28738 	}
28739 }
28740 
28741 /*
28742  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28743  */
28744 /* ARGSUSED */
28745 static void
28746 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28747 {
28748 	ill_t *ill = (ill_t *)q->q_ptr;
28749 	mblk_t	*mp1, *mp2;
28750 	ipif_t  *ipif;
28751 	int err = 0;
28752 	conn_t *connp = NULL;
28753 	ipsq_t	*ipsq;
28754 	arc_t	*arc;
28755 
28756 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28757 
28758 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28759 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28760 
28761 	ASSERT(IAM_WRITER_ILL(ill));
28762 	mp2 = mp->b_cont;
28763 	mp->b_cont = NULL;
28764 
28765 	/*
28766 	 * We have now received the arp bringup completion message
28767 	 * from ARP. Mark the arp bringup as done. Also if the arp
28768 	 * stream has already started closing, send up the AR_ARP_CLOSING
28769 	 * ack now since ARP is waiting in close for this ack.
28770 	 */
28771 	mutex_enter(&ill->ill_lock);
28772 	ill->ill_arp_bringup_pending = 0;
28773 	if (ill->ill_arp_closing) {
28774 		mutex_exit(&ill->ill_lock);
28775 		/* Let's reuse the mp for sending the ack */
28776 		arc = (arc_t *)mp->b_rptr;
28777 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28778 		arc->arc_cmd = AR_ARP_CLOSING;
28779 		qreply(q, mp);
28780 	} else {
28781 		mutex_exit(&ill->ill_lock);
28782 		freeb(mp);
28783 	}
28784 
28785 	ipsq = ill->ill_phyint->phyint_ipsq;
28786 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28787 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28788 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28789 	if (mp1 == NULL) {
28790 		/* bringup was aborted by the user */
28791 		freemsg(mp2);
28792 		return;
28793 	}
28794 
28795 	/*
28796 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28797 	 * must have an associated conn_t.  Otherwise, we're bringing this
28798 	 * interface back up as part of handling an asynchronous event (e.g.,
28799 	 * physical address change).
28800 	 */
28801 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28802 		ASSERT(connp != NULL);
28803 		q = CONNP_TO_WQ(connp);
28804 	} else {
28805 		ASSERT(connp == NULL);
28806 		q = ill->ill_rq;
28807 	}
28808 
28809 	/*
28810 	 * If the DL_BIND_REQ fails, it is noted
28811 	 * in arc_name_offset.
28812 	 */
28813 	err = *((int *)mp2->b_rptr);
28814 	if (err == 0) {
28815 		if (ipif->ipif_isv6) {
28816 			if ((err = ipif_up_done_v6(ipif)) != 0)
28817 				ip0dbg(("ip_arp_done: init failed\n"));
28818 		} else {
28819 			if ((err = ipif_up_done(ipif)) != 0)
28820 				ip0dbg(("ip_arp_done: init failed\n"));
28821 		}
28822 	} else {
28823 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28824 	}
28825 
28826 	freemsg(mp2);
28827 
28828 	if ((err == 0) && (ill->ill_up_ipifs)) {
28829 		err = ill_up_ipifs(ill, q, mp1);
28830 		if (err == EINPROGRESS)
28831 			return;
28832 	}
28833 
28834 	/*
28835 	 * If we have a moved ipif to bring up, and everything has succeeded
28836 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28837 	 * down -- the admin can try to bring it up by hand if need be.
28838 	 */
28839 	if (ill->ill_move_ipif != NULL) {
28840 		ipif = ill->ill_move_ipif;
28841 		ill->ill_move_ipif = NULL;
28842 		if (err == 0) {
28843 			err = ipif_up(ipif, q, mp1);
28844 			if (err == EINPROGRESS)
28845 				return;
28846 		}
28847 	}
28848 
28849 	/*
28850 	 * The operation must complete without EINPROGRESS since
28851 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28852 	 * operation will be stuck forever in the ipsq.
28853 	 */
28854 	ASSERT(err != EINPROGRESS);
28855 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28856 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28857 	else
28858 		ipsq_current_finish(ipsq);
28859 }
28860 
28861 /* Allocate the private structure */
28862 static int
28863 ip_priv_alloc(void **bufp)
28864 {
28865 	void	*buf;
28866 
28867 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28868 		return (ENOMEM);
28869 
28870 	*bufp = buf;
28871 	return (0);
28872 }
28873 
28874 /* Function to delete the private structure */
28875 void
28876 ip_priv_free(void *buf)
28877 {
28878 	ASSERT(buf != NULL);
28879 	kmem_free(buf, sizeof (ip_priv_t));
28880 }
28881 
28882 /*
28883  * The entry point for IPPF processing.
28884  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28885  * routine just returns.
28886  *
28887  * When called, ip_process generates an ipp_packet_t structure
28888  * which holds the state information for this packet and invokes the
28889  * the classifier (via ipp_packet_process). The classification, depending on
28890  * configured filters, results in a list of actions for this packet. Invoking
28891  * an action may cause the packet to be dropped, in which case the resulting
28892  * mblk (*mpp) is NULL. proc indicates the callout position for
28893  * this packet and ill_index is the interface this packet on or will leave
28894  * on (inbound and outbound resp.).
28895  */
28896 void
28897 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28898 {
28899 	mblk_t		*mp;
28900 	ip_priv_t	*priv;
28901 	ipp_action_id_t	aid;
28902 	int		rc = 0;
28903 	ipp_packet_t	*pp;
28904 #define	IP_CLASS	"ip"
28905 
28906 	/* If the classifier is not loaded, return  */
28907 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28908 		return;
28909 	}
28910 
28911 	mp = *mpp;
28912 	ASSERT(mp != NULL);
28913 
28914 	/* Allocate the packet structure */
28915 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28916 	if (rc != 0) {
28917 		*mpp = NULL;
28918 		freemsg(mp);
28919 		return;
28920 	}
28921 
28922 	/* Allocate the private structure */
28923 	rc = ip_priv_alloc((void **)&priv);
28924 	if (rc != 0) {
28925 		*mpp = NULL;
28926 		freemsg(mp);
28927 		ipp_packet_free(pp);
28928 		return;
28929 	}
28930 	priv->proc = proc;
28931 	priv->ill_index = ill_index;
28932 	ipp_packet_set_private(pp, priv, ip_priv_free);
28933 	ipp_packet_set_data(pp, mp);
28934 
28935 	/* Invoke the classifier */
28936 	rc = ipp_packet_process(&pp);
28937 	if (pp != NULL) {
28938 		mp = ipp_packet_get_data(pp);
28939 		ipp_packet_free(pp);
28940 		if (rc != 0) {
28941 			freemsg(mp);
28942 			*mpp = NULL;
28943 		}
28944 	} else {
28945 		*mpp = NULL;
28946 	}
28947 #undef	IP_CLASS
28948 }
28949 
28950 /*
28951  * Propagate a multicast group membership operation (add/drop) on
28952  * all the interfaces crossed by the related multirt routes.
28953  * The call is considered successful if the operation succeeds
28954  * on at least one interface.
28955  */
28956 static int
28957 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28958     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28959     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28960     mblk_t *first_mp)
28961 {
28962 	ire_t		*ire_gw;
28963 	irb_t		*irb;
28964 	int		error = 0;
28965 	opt_restart_t	*or;
28966 	ip_stack_t	*ipst = ire->ire_ipst;
28967 
28968 	irb = ire->ire_bucket;
28969 	ASSERT(irb != NULL);
28970 
28971 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28972 
28973 	or = (opt_restart_t *)first_mp->b_rptr;
28974 	IRB_REFHOLD(irb);
28975 	for (; ire != NULL; ire = ire->ire_next) {
28976 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28977 			continue;
28978 		if (ire->ire_addr != group)
28979 			continue;
28980 
28981 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28982 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28983 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28984 		/* No resolver exists for the gateway; skip this ire. */
28985 		if (ire_gw == NULL)
28986 			continue;
28987 
28988 		/*
28989 		 * This function can return EINPROGRESS. If so the operation
28990 		 * will be restarted from ip_restart_optmgmt which will
28991 		 * call ip_opt_set and option processing will restart for
28992 		 * this option. So we may end up calling 'fn' more than once.
28993 		 * This requires that 'fn' is idempotent except for the
28994 		 * return value. The operation is considered a success if
28995 		 * it succeeds at least once on any one interface.
28996 		 */
28997 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28998 		    NULL, fmode, src, first_mp);
28999 		if (error == 0)
29000 			or->or_private = CGTP_MCAST_SUCCESS;
29001 
29002 		if (ip_debug > 0) {
29003 			ulong_t	off;
29004 			char	*ksym;
29005 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29006 			ip2dbg(("ip_multirt_apply_membership: "
29007 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29008 			    "error %d [success %u]\n",
29009 			    ksym ? ksym : "?",
29010 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29011 			    error, or->or_private));
29012 		}
29013 
29014 		ire_refrele(ire_gw);
29015 		if (error == EINPROGRESS) {
29016 			IRB_REFRELE(irb);
29017 			return (error);
29018 		}
29019 	}
29020 	IRB_REFRELE(irb);
29021 	/*
29022 	 * Consider the call as successful if we succeeded on at least
29023 	 * one interface. Otherwise, return the last encountered error.
29024 	 */
29025 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29026 }
29027 
29028 /*
29029  * Issue a warning regarding a route crossing an interface with an
29030  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29031  * amount of time is logged.
29032  */
29033 static void
29034 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29035 {
29036 	hrtime_t	current = gethrtime();
29037 	char		buf[INET_ADDRSTRLEN];
29038 	ip_stack_t	*ipst = ire->ire_ipst;
29039 
29040 	/* Convert interval in ms to hrtime in ns */
29041 	if (ipst->ips_multirt_bad_mtu_last_time +
29042 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29043 	    current) {
29044 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29045 		    "to %s, incorrect MTU %u (expected %u)\n",
29046 		    ip_dot_addr(ire->ire_addr, buf),
29047 		    ire->ire_max_frag, max_frag);
29048 
29049 		ipst->ips_multirt_bad_mtu_last_time = current;
29050 	}
29051 }
29052 
29053 /*
29054  * Get the CGTP (multirouting) filtering status.
29055  * If 0, the CGTP hooks are transparent.
29056  */
29057 /* ARGSUSED */
29058 static int
29059 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29060 {
29061 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29062 
29063 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29064 	return (0);
29065 }
29066 
29067 /*
29068  * Set the CGTP (multirouting) filtering status.
29069  * If the status is changed from active to transparent
29070  * or from transparent to active, forward the new status
29071  * to the filtering module (if loaded).
29072  */
29073 /* ARGSUSED */
29074 static int
29075 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29076     cred_t *ioc_cr)
29077 {
29078 	long		new_value;
29079 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29080 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29081 
29082 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29083 		return (EPERM);
29084 
29085 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29086 	    new_value < 0 || new_value > 1) {
29087 		return (EINVAL);
29088 	}
29089 
29090 	if ((!*ip_cgtp_filter_value) && new_value) {
29091 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29092 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29093 		    " (module not loaded)" : "");
29094 	}
29095 	if (*ip_cgtp_filter_value && (!new_value)) {
29096 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29097 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29098 		    " (module not loaded)" : "");
29099 	}
29100 
29101 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29102 		int	res;
29103 		netstackid_t stackid;
29104 
29105 		stackid = ipst->ips_netstack->netstack_stackid;
29106 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29107 		    new_value);
29108 		if (res)
29109 			return (res);
29110 	}
29111 
29112 	*ip_cgtp_filter_value = (boolean_t)new_value;
29113 
29114 	return (0);
29115 }
29116 
29117 /*
29118  * Return the expected CGTP hooks version number.
29119  */
29120 int
29121 ip_cgtp_filter_supported(void)
29122 {
29123 	return (ip_cgtp_filter_rev);
29124 }
29125 
29126 /*
29127  * CGTP hooks can be registered by invoking this function.
29128  * Checks that the version number matches.
29129  */
29130 int
29131 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29132 {
29133 	netstack_t *ns;
29134 	ip_stack_t *ipst;
29135 
29136 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29137 		return (ENOTSUP);
29138 
29139 	ns = netstack_find_by_stackid(stackid);
29140 	if (ns == NULL)
29141 		return (EINVAL);
29142 	ipst = ns->netstack_ip;
29143 	ASSERT(ipst != NULL);
29144 
29145 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29146 		netstack_rele(ns);
29147 		return (EALREADY);
29148 	}
29149 
29150 	ipst->ips_ip_cgtp_filter_ops = ops;
29151 	netstack_rele(ns);
29152 	return (0);
29153 }
29154 
29155 /*
29156  * CGTP hooks can be unregistered by invoking this function.
29157  * Returns ENXIO if there was no registration.
29158  * Returns EBUSY if the ndd variable has not been turned off.
29159  */
29160 int
29161 ip_cgtp_filter_unregister(netstackid_t stackid)
29162 {
29163 	netstack_t *ns;
29164 	ip_stack_t *ipst;
29165 
29166 	ns = netstack_find_by_stackid(stackid);
29167 	if (ns == NULL)
29168 		return (EINVAL);
29169 	ipst = ns->netstack_ip;
29170 	ASSERT(ipst != NULL);
29171 
29172 	if (ipst->ips_ip_cgtp_filter) {
29173 		netstack_rele(ns);
29174 		return (EBUSY);
29175 	}
29176 
29177 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29178 		netstack_rele(ns);
29179 		return (ENXIO);
29180 	}
29181 	ipst->ips_ip_cgtp_filter_ops = NULL;
29182 	netstack_rele(ns);
29183 	return (0);
29184 }
29185 
29186 /*
29187  * Check whether there is a CGTP filter registration.
29188  * Returns non-zero if there is a registration, otherwise returns zero.
29189  * Note: returns zero if bad stackid.
29190  */
29191 int
29192 ip_cgtp_filter_is_registered(netstackid_t stackid)
29193 {
29194 	netstack_t *ns;
29195 	ip_stack_t *ipst;
29196 	int ret;
29197 
29198 	ns = netstack_find_by_stackid(stackid);
29199 	if (ns == NULL)
29200 		return (0);
29201 	ipst = ns->netstack_ip;
29202 	ASSERT(ipst != NULL);
29203 
29204 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29205 		ret = 1;
29206 	else
29207 		ret = 0;
29208 
29209 	netstack_rele(ns);
29210 	return (ret);
29211 }
29212 
29213 static int
29214 ip_squeue_switch(int val)
29215 {
29216 	int rval = SQ_FILL;
29217 
29218 	switch (val) {
29219 	case IP_SQUEUE_ENTER_NODRAIN:
29220 		rval = SQ_NODRAIN;
29221 		break;
29222 	case IP_SQUEUE_ENTER:
29223 		rval = SQ_PROCESS;
29224 		break;
29225 	default:
29226 		break;
29227 	}
29228 	return (rval);
29229 }
29230 
29231 /* ARGSUSED */
29232 static int
29233 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29234     caddr_t addr, cred_t *cr)
29235 {
29236 	int *v = (int *)addr;
29237 	long new_value;
29238 
29239 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29240 		return (EPERM);
29241 
29242 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29243 		return (EINVAL);
29244 
29245 	ip_squeue_flag = ip_squeue_switch(new_value);
29246 	*v = new_value;
29247 	return (0);
29248 }
29249 
29250 /*
29251  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29252  * ip_debug.
29253  */
29254 /* ARGSUSED */
29255 static int
29256 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29257     caddr_t addr, cred_t *cr)
29258 {
29259 	int *v = (int *)addr;
29260 	long new_value;
29261 
29262 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29263 		return (EPERM);
29264 
29265 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29266 		return (EINVAL);
29267 
29268 	*v = new_value;
29269 	return (0);
29270 }
29271 
29272 static void *
29273 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29274 {
29275 	kstat_t *ksp;
29276 
29277 	ip_stat_t template = {
29278 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29279 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29280 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29281 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29282 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29283 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29284 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29285 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29286 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29287 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29288 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29289 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29290 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29291 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29292 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29293 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29294 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29295 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29296 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29297 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29298 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29299 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29300 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29301 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29302 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29303 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29304 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29305 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29306 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29307 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29308 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29309 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29310 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29311 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29312 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29313 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29314 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29315 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29316 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29317 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29318 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29319 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29320 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29321 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29322 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29323 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29324 	};
29325 
29326 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29327 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29328 	    KSTAT_FLAG_VIRTUAL, stackid);
29329 
29330 	if (ksp == NULL)
29331 		return (NULL);
29332 
29333 	bcopy(&template, ip_statisticsp, sizeof (template));
29334 	ksp->ks_data = (void *)ip_statisticsp;
29335 	ksp->ks_private = (void *)(uintptr_t)stackid;
29336 
29337 	kstat_install(ksp);
29338 	return (ksp);
29339 }
29340 
29341 static void
29342 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29343 {
29344 	if (ksp != NULL) {
29345 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29346 		kstat_delete_netstack(ksp, stackid);
29347 	}
29348 }
29349 
29350 static void *
29351 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29352 {
29353 	kstat_t	*ksp;
29354 
29355 	ip_named_kstat_t template = {
29356 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29357 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29358 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29359 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29360 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29361 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29362 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29363 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29364 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29365 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29366 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29367 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29368 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29369 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29370 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29371 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29372 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29373 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29374 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29375 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29376 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29377 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29378 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29379 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29380 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29381 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29382 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29383 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29384 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29385 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29386 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29387 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29388 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29389 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29390 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29391 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29392 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29393 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29394 	};
29395 
29396 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29397 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29398 	if (ksp == NULL || ksp->ks_data == NULL)
29399 		return (NULL);
29400 
29401 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29402 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29403 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29404 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29405 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29406 
29407 	template.netToMediaEntrySize.value.i32 =
29408 	    sizeof (mib2_ipNetToMediaEntry_t);
29409 
29410 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29411 
29412 	bcopy(&template, ksp->ks_data, sizeof (template));
29413 	ksp->ks_update = ip_kstat_update;
29414 	ksp->ks_private = (void *)(uintptr_t)stackid;
29415 
29416 	kstat_install(ksp);
29417 	return (ksp);
29418 }
29419 
29420 static void
29421 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29422 {
29423 	if (ksp != NULL) {
29424 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29425 		kstat_delete_netstack(ksp, stackid);
29426 	}
29427 }
29428 
29429 static int
29430 ip_kstat_update(kstat_t *kp, int rw)
29431 {
29432 	ip_named_kstat_t *ipkp;
29433 	mib2_ipIfStatsEntry_t ipmib;
29434 	ill_walk_context_t ctx;
29435 	ill_t *ill;
29436 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29437 	netstack_t	*ns;
29438 	ip_stack_t	*ipst;
29439 
29440 	if (kp == NULL || kp->ks_data == NULL)
29441 		return (EIO);
29442 
29443 	if (rw == KSTAT_WRITE)
29444 		return (EACCES);
29445 
29446 	ns = netstack_find_by_stackid(stackid);
29447 	if (ns == NULL)
29448 		return (-1);
29449 	ipst = ns->netstack_ip;
29450 	if (ipst == NULL) {
29451 		netstack_rele(ns);
29452 		return (-1);
29453 	}
29454 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29455 
29456 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29457 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29458 	ill = ILL_START_WALK_V4(&ctx, ipst);
29459 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29460 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29461 	rw_exit(&ipst->ips_ill_g_lock);
29462 
29463 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29464 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29465 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29466 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29467 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29468 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29469 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29470 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29471 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29472 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29473 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29474 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29475 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29476 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29477 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29478 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29479 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29480 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29481 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29482 
29483 	ipkp->routingDiscards.value.ui32 =	0;
29484 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29485 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29486 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29487 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29488 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29489 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29490 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29491 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29492 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29493 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29494 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29495 
29496 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29497 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29498 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29499 
29500 	netstack_rele(ns);
29501 
29502 	return (0);
29503 }
29504 
29505 static void *
29506 icmp_kstat_init(netstackid_t stackid)
29507 {
29508 	kstat_t	*ksp;
29509 
29510 	icmp_named_kstat_t template = {
29511 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29512 		{ "inErrors",		KSTAT_DATA_UINT32 },
29513 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29514 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29515 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29516 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29517 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29518 		{ "inEchos",		KSTAT_DATA_UINT32 },
29519 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29520 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29521 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29522 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29523 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29524 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29525 		{ "outErrors",		KSTAT_DATA_UINT32 },
29526 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29527 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29528 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29529 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29530 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29531 		{ "outEchos",		KSTAT_DATA_UINT32 },
29532 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29533 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29534 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29535 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29536 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29537 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29538 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29539 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29540 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29541 		{ "outDrops",		KSTAT_DATA_UINT32 },
29542 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29543 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29544 	};
29545 
29546 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29547 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29548 	if (ksp == NULL || ksp->ks_data == NULL)
29549 		return (NULL);
29550 
29551 	bcopy(&template, ksp->ks_data, sizeof (template));
29552 
29553 	ksp->ks_update = icmp_kstat_update;
29554 	ksp->ks_private = (void *)(uintptr_t)stackid;
29555 
29556 	kstat_install(ksp);
29557 	return (ksp);
29558 }
29559 
29560 static void
29561 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29562 {
29563 	if (ksp != NULL) {
29564 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29565 		kstat_delete_netstack(ksp, stackid);
29566 	}
29567 }
29568 
29569 static int
29570 icmp_kstat_update(kstat_t *kp, int rw)
29571 {
29572 	icmp_named_kstat_t *icmpkp;
29573 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29574 	netstack_t	*ns;
29575 	ip_stack_t	*ipst;
29576 
29577 	if ((kp == NULL) || (kp->ks_data == NULL))
29578 		return (EIO);
29579 
29580 	if (rw == KSTAT_WRITE)
29581 		return (EACCES);
29582 
29583 	ns = netstack_find_by_stackid(stackid);
29584 	if (ns == NULL)
29585 		return (-1);
29586 	ipst = ns->netstack_ip;
29587 	if (ipst == NULL) {
29588 		netstack_rele(ns);
29589 		return (-1);
29590 	}
29591 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29592 
29593 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29594 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29595 	icmpkp->inDestUnreachs.value.ui32 =
29596 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29597 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29598 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29599 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29600 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29601 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29602 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29603 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29604 	icmpkp->inTimestampReps.value.ui32 =
29605 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29606 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29607 	icmpkp->inAddrMaskReps.value.ui32 =
29608 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29609 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29610 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29611 	icmpkp->outDestUnreachs.value.ui32 =
29612 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29613 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29614 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29615 	icmpkp->outSrcQuenchs.value.ui32 =
29616 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29617 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29618 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29619 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29620 	icmpkp->outTimestamps.value.ui32 =
29621 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29622 	icmpkp->outTimestampReps.value.ui32 =
29623 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29624 	icmpkp->outAddrMasks.value.ui32 =
29625 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29626 	icmpkp->outAddrMaskReps.value.ui32 =
29627 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29628 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29629 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29630 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29631 	icmpkp->outFragNeeded.value.ui32 =
29632 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29633 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29634 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29635 	icmpkp->inBadRedirects.value.ui32 =
29636 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29637 
29638 	netstack_rele(ns);
29639 	return (0);
29640 }
29641 
29642 /*
29643  * This is the fanout function for raw socket opened for SCTP.  Note
29644  * that it is called after SCTP checks that there is no socket which
29645  * wants a packet.  Then before SCTP handles this out of the blue packet,
29646  * this function is called to see if there is any raw socket for SCTP.
29647  * If there is and it is bound to the correct address, the packet will
29648  * be sent to that socket.  Note that only one raw socket can be bound to
29649  * a port.  This is assured in ipcl_sctp_hash_insert();
29650  */
29651 void
29652 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29653     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29654     zoneid_t zoneid)
29655 {
29656 	conn_t		*connp;
29657 	queue_t		*rq;
29658 	mblk_t		*first_mp;
29659 	boolean_t	secure;
29660 	ip6_t		*ip6h;
29661 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29662 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29663 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29664 	boolean_t	sctp_csum_err = B_FALSE;
29665 
29666 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29667 		sctp_csum_err = B_TRUE;
29668 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29669 	}
29670 
29671 	first_mp = mp;
29672 	if (mctl_present) {
29673 		mp = first_mp->b_cont;
29674 		secure = ipsec_in_is_secure(first_mp);
29675 		ASSERT(mp != NULL);
29676 	} else {
29677 		secure = B_FALSE;
29678 	}
29679 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29680 
29681 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29682 	if (connp == NULL) {
29683 		/*
29684 		 * Although raw sctp is not summed, OOB chunks must be.
29685 		 * Drop the packet here if the sctp checksum failed.
29686 		 */
29687 		if (sctp_csum_err) {
29688 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29689 			freemsg(first_mp);
29690 			return;
29691 		}
29692 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29693 		return;
29694 	}
29695 	rq = connp->conn_rq;
29696 	if (!canputnext(rq)) {
29697 		CONN_DEC_REF(connp);
29698 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29699 		freemsg(first_mp);
29700 		return;
29701 	}
29702 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29703 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29704 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29705 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29706 		if (first_mp == NULL) {
29707 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29708 			CONN_DEC_REF(connp);
29709 			return;
29710 		}
29711 	}
29712 	/*
29713 	 * We probably should not send M_CTL message up to
29714 	 * raw socket.
29715 	 */
29716 	if (mctl_present)
29717 		freeb(first_mp);
29718 
29719 	/* Initiate IPPF processing here if needed. */
29720 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29721 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29722 		ip_process(IPP_LOCAL_IN, &mp,
29723 		    recv_ill->ill_phyint->phyint_ifindex);
29724 		if (mp == NULL) {
29725 			CONN_DEC_REF(connp);
29726 			return;
29727 		}
29728 	}
29729 
29730 	if (connp->conn_recvif || connp->conn_recvslla ||
29731 	    ((connp->conn_ip_recvpktinfo ||
29732 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29733 	    (flags & IP_FF_IPINFO))) {
29734 		int in_flags = 0;
29735 
29736 		/*
29737 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29738 		 * IPF_RECVIF.
29739 		 */
29740 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29741 			in_flags = IPF_RECVIF;
29742 		}
29743 		if (connp->conn_recvslla) {
29744 			in_flags |= IPF_RECVSLLA;
29745 		}
29746 		if (isv4) {
29747 			mp = ip_add_info(mp, recv_ill, in_flags,
29748 			    IPCL_ZONEID(connp), ipst);
29749 		} else {
29750 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29751 			if (mp == NULL) {
29752 				BUMP_MIB(recv_ill->ill_ip_mib,
29753 				    ipIfStatsInDiscards);
29754 				CONN_DEC_REF(connp);
29755 				return;
29756 			}
29757 		}
29758 	}
29759 
29760 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29761 	/*
29762 	 * We are sending the IPSEC_IN message also up. Refer
29763 	 * to comments above this function.
29764 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29765 	 */
29766 	(connp->conn_recv)(connp, mp, NULL);
29767 	CONN_DEC_REF(connp);
29768 }
29769 
29770 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29771 {									\
29772 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29773 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29774 }
29775 /*
29776  * This function should be called only if all packet processing
29777  * including fragmentation is complete. Callers of this function
29778  * must set mp->b_prev to one of these values:
29779  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29780  * prior to handing over the mp as first argument to this function.
29781  *
29782  * If the ire passed by caller is incomplete, this function
29783  * queues the packet and if necessary, sends ARP request and bails.
29784  * If the ire passed is fully resolved, we simply prepend
29785  * the link-layer header to the packet, do ipsec hw acceleration
29786  * work if necessary, and send the packet out on the wire.
29787  *
29788  * NOTE: IPsec will only call this function with fully resolved
29789  * ires if hw acceleration is involved.
29790  * TODO list :
29791  * 	a Handle M_MULTIDATA so that
29792  *	  tcp_multisend->tcp_multisend_data can
29793  *	  call ip_xmit_v4 directly
29794  *	b Handle post-ARP work for fragments so that
29795  *	  ip_wput_frag can call this function.
29796  */
29797 ipxmit_state_t
29798 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29799     boolean_t flow_ctl_enabled, conn_t *connp)
29800 {
29801 	nce_t		*arpce;
29802 	ipha_t		*ipha;
29803 	queue_t		*q;
29804 	int		ill_index;
29805 	mblk_t		*nxt_mp, *first_mp;
29806 	boolean_t	xmit_drop = B_FALSE;
29807 	ip_proc_t	proc;
29808 	ill_t		*out_ill;
29809 	int		pkt_len;
29810 
29811 	arpce = ire->ire_nce;
29812 	ASSERT(arpce != NULL);
29813 
29814 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29815 
29816 	mutex_enter(&arpce->nce_lock);
29817 	switch (arpce->nce_state) {
29818 	case ND_REACHABLE:
29819 		/* If there are other queued packets, queue this packet */
29820 		if (arpce->nce_qd_mp != NULL) {
29821 			if (mp != NULL)
29822 				nce_queue_mp_common(arpce, mp, B_FALSE);
29823 			mp = arpce->nce_qd_mp;
29824 		}
29825 		arpce->nce_qd_mp = NULL;
29826 		mutex_exit(&arpce->nce_lock);
29827 
29828 		/*
29829 		 * Flush the queue.  In the common case, where the
29830 		 * ARP is already resolved,  it will go through the
29831 		 * while loop only once.
29832 		 */
29833 		while (mp != NULL) {
29834 
29835 			nxt_mp = mp->b_next;
29836 			mp->b_next = NULL;
29837 			ASSERT(mp->b_datap->db_type != M_CTL);
29838 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29839 			/*
29840 			 * This info is needed for IPQOS to do COS marking
29841 			 * in ip_wput_attach_llhdr->ip_process.
29842 			 */
29843 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29844 			mp->b_prev = NULL;
29845 
29846 			/* set up ill index for outbound qos processing */
29847 			out_ill = ire_to_ill(ire);
29848 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29849 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29850 			    ill_index, &ipha);
29851 			if (first_mp == NULL) {
29852 				xmit_drop = B_TRUE;
29853 				BUMP_MIB(out_ill->ill_ip_mib,
29854 				    ipIfStatsOutDiscards);
29855 				goto next_mp;
29856 			}
29857 
29858 			/* non-ipsec hw accel case */
29859 			if (io == NULL || !io->ipsec_out_accelerated) {
29860 				/* send it */
29861 				q = ire->ire_stq;
29862 				if (proc == IPP_FWD_OUT) {
29863 					UPDATE_IB_PKT_COUNT(ire);
29864 				} else {
29865 					UPDATE_OB_PKT_COUNT(ire);
29866 				}
29867 				ire->ire_last_used_time = lbolt;
29868 
29869 				if (flow_ctl_enabled || canputnext(q)) {
29870 					if (proc == IPP_FWD_OUT) {
29871 
29872 					BUMP_MIB(out_ill->ill_ip_mib,
29873 					    ipIfStatsHCOutForwDatagrams);
29874 
29875 					}
29876 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29877 					    pkt_len);
29878 
29879 					DTRACE_IP7(send, mblk_t *, first_mp,
29880 					    conn_t *, NULL, void_ip_t *, ipha,
29881 					    __dtrace_ipsr_ill_t *, out_ill,
29882 					    ipha_t *, ipha, ip6_t *, NULL, int,
29883 					    0);
29884 
29885 					ILL_SEND_TX(out_ill,
29886 					    ire, connp, first_mp, 0, connp);
29887 				} else {
29888 					BUMP_MIB(out_ill->ill_ip_mib,
29889 					    ipIfStatsOutDiscards);
29890 					xmit_drop = B_TRUE;
29891 					freemsg(first_mp);
29892 				}
29893 			} else {
29894 				/*
29895 				 * Safety Pup says: make sure this
29896 				 *  is going to the right interface!
29897 				 */
29898 				ill_t *ill1 =
29899 				    (ill_t *)ire->ire_stq->q_ptr;
29900 				int ifindex =
29901 				    ill1->ill_phyint->phyint_ifindex;
29902 				if (ifindex !=
29903 				    io->ipsec_out_capab_ill_index) {
29904 					xmit_drop = B_TRUE;
29905 					freemsg(mp);
29906 				} else {
29907 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29908 					    pkt_len);
29909 
29910 					DTRACE_IP7(send, mblk_t *, first_mp,
29911 					    conn_t *, NULL, void_ip_t *, ipha,
29912 					    __dtrace_ipsr_ill_t *, ill1,
29913 					    ipha_t *, ipha, ip6_t *, NULL,
29914 					    int, 0);
29915 
29916 					ipsec_hw_putnext(ire->ire_stq, mp);
29917 				}
29918 			}
29919 next_mp:
29920 			mp = nxt_mp;
29921 		} /* while (mp != NULL) */
29922 		if (xmit_drop)
29923 			return (SEND_FAILED);
29924 		else
29925 			return (SEND_PASSED);
29926 
29927 	case ND_INITIAL:
29928 	case ND_INCOMPLETE:
29929 
29930 		/*
29931 		 * While we do send off packets to dests that
29932 		 * use fully-resolved CGTP routes, we do not
29933 		 * handle unresolved CGTP routes.
29934 		 */
29935 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29936 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29937 
29938 		if (mp != NULL) {
29939 			/* queue the packet */
29940 			nce_queue_mp_common(arpce, mp, B_FALSE);
29941 		}
29942 
29943 		if (arpce->nce_state == ND_INCOMPLETE) {
29944 			mutex_exit(&arpce->nce_lock);
29945 			DTRACE_PROBE3(ip__xmit__incomplete,
29946 			    (ire_t *), ire, (mblk_t *), mp,
29947 			    (ipsec_out_t *), io);
29948 			return (LOOKUP_IN_PROGRESS);
29949 		}
29950 
29951 		arpce->nce_state = ND_INCOMPLETE;
29952 		mutex_exit(&arpce->nce_lock);
29953 
29954 		/*
29955 		 * Note that ire_add() (called from ire_forward())
29956 		 * holds a ref on the ire until ARP is completed.
29957 		 */
29958 		ire_arpresolve(ire);
29959 		return (LOOKUP_IN_PROGRESS);
29960 	default:
29961 		ASSERT(0);
29962 		mutex_exit(&arpce->nce_lock);
29963 		return (LLHDR_RESLV_FAILED);
29964 	}
29965 }
29966 
29967 #undef	UPDATE_IP_MIB_OB_COUNTERS
29968 
29969 /*
29970  * Return B_TRUE if the buffers differ in length or content.
29971  * This is used for comparing extension header buffers.
29972  * Note that an extension header would be declared different
29973  * even if all that changed was the next header value in that header i.e.
29974  * what really changed is the next extension header.
29975  */
29976 boolean_t
29977 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29978     uint_t blen)
29979 {
29980 	if (!b_valid)
29981 		blen = 0;
29982 
29983 	if (alen != blen)
29984 		return (B_TRUE);
29985 	if (alen == 0)
29986 		return (B_FALSE);	/* Both zero length */
29987 	return (bcmp(abuf, bbuf, alen));
29988 }
29989 
29990 /*
29991  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29992  * Return B_FALSE if memory allocation fails - don't change any state!
29993  */
29994 boolean_t
29995 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29996     const void *src, uint_t srclen)
29997 {
29998 	void *dst;
29999 
30000 	if (!src_valid)
30001 		srclen = 0;
30002 
30003 	ASSERT(*dstlenp == 0);
30004 	if (src != NULL && srclen != 0) {
30005 		dst = mi_alloc(srclen, BPRI_MED);
30006 		if (dst == NULL)
30007 			return (B_FALSE);
30008 	} else {
30009 		dst = NULL;
30010 	}
30011 	if (*dstp != NULL)
30012 		mi_free(*dstp);
30013 	*dstp = dst;
30014 	*dstlenp = dst == NULL ? 0 : srclen;
30015 	return (B_TRUE);
30016 }
30017 
30018 /*
30019  * Replace what is in *dst, *dstlen with the source.
30020  * Assumes ip_allocbuf has already been called.
30021  */
30022 void
30023 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30024     const void *src, uint_t srclen)
30025 {
30026 	if (!src_valid)
30027 		srclen = 0;
30028 
30029 	ASSERT(*dstlenp == srclen);
30030 	if (src != NULL && srclen != 0)
30031 		bcopy(src, *dstp, srclen);
30032 }
30033 
30034 /*
30035  * Free the storage pointed to by the members of an ip6_pkt_t.
30036  */
30037 void
30038 ip6_pkt_free(ip6_pkt_t *ipp)
30039 {
30040 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30041 
30042 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30043 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30044 		ipp->ipp_hopopts = NULL;
30045 		ipp->ipp_hopoptslen = 0;
30046 	}
30047 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30048 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30049 		ipp->ipp_rtdstopts = NULL;
30050 		ipp->ipp_rtdstoptslen = 0;
30051 	}
30052 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30053 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30054 		ipp->ipp_dstopts = NULL;
30055 		ipp->ipp_dstoptslen = 0;
30056 	}
30057 	if (ipp->ipp_fields & IPPF_RTHDR) {
30058 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30059 		ipp->ipp_rthdr = NULL;
30060 		ipp->ipp_rthdrlen = 0;
30061 	}
30062 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30063 	    IPPF_RTHDR);
30064 }
30065 
30066 zoneid_t
30067 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30068     zoneid_t lookup_zoneid)
30069 {
30070 	ire_t		*ire;
30071 	int		ire_flags = MATCH_IRE_TYPE;
30072 	zoneid_t	zoneid = ALL_ZONES;
30073 
30074 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30075 		return (ALL_ZONES);
30076 
30077 	if (lookup_zoneid != ALL_ZONES)
30078 		ire_flags |= MATCH_IRE_ZONEONLY;
30079 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30080 	    lookup_zoneid, NULL, ire_flags, ipst);
30081 	if (ire != NULL) {
30082 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30083 		ire_refrele(ire);
30084 	}
30085 	return (zoneid);
30086 }
30087 
30088 zoneid_t
30089 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30090     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30091 {
30092 	ire_t		*ire;
30093 	int		ire_flags = MATCH_IRE_TYPE;
30094 	zoneid_t	zoneid = ALL_ZONES;
30095 	ipif_t		*ipif_arg = NULL;
30096 
30097 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30098 		return (ALL_ZONES);
30099 
30100 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30101 		ire_flags |= MATCH_IRE_ILL;
30102 		ipif_arg = ill->ill_ipif;
30103 	}
30104 	if (lookup_zoneid != ALL_ZONES)
30105 		ire_flags |= MATCH_IRE_ZONEONLY;
30106 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30107 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30108 	if (ire != NULL) {
30109 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30110 		ire_refrele(ire);
30111 	}
30112 	return (zoneid);
30113 }
30114 
30115 /*
30116  * IP obserability hook support functions.
30117  */
30118 
30119 static void
30120 ipobs_init(ip_stack_t *ipst)
30121 {
30122 	ipst->ips_ipobs_enabled = B_FALSE;
30123 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30124 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30125 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30126 	ipst->ips_ipobs_cb_nwalkers = 0;
30127 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30128 }
30129 
30130 static void
30131 ipobs_fini(ip_stack_t *ipst)
30132 {
30133 	ipobs_cb_t *cb;
30134 
30135 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30136 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30137 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30138 
30139 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30140 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30141 		kmem_free(cb, sizeof (*cb));
30142 	}
30143 	list_destroy(&ipst->ips_ipobs_cb_list);
30144 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30145 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30146 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30147 }
30148 
30149 void
30150 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30151     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30152 {
30153 	mblk_t *mp2;
30154 	ipobs_cb_t *ipobs_cb;
30155 	ipobs_hook_data_t *ihd;
30156 	uint64_t grifindex = 0;
30157 
30158 	ASSERT(DB_TYPE(mp) == M_DATA);
30159 
30160 	if (IS_UNDER_IPMP(ill))
30161 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30162 
30163 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30164 	ipst->ips_ipobs_cb_nwalkers++;
30165 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30166 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30167 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30168 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30169 		if (mp2 != NULL) {
30170 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30171 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30172 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30173 				freemsg(mp2);
30174 				continue;
30175 			}
30176 			ihd->ihd_mp->b_rptr += hlen;
30177 			ihd->ihd_htype = htype;
30178 			ihd->ihd_ipver = ipver;
30179 			ihd->ihd_zsrc = zsrc;
30180 			ihd->ihd_zdst = zdst;
30181 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30182 			ihd->ihd_grifindex = grifindex;
30183 			ihd->ihd_stack = ipst->ips_netstack;
30184 			mp2->b_wptr += sizeof (*ihd);
30185 			ipobs_cb->ipobs_cbfunc(mp2);
30186 		}
30187 	}
30188 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30189 	ipst->ips_ipobs_cb_nwalkers--;
30190 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30191 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30192 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30193 }
30194 
30195 void
30196 ipobs_register_hook(netstack_t *ns, pfv_t func)
30197 {
30198 	ipobs_cb_t   *cb;
30199 	ip_stack_t *ipst = ns->netstack_ip;
30200 
30201 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30202 
30203 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30204 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30205 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30206 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30207 
30208 	cb->ipobs_cbfunc = func;
30209 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30210 	ipst->ips_ipobs_enabled = B_TRUE;
30211 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30212 }
30213 
30214 void
30215 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30216 {
30217 	ipobs_cb_t	*curcb;
30218 	ip_stack_t	*ipst = ns->netstack_ip;
30219 
30220 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30221 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30222 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30223 
30224 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30225 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30226 		if (func == curcb->ipobs_cbfunc) {
30227 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30228 			kmem_free(curcb, sizeof (*curcb));
30229 			break;
30230 		}
30231 	}
30232 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30233 		ipst->ips_ipobs_enabled = B_FALSE;
30234 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30235 }
30236