xref: /titanic_41/usr/src/uts/common/inet/ip/ip.c (revision 0a4675b3d422aaa480e8a456bc5dd2d67cc50222)
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/iptun/iptun_impl.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_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT		15
873 #define	IPV6_FRAG_TIMEOUT	60
874 
875 /*
876  * Threshold which determines whether MDT should be used when
877  * generating IP fragments; payload size must be greater than
878  * this threshold for MDT to take place.
879  */
880 #define	IP_WPUT_FRAG_MDT_MIN	32768
881 
882 /* Setable in /etc/system only */
883 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
884 
885 static long ip_rput_pullups;
886 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
887 
888 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
889 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
890 
891 int	ip_debug;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 
902 /*
903  * XXX following really should only be in a header. Would need more
904  * header and .c clean up first.
905  */
906 extern optdb_obj_t	ip_opt_obj;
907 
908 ulong_t ip_squeue_enter_unbound = 0;
909 
910 /*
911  * Named Dispatch Parameter Table.
912  * All of these are alterable, within the min/max values given, at run time.
913  */
914 static ipparam_t	lcl_param_arr[] = {
915 	/* min	max	value	name */
916 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
921 	{  0,	1,	1,	"ip_send_redirects"},
922 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
923 	{  0,	10,	0,	"ip_mrtdebug"},
924 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
925 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
926 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
927 	{  1,	255,	255,	"ip_def_ttl" },
928 	{  0,	1,	0,	"ip_forward_src_routed"},
929 	{  0,	256,	32,	"ip_wroff_extra" },
930 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
931 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
932 	{  0,	1,	1,	"ip_path_mtu_discovery" },
933 	{  0,	240,	30,	"ip_ignore_delete_time" },
934 	{  0,	1,	0,	"ip_ignore_redirect" },
935 	{  0,	1,	1,	"ip_output_queue" },
936 	{  1,	254,	1,	"ip_broadcast_ttl" },
937 	{  0,	99999,	100,	"ip_icmp_err_interval" },
938 	{  1,	99999,	10,	"ip_icmp_err_burst" },
939 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
940 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
941 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
942 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
943 	{  0,	1,	1,	"icmp_accept_clear_messages" },
944 	{  0,	1,	1,	"igmp_accept_clear_messages" },
945 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
946 				"ip_ndp_delay_first_probe_time"},
947 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
948 				"ip_ndp_max_unicast_solicit"},
949 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
950 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
951 	{  0,	1,	0,	"ip6_forward_src_routed"},
952 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
953 	{  0,	1,	1,	"ip6_send_redirects"},
954 	{  0,	1,	0,	"ip6_ignore_redirect" },
955 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
956 
957 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
958 
959 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
960 
961 	{  0,	1,	1,	"pim_accept_clear_messages" },
962 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
963 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
964 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
965 	{  0,	15,	0,	"ip_policy_mask" },
966 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
967 	{  0,	255,	1,	"ip_multirt_ttl" },
968 	{  0,	1,	1,	"ip_multidata_outbound" },
969 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
970 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
971 	{  0,	1000,	1,	"ip_max_temp_defend" },
972 	{  0,	1000,	3,	"ip_max_defend" },
973 	{  0,	999999,	30,	"ip_defend_interval" },
974 	{  0,	3600000, 300000, "ip_dup_recovery" },
975 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
976 	{  0,	1,	1,	"ip_lso_outbound" },
977 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
978 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
979 	{ 68,	65535,	576,	"ip_pmtu_min" },
980 #ifdef DEBUG
981 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
982 #else
983 	{  0,	0,	0,	"" },
984 #endif
985 };
986 
987 /*
988  * Extended NDP table
989  * The addresses for the first two are filled in to be ips_ip_g_forward
990  * and ips_ipv6_forward at init time.
991  */
992 static ipndp_t	lcl_ndp_arr[] = {
993 	/* getf			setf		data			name */
994 #define	IPNDP_IP_FORWARDING_OFFSET	0
995 	{  ip_param_generic_get,	ip_forward_set,	NULL,
996 	    "ip_forwarding" },
997 #define	IPNDP_IP6_FORWARDING_OFFSET	1
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip6_forwarding" },
1000 	{ ip_param_generic_get, ip_input_proc_set,
1001 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1002 	{ ip_param_generic_get, ip_int_set,
1003 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1004 #define	IPNDP_CGTP_FILTER_OFFSET	4
1005 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1006 	    "ip_cgtp_filter" },
1007 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1008 	    "ip_debug" },
1009 };
1010 
1011 /*
1012  * Table of IP ioctls encoding the various properties of the ioctl and
1013  * indexed based on the last byte of the ioctl command. Occasionally there
1014  * is a clash, and there is more than 1 ioctl with the same last byte.
1015  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1016  * ioctls are encoded in the misc table. An entry in the ndx table is
1017  * retrieved by indexing on the last byte of the ioctl command and comparing
1018  * the ioctl command with the value in the ndx table. In the event of a
1019  * mismatch the misc table is then searched sequentially for the desired
1020  * ioctl command.
1021  *
1022  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1023  */
1024 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1025 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1037 			MISC_CMD, ip_siocaddrt, NULL },
1038 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1039 			MISC_CMD, ip_siocdelrt, NULL },
1040 
1041 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1042 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1043 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1044 			IF_CMD, ip_sioctl_get_addr, NULL },
1045 
1046 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1048 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1050 
1051 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1052 			IPI_PRIV | IPI_WR,
1053 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1054 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1055 			IPI_MODOK | IPI_GET_CMD,
1056 			IF_CMD, ip_sioctl_get_flags, NULL },
1057 
1058 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* copyin size cannot be coded for SIOCGIFCONF */
1062 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1063 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1064 
1065 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_mtu, NULL },
1067 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1068 			IF_CMD, ip_sioctl_get_mtu, NULL },
1069 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1070 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1071 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1072 			IF_CMD, ip_sioctl_brdaddr, NULL },
1073 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1074 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1075 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1076 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1077 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1078 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1079 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1080 			IF_CMD, ip_sioctl_metric, NULL },
1081 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* See 166-168 below for extended SIOC*XARP ioctls */
1084 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1085 			ARP_CMD, ip_sioctl_arp, NULL },
1086 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1087 			ARP_CMD, ip_sioctl_arp, NULL },
1088 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1089 			ARP_CMD, ip_sioctl_arp, NULL },
1090 
1091 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1114 			MISC_CMD, if_unitsel, if_unitsel_restart },
1115 
1116 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1136 			IPI_PRIV | IPI_WR | IPI_MODOK,
1137 			IF_CMD, ip_sioctl_sifname, NULL },
1138 
1139 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 
1153 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1154 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1155 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1156 			IF_CMD, ip_sioctl_get_muxid, NULL },
1157 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1159 
1160 	/* Both if and lif variants share same func */
1161 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1162 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1163 	/* Both if and lif variants share same func */
1164 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1165 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1190 			ip_sioctl_removeif_restart },
1191 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_addif, NULL },
1194 #define	SIOCLIFADDR_NDX 112
1195 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1197 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1198 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1203 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1206 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_get_flags, NULL },
1209 
1210 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 
1213 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1214 			ip_sioctl_get_lifconf, NULL },
1215 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_mtu, NULL },
1217 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1218 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1219 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1220 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1221 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1223 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1225 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1227 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1229 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_metric, NULL },
1231 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR | IPI_MODOK,
1233 			LIF_CMD, ip_sioctl_slifname,
1234 			ip_sioctl_slifname_restart },
1235 
1236 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1237 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1238 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1239 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1240 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1242 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1244 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1246 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 			LIF_CMD, ip_sioctl_token, NULL },
1248 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1249 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1250 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1252 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1253 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1254 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1256 
1257 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1258 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1259 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1260 			LIF_CMD, ip_siocdelndp_v6, NULL },
1261 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1262 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1263 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1264 			LIF_CMD, ip_siocsetndp_v6, NULL },
1265 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1266 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1267 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1268 			MISC_CMD, ip_sioctl_tonlink, NULL },
1269 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1270 			MISC_CMD, ip_sioctl_tmysite, NULL },
1271 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1272 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1273 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1274 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1275 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1276 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1277 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1278 
1279 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 
1281 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1282 			LIF_CMD, ip_sioctl_get_binding, NULL },
1283 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1284 			IPI_PRIV | IPI_WR,
1285 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1286 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1287 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1288 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1289 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1290 
1291 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1292 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1293 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1294 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1295 
1296 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 
1298 	/* These are handled in ip_sioctl_copyin_setup itself */
1299 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1300 			MISC_CMD, NULL, NULL },
1301 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1302 			MISC_CMD, NULL, NULL },
1303 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1304 
1305 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1306 			ip_sioctl_get_lifconf, NULL },
1307 
1308 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1309 			XARP_CMD, ip_sioctl_arp, NULL },
1310 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1311 			XARP_CMD, ip_sioctl_arp, NULL },
1312 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1313 			XARP_CMD, ip_sioctl_arp, NULL },
1314 
1315 	/* SIOCPOPSOCKFS is not handled by IP */
1316 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1317 
1318 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1319 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1320 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1321 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1322 			ip_sioctl_slifzone_restart },
1323 	/* 172-174 are SCTP ioctls and not handled by IP */
1324 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1325 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1326 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1327 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1328 			IPI_GET_CMD, LIF_CMD,
1329 			ip_sioctl_get_lifusesrc, 0 },
1330 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1331 			IPI_PRIV | IPI_WR,
1332 			LIF_CMD, ip_sioctl_slifusesrc,
1333 			NULL },
1334 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1335 			ip_sioctl_get_lifsrcof, NULL },
1336 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1337 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1338 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1339 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1340 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1341 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1342 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1343 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1344 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1345 	/* SIOCSENABLESDP is handled by SDP */
1346 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1347 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1348 };
1349 
1350 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1351 
1352 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1353 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1354 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1355 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1356 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1357 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1358 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1359 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1360 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1361 		MISC_CMD, mrt_ioctl},
1362 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1363 		MISC_CMD, mrt_ioctl},
1364 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1365 		MISC_CMD, mrt_ioctl}
1366 };
1367 
1368 int ip_misc_ioctl_count =
1369     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1370 
1371 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1372 					/* Settable in /etc/system */
1373 /* Defined in ip_ire.c */
1374 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1375 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1376 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1377 
1378 static nv_t	ire_nv_arr[] = {
1379 	{ IRE_BROADCAST, "BROADCAST" },
1380 	{ IRE_LOCAL, "LOCAL" },
1381 	{ IRE_LOOPBACK, "LOOPBACK" },
1382 	{ IRE_CACHE, "CACHE" },
1383 	{ IRE_DEFAULT, "DEFAULT" },
1384 	{ IRE_PREFIX, "PREFIX" },
1385 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1386 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1387 	{ IRE_HOST, "HOST" },
1388 	{ 0 }
1389 };
1390 
1391 nv_t	*ire_nv_tbl = ire_nv_arr;
1392 
1393 /* Simple ICMP IP Header Template */
1394 static ipha_t icmp_ipha = {
1395 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1396 };
1397 
1398 struct module_info ip_mod_info = {
1399 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1400 	IP_MOD_LOWAT
1401 };
1402 
1403 /*
1404  * Duplicate static symbols within a module confuses mdb; so we avoid the
1405  * problem by making the symbols here distinct from those in udp.c.
1406  */
1407 
1408 /*
1409  * Entry points for IP as a device and as a module.
1410  * FIXME: down the road we might want a separate module and driver qinit.
1411  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1412  */
1413 static struct qinit iprinitv4 = {
1414 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1415 	&ip_mod_info
1416 };
1417 
1418 struct qinit iprinitv6 = {
1419 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1420 	&ip_mod_info
1421 };
1422 
1423 static struct qinit ipwinitv4 = {
1424 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1425 	&ip_mod_info
1426 };
1427 
1428 struct qinit ipwinitv6 = {
1429 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1430 	&ip_mod_info
1431 };
1432 
1433 static struct qinit iplrinit = {
1434 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1435 	&ip_mod_info
1436 };
1437 
1438 static struct qinit iplwinit = {
1439 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1440 	&ip_mod_info
1441 };
1442 
1443 /* For AF_INET aka /dev/ip */
1444 struct streamtab ipinfov4 = {
1445 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1446 };
1447 
1448 /* For AF_INET6 aka /dev/ip6 */
1449 struct streamtab ipinfov6 = {
1450 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1451 };
1452 
1453 #ifdef	DEBUG
1454 static boolean_t skip_sctp_cksum = B_FALSE;
1455 #endif
1456 
1457 /*
1458  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1459  * ip_rput_v6(), ip_output(), etc.  If the message
1460  * block already has a M_CTL at the front of it, then simply set the zoneid
1461  * appropriately.
1462  */
1463 mblk_t *
1464 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1465 {
1466 	mblk_t		*first_mp;
1467 	ipsec_out_t	*io;
1468 
1469 	ASSERT(zoneid != ALL_ZONES);
1470 	if (mp->b_datap->db_type == M_CTL) {
1471 		io = (ipsec_out_t *)mp->b_rptr;
1472 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1473 		io->ipsec_out_zoneid = zoneid;
1474 		return (mp);
1475 	}
1476 
1477 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1478 	if (first_mp == NULL)
1479 		return (NULL);
1480 	io = (ipsec_out_t *)first_mp->b_rptr;
1481 	/* This is not a secure packet */
1482 	io->ipsec_out_secure = B_FALSE;
1483 	io->ipsec_out_zoneid = zoneid;
1484 	first_mp->b_cont = mp;
1485 	return (first_mp);
1486 }
1487 
1488 /*
1489  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1490  */
1491 mblk_t *
1492 ip_copymsg(mblk_t *mp)
1493 {
1494 	mblk_t *nmp;
1495 	ipsec_info_t *in;
1496 
1497 	if (mp->b_datap->db_type != M_CTL)
1498 		return (copymsg(mp));
1499 
1500 	in = (ipsec_info_t *)mp->b_rptr;
1501 
1502 	/*
1503 	 * Note that M_CTL is also used for delivering ICMP error messages
1504 	 * upstream to transport layers.
1505 	 */
1506 	if (in->ipsec_info_type != IPSEC_OUT &&
1507 	    in->ipsec_info_type != IPSEC_IN)
1508 		return (copymsg(mp));
1509 
1510 	nmp = copymsg(mp->b_cont);
1511 
1512 	if (in->ipsec_info_type == IPSEC_OUT) {
1513 		return (ipsec_out_tag(mp, nmp,
1514 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1515 	} else {
1516 		return (ipsec_in_tag(mp, nmp,
1517 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1518 	}
1519 }
1520 
1521 /* Generate an ICMP fragmentation needed message. */
1522 static void
1523 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1524     ip_stack_t *ipst)
1525 {
1526 	icmph_t	icmph;
1527 	mblk_t *first_mp;
1528 	boolean_t mctl_present;
1529 
1530 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1531 
1532 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1533 		if (mctl_present)
1534 			freeb(first_mp);
1535 		return;
1536 	}
1537 
1538 	bzero(&icmph, sizeof (icmph_t));
1539 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1540 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1541 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1542 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1543 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1544 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1545 	    ipst);
1546 }
1547 
1548 /*
1549  * icmp_inbound deals with ICMP messages in the following ways.
1550  *
1551  * 1) It needs to send a reply back and possibly delivering it
1552  *    to the "interested" upper clients.
1553  * 2) It needs to send it to the upper clients only.
1554  * 3) It needs to change some values in IP only.
1555  * 4) It needs to change some values in IP and upper layers e.g TCP.
1556  *
1557  * We need to accomodate icmp messages coming in clear until we get
1558  * everything secure from the wire. If icmp_accept_clear_messages
1559  * is zero we check with the global policy and act accordingly. If
1560  * it is non-zero, we accept the message without any checks. But
1561  * *this does not mean* that this will be delivered to the upper
1562  * clients. By accepting we might send replies back, change our MTU
1563  * value etc. but delivery to the ULP/clients depends on their policy
1564  * dispositions.
1565  *
1566  * We handle the above 4 cases in the context of IPsec in the
1567  * following way :
1568  *
1569  * 1) Send the reply back in the same way as the request came in.
1570  *    If it came in encrypted, it goes out encrypted. If it came in
1571  *    clear, it goes out in clear. Thus, this will prevent chosen
1572  *    plain text attack.
1573  * 2) The client may or may not expect things to come in secure.
1574  *    If it comes in secure, the policy constraints are checked
1575  *    before delivering it to the upper layers. If it comes in
1576  *    clear, ipsec_inbound_accept_clear will decide whether to
1577  *    accept this in clear or not. In both the cases, if the returned
1578  *    message (IP header + 8 bytes) that caused the icmp message has
1579  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1580  *    sending up. If there are only 8 bytes of returned message, then
1581  *    upper client will not be notified.
1582  * 3) Check with global policy to see whether it matches the constaints.
1583  *    But this will be done only if icmp_accept_messages_in_clear is
1584  *    zero.
1585  * 4) If we need to change both in IP and ULP, then the decision taken
1586  *    while affecting the values in IP and while delivering up to TCP
1587  *    should be the same.
1588  *
1589  * 	There are two cases.
1590  *
1591  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1592  *	   failed), we will not deliver it to the ULP, even though they
1593  *	   are *willing* to accept in *clear*. This is fine as our global
1594  *	   disposition to icmp messages asks us reject the datagram.
1595  *
1596  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1597  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1598  *	   to deliver it to ULP (policy failed), it can lead to
1599  *	   consistency problems. The cases known at this time are
1600  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1601  *	   values :
1602  *
1603  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1604  *	     and Upper layer rejects. Then the communication will
1605  *	     come to a stop. This is solved by making similar decisions
1606  *	     at both levels. Currently, when we are unable to deliver
1607  *	     to the Upper Layer (due to policy failures) while IP has
1608  *	     adjusted ire_max_frag, the next outbound datagram would
1609  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1610  *	     will be with the right level of protection. Thus the right
1611  *	     value will be communicated even if we are not able to
1612  *	     communicate when we get from the wire initially. But this
1613  *	     assumes there would be at least one outbound datagram after
1614  *	     IP has adjusted its ire_max_frag value. To make things
1615  *	     simpler, we accept in clear after the validation of
1616  *	     AH/ESP headers.
1617  *
1618  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1619  *	     upper layer depending on the level of protection the upper
1620  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1621  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1622  *	     should be accepted in clear when the Upper layer expects secure.
1623  *	     Thus the communication may get aborted by some bad ICMP
1624  *	     packets.
1625  *
1626  * IPQoS Notes:
1627  * The only instance when a packet is sent for processing is when there
1628  * isn't an ICMP client and if we are interested in it.
1629  * If there is a client, IPPF processing will take place in the
1630  * ip_fanout_proto routine.
1631  *
1632  * Zones notes:
1633  * The packet is only processed in the context of the specified zone: typically
1634  * only this zone will reply to an echo request, and only interested clients in
1635  * this zone will receive a copy of the packet. This means that the caller must
1636  * call icmp_inbound() for each relevant zone.
1637  */
1638 static void
1639 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1640     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1641     ill_t *recv_ill, zoneid_t zoneid)
1642 {
1643 	icmph_t	*icmph;
1644 	ipha_t	*ipha;
1645 	int	iph_hdr_length;
1646 	int	hdr_length;
1647 	boolean_t	interested;
1648 	uint32_t	ts;
1649 	uchar_t	*wptr;
1650 	ipif_t	*ipif;
1651 	mblk_t *first_mp;
1652 	ipsec_in_t *ii;
1653 	timestruc_t now;
1654 	uint32_t ill_index;
1655 	ip_stack_t *ipst;
1656 
1657 	ASSERT(ill != NULL);
1658 	ipst = ill->ill_ipst;
1659 
1660 	first_mp = mp;
1661 	if (mctl_present) {
1662 		mp = first_mp->b_cont;
1663 		ASSERT(mp != NULL);
1664 	}
1665 
1666 	ipha = (ipha_t *)mp->b_rptr;
1667 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1668 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1669 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1670 		if (first_mp == NULL)
1671 			return;
1672 	}
1673 
1674 	/*
1675 	 * On a labeled system, we have to check whether the zone itself is
1676 	 * permitted to receive raw traffic.
1677 	 */
1678 	if (is_system_labeled()) {
1679 		if (zoneid == ALL_ZONES)
1680 			zoneid = tsol_packet_to_zoneid(mp);
1681 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1682 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1683 			    zoneid));
1684 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1685 			freemsg(first_mp);
1686 			return;
1687 		}
1688 	}
1689 
1690 	/*
1691 	 * We have accepted the ICMP message. It means that we will
1692 	 * respond to the packet if needed. It may not be delivered
1693 	 * to the upper client depending on the policy constraints
1694 	 * and the disposition in ipsec_inbound_accept_clear.
1695 	 */
1696 
1697 	ASSERT(ill != NULL);
1698 
1699 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1700 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1701 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1702 		/* Last chance to get real. */
1703 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1704 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1705 			freemsg(first_mp);
1706 			return;
1707 		}
1708 		/* Refresh iph following the pullup. */
1709 		ipha = (ipha_t *)mp->b_rptr;
1710 	}
1711 	/* ICMP header checksum, including checksum field, should be zero. */
1712 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1713 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1714 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1715 		freemsg(first_mp);
1716 		return;
1717 	}
1718 	/* The IP header will always be a multiple of four bytes */
1719 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1720 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1721 	    icmph->icmph_code));
1722 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1723 	/* We will set "interested" to "true" if we want a copy */
1724 	interested = B_FALSE;
1725 	switch (icmph->icmph_type) {
1726 	case ICMP_ECHO_REPLY:
1727 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1728 		break;
1729 	case ICMP_DEST_UNREACHABLE:
1730 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1731 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1732 		interested = B_TRUE;	/* Pass up to transport */
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1734 		break;
1735 	case ICMP_SOURCE_QUENCH:
1736 		interested = B_TRUE;	/* Pass up to transport */
1737 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1738 		break;
1739 	case ICMP_REDIRECT:
1740 		if (!ipst->ips_ip_ignore_redirect)
1741 			interested = B_TRUE;
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1743 		break;
1744 	case ICMP_ECHO_REQUEST:
1745 		/*
1746 		 * Whether to respond to echo requests that come in as IP
1747 		 * broadcasts or as IP multicast is subject to debate
1748 		 * (what isn't?).  We aim to please, you pick it.
1749 		 * Default is do it.
1750 		 */
1751 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1752 			/* unicast: always respond */
1753 			interested = B_TRUE;
1754 		} else if (CLASSD(ipha->ipha_dst)) {
1755 			/* multicast: respond based on tunable */
1756 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1757 		} else if (broadcast) {
1758 			/* broadcast: respond based on tunable */
1759 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1760 		}
1761 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1762 		break;
1763 	case ICMP_ROUTER_ADVERTISEMENT:
1764 	case ICMP_ROUTER_SOLICITATION:
1765 		break;
1766 	case ICMP_TIME_EXCEEDED:
1767 		interested = B_TRUE;	/* Pass up to transport */
1768 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1769 		break;
1770 	case ICMP_PARAM_PROBLEM:
1771 		interested = B_TRUE;	/* Pass up to transport */
1772 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1773 		break;
1774 	case ICMP_TIME_STAMP_REQUEST:
1775 		/* Response to Time Stamp Requests is local policy. */
1776 		if (ipst->ips_ip_g_resp_to_timestamp &&
1777 		    /* So is whether to respond if it was an IP broadcast. */
1778 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1779 			int tstamp_len = 3 * sizeof (uint32_t);
1780 
1781 			if (wptr +  tstamp_len > mp->b_wptr) {
1782 				if (!pullupmsg(mp, wptr + tstamp_len -
1783 				    mp->b_rptr)) {
1784 					BUMP_MIB(ill->ill_ip_mib,
1785 					    ipIfStatsInDiscards);
1786 					freemsg(first_mp);
1787 					return;
1788 				}
1789 				/* Refresh ipha following the pullup. */
1790 				ipha = (ipha_t *)mp->b_rptr;
1791 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1792 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1793 			}
1794 			interested = B_TRUE;
1795 		}
1796 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1797 		break;
1798 	case ICMP_TIME_STAMP_REPLY:
1799 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1800 		break;
1801 	case ICMP_INFO_REQUEST:
1802 		/* Per RFC 1122 3.2.2.7, ignore this. */
1803 	case ICMP_INFO_REPLY:
1804 		break;
1805 	case ICMP_ADDRESS_MASK_REQUEST:
1806 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1807 		    !broadcast) &&
1808 		    /* TODO m_pullup of complete header? */
1809 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1810 			interested = B_TRUE;
1811 		}
1812 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1813 		break;
1814 	case ICMP_ADDRESS_MASK_REPLY:
1815 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1816 		break;
1817 	default:
1818 		interested = B_TRUE;	/* Pass up to transport */
1819 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1820 		break;
1821 	}
1822 	/* See if there is an ICMP client. */
1823 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1824 		/* If there is an ICMP client and we want one too, copy it. */
1825 		mblk_t *first_mp1;
1826 
1827 		if (!interested) {
1828 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1829 			    ip_policy, recv_ill, zoneid);
1830 			return;
1831 		}
1832 		first_mp1 = ip_copymsg(first_mp);
1833 		if (first_mp1 != NULL) {
1834 			ip_fanout_proto(q, first_mp1, ill, ipha,
1835 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1836 		}
1837 	} else if (!interested) {
1838 		freemsg(first_mp);
1839 		return;
1840 	} else {
1841 		/*
1842 		 * Initiate policy processing for this packet if ip_policy
1843 		 * is true.
1844 		 */
1845 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1846 			ill_index = ill->ill_phyint->phyint_ifindex;
1847 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1848 			if (mp == NULL) {
1849 				if (mctl_present) {
1850 					freeb(first_mp);
1851 				}
1852 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1853 				return;
1854 			}
1855 		}
1856 	}
1857 	/* We want to do something with it. */
1858 	/* Check db_ref to make sure we can modify the packet. */
1859 	if (mp->b_datap->db_ref > 1) {
1860 		mblk_t	*first_mp1;
1861 
1862 		first_mp1 = ip_copymsg(first_mp);
1863 		freemsg(first_mp);
1864 		if (!first_mp1) {
1865 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1866 			return;
1867 		}
1868 		first_mp = first_mp1;
1869 		if (mctl_present) {
1870 			mp = first_mp->b_cont;
1871 			ASSERT(mp != NULL);
1872 		} else {
1873 			mp = first_mp;
1874 		}
1875 		ipha = (ipha_t *)mp->b_rptr;
1876 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1877 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1878 	}
1879 	switch (icmph->icmph_type) {
1880 	case ICMP_ADDRESS_MASK_REQUEST:
1881 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1882 		if (ipif == NULL) {
1883 			freemsg(first_mp);
1884 			return;
1885 		}
1886 		/*
1887 		 * outging interface must be IPv4
1888 		 */
1889 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1890 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1891 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1892 		ipif_refrele(ipif);
1893 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1894 		break;
1895 	case ICMP_ECHO_REQUEST:
1896 		icmph->icmph_type = ICMP_ECHO_REPLY;
1897 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1898 		break;
1899 	case ICMP_TIME_STAMP_REQUEST: {
1900 		uint32_t *tsp;
1901 
1902 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1903 		tsp = (uint32_t *)wptr;
1904 		tsp++;		/* Skip past 'originate time' */
1905 		/* Compute # of milliseconds since midnight */
1906 		gethrestime(&now);
1907 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1908 		    now.tv_nsec / (NANOSEC / MILLISEC);
1909 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1910 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1911 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1912 		break;
1913 	}
1914 	default:
1915 		ipha = (ipha_t *)&icmph[1];
1916 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1917 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1918 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1919 				freemsg(first_mp);
1920 				return;
1921 			}
1922 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1923 			ipha = (ipha_t *)&icmph[1];
1924 		}
1925 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1926 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1927 			freemsg(first_mp);
1928 			return;
1929 		}
1930 		hdr_length = IPH_HDR_LENGTH(ipha);
1931 		if (hdr_length < sizeof (ipha_t)) {
1932 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1933 			freemsg(first_mp);
1934 			return;
1935 		}
1936 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1937 			if (!pullupmsg(mp,
1938 			    (uchar_t *)ipha + hdr_length - 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 		switch (icmph->icmph_type) {
1947 		case ICMP_REDIRECT:
1948 			/*
1949 			 * As there is no upper client to deliver, we don't
1950 			 * need the first_mp any more.
1951 			 */
1952 			if (mctl_present) {
1953 				freeb(first_mp);
1954 			}
1955 			icmp_redirect(ill, mp);
1956 			return;
1957 		case ICMP_DEST_UNREACHABLE:
1958 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1959 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1960 				    zoneid, mp, iph_hdr_length, ipst)) {
1961 					freemsg(first_mp);
1962 					return;
1963 				}
1964 				/*
1965 				 * icmp_inbound_too_big() may alter mp.
1966 				 * Resynch ipha and icmph accordingly.
1967 				 */
1968 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1969 				ipha = (ipha_t *)&icmph[1];
1970 			}
1971 			/* FALLTHRU */
1972 		default :
1973 			/*
1974 			 * IPQoS notes: Since we have already done IPQoS
1975 			 * processing we don't want to do it again in
1976 			 * the fanout routines called by
1977 			 * icmp_inbound_error_fanout, hence the last
1978 			 * argument, ip_policy, is B_FALSE.
1979 			 */
1980 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1981 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1982 			    B_FALSE, recv_ill, zoneid);
1983 		}
1984 		return;
1985 	}
1986 	/* Send out an ICMP packet */
1987 	icmph->icmph_checksum = 0;
1988 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1989 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1990 		ipif_t	*ipif_chosen;
1991 		/*
1992 		 * Make it look like it was directed to us, so we don't look
1993 		 * like a fool with a broadcast or multicast source address.
1994 		 */
1995 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1996 		/*
1997 		 * Make sure that we haven't grabbed an interface that's DOWN.
1998 		 */
1999 		if (ipif != NULL) {
2000 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2001 			    ipha->ipha_src, zoneid);
2002 			if (ipif_chosen != NULL) {
2003 				ipif_refrele(ipif);
2004 				ipif = ipif_chosen;
2005 			}
2006 		}
2007 		if (ipif == NULL) {
2008 			ip0dbg(("icmp_inbound: "
2009 			    "No source for broadcast/multicast:\n"
2010 			    "\tsrc 0x%x dst 0x%x ill %p "
2011 			    "ipif_lcl_addr 0x%x\n",
2012 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2013 			    (void *)ill,
2014 			    ill->ill_ipif->ipif_lcl_addr));
2015 			freemsg(first_mp);
2016 			return;
2017 		}
2018 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2019 		ipha->ipha_dst = ipif->ipif_src_addr;
2020 		ipif_refrele(ipif);
2021 	}
2022 	/* Reset time to live. */
2023 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2024 	{
2025 		/* Swap source and destination addresses */
2026 		ipaddr_t tmp;
2027 
2028 		tmp = ipha->ipha_src;
2029 		ipha->ipha_src = ipha->ipha_dst;
2030 		ipha->ipha_dst = tmp;
2031 	}
2032 	ipha->ipha_ident = 0;
2033 	if (!IS_SIMPLE_IPH(ipha))
2034 		icmp_options_update(ipha);
2035 
2036 	if (!mctl_present) {
2037 		/*
2038 		 * This packet should go out the same way as it
2039 		 * came in i.e in clear. To make sure that global
2040 		 * policy will not be applied to this in ip_wput_ire,
2041 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2042 		 */
2043 		ASSERT(first_mp == mp);
2044 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2045 		if (first_mp == NULL) {
2046 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2047 			freemsg(mp);
2048 			return;
2049 		}
2050 		ii = (ipsec_in_t *)first_mp->b_rptr;
2051 
2052 		/* This is not a secure packet */
2053 		ii->ipsec_in_secure = B_FALSE;
2054 		first_mp->b_cont = mp;
2055 	} else {
2056 		ii = (ipsec_in_t *)first_mp->b_rptr;
2057 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2058 	}
2059 	ii->ipsec_in_zoneid = zoneid;
2060 	ASSERT(zoneid != ALL_ZONES);
2061 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2062 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2063 		return;
2064 	}
2065 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2066 	put(WR(q), first_mp);
2067 }
2068 
2069 static ipaddr_t
2070 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2071 {
2072 	conn_t *connp;
2073 	connf_t *connfp;
2074 	ipaddr_t nexthop_addr = INADDR_ANY;
2075 	int hdr_length = IPH_HDR_LENGTH(ipha);
2076 	uint16_t *up;
2077 	uint32_t ports;
2078 	ip_stack_t *ipst = ill->ill_ipst;
2079 
2080 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2081 	switch (ipha->ipha_protocol) {
2082 		case IPPROTO_TCP:
2083 		{
2084 			tcph_t *tcph;
2085 
2086 			/* do a reverse lookup */
2087 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2088 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2089 			    TCPS_LISTEN, ipst);
2090 			break;
2091 		}
2092 		case IPPROTO_UDP:
2093 		{
2094 			uint32_t dstport, srcport;
2095 
2096 			((uint16_t *)&ports)[0] = up[1];
2097 			((uint16_t *)&ports)[1] = up[0];
2098 
2099 			/* Extract ports in net byte order */
2100 			dstport = htons(ntohl(ports) & 0xFFFF);
2101 			srcport = htons(ntohl(ports) >> 16);
2102 
2103 			connfp = &ipst->ips_ipcl_udp_fanout[
2104 			    IPCL_UDP_HASH(dstport, ipst)];
2105 			mutex_enter(&connfp->connf_lock);
2106 			connp = connfp->connf_head;
2107 
2108 			/* do a reverse lookup */
2109 			while ((connp != NULL) &&
2110 			    (!IPCL_UDP_MATCH(connp, dstport,
2111 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2112 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2113 				connp = connp->conn_next;
2114 			}
2115 			if (connp != NULL)
2116 				CONN_INC_REF(connp);
2117 			mutex_exit(&connfp->connf_lock);
2118 			break;
2119 		}
2120 		case IPPROTO_SCTP:
2121 		{
2122 			in6_addr_t map_src, map_dst;
2123 
2124 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2125 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2126 			((uint16_t *)&ports)[0] = up[1];
2127 			((uint16_t *)&ports)[1] = up[0];
2128 
2129 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2130 			    zoneid, ipst->ips_netstack->netstack_sctp);
2131 			if (connp == NULL) {
2132 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2133 				    zoneid, ports, ipha, ipst);
2134 			} else {
2135 				CONN_INC_REF(connp);
2136 				SCTP_REFRELE(CONN2SCTP(connp));
2137 			}
2138 			break;
2139 		}
2140 		default:
2141 		{
2142 			ipha_t ripha;
2143 
2144 			ripha.ipha_src = ipha->ipha_dst;
2145 			ripha.ipha_dst = ipha->ipha_src;
2146 			ripha.ipha_protocol = ipha->ipha_protocol;
2147 
2148 			connfp = &ipst->ips_ipcl_proto_fanout[
2149 			    ipha->ipha_protocol];
2150 			mutex_enter(&connfp->connf_lock);
2151 			connp = connfp->connf_head;
2152 			for (connp = connfp->connf_head; connp != NULL;
2153 			    connp = connp->conn_next) {
2154 				if (IPCL_PROTO_MATCH(connp,
2155 				    ipha->ipha_protocol, &ripha, ill,
2156 				    0, zoneid)) {
2157 					CONN_INC_REF(connp);
2158 					break;
2159 				}
2160 			}
2161 			mutex_exit(&connfp->connf_lock);
2162 		}
2163 	}
2164 	if (connp != NULL) {
2165 		if (connp->conn_nexthop_set)
2166 			nexthop_addr = connp->conn_nexthop_v4;
2167 		CONN_DEC_REF(connp);
2168 	}
2169 	return (nexthop_addr);
2170 }
2171 
2172 /* Table from RFC 1191 */
2173 static int icmp_frag_size_table[] =
2174 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2175 
2176 /*
2177  * Process received ICMP Packet too big.
2178  * After updating any IRE it does the fanout to any matching transport streams.
2179  * Assumes the message has been pulled up till the IP header that caused
2180  * the error.
2181  *
2182  * Returns B_FALSE on failure and B_TRUE on success.
2183  */
2184 static boolean_t
2185 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2186     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2187     ip_stack_t *ipst)
2188 {
2189 	ire_t	*ire, *first_ire;
2190 	int	mtu, orig_mtu;
2191 	int	hdr_length;
2192 	ipaddr_t nexthop_addr;
2193 	boolean_t disable_pmtud;
2194 
2195 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2196 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2197 	ASSERT(ill != NULL);
2198 
2199 	hdr_length = IPH_HDR_LENGTH(ipha);
2200 
2201 	/* Drop if the original packet contained a source route */
2202 	if (ip_source_route_included(ipha)) {
2203 		return (B_FALSE);
2204 	}
2205 	/*
2206 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2207 	 * header.
2208 	 */
2209 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2210 	    mp->b_wptr) {
2211 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2212 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2213 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2214 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2215 			return (B_FALSE);
2216 		}
2217 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2218 		ipha = (ipha_t *)&icmph[1];
2219 	}
2220 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2221 	if (nexthop_addr != INADDR_ANY) {
2222 		/* nexthop set */
2223 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2224 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2225 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2226 	} else {
2227 		/* nexthop not set */
2228 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2229 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2230 	}
2231 
2232 	if (!first_ire) {
2233 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2234 		    ntohl(ipha->ipha_dst)));
2235 		return (B_FALSE);
2236 	}
2237 
2238 	/* Check for MTU discovery advice as described in RFC 1191 */
2239 	mtu = ntohs(icmph->icmph_du_mtu);
2240 	orig_mtu = mtu;
2241 	disable_pmtud = B_FALSE;
2242 
2243 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2244 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2245 	    ire = ire->ire_next) {
2246 		/*
2247 		 * Look for the connection to which this ICMP message is
2248 		 * directed. If it has the IP_NEXTHOP option set, then the
2249 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2250 		 * option. Else the search is limited to regular IREs.
2251 		 */
2252 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2253 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2254 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2255 		    (nexthop_addr != INADDR_ANY)))
2256 			continue;
2257 
2258 		mutex_enter(&ire->ire_lock);
2259 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2260 			uint32_t length;
2261 			int	i;
2262 
2263 			/*
2264 			 * Use the table from RFC 1191 to figure out
2265 			 * the next "plateau" based on the length in
2266 			 * the original IP packet.
2267 			 */
2268 			length = ntohs(ipha->ipha_length);
2269 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2270 			    uint32_t, length);
2271 			if (ire->ire_max_frag <= length &&
2272 			    ire->ire_max_frag >= length - hdr_length) {
2273 				/*
2274 				 * Handle broken BSD 4.2 systems that
2275 				 * return the wrong iph_length in ICMP
2276 				 * errors.
2277 				 */
2278 				length -= hdr_length;
2279 			}
2280 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2281 				if (length > icmp_frag_size_table[i])
2282 					break;
2283 			}
2284 			if (i == A_CNT(icmp_frag_size_table)) {
2285 				/* Smaller than 68! */
2286 				disable_pmtud = B_TRUE;
2287 				mtu = ipst->ips_ip_pmtu_min;
2288 			} else {
2289 				mtu = icmp_frag_size_table[i];
2290 				if (mtu < ipst->ips_ip_pmtu_min) {
2291 					mtu = ipst->ips_ip_pmtu_min;
2292 					disable_pmtud = B_TRUE;
2293 				}
2294 			}
2295 			/* Fool the ULP into believing our guessed PMTU. */
2296 			icmph->icmph_du_zero = 0;
2297 			icmph->icmph_du_mtu = htons(mtu);
2298 		}
2299 		if (disable_pmtud)
2300 			ire->ire_frag_flag = 0;
2301 		/* Reduce the IRE max frag value as advised. */
2302 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2303 		if (ire->ire_max_frag == mtu) {
2304 			/* Decreased it */
2305 			ire->ire_marks |= IRE_MARK_PMTU;
2306 		}
2307 		mutex_exit(&ire->ire_lock);
2308 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2309 		    ire, int, orig_mtu, int, mtu);
2310 	}
2311 	rw_exit(&first_ire->ire_bucket->irb_lock);
2312 	ire_refrele(first_ire);
2313 	return (B_TRUE);
2314 }
2315 
2316 /*
2317  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2318  * calls this function.
2319  */
2320 static mblk_t *
2321 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2322 {
2323 	ipha_t *ipha;
2324 	icmph_t *icmph;
2325 	ipha_t *in_ipha;
2326 	int length;
2327 
2328 	ASSERT(mp->b_datap->db_type == M_DATA);
2329 
2330 	/*
2331 	 * For Self-encapsulated packets, we added an extra IP header
2332 	 * without the options. Inner IP header is the one from which
2333 	 * the outer IP header was formed. Thus, we need to remove the
2334 	 * outer IP header. To do this, we pullup the whole message
2335 	 * and overlay whatever follows the outer IP header over the
2336 	 * outer IP header.
2337 	 */
2338 
2339 	if (!pullupmsg(mp, -1))
2340 		return (NULL);
2341 
2342 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2343 	ipha = (ipha_t *)&icmph[1];
2344 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2345 
2346 	/*
2347 	 * The length that we want to overlay is following the inner
2348 	 * IP header. Subtracting the IP header + icmp header + outer
2349 	 * IP header's length should give us the length that we want to
2350 	 * overlay.
2351 	 */
2352 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2353 	    hdr_length;
2354 	/*
2355 	 * Overlay whatever follows the inner header over the
2356 	 * outer header.
2357 	 */
2358 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2359 
2360 	/* Set the wptr to account for the outer header */
2361 	mp->b_wptr -= hdr_length;
2362 	return (mp);
2363 }
2364 
2365 /*
2366  * Fanout for ICMP errors containing IP-in-IPv4 packets.  Returns B_TRUE if a
2367  * tunnel consumed the message, and B_FALSE otherwise.
2368  */
2369 static boolean_t
2370 icmp_inbound_iptun_fanout(mblk_t *first_mp, ipha_t *ripha, ill_t *ill,
2371     ip_stack_t *ipst)
2372 {
2373 	conn_t	*connp;
2374 
2375 	if ((connp = ipcl_iptun_classify_v4(&ripha->ipha_src, &ripha->ipha_dst,
2376 	    ipst)) == NULL)
2377 		return (B_FALSE);
2378 
2379 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
2380 	connp->conn_recv(connp, first_mp, NULL);
2381 	CONN_DEC_REF(connp);
2382 	return (B_TRUE);
2383 }
2384 
2385 /*
2386  * Try to pass the ICMP message upstream in case the ULP cares.
2387  *
2388  * If the packet that caused the ICMP error is secure, we send
2389  * it to AH/ESP to make sure that the attached packet has a
2390  * valid association. ipha in the code below points to the
2391  * IP header of the packet that caused the error.
2392  *
2393  * For IPsec cases, we let the next-layer-up (which has access to
2394  * cached policy on the conn_t, or can query the SPD directly)
2395  * subtract out any IPsec overhead if they must.  We therefore make no
2396  * adjustments here for IPsec overhead.
2397  *
2398  * IFN could have been generated locally or by some router.
2399  *
2400  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2401  *	    This happens because IP adjusted its value of MTU on an
2402  *	    earlier IFN message and could not tell the upper layer,
2403  *	    the new adjusted value of MTU e.g. Packet was encrypted
2404  *	    or there was not enough information to fanout to upper
2405  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2406  *	    generates the IFN, where IPsec processing has *not* been
2407  *	    done.
2408  *
2409  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2410  *	    could have generated this. This happens because ire_max_frag
2411  *	    value in IP was set to a new value, while the IPsec processing
2412  *	    was being done and after we made the fragmentation check in
2413  *	    ip_wput_ire. Thus on return from IPsec processing,
2414  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2415  *	    and generates the IFN. As IPsec processing is over, we fanout
2416  *	    to AH/ESP to remove the header.
2417  *
2418  *	    In both these cases, ipsec_in_loopback will be set indicating
2419  *	    that IFN was generated locally.
2420  *
2421  * ROUTER : IFN could be secure or non-secure.
2422  *
2423  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2424  *	      packet in error has AH/ESP headers to validate the AH/ESP
2425  *	      headers. AH/ESP will verify whether there is a valid SA or
2426  *	      not and send it back. We will fanout again if we have more
2427  *	      data in the packet.
2428  *
2429  *	      If the packet in error does not have AH/ESP, we handle it
2430  *	      like any other case.
2431  *
2432  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2433  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2434  *	      for validation. AH/ESP will verify whether there is a
2435  *	      valid SA or not and send it back. We will fanout again if
2436  *	      we have more data in the packet.
2437  *
2438  *	      If the packet in error does not have AH/ESP, we handle it
2439  *	      like any other case.
2440  */
2441 static void
2442 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2443     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2444     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2445     zoneid_t zoneid)
2446 {
2447 	uint16_t *up;	/* Pointer to ports in ULP header */
2448 	uint32_t ports;	/* reversed ports for fanout */
2449 	ipha_t ripha;	/* With reversed addresses */
2450 	mblk_t *first_mp;
2451 	ipsec_in_t *ii;
2452 	tcph_t	*tcph;
2453 	conn_t	*connp;
2454 	ip_stack_t *ipst;
2455 
2456 	ASSERT(ill != NULL);
2457 
2458 	ASSERT(recv_ill != NULL);
2459 	ipst = recv_ill->ill_ipst;
2460 
2461 	first_mp = mp;
2462 	if (mctl_present) {
2463 		mp = first_mp->b_cont;
2464 		ASSERT(mp != NULL);
2465 
2466 		ii = (ipsec_in_t *)first_mp->b_rptr;
2467 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2468 	} else {
2469 		ii = NULL;
2470 	}
2471 
2472 	/*
2473 	 * We need a separate IP header with the source and destination
2474 	 * addresses reversed to do fanout/classification because the ipha in
2475 	 * the ICMP error is in the form we sent it out.
2476 	 */
2477 	ripha.ipha_src = ipha->ipha_dst;
2478 	ripha.ipha_dst = ipha->ipha_src;
2479 	ripha.ipha_protocol = ipha->ipha_protocol;
2480 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2481 
2482 	ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2483 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2484 	    ntohl(ipha->ipha_dst),
2485 	    icmph->icmph_type, icmph->icmph_code));
2486 
2487 	switch (ipha->ipha_protocol) {
2488 	case IPPROTO_UDP:
2489 		/*
2490 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2491 		 * transport header.
2492 		 */
2493 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2494 		    mp->b_wptr) {
2495 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2496 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2497 				goto discard_pkt;
2498 			}
2499 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2500 			ipha = (ipha_t *)&icmph[1];
2501 		}
2502 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2503 
2504 		/* Attempt to find a client stream based on port. */
2505 		((uint16_t *)&ports)[0] = up[1];
2506 		((uint16_t *)&ports)[1] = up[0];
2507 		ip2dbg(("icmp_inbound_error: UDP ports %d to %d\n",
2508 		    ntohs(up[0]), ntohs(up[1])));
2509 
2510 		/* Have to change db_type after any pullupmsg */
2511 		DB_TYPE(mp) = M_CTL;
2512 
2513 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2514 		    mctl_present, ip_policy, recv_ill, zoneid);
2515 		return;
2516 
2517 	case IPPROTO_TCP:
2518 		/*
2519 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2520 		 * transport header.
2521 		 */
2522 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2523 		    mp->b_wptr) {
2524 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2525 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2526 				goto discard_pkt;
2527 			}
2528 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2529 			ipha = (ipha_t *)&icmph[1];
2530 		}
2531 		/*
2532 		 * Find a TCP client stream for this packet.
2533 		 * Note that we do a reverse lookup since the header is
2534 		 * in the form we sent it out.
2535 		 */
2536 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2537 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2538 		    ipst);
2539 		if (connp == NULL)
2540 			goto discard_pkt;
2541 
2542 		/* Have to change db_type after any pullupmsg */
2543 		DB_TYPE(mp) = M_CTL;
2544 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2545 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2546 		return;
2547 
2548 	case IPPROTO_SCTP:
2549 		/*
2550 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2551 		 * transport header.
2552 		 */
2553 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2554 		    mp->b_wptr) {
2555 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2556 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2557 				goto discard_pkt;
2558 			}
2559 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2560 			ipha = (ipha_t *)&icmph[1];
2561 		}
2562 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2563 		/* Find a SCTP client stream for this packet. */
2564 		((uint16_t *)&ports)[0] = up[1];
2565 		((uint16_t *)&ports)[1] = up[0];
2566 
2567 		/* Have to change db_type after any pullupmsg */
2568 		DB_TYPE(mp) = M_CTL;
2569 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2570 		    mctl_present, ip_policy, zoneid);
2571 		return;
2572 
2573 	case IPPROTO_ESP:
2574 	case IPPROTO_AH: {
2575 		int ipsec_rc;
2576 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2577 
2578 		/*
2579 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2580 		 * We will re-use the IPSEC_IN if it is already present as
2581 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2582 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2583 		 * one and attach it in the front.
2584 		 */
2585 		if (ii != NULL) {
2586 			/*
2587 			 * ip_fanout_proto_again converts the ICMP errors
2588 			 * that come back from AH/ESP to M_DATA so that
2589 			 * if it is non-AH/ESP and we do a pullupmsg in
2590 			 * this function, it would work. Convert it back
2591 			 * to M_CTL before we send up as this is a ICMP
2592 			 * error. This could have been generated locally or
2593 			 * by some router. Validate the inner IPsec
2594 			 * headers.
2595 			 *
2596 			 * NOTE : ill_index is used by ip_fanout_proto_again
2597 			 * to locate the ill.
2598 			 */
2599 			ASSERT(ill != NULL);
2600 			ii->ipsec_in_ill_index =
2601 			    ill->ill_phyint->phyint_ifindex;
2602 			ii->ipsec_in_rill_index =
2603 			    recv_ill->ill_phyint->phyint_ifindex;
2604 			DB_TYPE(first_mp->b_cont) = M_CTL;
2605 		} else {
2606 			/*
2607 			 * IPSEC_IN is not present. We attach a ipsec_in
2608 			 * message and send up to IPsec for validating
2609 			 * and removing the IPsec headers. Clear
2610 			 * ipsec_in_secure so that when we return
2611 			 * from IPsec, we don't mistakenly think that this
2612 			 * is a secure packet came from the network.
2613 			 *
2614 			 * NOTE : ill_index is used by ip_fanout_proto_again
2615 			 * to locate the ill.
2616 			 */
2617 			ASSERT(first_mp == mp);
2618 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2619 			if (first_mp == NULL) {
2620 				freemsg(mp);
2621 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2622 				return;
2623 			}
2624 			ii = (ipsec_in_t *)first_mp->b_rptr;
2625 
2626 			/* This is not a secure packet */
2627 			ii->ipsec_in_secure = B_FALSE;
2628 			first_mp->b_cont = mp;
2629 			DB_TYPE(mp) = M_CTL;
2630 			ASSERT(ill != NULL);
2631 			ii->ipsec_in_ill_index =
2632 			    ill->ill_phyint->phyint_ifindex;
2633 			ii->ipsec_in_rill_index =
2634 			    recv_ill->ill_phyint->phyint_ifindex;
2635 		}
2636 
2637 		if (!ipsec_loaded(ipss)) {
2638 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2639 			return;
2640 		}
2641 
2642 		if (ipha->ipha_protocol == IPPROTO_ESP)
2643 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2644 		else
2645 			ipsec_rc = ipsecah_icmp_error(first_mp);
2646 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2647 			return;
2648 
2649 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2650 		return;
2651 	}
2652 	case IPPROTO_ENCAP:
2653 	case IPPROTO_IPV6:
2654 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2655 			ipha_t *in_ipha;
2656 
2657 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2658 			    mp->b_wptr) {
2659 				if (!pullupmsg(mp, (uchar_t *)ipha +
2660 				    hdr_length + sizeof (ipha_t) -
2661 				    mp->b_rptr)) {
2662 					goto discard_pkt;
2663 				}
2664 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2665 				ipha = (ipha_t *)&icmph[1];
2666 			}
2667 			/*
2668 			 * Caller has verified that length has to be
2669 			 * at least the size of IP header.
2670 			 */
2671 			ASSERT(hdr_length >= sizeof (ipha_t));
2672 			/*
2673 			 * Check the sanity of the inner IP header like
2674 			 * we did for the outer header.
2675 			 */
2676 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2677 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION) ||
2678 			    IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t))
2679 				goto discard_pkt;
2680 			/* Check for Self-encapsulated tunnels */
2681 			if (in_ipha->ipha_src == ipha->ipha_src &&
2682 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2683 
2684 				mp = icmp_inbound_self_encap_error(mp,
2685 				    iph_hdr_length, hdr_length);
2686 				if (mp == NULL)
2687 					goto discard_pkt;
2688 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2689 				ipha = (ipha_t *)&icmph[1];
2690 				hdr_length = IPH_HDR_LENGTH(ipha);
2691 				/*
2692 				 * The packet in error is self-encapsualted.
2693 				 * And we are finding it further encapsulated
2694 				 * which we could not have possibly generated.
2695 				 */
2696 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2697 					goto discard_pkt;
2698 				}
2699 				icmp_inbound_error_fanout(q, ill, first_mp,
2700 				    icmph, ipha, iph_hdr_length, hdr_length,
2701 				    mctl_present, ip_policy, recv_ill, zoneid);
2702 				return;
2703 			}
2704 		}
2705 
2706 		DB_TYPE(mp) = M_CTL;
2707 		if (icmp_inbound_iptun_fanout(first_mp, &ripha, ill, ipst))
2708 			return;
2709 		/*
2710 		 * No IP tunnel is interested, fallthrough and see
2711 		 * if a raw socket will want it.
2712 		 */
2713 		/* FALLTHRU */
2714 	default:
2715 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2716 		    ip_policy, recv_ill, zoneid);
2717 		return;
2718 	}
2719 	/* NOTREACHED */
2720 discard_pkt:
2721 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2722 drop_pkt:;
2723 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2724 	freemsg(first_mp);
2725 }
2726 
2727 /*
2728  * Common IP options parser.
2729  *
2730  * Setup routine: fill in *optp with options-parsing state, then
2731  * tail-call ipoptp_next to return the first option.
2732  */
2733 uint8_t
2734 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2735 {
2736 	uint32_t totallen; /* total length of all options */
2737 
2738 	totallen = ipha->ipha_version_and_hdr_length -
2739 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2740 	totallen <<= 2;
2741 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2742 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2743 	optp->ipoptp_flags = 0;
2744 	return (ipoptp_next(optp));
2745 }
2746 
2747 /*
2748  * Common IP options parser: extract next option.
2749  */
2750 uint8_t
2751 ipoptp_next(ipoptp_t *optp)
2752 {
2753 	uint8_t *end = optp->ipoptp_end;
2754 	uint8_t *cur = optp->ipoptp_next;
2755 	uint8_t opt, len, pointer;
2756 
2757 	/*
2758 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2759 	 * has been corrupted.
2760 	 */
2761 	ASSERT(cur <= end);
2762 
2763 	if (cur == end)
2764 		return (IPOPT_EOL);
2765 
2766 	opt = cur[IPOPT_OPTVAL];
2767 
2768 	/*
2769 	 * Skip any NOP options.
2770 	 */
2771 	while (opt == IPOPT_NOP) {
2772 		cur++;
2773 		if (cur == end)
2774 			return (IPOPT_EOL);
2775 		opt = cur[IPOPT_OPTVAL];
2776 	}
2777 
2778 	if (opt == IPOPT_EOL)
2779 		return (IPOPT_EOL);
2780 
2781 	/*
2782 	 * Option requiring a length.
2783 	 */
2784 	if ((cur + 1) >= end) {
2785 		optp->ipoptp_flags |= IPOPTP_ERROR;
2786 		return (IPOPT_EOL);
2787 	}
2788 	len = cur[IPOPT_OLEN];
2789 	if (len < 2) {
2790 		optp->ipoptp_flags |= IPOPTP_ERROR;
2791 		return (IPOPT_EOL);
2792 	}
2793 	optp->ipoptp_cur = cur;
2794 	optp->ipoptp_len = len;
2795 	optp->ipoptp_next = cur + len;
2796 	if (cur + len > end) {
2797 		optp->ipoptp_flags |= IPOPTP_ERROR;
2798 		return (IPOPT_EOL);
2799 	}
2800 
2801 	/*
2802 	 * For the options which require a pointer field, make sure
2803 	 * its there, and make sure it points to either something
2804 	 * inside this option, or the end of the option.
2805 	 */
2806 	switch (opt) {
2807 	case IPOPT_RR:
2808 	case IPOPT_TS:
2809 	case IPOPT_LSRR:
2810 	case IPOPT_SSRR:
2811 		if (len <= IPOPT_OFFSET) {
2812 			optp->ipoptp_flags |= IPOPTP_ERROR;
2813 			return (opt);
2814 		}
2815 		pointer = cur[IPOPT_OFFSET];
2816 		if (pointer - 1 > len) {
2817 			optp->ipoptp_flags |= IPOPTP_ERROR;
2818 			return (opt);
2819 		}
2820 		break;
2821 	}
2822 
2823 	/*
2824 	 * Sanity check the pointer field based on the type of the
2825 	 * option.
2826 	 */
2827 	switch (opt) {
2828 	case IPOPT_RR:
2829 	case IPOPT_SSRR:
2830 	case IPOPT_LSRR:
2831 		if (pointer < IPOPT_MINOFF_SR)
2832 			optp->ipoptp_flags |= IPOPTP_ERROR;
2833 		break;
2834 	case IPOPT_TS:
2835 		if (pointer < IPOPT_MINOFF_IT)
2836 			optp->ipoptp_flags |= IPOPTP_ERROR;
2837 		/*
2838 		 * Note that the Internet Timestamp option also
2839 		 * contains two four bit fields (the Overflow field,
2840 		 * and the Flag field), which follow the pointer
2841 		 * field.  We don't need to check that these fields
2842 		 * fall within the length of the option because this
2843 		 * was implicitely done above.  We've checked that the
2844 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2845 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2846 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2847 		 */
2848 		ASSERT(len > IPOPT_POS_OV_FLG);
2849 		break;
2850 	}
2851 
2852 	return (opt);
2853 }
2854 
2855 /*
2856  * Use the outgoing IP header to create an IP_OPTIONS option the way
2857  * it was passed down from the application.
2858  */
2859 int
2860 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2861 {
2862 	ipoptp_t	opts;
2863 	const uchar_t	*opt;
2864 	uint8_t		optval;
2865 	uint8_t		optlen;
2866 	uint32_t	len = 0;
2867 	uchar_t	*buf1 = buf;
2868 
2869 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2870 	len += IP_ADDR_LEN;
2871 	bzero(buf1, IP_ADDR_LEN);
2872 
2873 	/*
2874 	 * OK to cast away const here, as we don't store through the returned
2875 	 * opts.ipoptp_cur pointer.
2876 	 */
2877 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2878 	    optval != IPOPT_EOL;
2879 	    optval = ipoptp_next(&opts)) {
2880 		int	off;
2881 
2882 		opt = opts.ipoptp_cur;
2883 		optlen = opts.ipoptp_len;
2884 		switch (optval) {
2885 		case IPOPT_SSRR:
2886 		case IPOPT_LSRR:
2887 
2888 			/*
2889 			 * Insert ipha_dst as the first entry in the source
2890 			 * route and move down the entries on step.
2891 			 * The last entry gets placed at buf1.
2892 			 */
2893 			buf[IPOPT_OPTVAL] = optval;
2894 			buf[IPOPT_OLEN] = optlen;
2895 			buf[IPOPT_OFFSET] = optlen;
2896 
2897 			off = optlen - IP_ADDR_LEN;
2898 			if (off < 0) {
2899 				/* No entries in source route */
2900 				break;
2901 			}
2902 			/* Last entry in source route */
2903 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2904 			off -= IP_ADDR_LEN;
2905 
2906 			while (off > 0) {
2907 				bcopy(opt + off,
2908 				    buf + off + IP_ADDR_LEN,
2909 				    IP_ADDR_LEN);
2910 				off -= IP_ADDR_LEN;
2911 			}
2912 			/* ipha_dst into first slot */
2913 			bcopy(&ipha->ipha_dst,
2914 			    buf + off + IP_ADDR_LEN,
2915 			    IP_ADDR_LEN);
2916 			buf += optlen;
2917 			len += optlen;
2918 			break;
2919 
2920 		case IPOPT_COMSEC:
2921 		case IPOPT_SECURITY:
2922 			/* if passing up a label is not ok, then remove */
2923 			if (is_system_labeled())
2924 				break;
2925 			/* FALLTHROUGH */
2926 		default:
2927 			bcopy(opt, buf, optlen);
2928 			buf += optlen;
2929 			len += optlen;
2930 			break;
2931 		}
2932 	}
2933 done:
2934 	/* Pad the resulting options */
2935 	while (len & 0x3) {
2936 		*buf++ = IPOPT_EOL;
2937 		len++;
2938 	}
2939 	return (len);
2940 }
2941 
2942 /*
2943  * Update any record route or timestamp options to include this host.
2944  * Reverse any source route option.
2945  * This routine assumes that the options are well formed i.e. that they
2946  * have already been checked.
2947  */
2948 static void
2949 icmp_options_update(ipha_t *ipha)
2950 {
2951 	ipoptp_t	opts;
2952 	uchar_t		*opt;
2953 	uint8_t		optval;
2954 	ipaddr_t	src;		/* Our local address */
2955 	ipaddr_t	dst;
2956 
2957 	ip2dbg(("icmp_options_update\n"));
2958 	src = ipha->ipha_src;
2959 	dst = ipha->ipha_dst;
2960 
2961 	for (optval = ipoptp_first(&opts, ipha);
2962 	    optval != IPOPT_EOL;
2963 	    optval = ipoptp_next(&opts)) {
2964 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2965 		opt = opts.ipoptp_cur;
2966 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2967 		    optval, opts.ipoptp_len));
2968 		switch (optval) {
2969 			int off1, off2;
2970 		case IPOPT_SSRR:
2971 		case IPOPT_LSRR:
2972 			/*
2973 			 * Reverse the source route.  The first entry
2974 			 * should be the next to last one in the current
2975 			 * source route (the last entry is our address).
2976 			 * The last entry should be the final destination.
2977 			 */
2978 			off1 = IPOPT_MINOFF_SR - 1;
2979 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2980 			if (off2 < 0) {
2981 				/* No entries in source route */
2982 				ip1dbg((
2983 				    "icmp_options_update: bad src route\n"));
2984 				break;
2985 			}
2986 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2987 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2988 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2989 			off2 -= IP_ADDR_LEN;
2990 
2991 			while (off1 < off2) {
2992 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2993 				bcopy((char *)opt + off2, (char *)opt + off1,
2994 				    IP_ADDR_LEN);
2995 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2996 				off1 += IP_ADDR_LEN;
2997 				off2 -= IP_ADDR_LEN;
2998 			}
2999 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3000 			break;
3001 		}
3002 	}
3003 }
3004 
3005 /*
3006  * Process received ICMP Redirect messages.
3007  */
3008 static void
3009 icmp_redirect(ill_t *ill, mblk_t *mp)
3010 {
3011 	ipha_t	*ipha;
3012 	int	iph_hdr_length;
3013 	icmph_t	*icmph;
3014 	ipha_t	*ipha_err;
3015 	ire_t	*ire;
3016 	ire_t	*prev_ire;
3017 	ire_t	*save_ire;
3018 	ipaddr_t  src, dst, gateway;
3019 	iulp_t	ulp_info = { 0 };
3020 	int	error;
3021 	ip_stack_t *ipst;
3022 
3023 	ASSERT(ill != NULL);
3024 	ipst = ill->ill_ipst;
3025 
3026 	ipha = (ipha_t *)mp->b_rptr;
3027 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3028 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3029 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3030 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3031 		freemsg(mp);
3032 		return;
3033 	}
3034 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3035 	ipha_err = (ipha_t *)&icmph[1];
3036 	src = ipha->ipha_src;
3037 	dst = ipha_err->ipha_dst;
3038 	gateway = icmph->icmph_rd_gateway;
3039 	/* Make sure the new gateway is reachable somehow. */
3040 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3041 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3042 	/*
3043 	 * Make sure we had a route for the dest in question and that
3044 	 * that route was pointing to the old gateway (the source of the
3045 	 * redirect packet.)
3046 	 */
3047 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3048 	    NULL, MATCH_IRE_GW, ipst);
3049 	/*
3050 	 * Check that
3051 	 *	the redirect was not from ourselves
3052 	 *	the new gateway and the old gateway are directly reachable
3053 	 */
3054 	if (!prev_ire ||
3055 	    !ire ||
3056 	    ire->ire_type == IRE_LOCAL) {
3057 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3058 		freemsg(mp);
3059 		if (ire != NULL)
3060 			ire_refrele(ire);
3061 		if (prev_ire != NULL)
3062 			ire_refrele(prev_ire);
3063 		return;
3064 	}
3065 
3066 	/*
3067 	 * Should we use the old ULP info to create the new gateway?  From
3068 	 * a user's perspective, we should inherit the info so that it
3069 	 * is a "smooth" transition.  If we do not do that, then new
3070 	 * connections going thru the new gateway will have no route metrics,
3071 	 * which is counter-intuitive to user.  From a network point of
3072 	 * view, this may or may not make sense even though the new gateway
3073 	 * is still directly connected to us so the route metrics should not
3074 	 * change much.
3075 	 *
3076 	 * But if the old ire_uinfo is not initialized, we do another
3077 	 * recursive lookup on the dest using the new gateway.  There may
3078 	 * be a route to that.  If so, use it to initialize the redirect
3079 	 * route.
3080 	 */
3081 	if (prev_ire->ire_uinfo.iulp_set) {
3082 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3083 	} else {
3084 		ire_t *tmp_ire;
3085 		ire_t *sire;
3086 
3087 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3088 		    ALL_ZONES, 0, NULL,
3089 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3090 		    ipst);
3091 		if (sire != NULL) {
3092 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3093 			/*
3094 			 * If sire != NULL, ire_ftable_lookup() should not
3095 			 * return a NULL value.
3096 			 */
3097 			ASSERT(tmp_ire != NULL);
3098 			ire_refrele(tmp_ire);
3099 			ire_refrele(sire);
3100 		} else if (tmp_ire != NULL) {
3101 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3102 			    sizeof (iulp_t));
3103 			ire_refrele(tmp_ire);
3104 		}
3105 	}
3106 	if (prev_ire->ire_type == IRE_CACHE)
3107 		ire_delete(prev_ire);
3108 	ire_refrele(prev_ire);
3109 	/*
3110 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3111 	 * require TOS routing
3112 	 */
3113 	switch (icmph->icmph_code) {
3114 	case 0:
3115 	case 1:
3116 		/* TODO: TOS specificity for cases 2 and 3 */
3117 	case 2:
3118 	case 3:
3119 		break;
3120 	default:
3121 		freemsg(mp);
3122 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3123 		ire_refrele(ire);
3124 		return;
3125 	}
3126 	/*
3127 	 * Create a Route Association.  This will allow us to remember that
3128 	 * someone we believe told us to use the particular gateway.
3129 	 */
3130 	save_ire = ire;
3131 	ire = ire_create(
3132 	    (uchar_t *)&dst,			/* dest addr */
3133 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3134 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3135 	    (uchar_t *)&gateway,		/* gateway addr */
3136 	    &save_ire->ire_max_frag,		/* max frag */
3137 	    NULL,				/* no src nce */
3138 	    NULL,				/* no rfq */
3139 	    NULL,				/* no stq */
3140 	    IRE_HOST,
3141 	    NULL,				/* ipif */
3142 	    0,					/* cmask */
3143 	    0,					/* phandle */
3144 	    0,					/* ihandle */
3145 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3146 	    &ulp_info,
3147 	    NULL,				/* tsol_gc_t */
3148 	    NULL,				/* gcgrp */
3149 	    ipst);
3150 
3151 	if (ire == NULL) {
3152 		freemsg(mp);
3153 		ire_refrele(save_ire);
3154 		return;
3155 	}
3156 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3157 	ire_refrele(save_ire);
3158 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3159 
3160 	if (error == 0) {
3161 		ire_refrele(ire);		/* Held in ire_add_v4 */
3162 		/* tell routing sockets that we received a redirect */
3163 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3164 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3165 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3166 	}
3167 
3168 	/*
3169 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3170 	 * This together with the added IRE has the effect of
3171 	 * modifying an existing redirect.
3172 	 */
3173 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3174 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3175 	if (prev_ire != NULL) {
3176 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3177 			ire_delete(prev_ire);
3178 		ire_refrele(prev_ire);
3179 	}
3180 
3181 	freemsg(mp);
3182 }
3183 
3184 /*
3185  * Generate an ICMP parameter problem message.
3186  */
3187 static void
3188 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3189 	ip_stack_t *ipst)
3190 {
3191 	icmph_t	icmph;
3192 	boolean_t mctl_present;
3193 	mblk_t *first_mp;
3194 
3195 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3196 
3197 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3198 		if (mctl_present)
3199 			freeb(first_mp);
3200 		return;
3201 	}
3202 
3203 	bzero(&icmph, sizeof (icmph_t));
3204 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3205 	icmph.icmph_pp_ptr = ptr;
3206 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3207 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3208 	    ipst);
3209 }
3210 
3211 /*
3212  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3213  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3214  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3215  * an icmp error packet can be sent.
3216  * Assigns an appropriate source address to the packet. If ipha_dst is
3217  * one of our addresses use it for source. Otherwise pick a source based
3218  * on a route lookup back to ipha_src.
3219  * Note that ipha_src must be set here since the
3220  * packet is likely to arrive on an ill queue in ip_wput() which will
3221  * not set a source address.
3222  */
3223 static void
3224 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3225     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3226 {
3227 	ipaddr_t dst;
3228 	icmph_t	*icmph;
3229 	ipha_t	*ipha;
3230 	uint_t	len_needed;
3231 	size_t	msg_len;
3232 	mblk_t	*mp1;
3233 	ipaddr_t src;
3234 	ire_t	*ire;
3235 	mblk_t *ipsec_mp;
3236 	ipsec_out_t	*io = NULL;
3237 
3238 	if (mctl_present) {
3239 		/*
3240 		 * If it is :
3241 		 *
3242 		 * 1) a IPSEC_OUT, then this is caused by outbound
3243 		 *    datagram originating on this host. IPsec processing
3244 		 *    may or may not have been done. Refer to comments above
3245 		 *    icmp_inbound_error_fanout for details.
3246 		 *
3247 		 * 2) a IPSEC_IN if we are generating a icmp_message
3248 		 *    for an incoming datagram destined for us i.e called
3249 		 *    from ip_fanout_send_icmp.
3250 		 */
3251 		ipsec_info_t *in;
3252 		ipsec_mp = mp;
3253 		mp = ipsec_mp->b_cont;
3254 
3255 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3256 		ipha = (ipha_t *)mp->b_rptr;
3257 
3258 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3259 		    in->ipsec_info_type == IPSEC_IN);
3260 
3261 		if (in->ipsec_info_type == IPSEC_IN) {
3262 			/*
3263 			 * Convert the IPSEC_IN to IPSEC_OUT.
3264 			 */
3265 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3266 				BUMP_MIB(&ipst->ips_ip_mib,
3267 				    ipIfStatsOutDiscards);
3268 				return;
3269 			}
3270 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3271 		} else {
3272 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3273 			io = (ipsec_out_t *)in;
3274 			/*
3275 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3276 			 * ire lookup.
3277 			 */
3278 			io->ipsec_out_proc_begin = B_FALSE;
3279 		}
3280 		ASSERT(zoneid != ALL_ZONES);
3281 		/*
3282 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3283 		 * initialized.  We need to do that now.
3284 		 */
3285 		io->ipsec_out_zoneid = zoneid;
3286 	} else {
3287 		/*
3288 		 * This is in clear. The icmp message we are building
3289 		 * here should go out in clear.
3290 		 *
3291 		 * Pardon the convolution of it all, but it's easier to
3292 		 * allocate a "use cleartext" IPSEC_IN message and convert
3293 		 * it than it is to allocate a new one.
3294 		 */
3295 		ipsec_in_t *ii;
3296 		ASSERT(DB_TYPE(mp) == M_DATA);
3297 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3298 		if (ipsec_mp == NULL) {
3299 			freemsg(mp);
3300 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3301 			return;
3302 		}
3303 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3304 
3305 		/* This is not a secure packet */
3306 		ii->ipsec_in_secure = B_FALSE;
3307 		/*
3308 		 * For trusted extensions using a shared IP address we can
3309 		 * send using any zoneid.
3310 		 */
3311 		if (zoneid == ALL_ZONES)
3312 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3313 		else
3314 			ii->ipsec_in_zoneid = zoneid;
3315 		ipsec_mp->b_cont = mp;
3316 		ipha = (ipha_t *)mp->b_rptr;
3317 		/*
3318 		 * Convert the IPSEC_IN to IPSEC_OUT.
3319 		 */
3320 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3321 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3322 			return;
3323 		}
3324 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3325 	}
3326 
3327 	/* Remember our eventual destination */
3328 	dst = ipha->ipha_src;
3329 
3330 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3331 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3332 	if (ire != NULL &&
3333 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3334 		src = ipha->ipha_dst;
3335 	} else {
3336 		if (ire != NULL)
3337 			ire_refrele(ire);
3338 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3339 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3340 		    ipst);
3341 		if (ire == NULL) {
3342 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3343 			freemsg(ipsec_mp);
3344 			return;
3345 		}
3346 		src = ire->ire_src_addr;
3347 	}
3348 
3349 	if (ire != NULL)
3350 		ire_refrele(ire);
3351 
3352 	/*
3353 	 * Check if we can send back more then 8 bytes in addition to
3354 	 * the IP header.  We try to send 64 bytes of data and the internal
3355 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3356 	 */
3357 	len_needed = IPH_HDR_LENGTH(ipha);
3358 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3359 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3360 
3361 		if (!pullupmsg(mp, -1)) {
3362 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3363 			freemsg(ipsec_mp);
3364 			return;
3365 		}
3366 		ipha = (ipha_t *)mp->b_rptr;
3367 
3368 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3369 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3370 			    len_needed));
3371 		} else {
3372 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3373 
3374 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3375 			len_needed += ip_hdr_length_v6(mp, ip6h);
3376 		}
3377 	}
3378 	len_needed += ipst->ips_ip_icmp_return;
3379 	msg_len = msgdsize(mp);
3380 	if (msg_len > len_needed) {
3381 		(void) adjmsg(mp, len_needed - msg_len);
3382 		msg_len = len_needed;
3383 	}
3384 	/* Make sure we propagate the cred/label for TX */
3385 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3386 	if (mp1 == NULL) {
3387 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3388 		freemsg(ipsec_mp);
3389 		return;
3390 	}
3391 	mp1->b_cont = mp;
3392 	mp = mp1;
3393 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3394 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3395 	    io->ipsec_out_type == IPSEC_OUT);
3396 	ipsec_mp->b_cont = mp;
3397 
3398 	/*
3399 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3400 	 * node generates be accepted in peace by all on-host destinations.
3401 	 * If we do NOT assume that all on-host destinations trust
3402 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3403 	 * (Look for ipsec_out_icmp_loopback).
3404 	 */
3405 	io->ipsec_out_icmp_loopback = B_TRUE;
3406 
3407 	ipha = (ipha_t *)mp->b_rptr;
3408 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3409 	*ipha = icmp_ipha;
3410 	ipha->ipha_src = src;
3411 	ipha->ipha_dst = dst;
3412 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3413 	msg_len += sizeof (icmp_ipha) + len;
3414 	if (msg_len > IP_MAXPACKET) {
3415 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3416 		msg_len = IP_MAXPACKET;
3417 	}
3418 	ipha->ipha_length = htons((uint16_t)msg_len);
3419 	icmph = (icmph_t *)&ipha[1];
3420 	bcopy(stuff, icmph, len);
3421 	icmph->icmph_checksum = 0;
3422 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3423 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3424 	put(q, ipsec_mp);
3425 }
3426 
3427 /*
3428  * Determine if an ICMP error packet can be sent given the rate limit.
3429  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3430  * in milliseconds) and a burst size. Burst size number of packets can
3431  * be sent arbitrarely closely spaced.
3432  * The state is tracked using two variables to implement an approximate
3433  * token bucket filter:
3434  *	icmp_pkt_err_last - lbolt value when the last burst started
3435  *	icmp_pkt_err_sent - number of packets sent in current burst
3436  */
3437 boolean_t
3438 icmp_err_rate_limit(ip_stack_t *ipst)
3439 {
3440 	clock_t now = TICK_TO_MSEC(lbolt);
3441 	uint_t refilled; /* Number of packets refilled in tbf since last */
3442 	/* Guard against changes by loading into local variable */
3443 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3444 
3445 	if (err_interval == 0)
3446 		return (B_FALSE);
3447 
3448 	if (ipst->ips_icmp_pkt_err_last > now) {
3449 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3450 		ipst->ips_icmp_pkt_err_last = 0;
3451 		ipst->ips_icmp_pkt_err_sent = 0;
3452 	}
3453 	/*
3454 	 * If we are in a burst update the token bucket filter.
3455 	 * Update the "last" time to be close to "now" but make sure
3456 	 * we don't loose precision.
3457 	 */
3458 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3459 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3460 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3461 			ipst->ips_icmp_pkt_err_sent = 0;
3462 		} else {
3463 			ipst->ips_icmp_pkt_err_sent -= refilled;
3464 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3465 		}
3466 	}
3467 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3468 		/* Start of new burst */
3469 		ipst->ips_icmp_pkt_err_last = now;
3470 	}
3471 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3472 		ipst->ips_icmp_pkt_err_sent++;
3473 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3474 		    ipst->ips_icmp_pkt_err_sent));
3475 		return (B_FALSE);
3476 	}
3477 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3478 	return (B_TRUE);
3479 }
3480 
3481 /*
3482  * Check if it is ok to send an IPv4 ICMP error packet in
3483  * response to the IPv4 packet in mp.
3484  * Free the message and return null if no
3485  * ICMP error packet should be sent.
3486  */
3487 static mblk_t *
3488 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3489 {
3490 	icmph_t	*icmph;
3491 	ipha_t	*ipha;
3492 	uint_t	len_needed;
3493 	ire_t	*src_ire;
3494 	ire_t	*dst_ire;
3495 
3496 	if (!mp)
3497 		return (NULL);
3498 	ipha = (ipha_t *)mp->b_rptr;
3499 	if (ip_csum_hdr(ipha)) {
3500 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3501 		freemsg(mp);
3502 		return (NULL);
3503 	}
3504 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3505 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3506 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3507 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3508 	if (src_ire != NULL || dst_ire != NULL ||
3509 	    CLASSD(ipha->ipha_dst) ||
3510 	    CLASSD(ipha->ipha_src) ||
3511 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3512 		/* Note: only errors to the fragment with offset 0 */
3513 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3514 		freemsg(mp);
3515 		if (src_ire != NULL)
3516 			ire_refrele(src_ire);
3517 		if (dst_ire != NULL)
3518 			ire_refrele(dst_ire);
3519 		return (NULL);
3520 	}
3521 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3522 		/*
3523 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3524 		 * errors in response to any ICMP errors.
3525 		 */
3526 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3527 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3528 			if (!pullupmsg(mp, len_needed)) {
3529 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3530 				freemsg(mp);
3531 				return (NULL);
3532 			}
3533 			ipha = (ipha_t *)mp->b_rptr;
3534 		}
3535 		icmph = (icmph_t *)
3536 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3537 		switch (icmph->icmph_type) {
3538 		case ICMP_DEST_UNREACHABLE:
3539 		case ICMP_SOURCE_QUENCH:
3540 		case ICMP_TIME_EXCEEDED:
3541 		case ICMP_PARAM_PROBLEM:
3542 		case ICMP_REDIRECT:
3543 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3544 			freemsg(mp);
3545 			return (NULL);
3546 		default:
3547 			break;
3548 		}
3549 	}
3550 	/*
3551 	 * If this is a labeled system, then check to see if we're allowed to
3552 	 * send a response to this particular sender.  If not, then just drop.
3553 	 */
3554 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3555 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3556 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3557 		freemsg(mp);
3558 		return (NULL);
3559 	}
3560 	if (icmp_err_rate_limit(ipst)) {
3561 		/*
3562 		 * Only send ICMP error packets every so often.
3563 		 * This should be done on a per port/source basis,
3564 		 * but for now this will suffice.
3565 		 */
3566 		freemsg(mp);
3567 		return (NULL);
3568 	}
3569 	return (mp);
3570 }
3571 
3572 /*
3573  * Generate an ICMP redirect message.
3574  */
3575 static void
3576 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3577 {
3578 	icmph_t	icmph;
3579 
3580 	/*
3581 	 * We are called from ip_rput where we could
3582 	 * not have attached an IPSEC_IN.
3583 	 */
3584 	ASSERT(mp->b_datap->db_type == M_DATA);
3585 
3586 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3587 		return;
3588 	}
3589 
3590 	bzero(&icmph, sizeof (icmph_t));
3591 	icmph.icmph_type = ICMP_REDIRECT;
3592 	icmph.icmph_code = 1;
3593 	icmph.icmph_rd_gateway = gateway;
3594 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3595 	/* Redirects sent by router, and router is global zone */
3596 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3597 }
3598 
3599 /*
3600  * Generate an ICMP time exceeded message.
3601  */
3602 void
3603 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3604     ip_stack_t *ipst)
3605 {
3606 	icmph_t	icmph;
3607 	boolean_t mctl_present;
3608 	mblk_t *first_mp;
3609 
3610 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3611 
3612 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3613 		if (mctl_present)
3614 			freeb(first_mp);
3615 		return;
3616 	}
3617 
3618 	bzero(&icmph, sizeof (icmph_t));
3619 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3620 	icmph.icmph_code = code;
3621 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3622 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3623 	    ipst);
3624 }
3625 
3626 /*
3627  * Generate an ICMP unreachable message.
3628  */
3629 void
3630 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3631     ip_stack_t *ipst)
3632 {
3633 	icmph_t	icmph;
3634 	mblk_t *first_mp;
3635 	boolean_t mctl_present;
3636 
3637 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3638 
3639 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3640 		if (mctl_present)
3641 			freeb(first_mp);
3642 		return;
3643 	}
3644 
3645 	bzero(&icmph, sizeof (icmph_t));
3646 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3647 	icmph.icmph_code = code;
3648 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3649 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3650 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3651 	    zoneid, ipst);
3652 }
3653 
3654 /*
3655  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3656  * duplicate.  As long as someone else holds the address, the interface will
3657  * stay down.  When that conflict goes away, the interface is brought back up.
3658  * This is done so that accidental shutdowns of addresses aren't made
3659  * permanent.  Your server will recover from a failure.
3660  *
3661  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3662  * user space process (dhcpagent).
3663  *
3664  * Recovery completes if ARP reports that the address is now ours (via
3665  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3666  *
3667  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3668  */
3669 static void
3670 ipif_dup_recovery(void *arg)
3671 {
3672 	ipif_t *ipif = arg;
3673 	ill_t *ill = ipif->ipif_ill;
3674 	mblk_t *arp_add_mp;
3675 	mblk_t *arp_del_mp;
3676 	ip_stack_t *ipst = ill->ill_ipst;
3677 
3678 	ipif->ipif_recovery_id = 0;
3679 
3680 	/*
3681 	 * No lock needed for moving or condemned check, as this is just an
3682 	 * optimization.
3683 	 */
3684 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3685 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3686 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3687 		/* No reason to try to bring this address back. */
3688 		return;
3689 	}
3690 
3691 	/* ACE_F_UNVERIFIED restarts DAD */
3692 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3693 		goto alloc_fail;
3694 
3695 	if (ipif->ipif_arp_del_mp == NULL) {
3696 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3697 			goto alloc_fail;
3698 		ipif->ipif_arp_del_mp = arp_del_mp;
3699 	}
3700 
3701 	putnext(ill->ill_rq, arp_add_mp);
3702 	return;
3703 
3704 alloc_fail:
3705 	/*
3706 	 * On allocation failure, just restart the timer.  Note that the ipif
3707 	 * is down here, so no other thread could be trying to start a recovery
3708 	 * timer.  The ill_lock protects the condemned flag and the recovery
3709 	 * timer ID.
3710 	 */
3711 	freemsg(arp_add_mp);
3712 	mutex_enter(&ill->ill_lock);
3713 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3714 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3715 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3716 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3717 	}
3718 	mutex_exit(&ill->ill_lock);
3719 }
3720 
3721 /*
3722  * This is for exclusive changes due to ARP.  Either tear down an interface due
3723  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3724  */
3725 /* ARGSUSED */
3726 static void
3727 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3728 {
3729 	ill_t	*ill = rq->q_ptr;
3730 	arh_t *arh;
3731 	ipaddr_t src;
3732 	ipif_t	*ipif;
3733 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3734 	char hbuf[MAC_STR_LEN];
3735 	char sbuf[INET_ADDRSTRLEN];
3736 	const char *failtype;
3737 	boolean_t bring_up;
3738 	ip_stack_t *ipst = ill->ill_ipst;
3739 
3740 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3741 	case AR_CN_READY:
3742 		failtype = NULL;
3743 		bring_up = B_TRUE;
3744 		break;
3745 	case AR_CN_FAILED:
3746 		failtype = "in use";
3747 		bring_up = B_FALSE;
3748 		break;
3749 	default:
3750 		failtype = "claimed";
3751 		bring_up = B_FALSE;
3752 		break;
3753 	}
3754 
3755 	arh = (arh_t *)mp->b_cont->b_rptr;
3756 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3757 
3758 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3759 	    sizeof (hbuf));
3760 	(void) ip_dot_addr(src, sbuf);
3761 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3762 
3763 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3764 		    ipif->ipif_lcl_addr != src) {
3765 			continue;
3766 		}
3767 
3768 		/*
3769 		 * If we failed on a recovery probe, then restart the timer to
3770 		 * try again later.
3771 		 */
3772 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3773 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3774 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3775 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3776 		    ipst->ips_ip_dup_recovery > 0 &&
3777 		    ipif->ipif_recovery_id == 0) {
3778 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3779 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3780 			continue;
3781 		}
3782 
3783 		/*
3784 		 * If what we're trying to do has already been done, then do
3785 		 * nothing.
3786 		 */
3787 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3788 			continue;
3789 
3790 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3791 
3792 		if (failtype == NULL) {
3793 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3794 			    ibuf);
3795 		} else {
3796 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3797 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3798 		}
3799 
3800 		if (bring_up) {
3801 			ASSERT(ill->ill_dl_up);
3802 			/*
3803 			 * Free up the ARP delete message so we can allocate
3804 			 * a fresh one through the normal path.
3805 			 */
3806 			freemsg(ipif->ipif_arp_del_mp);
3807 			ipif->ipif_arp_del_mp = NULL;
3808 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3809 			    EINPROGRESS) {
3810 				ipif->ipif_addr_ready = 1;
3811 				(void) ipif_up_done(ipif);
3812 				ASSERT(ill->ill_move_ipif == NULL);
3813 			}
3814 			continue;
3815 		}
3816 
3817 		mutex_enter(&ill->ill_lock);
3818 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3819 		ipif->ipif_flags |= IPIF_DUPLICATE;
3820 		ill->ill_ipif_dup_count++;
3821 		mutex_exit(&ill->ill_lock);
3822 		/*
3823 		 * Already exclusive on the ill; no need to handle deferred
3824 		 * processing here.
3825 		 */
3826 		(void) ipif_down(ipif, NULL, NULL);
3827 		ipif_down_tail(ipif);
3828 		mutex_enter(&ill->ill_lock);
3829 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3830 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3831 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3832 		    ipst->ips_ip_dup_recovery > 0) {
3833 			ASSERT(ipif->ipif_recovery_id == 0);
3834 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3835 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3836 		}
3837 		mutex_exit(&ill->ill_lock);
3838 	}
3839 	freemsg(mp);
3840 }
3841 
3842 /* ARGSUSED */
3843 static void
3844 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3845 {
3846 	ill_t	*ill = rq->q_ptr;
3847 	arh_t *arh;
3848 	ipaddr_t src;
3849 	ipif_t	*ipif;
3850 
3851 	arh = (arh_t *)mp->b_cont->b_rptr;
3852 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3853 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3854 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3855 			(void) ipif_resolver_up(ipif, Res_act_defend);
3856 	}
3857 	freemsg(mp);
3858 }
3859 
3860 /*
3861  * News from ARP.  ARP sends notification of interesting events down
3862  * to its clients using M_CTL messages with the interesting ARP packet
3863  * attached via b_cont.
3864  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3865  * queue as opposed to ARP sending the message to all the clients, i.e. all
3866  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3867  * table if a cache IRE is found to delete all the entries for the address in
3868  * the packet.
3869  */
3870 static void
3871 ip_arp_news(queue_t *q, mblk_t *mp)
3872 {
3873 	arcn_t		*arcn;
3874 	arh_t		*arh;
3875 	ire_t		*ire = NULL;
3876 	char		hbuf[MAC_STR_LEN];
3877 	char		sbuf[INET_ADDRSTRLEN];
3878 	ipaddr_t	src;
3879 	in6_addr_t	v6src;
3880 	boolean_t	isv6 = B_FALSE;
3881 	ipif_t		*ipif;
3882 	ill_t		*ill;
3883 	ip_stack_t	*ipst;
3884 
3885 	if (CONN_Q(q)) {
3886 		conn_t *connp = Q_TO_CONN(q);
3887 
3888 		ipst = connp->conn_netstack->netstack_ip;
3889 	} else {
3890 		ill_t *ill = (ill_t *)q->q_ptr;
3891 
3892 		ipst = ill->ill_ipst;
3893 	}
3894 
3895 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3896 		if (q->q_next) {
3897 			putnext(q, mp);
3898 		} else
3899 			freemsg(mp);
3900 		return;
3901 	}
3902 	arh = (arh_t *)mp->b_cont->b_rptr;
3903 	/* Is it one we are interested in? */
3904 	if (BE16_TO_U16(arh->arh_proto) == ETHERTYPE_IPV6) {
3905 		isv6 = B_TRUE;
3906 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3907 		    IPV6_ADDR_LEN);
3908 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3909 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3910 		    IP_ADDR_LEN);
3911 	} else {
3912 		freemsg(mp);
3913 		return;
3914 	}
3915 
3916 	ill = q->q_ptr;
3917 
3918 	arcn = (arcn_t *)mp->b_rptr;
3919 	switch (arcn->arcn_code) {
3920 	case AR_CN_BOGON:
3921 		/*
3922 		 * Someone is sending ARP packets with a source protocol
3923 		 * address that we have published and for which we believe our
3924 		 * entry is authoritative and (when ill_arp_extend is set)
3925 		 * verified to be unique on the network.
3926 		 *
3927 		 * The ARP module internally handles the cases where the sender
3928 		 * is just probing (for DAD) and where the hardware address of
3929 		 * a non-authoritative entry has changed.  Thus, these are the
3930 		 * real conflicts, and we have to do resolution.
3931 		 *
3932 		 * We back away quickly from the address if it's from DHCP or
3933 		 * otherwise temporary and hasn't been used recently (or at
3934 		 * all).  We'd like to include "deprecated" addresses here as
3935 		 * well (as there's no real reason to defend something we're
3936 		 * discarding), but IPMP "reuses" this flag to mean something
3937 		 * other than the standard meaning.
3938 		 *
3939 		 * If the ARP module above is not extended (meaning that it
3940 		 * doesn't know how to defend the address), then we just log
3941 		 * the problem as we always did and continue on.  It's not
3942 		 * right, but there's little else we can do, and those old ATM
3943 		 * users are going away anyway.
3944 		 */
3945 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3946 		    hbuf, sizeof (hbuf));
3947 		(void) ip_dot_addr(src, sbuf);
3948 		if (isv6) {
3949 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3950 			    ipst);
3951 		} else {
3952 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3953 		}
3954 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3955 			uint32_t now;
3956 			uint32_t maxage;
3957 			clock_t lused;
3958 			uint_t maxdefense;
3959 			uint_t defs;
3960 
3961 			/*
3962 			 * First, figure out if this address hasn't been used
3963 			 * in a while.  If it hasn't, then it's a better
3964 			 * candidate for abandoning.
3965 			 */
3966 			ipif = ire->ire_ipif;
3967 			ASSERT(ipif != NULL);
3968 			now = gethrestime_sec();
3969 			maxage = now - ire->ire_create_time;
3970 			if (maxage > ipst->ips_ip_max_temp_idle)
3971 				maxage = ipst->ips_ip_max_temp_idle;
3972 			lused = drv_hztousec(ddi_get_lbolt() -
3973 			    ire->ire_last_used_time) / MICROSEC + 1;
3974 			if (lused >= maxage && (ipif->ipif_flags &
3975 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3976 				maxdefense = ipst->ips_ip_max_temp_defend;
3977 			else
3978 				maxdefense = ipst->ips_ip_max_defend;
3979 
3980 			/*
3981 			 * Now figure out how many times we've defended
3982 			 * ourselves.  Ignore defenses that happened long in
3983 			 * the past.
3984 			 */
3985 			mutex_enter(&ire->ire_lock);
3986 			if ((defs = ire->ire_defense_count) > 0 &&
3987 			    now - ire->ire_defense_time >
3988 			    ipst->ips_ip_defend_interval) {
3989 				ire->ire_defense_count = defs = 0;
3990 			}
3991 			ire->ire_defense_count++;
3992 			ire->ire_defense_time = now;
3993 			mutex_exit(&ire->ire_lock);
3994 			ill_refhold(ill);
3995 			ire_refrele(ire);
3996 
3997 			/*
3998 			 * If we've defended ourselves too many times already,
3999 			 * then give up and tear down the interface(s) using
4000 			 * this address.  Otherwise, defend by sending out a
4001 			 * gratuitous ARP.
4002 			 */
4003 			if (defs >= maxdefense && ill->ill_arp_extend) {
4004 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4005 				    B_FALSE);
4006 			} else {
4007 				cmn_err(CE_WARN,
4008 				    "node %s is using our IP address %s on %s",
4009 				    hbuf, sbuf, ill->ill_name);
4010 				/*
4011 				 * If this is an old (ATM) ARP module, then
4012 				 * don't try to defend the address.  Remain
4013 				 * compatible with the old behavior.  Defend
4014 				 * only with new ARP.
4015 				 */
4016 				if (ill->ill_arp_extend) {
4017 					qwriter_ip(ill, q, mp, ip_arp_defend,
4018 					    NEW_OP, B_FALSE);
4019 				} else {
4020 					ill_refrele(ill);
4021 				}
4022 			}
4023 			return;
4024 		}
4025 		cmn_err(CE_WARN,
4026 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4027 		    hbuf, sbuf, ill->ill_name);
4028 		if (ire != NULL)
4029 			ire_refrele(ire);
4030 		break;
4031 	case AR_CN_ANNOUNCE:
4032 		if (isv6) {
4033 			/*
4034 			 * For XRESOLV interfaces.
4035 			 * Delete the IRE cache entry and NCE for this
4036 			 * v6 address
4037 			 */
4038 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4039 			/*
4040 			 * If v6src is a non-zero, it's a router address
4041 			 * as below. Do the same sort of thing to clean
4042 			 * out off-net IRE_CACHE entries that go through
4043 			 * the router.
4044 			 */
4045 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4046 				ire_walk_v6(ire_delete_cache_gw_v6,
4047 				    (char *)&v6src, ALL_ZONES, ipst);
4048 			}
4049 		} else {
4050 			nce_hw_map_t hwm;
4051 
4052 			/*
4053 			 * ARP gives us a copy of any packet where it thinks
4054 			 * the address has changed, so that we can update our
4055 			 * caches.  We're responsible for caching known answers
4056 			 * in the current design.  We check whether the
4057 			 * hardware address really has changed in all of our
4058 			 * entries that have cached this mapping, and if so, we
4059 			 * blow them away.  This way we will immediately pick
4060 			 * up the rare case of a host changing hardware
4061 			 * address.
4062 			 */
4063 			if (src == 0)
4064 				break;
4065 			hwm.hwm_addr = src;
4066 			hwm.hwm_hwlen = arh->arh_hlen;
4067 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4068 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4069 			ndp_walk_common(ipst->ips_ndp4, NULL,
4070 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4071 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4072 		}
4073 		break;
4074 	case AR_CN_READY:
4075 		/* No external v6 resolver has a contract to use this */
4076 		if (isv6)
4077 			break;
4078 		/* If the link is down, we'll retry this later */
4079 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4080 			break;
4081 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4082 		    NULL, NULL, ipst);
4083 		if (ipif != NULL) {
4084 			/*
4085 			 * If this is a duplicate recovery, then we now need to
4086 			 * go exclusive to bring this thing back up.
4087 			 */
4088 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4089 			    IPIF_DUPLICATE) {
4090 				ipif_refrele(ipif);
4091 				ill_refhold(ill);
4092 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4093 				    B_FALSE);
4094 				return;
4095 			}
4096 			/*
4097 			 * If this is the first notice that this address is
4098 			 * ready, then let the user know now.
4099 			 */
4100 			if ((ipif->ipif_flags & IPIF_UP) &&
4101 			    !ipif->ipif_addr_ready) {
4102 				ipif_mask_reply(ipif);
4103 				ipif_up_notify(ipif);
4104 			}
4105 			ipif->ipif_addr_ready = 1;
4106 			ipif_refrele(ipif);
4107 		}
4108 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4109 		if (ire != NULL) {
4110 			ire->ire_defense_count = 0;
4111 			ire_refrele(ire);
4112 		}
4113 		break;
4114 	case AR_CN_FAILED:
4115 		/* No external v6 resolver has a contract to use this */
4116 		if (isv6)
4117 			break;
4118 		if (!ill->ill_arp_extend) {
4119 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4120 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4121 			(void) ip_dot_addr(src, sbuf);
4122 
4123 			cmn_err(CE_WARN,
4124 			    "node %s is using our IP address %s on %s",
4125 			    hbuf, sbuf, ill->ill_name);
4126 			break;
4127 		}
4128 		ill_refhold(ill);
4129 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4130 		return;
4131 	}
4132 	freemsg(mp);
4133 }
4134 
4135 /*
4136  * Create a mblk suitable for carrying the interface index and/or source link
4137  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4138  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4139  * application.
4140  */
4141 mblk_t *
4142 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4143     ip_stack_t *ipst)
4144 {
4145 	mblk_t		*mp;
4146 	ip_pktinfo_t	*pinfo;
4147 	ipha_t 		*ipha;
4148 	struct ether_header *pether;
4149 	boolean_t	ipmp_ill_held = B_FALSE;
4150 
4151 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4152 	if (mp == NULL) {
4153 		ip1dbg(("ip_add_info: allocation failure.\n"));
4154 		return (data_mp);
4155 	}
4156 
4157 	ipha = (ipha_t *)data_mp->b_rptr;
4158 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4159 	bzero(pinfo, sizeof (ip_pktinfo_t));
4160 	pinfo->ip_pkt_flags = (uchar_t)flags;
4161 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4162 
4163 	pether = (struct ether_header *)((char *)ipha
4164 	    - sizeof (struct ether_header));
4165 
4166 	/*
4167 	 * Make sure the interface is an ethernet type, since this option
4168 	 * is currently supported only on this type of interface. Also make
4169 	 * sure we are pointing correctly above db_base.
4170 	 */
4171 	if ((flags & IPF_RECVSLLA) &&
4172 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4173 	    (ill->ill_type == IFT_ETHER) &&
4174 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4175 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4176 		bcopy(pether->ether_shost.ether_addr_octet,
4177 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4178 	} else {
4179 		/*
4180 		 * Clear the bit. Indicate to upper layer that IP is not
4181 		 * sending this ancillary info.
4182 		 */
4183 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4184 	}
4185 
4186 	/*
4187 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4188 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4189 	 * IPF_RECVADDR support on test addresses is not needed.)
4190 	 *
4191 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4192 	 * processing a packet looped back to an IPMP data address
4193 	 * (since those IRE_LOCALs are tied to IPMP ills).
4194 	 */
4195 	if (IS_UNDER_IPMP(ill)) {
4196 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4197 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4198 			freemsg(mp);
4199 			return (data_mp);
4200 		}
4201 		ipmp_ill_held = B_TRUE;
4202 	}
4203 
4204 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4205 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4206 	if (flags & IPF_RECVADDR) {
4207 		ipif_t	*ipif;
4208 		ire_t	*ire;
4209 
4210 		/*
4211 		 * Only valid for V4
4212 		 */
4213 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4214 		    (IPV4_VERSION << 4));
4215 
4216 		ipif = ipif_get_next_ipif(NULL, ill);
4217 		if (ipif != NULL) {
4218 			/*
4219 			 * Since a decision has already been made to deliver the
4220 			 * packet, there is no need to test for SECATTR and
4221 			 * ZONEONLY.
4222 			 * When a multicast packet is transmitted
4223 			 * a cache entry is created for the multicast address.
4224 			 * When delivering a copy of the packet or when new
4225 			 * packets are received we do not want to match on the
4226 			 * cached entry so explicitly match on
4227 			 * IRE_LOCAL and IRE_LOOPBACK
4228 			 */
4229 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4230 			    IRE_LOCAL | IRE_LOOPBACK,
4231 			    ipif, zoneid, NULL,
4232 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4233 			if (ire == NULL) {
4234 				/*
4235 				 * packet must have come on a different
4236 				 * interface.
4237 				 * Since a decision has already been made to
4238 				 * deliver the packet, there is no need to test
4239 				 * for SECATTR and ZONEONLY.
4240 				 * Only match on local and broadcast ire's.
4241 				 * See detailed comment above.
4242 				 */
4243 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4244 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4245 				    NULL, MATCH_IRE_TYPE, ipst);
4246 			}
4247 
4248 			if (ire == NULL) {
4249 				/*
4250 				 * This is either a multicast packet or
4251 				 * the address has been removed since
4252 				 * the packet was received.
4253 				 * Return INADDR_ANY so that normal source
4254 				 * selection occurs for the response.
4255 				 */
4256 
4257 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4258 			} else {
4259 				pinfo->ip_pkt_match_addr.s_addr =
4260 				    ire->ire_src_addr;
4261 				ire_refrele(ire);
4262 			}
4263 			ipif_refrele(ipif);
4264 		} else {
4265 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4266 		}
4267 	}
4268 
4269 	if (ipmp_ill_held)
4270 		ill_refrele(ill);
4271 
4272 	mp->b_datap->db_type = M_CTL;
4273 	mp->b_wptr += sizeof (ip_pktinfo_t);
4274 	mp->b_cont = data_mp;
4275 
4276 	return (mp);
4277 }
4278 
4279 /*
4280  * Used to determine the most accurate cred_t to use for TX.
4281  * First priority is SCM_UCRED having set the label in the message,
4282  * which is used for MLP on UDP. Second priority is the open credentials
4283  * with the peer's label (aka conn_effective_cred), which is needed for
4284  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4285  */
4286 cred_t *
4287 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4288 {
4289 	cred_t *cr;
4290 
4291 	cr = msg_getcred(mp, pidp);
4292 	if (cr != NULL && crgetlabel(cr) != NULL)
4293 		return (cr);
4294 	*pidp = NOPID;
4295 	return (CONN_CRED(connp));
4296 }
4297 
4298 /*
4299  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4300  * part of the bind request.
4301  */
4302 
4303 boolean_t
4304 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4305 {
4306 	ipsec_in_t *ii;
4307 
4308 	ASSERT(policy_mp != NULL);
4309 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4310 
4311 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4312 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4313 
4314 	connp->conn_policy = ii->ipsec_in_policy;
4315 	ii->ipsec_in_policy = NULL;
4316 
4317 	if (ii->ipsec_in_action != NULL) {
4318 		if (connp->conn_latch == NULL) {
4319 			connp->conn_latch = iplatch_create();
4320 			if (connp->conn_latch == NULL)
4321 				return (B_FALSE);
4322 		}
4323 		ipsec_latch_inbound(connp->conn_latch, ii);
4324 	}
4325 	return (B_TRUE);
4326 }
4327 
4328 /*
4329  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4330  * and to arrange for power-fanout assist.  The ULP is identified by
4331  * adding a single byte at the end of the original bind message.
4332  * A ULP other than UDP or TCP that wishes to be recognized passes
4333  * down a bind with a zero length address.
4334  *
4335  * The binding works as follows:
4336  * - A zero byte address means just bind to the protocol.
4337  * - A four byte address is treated as a request to validate
4338  *   that the address is a valid local address, appropriate for
4339  *   an application to bind to. This does not affect any fanout
4340  *   information in IP.
4341  * - A sizeof sin_t byte address is used to bind to only the local address
4342  *   and port.
4343  * - A sizeof ipa_conn_t byte address contains complete fanout information
4344  *   consisting of local and remote addresses and ports.  In
4345  *   this case, the addresses are both validated as appropriate
4346  *   for this operation, and, if so, the information is retained
4347  *   for use in the inbound fanout.
4348  *
4349  * The ULP (except in the zero-length bind) can append an
4350  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4351  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4352  * a copy of the source or destination IRE (source for local bind;
4353  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4354  * policy information contained should be copied on to the conn.
4355  *
4356  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4357  */
4358 mblk_t *
4359 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4360 {
4361 	ssize_t		len;
4362 	struct T_bind_req	*tbr;
4363 	sin_t		*sin;
4364 	ipa_conn_t	*ac;
4365 	uchar_t		*ucp;
4366 	mblk_t		*mp1;
4367 	int		error = 0;
4368 	int		protocol;
4369 	ipa_conn_x_t	*acx;
4370 	cred_t		*cr;
4371 
4372 	/*
4373 	 * All Solaris components should pass a db_credp
4374 	 * for this TPI message, hence we ASSERT.
4375 	 * But in case there is some other M_PROTO that looks
4376 	 * like a TPI message sent by some other kernel
4377 	 * component, we check and return an error.
4378 	 */
4379 	cr = msg_getcred(mp, NULL);
4380 	ASSERT(cr != NULL);
4381 	if (cr == NULL) {
4382 		error = EINVAL;
4383 		goto bad_addr;
4384 	}
4385 
4386 	ASSERT(!connp->conn_af_isv6);
4387 	connp->conn_pkt_isv6 = B_FALSE;
4388 
4389 	len = MBLKL(mp);
4390 	if (len < (sizeof (*tbr) + 1)) {
4391 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4392 		    "ip_bind: bogus msg, len %ld", len);
4393 		/* XXX: Need to return something better */
4394 		goto bad_addr;
4395 	}
4396 	/* Back up and extract the protocol identifier. */
4397 	mp->b_wptr--;
4398 	protocol = *mp->b_wptr & 0xFF;
4399 	tbr = (struct T_bind_req *)mp->b_rptr;
4400 	/* Reset the message type in preparation for shipping it back. */
4401 	DB_TYPE(mp) = M_PCPROTO;
4402 
4403 	connp->conn_ulp = (uint8_t)protocol;
4404 
4405 	/*
4406 	 * Check for a zero length address.  This is from a protocol that
4407 	 * wants to register to receive all packets of its type.
4408 	 */
4409 	if (tbr->ADDR_length == 0) {
4410 		/*
4411 		 * These protocols are now intercepted in ip_bind_v6().
4412 		 * Reject protocol-level binds here for now.
4413 		 *
4414 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4415 		 * so that the protocol type cannot be SCTP.
4416 		 */
4417 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4418 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4419 			goto bad_addr;
4420 		}
4421 
4422 		/*
4423 		 *
4424 		 * The udp module never sends down a zero-length address,
4425 		 * and allowing this on a labeled system will break MLP
4426 		 * functionality.
4427 		 */
4428 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4429 			goto bad_addr;
4430 
4431 		if (connp->conn_mac_exempt)
4432 			goto bad_addr;
4433 
4434 		/* No hash here really.  The table is big enough. */
4435 		connp->conn_srcv6 = ipv6_all_zeros;
4436 
4437 		ipcl_proto_insert(connp, protocol);
4438 
4439 		tbr->PRIM_type = T_BIND_ACK;
4440 		return (mp);
4441 	}
4442 
4443 	/* Extract the address pointer from the message. */
4444 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4445 	    tbr->ADDR_length);
4446 	if (ucp == NULL) {
4447 		ip1dbg(("ip_bind: no address\n"));
4448 		goto bad_addr;
4449 	}
4450 	if (!OK_32PTR(ucp)) {
4451 		ip1dbg(("ip_bind: unaligned address\n"));
4452 		goto bad_addr;
4453 	}
4454 	/*
4455 	 * Check for trailing mps.
4456 	 */
4457 	mp1 = mp->b_cont;
4458 
4459 	switch (tbr->ADDR_length) {
4460 	default:
4461 		ip1dbg(("ip_bind: bad address length %d\n",
4462 		    (int)tbr->ADDR_length));
4463 		goto bad_addr;
4464 
4465 	case IP_ADDR_LEN:
4466 		/* Verification of local address only */
4467 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4468 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4469 		break;
4470 
4471 	case sizeof (sin_t):
4472 		sin = (sin_t *)ucp;
4473 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4474 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4475 		break;
4476 
4477 	case sizeof (ipa_conn_t):
4478 		ac = (ipa_conn_t *)ucp;
4479 		/* For raw socket, the local port is not set. */
4480 		if (ac->ac_lport == 0)
4481 			ac->ac_lport = connp->conn_lport;
4482 		/* Always verify destination reachability. */
4483 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4484 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4485 		    B_TRUE, B_TRUE, cr);
4486 		break;
4487 
4488 	case sizeof (ipa_conn_x_t):
4489 		acx = (ipa_conn_x_t *)ucp;
4490 		/*
4491 		 * Whether or not to verify destination reachability depends
4492 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4493 		 */
4494 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4495 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4496 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4497 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4498 		break;
4499 	}
4500 	ASSERT(error != EINPROGRESS);
4501 	if (error != 0)
4502 		goto bad_addr;
4503 
4504 	/* Send it home. */
4505 	mp->b_datap->db_type = M_PCPROTO;
4506 	tbr->PRIM_type = T_BIND_ACK;
4507 	return (mp);
4508 
4509 bad_addr:
4510 	/*
4511 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4512 	 * a unix errno.
4513 	 */
4514 	if (error > 0)
4515 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4516 	else
4517 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4518 	return (mp);
4519 }
4520 
4521 /*
4522  * Here address is verified to be a valid local address.
4523  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4524  * address is also considered a valid local address.
4525  * In the case of a broadcast/multicast address, however, the
4526  * upper protocol is expected to reset the src address
4527  * to 0 if it sees a IRE_BROADCAST type returned so that
4528  * no packets are emitted with broadcast/multicast address as
4529  * source address (that violates hosts requirements RFC 1122)
4530  * The addresses valid for bind are:
4531  *	(1) - INADDR_ANY (0)
4532  *	(2) - IP address of an UP interface
4533  *	(3) - IP address of a DOWN interface
4534  *	(4) - valid local IP broadcast addresses. In this case
4535  *	the conn will only receive packets destined to
4536  *	the specified broadcast address.
4537  *	(5) - a multicast address. In this case
4538  *	the conn will only receive packets destined to
4539  *	the specified multicast address. Note: the
4540  *	application still has to issue an
4541  *	IP_ADD_MEMBERSHIP socket option.
4542  *
4543  * On error, return -1 for TBADADDR otherwise pass the
4544  * errno with TSYSERR reply.
4545  *
4546  * In all the above cases, the bound address must be valid in the current zone.
4547  * When the address is loopback, multicast or broadcast, there might be many
4548  * matching IREs so bind has to look up based on the zone.
4549  *
4550  * Note: lport is in network byte order.
4551  *
4552  */
4553 int
4554 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4555     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4556 {
4557 	int		error = 0;
4558 	ire_t		*src_ire;
4559 	zoneid_t	zoneid;
4560 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4561 	mblk_t		*mp = NULL;
4562 	boolean_t	ire_requested = B_FALSE;
4563 	boolean_t	ipsec_policy_set = B_FALSE;
4564 
4565 	if (mpp)
4566 		mp = *mpp;
4567 
4568 	if (mp != NULL) {
4569 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4570 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4571 	}
4572 
4573 	/*
4574 	 * If it was previously connected, conn_fully_bound would have
4575 	 * been set.
4576 	 */
4577 	connp->conn_fully_bound = B_FALSE;
4578 
4579 	src_ire = NULL;
4580 
4581 	zoneid = IPCL_ZONEID(connp);
4582 
4583 	if (src_addr) {
4584 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4585 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4586 		/*
4587 		 * If an address other than 0.0.0.0 is requested,
4588 		 * we verify that it is a valid address for bind
4589 		 * Note: Following code is in if-else-if form for
4590 		 * readability compared to a condition check.
4591 		 */
4592 		/* LINTED - statement has no consequence */
4593 		if (IRE_IS_LOCAL(src_ire)) {
4594 			/*
4595 			 * (2) Bind to address of local UP interface
4596 			 */
4597 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4598 			/*
4599 			 * (4) Bind to broadcast address
4600 			 * Note: permitted only from transports that
4601 			 * request IRE
4602 			 */
4603 			if (!ire_requested)
4604 				error = EADDRNOTAVAIL;
4605 		} else {
4606 			/*
4607 			 * (3) Bind to address of local DOWN interface
4608 			 * (ipif_lookup_addr() looks up all interfaces
4609 			 * but we do not get here for UP interfaces
4610 			 * - case (2) above)
4611 			 */
4612 			/* LINTED - statement has no consequent */
4613 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4614 				/* The address exists */
4615 			} else if (CLASSD(src_addr)) {
4616 				error = 0;
4617 				if (src_ire != NULL)
4618 					ire_refrele(src_ire);
4619 				/*
4620 				 * (5) bind to multicast address.
4621 				 * Fake out the IRE returned to upper
4622 				 * layer to be a broadcast IRE.
4623 				 */
4624 				src_ire = ire_ctable_lookup(
4625 				    INADDR_BROADCAST, INADDR_ANY,
4626 				    IRE_BROADCAST, NULL, zoneid, NULL,
4627 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4628 				    ipst);
4629 				if (src_ire == NULL || !ire_requested)
4630 					error = EADDRNOTAVAIL;
4631 			} else {
4632 				/*
4633 				 * Not a valid address for bind
4634 				 */
4635 				error = EADDRNOTAVAIL;
4636 			}
4637 		}
4638 		if (error) {
4639 			/* Red Alert!  Attempting to be a bogon! */
4640 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4641 			    ntohl(src_addr)));
4642 			goto bad_addr;
4643 		}
4644 	}
4645 
4646 	/*
4647 	 * Allow setting new policies. For example, disconnects come
4648 	 * down as ipa_t bind. As we would have set conn_policy_cached
4649 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4650 	 * can change after the disconnect.
4651 	 */
4652 	connp->conn_policy_cached = B_FALSE;
4653 
4654 	/*
4655 	 * If not fanout_insert this was just an address verification
4656 	 */
4657 	if (fanout_insert) {
4658 		/*
4659 		 * The addresses have been verified. Time to insert in
4660 		 * the correct fanout list.
4661 		 */
4662 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4663 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4664 		connp->conn_lport = lport;
4665 		connp->conn_fport = 0;
4666 		/*
4667 		 * Do we need to add a check to reject Multicast packets
4668 		 */
4669 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4670 	}
4671 
4672 	if (error == 0) {
4673 		if (ire_requested) {
4674 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4675 				error = -1;
4676 				/* Falls through to bad_addr */
4677 			}
4678 		} else if (ipsec_policy_set) {
4679 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4680 				error = -1;
4681 				/* Falls through to bad_addr */
4682 			}
4683 		}
4684 	}
4685 bad_addr:
4686 	if (error != 0) {
4687 		if (connp->conn_anon_port) {
4688 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4689 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4690 			    B_FALSE);
4691 		}
4692 		connp->conn_mlp_type = mlptSingle;
4693 	}
4694 	if (src_ire != NULL)
4695 		IRE_REFRELE(src_ire);
4696 	return (error);
4697 }
4698 
4699 int
4700 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4701     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4702 {
4703 	int error;
4704 
4705 	ASSERT(!connp->conn_af_isv6);
4706 	connp->conn_pkt_isv6 = B_FALSE;
4707 	connp->conn_ulp = protocol;
4708 
4709 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4710 	    fanout_insert);
4711 	if (error < 0)
4712 		error = -TBADADDR;
4713 	return (error);
4714 }
4715 
4716 /*
4717  * Verify that both the source and destination addresses
4718  * are valid.  If verify_dst is false, then the destination address may be
4719  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4720  * destination reachability, while tunnels do not.
4721  * Note that we allow connect to broadcast and multicast
4722  * addresses when ire_requested is set. Thus the ULP
4723  * has to check for IRE_BROADCAST and multicast.
4724  *
4725  * Returns zero if ok.
4726  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4727  * (for use with TSYSERR reply).
4728  *
4729  * Note: lport and fport are in network byte order.
4730  */
4731 int
4732 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4733     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4734     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4735 {
4736 
4737 	ire_t		*src_ire;
4738 	ire_t		*dst_ire;
4739 	int		error = 0;
4740 	ire_t		*sire = NULL;
4741 	ire_t		*md_dst_ire = NULL;
4742 	ire_t		*lso_dst_ire = NULL;
4743 	ill_t		*ill = NULL;
4744 	zoneid_t	zoneid;
4745 	ipaddr_t	src_addr = *src_addrp;
4746 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4747 	mblk_t		*mp = NULL;
4748 	boolean_t	ire_requested = B_FALSE;
4749 	boolean_t	ipsec_policy_set = B_FALSE;
4750 	ts_label_t	*tsl = NULL;
4751 	cred_t		*effective_cred = NULL;
4752 
4753 	if (mpp)
4754 		mp = *mpp;
4755 
4756 	if (mp != NULL) {
4757 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4758 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4759 	}
4760 
4761 	src_ire = dst_ire = NULL;
4762 
4763 	/*
4764 	 * If we never got a disconnect before, clear it now.
4765 	 */
4766 	connp->conn_fully_bound = B_FALSE;
4767 
4768 	zoneid = IPCL_ZONEID(connp);
4769 
4770 	/*
4771 	 * Check whether Trusted Solaris policy allows communication with this
4772 	 * host, and pretend that the destination is unreachable if not.
4773 	 *
4774 	 * This is never a problem for TCP, since that transport is known to
4775 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4776 	 * handling.  If the remote is unreachable, it will be detected at that
4777 	 * point, so there's no reason to check it here.
4778 	 *
4779 	 * Note that for sendto (and other datagram-oriented friends), this
4780 	 * check is done as part of the data path label computation instead.
4781 	 * The check here is just to make non-TCP connect() report the right
4782 	 * error.
4783 	 */
4784 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4785 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4786 		    connp->conn_mac_exempt, &effective_cred)) != 0) {
4787 			if (ip_debug > 2) {
4788 				pr_addr_dbg(
4789 				    "ip_bind_connected_v4:"
4790 				    " no label for dst %s\n",
4791 				    AF_INET, &dst_addr);
4792 			}
4793 			goto bad_addr;
4794 		}
4795 
4796 		/*
4797 		 * tsol_check_dest() may have created a new cred with
4798 		 * a modified security label. Use that cred if it exists
4799 		 * for ire lookups.
4800 		 */
4801 		if (effective_cred == NULL) {
4802 			tsl = crgetlabel(cr);
4803 		} else {
4804 			tsl = crgetlabel(effective_cred);
4805 		}
4806 	}
4807 
4808 	if (CLASSD(dst_addr)) {
4809 		/* Pick up an IRE_BROADCAST */
4810 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4811 		    NULL, zoneid, tsl,
4812 		    (MATCH_IRE_RECURSIVE |
4813 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4814 		    MATCH_IRE_SECATTR), ipst);
4815 	} else {
4816 		/*
4817 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4818 		 * and onlink ipif is not found set ENETUNREACH error.
4819 		 */
4820 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4821 			ipif_t *ipif;
4822 
4823 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4824 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4825 			if (ipif == NULL) {
4826 				error = ENETUNREACH;
4827 				goto bad_addr;
4828 			}
4829 			ipif_refrele(ipif);
4830 		}
4831 
4832 		if (connp->conn_nexthop_set) {
4833 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4834 			    0, 0, NULL, NULL, zoneid, tsl,
4835 			    MATCH_IRE_SECATTR, ipst);
4836 		} else {
4837 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4838 			    &sire, zoneid, tsl,
4839 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4840 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4841 			    MATCH_IRE_SECATTR), ipst);
4842 		}
4843 	}
4844 	/*
4845 	 * dst_ire can't be a broadcast when not ire_requested.
4846 	 * We also prevent ire's with src address INADDR_ANY to
4847 	 * be used, which are created temporarily for
4848 	 * sending out packets from endpoints that have
4849 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4850 	 * reachable.  If verify_dst is false, the destination needn't be
4851 	 * reachable.
4852 	 *
4853 	 * If we match on a reject or black hole, then we've got a
4854 	 * local failure.  May as well fail out the connect() attempt,
4855 	 * since it's never going to succeed.
4856 	 */
4857 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4858 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4859 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4860 		/*
4861 		 * If we're verifying destination reachability, we always want
4862 		 * to complain here.
4863 		 *
4864 		 * If we're not verifying destination reachability but the
4865 		 * destination has a route, we still want to fail on the
4866 		 * temporary address and broadcast address tests.
4867 		 */
4868 		if (verify_dst || (dst_ire != NULL)) {
4869 			if (ip_debug > 2) {
4870 				pr_addr_dbg("ip_bind_connected_v4:"
4871 				    "bad connected dst %s\n",
4872 				    AF_INET, &dst_addr);
4873 			}
4874 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4875 				error = ENETUNREACH;
4876 			else
4877 				error = EHOSTUNREACH;
4878 			goto bad_addr;
4879 		}
4880 	}
4881 
4882 	/*
4883 	 * If the app does a connect(), it means that it will most likely
4884 	 * send more than 1 packet to the destination.  It makes sense
4885 	 * to clear the temporary flag.
4886 	 */
4887 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4888 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4889 		irb_t *irb = dst_ire->ire_bucket;
4890 
4891 		rw_enter(&irb->irb_lock, RW_WRITER);
4892 		/*
4893 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4894 		 * the lock to guarantee irb_tmp_ire_cnt.
4895 		 */
4896 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4897 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4898 			irb->irb_tmp_ire_cnt--;
4899 		}
4900 		rw_exit(&irb->irb_lock);
4901 	}
4902 
4903 	/*
4904 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4905 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4906 	 * eligibility tests for passive connects are handled separately
4907 	 * through tcp_adapt_ire().  We do this before the source address
4908 	 * selection, because dst_ire may change after a call to
4909 	 * ipif_select_source().  This is a best-effort check, as the
4910 	 * packet for this connection may not actually go through
4911 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4912 	 * calling ip_newroute().  This is why we further check on the
4913 	 * IRE during LSO/Multidata packet transmission in
4914 	 * tcp_lsosend()/tcp_multisend().
4915 	 */
4916 	if (!ipsec_policy_set && dst_ire != NULL &&
4917 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4918 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4919 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4920 			lso_dst_ire = dst_ire;
4921 			IRE_REFHOLD(lso_dst_ire);
4922 		} else if (ipst->ips_ip_multidata_outbound &&
4923 		    ILL_MDT_CAPABLE(ill)) {
4924 			md_dst_ire = dst_ire;
4925 			IRE_REFHOLD(md_dst_ire);
4926 		}
4927 	}
4928 
4929 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4930 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4931 		/*
4932 		 * If the IRE belongs to a different zone, look for a matching
4933 		 * route in the forwarding table and use the source address from
4934 		 * that route.
4935 		 */
4936 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4937 		    zoneid, 0, NULL,
4938 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4939 		    MATCH_IRE_RJ_BHOLE, ipst);
4940 		if (src_ire == NULL) {
4941 			error = EHOSTUNREACH;
4942 			goto bad_addr;
4943 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4944 			if (!(src_ire->ire_type & IRE_HOST))
4945 				error = ENETUNREACH;
4946 			else
4947 				error = EHOSTUNREACH;
4948 			goto bad_addr;
4949 		}
4950 		if (src_addr == INADDR_ANY)
4951 			src_addr = src_ire->ire_src_addr;
4952 		ire_refrele(src_ire);
4953 		src_ire = NULL;
4954 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4955 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4956 			src_addr = sire->ire_src_addr;
4957 			ire_refrele(dst_ire);
4958 			dst_ire = sire;
4959 			sire = NULL;
4960 		} else {
4961 			/*
4962 			 * Pick a source address so that a proper inbound
4963 			 * load spreading would happen.
4964 			 */
4965 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
4966 			ipif_t *src_ipif = NULL;
4967 			ire_t *ipif_ire;
4968 
4969 			/*
4970 			 * Supply a local source address such that inbound
4971 			 * load spreading happens.
4972 			 *
4973 			 * Determine the best source address on this ill for
4974 			 * the destination.
4975 			 *
4976 			 * 1) For broadcast, we should return a broadcast ire
4977 			 *    found above so that upper layers know that the
4978 			 *    destination address is a broadcast address.
4979 			 *
4980 			 * 2) If the ipif is DEPRECATED, select a better
4981 			 *    source address.  Similarly, if the ipif is on
4982 			 *    the IPMP meta-interface, pick a source address
4983 			 *    at random to improve inbound load spreading.
4984 			 *
4985 			 * 3) If the outgoing interface is part of a usesrc
4986 			 *    group, then try selecting a source address from
4987 			 *    the usesrc ILL.
4988 			 */
4989 			if ((dst_ire->ire_zoneid != zoneid &&
4990 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4991 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4992 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4993 			    (IS_IPMP(ire_ill) ||
4994 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4995 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
4996 				/*
4997 				 * If the destination is reachable via a
4998 				 * given gateway, the selected source address
4999 				 * should be in the same subnet as the gateway.
5000 				 * Otherwise, the destination is not reachable.
5001 				 *
5002 				 * If there are no interfaces on the same subnet
5003 				 * as the destination, ipif_select_source gives
5004 				 * first non-deprecated interface which might be
5005 				 * on a different subnet than the gateway.
5006 				 * This is not desirable. Hence pass the dst_ire
5007 				 * source address to ipif_select_source.
5008 				 * It is sure that the destination is reachable
5009 				 * with the dst_ire source address subnet.
5010 				 * So passing dst_ire source address to
5011 				 * ipif_select_source will make sure that the
5012 				 * selected source will be on the same subnet
5013 				 * as dst_ire source address.
5014 				 */
5015 				ipaddr_t saddr =
5016 				    dst_ire->ire_ipif->ipif_src_addr;
5017 				src_ipif = ipif_select_source(ire_ill,
5018 				    saddr, zoneid);
5019 				if (src_ipif != NULL) {
5020 					if (IS_VNI(src_ipif->ipif_ill)) {
5021 						/*
5022 						 * For VNI there is no
5023 						 * interface route
5024 						 */
5025 						src_addr =
5026 						    src_ipif->ipif_src_addr;
5027 					} else {
5028 						ipif_ire =
5029 						    ipif_to_ire(src_ipif);
5030 						if (ipif_ire != NULL) {
5031 							IRE_REFRELE(dst_ire);
5032 							dst_ire = ipif_ire;
5033 						}
5034 						src_addr =
5035 						    dst_ire->ire_src_addr;
5036 					}
5037 					ipif_refrele(src_ipif);
5038 				} else {
5039 					src_addr = dst_ire->ire_src_addr;
5040 				}
5041 			} else {
5042 				src_addr = dst_ire->ire_src_addr;
5043 			}
5044 		}
5045 	}
5046 
5047 	/*
5048 	 * We do ire_route_lookup() here (and not
5049 	 * interface lookup as we assert that
5050 	 * src_addr should only come from an
5051 	 * UP interface for hard binding.
5052 	 */
5053 	ASSERT(src_ire == NULL);
5054 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5055 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5056 	/* src_ire must be a local|loopback */
5057 	if (!IRE_IS_LOCAL(src_ire)) {
5058 		if (ip_debug > 2) {
5059 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5060 			    "src %s\n", AF_INET, &src_addr);
5061 		}
5062 		error = EADDRNOTAVAIL;
5063 		goto bad_addr;
5064 	}
5065 
5066 	/*
5067 	 * If the source address is a loopback address, the
5068 	 * destination had best be local or multicast.
5069 	 * The transports that can't handle multicast will reject
5070 	 * those addresses.
5071 	 */
5072 	if (src_ire->ire_type == IRE_LOOPBACK &&
5073 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5074 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5075 		error = -1;
5076 		goto bad_addr;
5077 	}
5078 
5079 	/*
5080 	 * Allow setting new policies. For example, disconnects come
5081 	 * down as ipa_t bind. As we would have set conn_policy_cached
5082 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5083 	 * can change after the disconnect.
5084 	 */
5085 	connp->conn_policy_cached = B_FALSE;
5086 
5087 	/*
5088 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5089 	 * can handle their passed-in conn's.
5090 	 */
5091 
5092 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5093 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5094 	connp->conn_lport = lport;
5095 	connp->conn_fport = fport;
5096 	*src_addrp = src_addr;
5097 
5098 	ASSERT(!(ipsec_policy_set && ire_requested));
5099 	if (ire_requested) {
5100 		iulp_t *ulp_info = NULL;
5101 
5102 		/*
5103 		 * Note that sire will not be NULL if this is an off-link
5104 		 * connection and there is not cache for that dest yet.
5105 		 *
5106 		 * XXX Because of an existing bug, if there are multiple
5107 		 * default routes, the IRE returned now may not be the actual
5108 		 * default route used (default routes are chosen in a
5109 		 * round robin fashion).  So if the metrics for different
5110 		 * default routes are different, we may return the wrong
5111 		 * metrics.  This will not be a problem if the existing
5112 		 * bug is fixed.
5113 		 */
5114 		if (sire != NULL) {
5115 			ulp_info = &(sire->ire_uinfo);
5116 		}
5117 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5118 			error = -1;
5119 			goto bad_addr;
5120 		}
5121 		mp = *mpp;
5122 	} else if (ipsec_policy_set) {
5123 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5124 			error = -1;
5125 			goto bad_addr;
5126 		}
5127 	}
5128 
5129 	/*
5130 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5131 	 * we'll cache that.  If we don't, we'll inherit global policy.
5132 	 *
5133 	 * We can't insert until the conn reflects the policy. Note that
5134 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5135 	 * connections where we don't have a policy. This is to prevent
5136 	 * global policy lookups in the inbound path.
5137 	 *
5138 	 * If we insert before we set conn_policy_cached,
5139 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5140 	 * because global policy cound be non-empty. We normally call
5141 	 * ipsec_check_policy() for conn_policy_cached connections only if
5142 	 * ipc_in_enforce_policy is set. But in this case,
5143 	 * conn_policy_cached can get set anytime since we made the
5144 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5145 	 * called, which will make the above assumption false.  Thus, we
5146 	 * need to insert after we set conn_policy_cached.
5147 	 */
5148 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5149 		goto bad_addr;
5150 
5151 	if (fanout_insert) {
5152 		/*
5153 		 * The addresses have been verified. Time to insert in
5154 		 * the correct fanout list.
5155 		 */
5156 		error = ipcl_conn_insert(connp, protocol, src_addr,
5157 		    dst_addr, connp->conn_ports);
5158 	}
5159 
5160 	if (error == 0) {
5161 		connp->conn_fully_bound = B_TRUE;
5162 		/*
5163 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5164 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5165 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5166 		 * ip_xxinfo_return(), which performs further checks
5167 		 * against them and upon success, returns the LSO/MDT info
5168 		 * mblk which we will attach to the bind acknowledgment.
5169 		 */
5170 		if (lso_dst_ire != NULL) {
5171 			mblk_t *lsoinfo_mp;
5172 
5173 			ASSERT(ill->ill_lso_capab != NULL);
5174 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5175 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5176 				if (mp == NULL) {
5177 					*mpp = lsoinfo_mp;
5178 				} else {
5179 					linkb(mp, lsoinfo_mp);
5180 				}
5181 			}
5182 		} else if (md_dst_ire != NULL) {
5183 			mblk_t *mdinfo_mp;
5184 
5185 			ASSERT(ill->ill_mdt_capab != NULL);
5186 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5187 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5188 				if (mp == NULL) {
5189 					*mpp = mdinfo_mp;
5190 				} else {
5191 					linkb(mp, mdinfo_mp);
5192 				}
5193 			}
5194 		}
5195 	}
5196 bad_addr:
5197 	if (ipsec_policy_set) {
5198 		ASSERT(mp != NULL);
5199 		freeb(mp);
5200 		/*
5201 		 * As of now assume that nothing else accompanies
5202 		 * IPSEC_POLICY_SET.
5203 		 */
5204 		*mpp = NULL;
5205 	}
5206 	if (src_ire != NULL)
5207 		IRE_REFRELE(src_ire);
5208 	if (dst_ire != NULL)
5209 		IRE_REFRELE(dst_ire);
5210 	if (sire != NULL)
5211 		IRE_REFRELE(sire);
5212 	if (md_dst_ire != NULL)
5213 		IRE_REFRELE(md_dst_ire);
5214 	if (lso_dst_ire != NULL)
5215 		IRE_REFRELE(lso_dst_ire);
5216 	if (effective_cred != NULL)
5217 		crfree(effective_cred);
5218 	return (error);
5219 }
5220 
5221 int
5222 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5223     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5224     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5225 {
5226 	int error;
5227 
5228 	ASSERT(!connp->conn_af_isv6);
5229 	connp->conn_pkt_isv6 = B_FALSE;
5230 	connp->conn_ulp = protocol;
5231 
5232 	/* For raw socket, the local port is not set. */
5233 	if (lport == 0)
5234 		lport = connp->conn_lport;
5235 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5236 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5237 	if (error < 0)
5238 		error = -TBADADDR;
5239 	return (error);
5240 }
5241 
5242 /*
5243  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5244  * Prefers dst_ire over src_ire.
5245  */
5246 static boolean_t
5247 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5248 {
5249 	mblk_t	*mp = *mpp;
5250 	ire_t	*ret_ire;
5251 
5252 	ASSERT(mp != NULL);
5253 
5254 	if (ire != NULL) {
5255 		/*
5256 		 * mp initialized above to IRE_DB_REQ_TYPE
5257 		 * appended mblk. Its <upper protocol>'s
5258 		 * job to make sure there is room.
5259 		 */
5260 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5261 			return (B_FALSE);
5262 
5263 		mp->b_datap->db_type = IRE_DB_TYPE;
5264 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5265 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5266 		ret_ire = (ire_t *)mp->b_rptr;
5267 		/*
5268 		 * Pass the latest setting of the ip_path_mtu_discovery and
5269 		 * copy the ulp info if any.
5270 		 */
5271 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5272 		    IPH_DF : 0;
5273 		if (ulp_info != NULL) {
5274 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5275 			    sizeof (iulp_t));
5276 		}
5277 		ret_ire->ire_mp = mp;
5278 	} else {
5279 		/*
5280 		 * No IRE was found. Remove IRE mblk.
5281 		 */
5282 		*mpp = mp->b_cont;
5283 		freeb(mp);
5284 	}
5285 	return (B_TRUE);
5286 }
5287 
5288 /*
5289  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5290  * the final piece where we don't.  Return a pointer to the first mblk in the
5291  * result, and update the pointer to the next mblk to chew on.  If anything
5292  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5293  * NULL pointer.
5294  */
5295 mblk_t *
5296 ip_carve_mp(mblk_t **mpp, ssize_t len)
5297 {
5298 	mblk_t	*mp0;
5299 	mblk_t	*mp1;
5300 	mblk_t	*mp2;
5301 
5302 	if (!len || !mpp || !(mp0 = *mpp))
5303 		return (NULL);
5304 	/* If we aren't going to consume the first mblk, we need a dup. */
5305 	if (mp0->b_wptr - mp0->b_rptr > len) {
5306 		mp1 = dupb(mp0);
5307 		if (mp1) {
5308 			/* Partition the data between the two mblks. */
5309 			mp1->b_wptr = mp1->b_rptr + len;
5310 			mp0->b_rptr = mp1->b_wptr;
5311 			/*
5312 			 * after adjustments if mblk not consumed is now
5313 			 * unaligned, try to align it. If this fails free
5314 			 * all messages and let upper layer recover.
5315 			 */
5316 			if (!OK_32PTR(mp0->b_rptr)) {
5317 				if (!pullupmsg(mp0, -1)) {
5318 					freemsg(mp0);
5319 					freemsg(mp1);
5320 					*mpp = NULL;
5321 					return (NULL);
5322 				}
5323 			}
5324 		}
5325 		return (mp1);
5326 	}
5327 	/* Eat through as many mblks as we need to get len bytes. */
5328 	len -= mp0->b_wptr - mp0->b_rptr;
5329 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5330 		if (mp2->b_wptr - mp2->b_rptr > len) {
5331 			/*
5332 			 * We won't consume the entire last mblk.  Like
5333 			 * above, dup and partition it.
5334 			 */
5335 			mp1->b_cont = dupb(mp2);
5336 			mp1 = mp1->b_cont;
5337 			if (!mp1) {
5338 				/*
5339 				 * Trouble.  Rather than go to a lot of
5340 				 * trouble to clean up, we free the messages.
5341 				 * This won't be any worse than losing it on
5342 				 * the wire.
5343 				 */
5344 				freemsg(mp0);
5345 				freemsg(mp2);
5346 				*mpp = NULL;
5347 				return (NULL);
5348 			}
5349 			mp1->b_wptr = mp1->b_rptr + len;
5350 			mp2->b_rptr = mp1->b_wptr;
5351 			/*
5352 			 * after adjustments if mblk not consumed is now
5353 			 * unaligned, try to align it. If this fails free
5354 			 * all messages and let upper layer recover.
5355 			 */
5356 			if (!OK_32PTR(mp2->b_rptr)) {
5357 				if (!pullupmsg(mp2, -1)) {
5358 					freemsg(mp0);
5359 					freemsg(mp2);
5360 					*mpp = NULL;
5361 					return (NULL);
5362 				}
5363 			}
5364 			*mpp = mp2;
5365 			return (mp0);
5366 		}
5367 		/* Decrement len by the amount we just got. */
5368 		len -= mp2->b_wptr - mp2->b_rptr;
5369 	}
5370 	/*
5371 	 * len should be reduced to zero now.  If not our caller has
5372 	 * screwed up.
5373 	 */
5374 	if (len) {
5375 		/* Shouldn't happen! */
5376 		freemsg(mp0);
5377 		*mpp = NULL;
5378 		return (NULL);
5379 	}
5380 	/*
5381 	 * We consumed up to exactly the end of an mblk.  Detach the part
5382 	 * we are returning from the rest of the chain.
5383 	 */
5384 	mp1->b_cont = NULL;
5385 	*mpp = mp2;
5386 	return (mp0);
5387 }
5388 
5389 /* The ill stream is being unplumbed. Called from ip_close */
5390 int
5391 ip_modclose(ill_t *ill)
5392 {
5393 	boolean_t success;
5394 	ipsq_t	*ipsq;
5395 	ipif_t	*ipif;
5396 	queue_t	*q = ill->ill_rq;
5397 	ip_stack_t	*ipst = ill->ill_ipst;
5398 	int	i;
5399 
5400 	/*
5401 	 * The punlink prior to this may have initiated a capability
5402 	 * negotiation. But ipsq_enter will block until that finishes or
5403 	 * times out.
5404 	 */
5405 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5406 
5407 	/*
5408 	 * Open/close/push/pop is guaranteed to be single threaded
5409 	 * per stream by STREAMS. FS guarantees that all references
5410 	 * from top are gone before close is called. So there can't
5411 	 * be another close thread that has set CONDEMNED on this ill.
5412 	 * and cause ipsq_enter to return failure.
5413 	 */
5414 	ASSERT(success);
5415 	ipsq = ill->ill_phyint->phyint_ipsq;
5416 
5417 	/*
5418 	 * Mark it condemned. No new reference will be made to this ill.
5419 	 * Lookup functions will return an error. Threads that try to
5420 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5421 	 * that the refcnt will drop down to zero.
5422 	 */
5423 	mutex_enter(&ill->ill_lock);
5424 	ill->ill_state_flags |= ILL_CONDEMNED;
5425 	for (ipif = ill->ill_ipif; ipif != NULL;
5426 	    ipif = ipif->ipif_next) {
5427 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5428 	}
5429 	/*
5430 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5431 	 * returns  error if ILL_CONDEMNED is set
5432 	 */
5433 	cv_broadcast(&ill->ill_cv);
5434 	mutex_exit(&ill->ill_lock);
5435 
5436 	/*
5437 	 * Send all the deferred DLPI messages downstream which came in
5438 	 * during the small window right before ipsq_enter(). We do this
5439 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5440 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5441 	 */
5442 	ill_dlpi_send_deferred(ill);
5443 
5444 	/*
5445 	 * Shut down fragmentation reassembly.
5446 	 * ill_frag_timer won't start a timer again.
5447 	 * Now cancel any existing timer
5448 	 */
5449 	(void) untimeout(ill->ill_frag_timer_id);
5450 	(void) ill_frag_timeout(ill, 0);
5451 
5452 	/*
5453 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5454 	 * this ill. Then wait for the refcnts to drop to zero.
5455 	 * ill_is_freeable checks whether the ill is really quiescent.
5456 	 * Then make sure that threads that are waiting to enter the
5457 	 * ipsq have seen the error returned by ipsq_enter and have
5458 	 * gone away. Then we call ill_delete_tail which does the
5459 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5460 	 */
5461 	ill_delete(ill);
5462 	mutex_enter(&ill->ill_lock);
5463 	while (!ill_is_freeable(ill))
5464 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5465 	while (ill->ill_waiters)
5466 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5467 
5468 	mutex_exit(&ill->ill_lock);
5469 
5470 	/*
5471 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5472 	 * it held until the end of the function since the cleanup
5473 	 * below needs to be able to use the ip_stack_t.
5474 	 */
5475 	netstack_hold(ipst->ips_netstack);
5476 
5477 	/* qprocsoff is done via ill_delete_tail */
5478 	ill_delete_tail(ill);
5479 	ASSERT(ill->ill_ipst == NULL);
5480 
5481 	/*
5482 	 * Walk through all upper (conn) streams and qenable
5483 	 * those that have queued data.
5484 	 * close synchronization needs this to
5485 	 * be done to ensure that all upper layers blocked
5486 	 * due to flow control to the closing device
5487 	 * get unblocked.
5488 	 */
5489 	ip1dbg(("ip_wsrv: walking\n"));
5490 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5491 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5492 	}
5493 
5494 	mutex_enter(&ipst->ips_ip_mi_lock);
5495 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5496 	mutex_exit(&ipst->ips_ip_mi_lock);
5497 
5498 	/*
5499 	 * credp could be null if the open didn't succeed and ip_modopen
5500 	 * itself calls ip_close.
5501 	 */
5502 	if (ill->ill_credp != NULL)
5503 		crfree(ill->ill_credp);
5504 
5505 	/*
5506 	 * Now we are done with the module close pieces that
5507 	 * need the netstack_t.
5508 	 */
5509 	netstack_rele(ipst->ips_netstack);
5510 
5511 	mi_close_free((IDP)ill);
5512 	q->q_ptr = WR(q)->q_ptr = NULL;
5513 
5514 	ipsq_exit(ipsq);
5515 
5516 	return (0);
5517 }
5518 
5519 /*
5520  * This is called as part of close() for IP, UDP, ICMP, and RTS
5521  * in order to quiesce the conn.
5522  */
5523 void
5524 ip_quiesce_conn(conn_t *connp)
5525 {
5526 	boolean_t	drain_cleanup_reqd = B_FALSE;
5527 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5528 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5529 	ip_stack_t	*ipst;
5530 
5531 	ASSERT(!IPCL_IS_TCP(connp));
5532 	ipst = connp->conn_netstack->netstack_ip;
5533 
5534 	/*
5535 	 * Mark the conn as closing, and this conn must not be
5536 	 * inserted in future into any list. Eg. conn_drain_insert(),
5537 	 * won't insert this conn into the conn_drain_list.
5538 	 * Similarly ill_pending_mp_add() will not add any mp to
5539 	 * the pending mp list, after this conn has started closing.
5540 	 *
5541 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5542 	 * cannot get set henceforth.
5543 	 */
5544 	mutex_enter(&connp->conn_lock);
5545 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5546 	connp->conn_state_flags |= CONN_CLOSING;
5547 	if (connp->conn_idl != NULL)
5548 		drain_cleanup_reqd = B_TRUE;
5549 	if (connp->conn_oper_pending_ill != NULL)
5550 		conn_ioctl_cleanup_reqd = B_TRUE;
5551 	if (connp->conn_dhcpinit_ill != NULL) {
5552 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5553 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5554 		connp->conn_dhcpinit_ill = NULL;
5555 	}
5556 	if (connp->conn_ilg_inuse != 0)
5557 		ilg_cleanup_reqd = B_TRUE;
5558 	mutex_exit(&connp->conn_lock);
5559 
5560 	if (conn_ioctl_cleanup_reqd)
5561 		conn_ioctl_cleanup(connp);
5562 
5563 	if (is_system_labeled() && connp->conn_anon_port) {
5564 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5565 		    connp->conn_mlp_type, connp->conn_ulp,
5566 		    ntohs(connp->conn_lport), B_FALSE);
5567 		connp->conn_anon_port = 0;
5568 	}
5569 	connp->conn_mlp_type = mlptSingle;
5570 
5571 	/*
5572 	 * Remove this conn from any fanout list it is on.
5573 	 * and then wait for any threads currently operating
5574 	 * on this endpoint to finish
5575 	 */
5576 	ipcl_hash_remove(connp);
5577 
5578 	/*
5579 	 * Remove this conn from the drain list, and do
5580 	 * any other cleanup that may be required.
5581 	 * (Only non-tcp streams may have a non-null conn_idl.
5582 	 * TCP streams are never flow controlled, and
5583 	 * conn_idl will be null)
5584 	 */
5585 	if (drain_cleanup_reqd)
5586 		conn_drain_tail(connp, B_TRUE);
5587 
5588 	if (connp == ipst->ips_ip_g_mrouter)
5589 		(void) ip_mrouter_done(NULL, ipst);
5590 
5591 	if (ilg_cleanup_reqd)
5592 		ilg_delete_all(connp);
5593 
5594 	conn_delete_ire(connp, NULL);
5595 
5596 	/*
5597 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5598 	 * callers from write side can't be there now because close
5599 	 * is in progress. The only other caller is ipcl_walk
5600 	 * which checks for the condemned flag.
5601 	 */
5602 	mutex_enter(&connp->conn_lock);
5603 	connp->conn_state_flags |= CONN_CONDEMNED;
5604 	while (connp->conn_ref != 1)
5605 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5606 	connp->conn_state_flags |= CONN_QUIESCED;
5607 	mutex_exit(&connp->conn_lock);
5608 }
5609 
5610 /* ARGSUSED */
5611 int
5612 ip_close(queue_t *q, int flags)
5613 {
5614 	conn_t		*connp;
5615 
5616 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5617 
5618 	/*
5619 	 * Call the appropriate delete routine depending on whether this is
5620 	 * a module or device.
5621 	 */
5622 	if (WR(q)->q_next != NULL) {
5623 		/* This is a module close */
5624 		return (ip_modclose((ill_t *)q->q_ptr));
5625 	}
5626 
5627 	connp = q->q_ptr;
5628 	ip_quiesce_conn(connp);
5629 
5630 	qprocsoff(q);
5631 
5632 	/*
5633 	 * Now we are truly single threaded on this stream, and can
5634 	 * delete the things hanging off the connp, and finally the connp.
5635 	 * We removed this connp from the fanout list, it cannot be
5636 	 * accessed thru the fanouts, and we already waited for the
5637 	 * conn_ref to drop to 0. We are already in close, so
5638 	 * there cannot be any other thread from the top. qprocsoff
5639 	 * has completed, and service has completed or won't run in
5640 	 * future.
5641 	 */
5642 	ASSERT(connp->conn_ref == 1);
5643 
5644 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5645 
5646 	connp->conn_ref--;
5647 	ipcl_conn_destroy(connp);
5648 
5649 	q->q_ptr = WR(q)->q_ptr = NULL;
5650 	return (0);
5651 }
5652 
5653 /*
5654  * Wapper around putnext() so that ip_rts_request can merely use
5655  * conn_recv.
5656  */
5657 /*ARGSUSED2*/
5658 static void
5659 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5660 {
5661 	conn_t *connp = (conn_t *)arg1;
5662 
5663 	putnext(connp->conn_rq, mp);
5664 }
5665 
5666 /*
5667  * Called when the module is about to be unloaded
5668  */
5669 void
5670 ip_ddi_destroy(void)
5671 {
5672 	tnet_fini();
5673 
5674 	icmp_ddi_g_destroy();
5675 	rts_ddi_g_destroy();
5676 	udp_ddi_g_destroy();
5677 	sctp_ddi_g_destroy();
5678 	tcp_ddi_g_destroy();
5679 	ipsec_policy_g_destroy();
5680 	ipcl_g_destroy();
5681 	ip_net_g_destroy();
5682 	ip_ire_g_fini();
5683 	inet_minor_destroy(ip_minor_arena_sa);
5684 #if defined(_LP64)
5685 	inet_minor_destroy(ip_minor_arena_la);
5686 #endif
5687 
5688 #ifdef DEBUG
5689 	list_destroy(&ip_thread_list);
5690 	rw_destroy(&ip_thread_rwlock);
5691 	tsd_destroy(&ip_thread_data);
5692 #endif
5693 
5694 	netstack_unregister(NS_IP);
5695 }
5696 
5697 /*
5698  * First step in cleanup.
5699  */
5700 /* ARGSUSED */
5701 static void
5702 ip_stack_shutdown(netstackid_t stackid, void *arg)
5703 {
5704 	ip_stack_t *ipst = (ip_stack_t *)arg;
5705 
5706 #ifdef NS_DEBUG
5707 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5708 #endif
5709 
5710 	/* Get rid of loopback interfaces and their IREs */
5711 	ip_loopback_cleanup(ipst);
5712 
5713 	/*
5714 	 * The *_hook_shutdown()s start the process of notifying any
5715 	 * consumers that things are going away.... nothing is destroyed.
5716 	 */
5717 	ipv4_hook_shutdown(ipst);
5718 	ipv6_hook_shutdown(ipst);
5719 
5720 	mutex_enter(&ipst->ips_capab_taskq_lock);
5721 	ipst->ips_capab_taskq_quit = B_TRUE;
5722 	cv_signal(&ipst->ips_capab_taskq_cv);
5723 	mutex_exit(&ipst->ips_capab_taskq_lock);
5724 
5725 	mutex_enter(&ipst->ips_mrt_lock);
5726 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5727 	cv_signal(&ipst->ips_mrt_cv);
5728 	mutex_exit(&ipst->ips_mrt_lock);
5729 }
5730 
5731 /*
5732  * Free the IP stack instance.
5733  */
5734 static void
5735 ip_stack_fini(netstackid_t stackid, void *arg)
5736 {
5737 	ip_stack_t *ipst = (ip_stack_t *)arg;
5738 	int ret;
5739 
5740 #ifdef NS_DEBUG
5741 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5742 #endif
5743 	/*
5744 	 * At this point, all of the notifications that the events and
5745 	 * protocols are going away have been run, meaning that we can
5746 	 * now set about starting to clean things up.
5747 	 */
5748 	ipobs_fini(ipst);
5749 	ipv4_hook_destroy(ipst);
5750 	ipv6_hook_destroy(ipst);
5751 	ip_net_destroy(ipst);
5752 
5753 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5754 	cv_destroy(&ipst->ips_capab_taskq_cv);
5755 
5756 	mutex_enter(&ipst->ips_mrt_lock);
5757 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5758 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5759 	mutex_destroy(&ipst->ips_mrt_lock);
5760 	cv_destroy(&ipst->ips_mrt_cv);
5761 	cv_destroy(&ipst->ips_mrt_done_cv);
5762 
5763 	ipmp_destroy(ipst);
5764 	rw_destroy(&ipst->ips_srcid_lock);
5765 
5766 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5767 	ipst->ips_ip_mibkp = NULL;
5768 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5769 	ipst->ips_icmp_mibkp = NULL;
5770 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5771 	ipst->ips_ip_kstat = NULL;
5772 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5773 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5774 	ipst->ips_ip6_kstat = NULL;
5775 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5776 
5777 	nd_free(&ipst->ips_ip_g_nd);
5778 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5779 	ipst->ips_param_arr = NULL;
5780 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5781 	ipst->ips_ndp_arr = NULL;
5782 
5783 	ip_mrouter_stack_destroy(ipst);
5784 
5785 	mutex_destroy(&ipst->ips_ip_mi_lock);
5786 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5787 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5788 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5789 
5790 	ret = untimeout(ipst->ips_igmp_timeout_id);
5791 	if (ret == -1) {
5792 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5793 	} else {
5794 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5795 		ipst->ips_igmp_timeout_id = 0;
5796 	}
5797 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5798 	if (ret == -1) {
5799 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5800 	} else {
5801 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5802 		ipst->ips_igmp_slowtimeout_id = 0;
5803 	}
5804 	ret = untimeout(ipst->ips_mld_timeout_id);
5805 	if (ret == -1) {
5806 		ASSERT(ipst->ips_mld_timeout_id == 0);
5807 	} else {
5808 		ASSERT(ipst->ips_mld_timeout_id != 0);
5809 		ipst->ips_mld_timeout_id = 0;
5810 	}
5811 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5812 	if (ret == -1) {
5813 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5814 	} else {
5815 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5816 		ipst->ips_mld_slowtimeout_id = 0;
5817 	}
5818 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5819 	if (ret == -1) {
5820 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5821 	} else {
5822 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5823 		ipst->ips_ip_ire_expire_id = 0;
5824 	}
5825 
5826 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5827 	mutex_destroy(&ipst->ips_mld_timer_lock);
5828 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5829 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5830 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5831 	rw_destroy(&ipst->ips_ill_g_lock);
5832 
5833 	ip_ire_fini(ipst);
5834 	ip6_asp_free(ipst);
5835 	conn_drain_fini(ipst);
5836 	ipcl_destroy(ipst);
5837 
5838 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5839 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5840 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5841 	ipst->ips_ndp4 = NULL;
5842 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5843 	ipst->ips_ndp6 = NULL;
5844 
5845 	if (ipst->ips_loopback_ksp != NULL) {
5846 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5847 		ipst->ips_loopback_ksp = NULL;
5848 	}
5849 
5850 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5851 	ipst->ips_phyint_g_list = NULL;
5852 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5853 	ipst->ips_ill_g_heads = NULL;
5854 
5855 	ldi_ident_release(ipst->ips_ldi_ident);
5856 	kmem_free(ipst, sizeof (*ipst));
5857 }
5858 
5859 /*
5860  * This function is called from the TSD destructor, and is used to debug
5861  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5862  * details.
5863  */
5864 static void
5865 ip_thread_exit(void *phash)
5866 {
5867 	th_hash_t *thh = phash;
5868 
5869 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5870 	list_remove(&ip_thread_list, thh);
5871 	rw_exit(&ip_thread_rwlock);
5872 	mod_hash_destroy_hash(thh->thh_hash);
5873 	kmem_free(thh, sizeof (*thh));
5874 }
5875 
5876 /*
5877  * Called when the IP kernel module is loaded into the kernel
5878  */
5879 void
5880 ip_ddi_init(void)
5881 {
5882 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5883 
5884 	/*
5885 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5886 	 * initial devices: ip, ip6, tcp, tcp6.
5887 	 */
5888 	/*
5889 	 * If this is a 64-bit kernel, then create two separate arenas -
5890 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5891 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5892 	 */
5893 	ip_minor_arena_la = NULL;
5894 	ip_minor_arena_sa = NULL;
5895 #if defined(_LP64)
5896 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5897 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5898 		cmn_err(CE_PANIC,
5899 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5900 	}
5901 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5902 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5903 		cmn_err(CE_PANIC,
5904 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5905 	}
5906 #else
5907 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5908 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5909 		cmn_err(CE_PANIC,
5910 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5911 	}
5912 #endif
5913 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5914 
5915 	ipcl_g_init();
5916 	ip_ire_g_init();
5917 	ip_net_g_init();
5918 
5919 #ifdef DEBUG
5920 	tsd_create(&ip_thread_data, ip_thread_exit);
5921 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5922 	list_create(&ip_thread_list, sizeof (th_hash_t),
5923 	    offsetof(th_hash_t, thh_link));
5924 #endif
5925 
5926 	/*
5927 	 * We want to be informed each time a stack is created or
5928 	 * destroyed in the kernel, so we can maintain the
5929 	 * set of udp_stack_t's.
5930 	 */
5931 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5932 	    ip_stack_fini);
5933 
5934 	ipsec_policy_g_init();
5935 	tcp_ddi_g_init();
5936 	sctp_ddi_g_init();
5937 
5938 	tnet_init();
5939 
5940 	udp_ddi_g_init();
5941 	rts_ddi_g_init();
5942 	icmp_ddi_g_init();
5943 }
5944 
5945 /*
5946  * Initialize the IP stack instance.
5947  */
5948 static void *
5949 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5950 {
5951 	ip_stack_t	*ipst;
5952 	ipparam_t	*pa;
5953 	ipndp_t		*na;
5954 	major_t		major;
5955 
5956 #ifdef NS_DEBUG
5957 	printf("ip_stack_init(stack %d)\n", stackid);
5958 #endif
5959 
5960 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5961 	ipst->ips_netstack = ns;
5962 
5963 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5964 	    KM_SLEEP);
5965 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5966 	    KM_SLEEP);
5967 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5968 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5969 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5970 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5971 
5972 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5973 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5974 	ipst->ips_igmp_deferred_next = INFINITY;
5975 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5976 	ipst->ips_mld_deferred_next = INFINITY;
5977 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5978 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5979 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5980 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5981 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5982 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5983 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5984 
5985 	ipcl_init(ipst);
5986 	ip_ire_init(ipst);
5987 	ip6_asp_init(ipst);
5988 	ipif_init(ipst);
5989 	conn_drain_init(ipst);
5990 	ip_mrouter_stack_init(ipst);
5991 
5992 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5993 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5994 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
5995 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
5996 
5997 	ipst->ips_ip_multirt_log_interval = 1000;
5998 
5999 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6000 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6001 	ipst->ips_ill_index = 1;
6002 
6003 	ipst->ips_saved_ip_g_forward = -1;
6004 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6005 
6006 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6007 	ipst->ips_param_arr = pa;
6008 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6009 
6010 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6011 	ipst->ips_ndp_arr = na;
6012 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6013 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6014 	    (caddr_t)&ipst->ips_ip_g_forward;
6015 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6016 	    (caddr_t)&ipst->ips_ipv6_forward;
6017 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6018 	    "ip_cgtp_filter") == 0);
6019 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6020 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6021 
6022 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6023 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6024 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6025 
6026 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6027 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6028 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6029 	ipst->ips_ip6_kstat =
6030 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6031 
6032 	ipst->ips_ip_src_id = 1;
6033 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6034 
6035 	ip_net_init(ipst, ns);
6036 	ipv4_hook_init(ipst);
6037 	ipv6_hook_init(ipst);
6038 	ipmp_init(ipst);
6039 	ipobs_init(ipst);
6040 
6041 	/*
6042 	 * Create the taskq dispatcher thread and initialize related stuff.
6043 	 */
6044 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6045 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6046 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6048 
6049 	/*
6050 	 * Create the mcast_restart_timers_thread() worker thread.
6051 	 */
6052 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6053 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6054 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6055 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6056 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6057 
6058 	major = mod_name_to_major(INET_NAME);
6059 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6060 	return (ipst);
6061 }
6062 
6063 /*
6064  * Allocate and initialize a DLPI template of the specified length.  (May be
6065  * called as writer.)
6066  */
6067 mblk_t *
6068 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6069 {
6070 	mblk_t	*mp;
6071 
6072 	mp = allocb(len, BPRI_MED);
6073 	if (!mp)
6074 		return (NULL);
6075 
6076 	/*
6077 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6078 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6079 	 * that other DLPI are M_PROTO.
6080 	 */
6081 	if (prim == DL_INFO_REQ) {
6082 		mp->b_datap->db_type = M_PCPROTO;
6083 	} else {
6084 		mp->b_datap->db_type = M_PROTO;
6085 	}
6086 
6087 	mp->b_wptr = mp->b_rptr + len;
6088 	bzero(mp->b_rptr, len);
6089 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6090 	return (mp);
6091 }
6092 
6093 /*
6094  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6095  */
6096 mblk_t *
6097 ip_dlnotify_alloc(uint_t notification, uint_t data)
6098 {
6099 	dl_notify_ind_t	*notifyp;
6100 	mblk_t		*mp;
6101 
6102 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6103 		return (NULL);
6104 
6105 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6106 	notifyp->dl_notification = notification;
6107 	notifyp->dl_data = data;
6108 	return (mp);
6109 }
6110 
6111 /*
6112  * Debug formatting routine.  Returns a character string representation of the
6113  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6114  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6115  *
6116  * Once the ndd table-printing interfaces are removed, this can be changed to
6117  * standard dotted-decimal form.
6118  */
6119 char *
6120 ip_dot_addr(ipaddr_t addr, char *buf)
6121 {
6122 	uint8_t *ap = (uint8_t *)&addr;
6123 
6124 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6125 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6126 	return (buf);
6127 }
6128 
6129 /*
6130  * Write the given MAC address as a printable string in the usual colon-
6131  * separated format.
6132  */
6133 const char *
6134 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6135 {
6136 	char *bp;
6137 
6138 	if (alen == 0 || buflen < 4)
6139 		return ("?");
6140 	bp = buf;
6141 	for (;;) {
6142 		/*
6143 		 * If there are more MAC address bytes available, but we won't
6144 		 * have any room to print them, then add "..." to the string
6145 		 * instead.  See below for the 'magic number' explanation.
6146 		 */
6147 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6148 			(void) strcpy(bp, "...");
6149 			break;
6150 		}
6151 		(void) sprintf(bp, "%02x", *addr++);
6152 		bp += 2;
6153 		if (--alen == 0)
6154 			break;
6155 		*bp++ = ':';
6156 		buflen -= 3;
6157 		/*
6158 		 * At this point, based on the first 'if' statement above,
6159 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6160 		 * buflen >= 4.  The first case leaves room for the final "xx"
6161 		 * number and trailing NUL byte.  The second leaves room for at
6162 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6163 		 * that statement.
6164 		 */
6165 	}
6166 	return (buf);
6167 }
6168 
6169 /*
6170  * Send an ICMP error after patching up the packet appropriately.  Returns
6171  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6172  */
6173 static boolean_t
6174 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6175     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6176     zoneid_t zoneid, ip_stack_t *ipst)
6177 {
6178 	ipha_t *ipha;
6179 	mblk_t *first_mp;
6180 	boolean_t secure;
6181 	unsigned char db_type;
6182 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6183 
6184 	first_mp = mp;
6185 	if (mctl_present) {
6186 		mp = mp->b_cont;
6187 		secure = ipsec_in_is_secure(first_mp);
6188 		ASSERT(mp != NULL);
6189 	} else {
6190 		/*
6191 		 * If this is an ICMP error being reported - which goes
6192 		 * up as M_CTLs, we need to convert them to M_DATA till
6193 		 * we finish checking with global policy because
6194 		 * ipsec_check_global_policy() assumes M_DATA as clear
6195 		 * and M_CTL as secure.
6196 		 */
6197 		db_type = DB_TYPE(mp);
6198 		DB_TYPE(mp) = M_DATA;
6199 		secure = B_FALSE;
6200 	}
6201 	/*
6202 	 * We are generating an icmp error for some inbound packet.
6203 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6204 	 * Before we generate an error, check with global policy
6205 	 * to see whether this is allowed to enter the system. As
6206 	 * there is no "conn", we are checking with global policy.
6207 	 */
6208 	ipha = (ipha_t *)mp->b_rptr;
6209 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6210 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6211 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6212 		if (first_mp == NULL)
6213 			return (B_FALSE);
6214 	}
6215 
6216 	if (!mctl_present)
6217 		DB_TYPE(mp) = db_type;
6218 
6219 	if (flags & IP_FF_SEND_ICMP) {
6220 		if (flags & IP_FF_HDR_COMPLETE) {
6221 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6222 				freemsg(first_mp);
6223 				return (B_TRUE);
6224 			}
6225 		}
6226 		if (flags & IP_FF_CKSUM) {
6227 			/*
6228 			 * Have to correct checksum since
6229 			 * the packet might have been
6230 			 * fragmented and the reassembly code in ip_rput
6231 			 * does not restore the IP checksum.
6232 			 */
6233 			ipha->ipha_hdr_checksum = 0;
6234 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6235 		}
6236 		switch (icmp_type) {
6237 		case ICMP_DEST_UNREACHABLE:
6238 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6239 			    ipst);
6240 			break;
6241 		default:
6242 			freemsg(first_mp);
6243 			break;
6244 		}
6245 	} else {
6246 		freemsg(first_mp);
6247 		return (B_FALSE);
6248 	}
6249 
6250 	return (B_TRUE);
6251 }
6252 
6253 /*
6254  * Used to send an ICMP error message when a packet is received for
6255  * a protocol that is not supported. The mblk passed as argument
6256  * is consumed by this function.
6257  */
6258 void
6259 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6260     ip_stack_t *ipst)
6261 {
6262 	mblk_t *mp;
6263 	ipha_t *ipha;
6264 	ill_t *ill;
6265 	ipsec_in_t *ii;
6266 
6267 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6268 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6269 
6270 	mp = ipsec_mp->b_cont;
6271 	ipsec_mp->b_cont = NULL;
6272 	ipha = (ipha_t *)mp->b_rptr;
6273 	/* Get ill from index in ipsec_in_t. */
6274 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6275 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6276 	    ipst);
6277 	if (ill != NULL) {
6278 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6279 			if (ip_fanout_send_icmp(q, mp, flags,
6280 			    ICMP_DEST_UNREACHABLE,
6281 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6282 				BUMP_MIB(ill->ill_ip_mib,
6283 				    ipIfStatsInUnknownProtos);
6284 			}
6285 		} else {
6286 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6287 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6288 			    0, B_FALSE, zoneid, ipst)) {
6289 				BUMP_MIB(ill->ill_ip_mib,
6290 				    ipIfStatsInUnknownProtos);
6291 			}
6292 		}
6293 		ill_refrele(ill);
6294 	} else { /* re-link for the freemsg() below. */
6295 		ipsec_mp->b_cont = mp;
6296 	}
6297 
6298 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6299 	freemsg(ipsec_mp);
6300 }
6301 
6302 /*
6303  * See if the inbound datagram has had IPsec processing applied to it.
6304  */
6305 boolean_t
6306 ipsec_in_is_secure(mblk_t *ipsec_mp)
6307 {
6308 	ipsec_in_t *ii;
6309 
6310 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6311 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6312 
6313 	if (ii->ipsec_in_loopback) {
6314 		return (ii->ipsec_in_secure);
6315 	} else {
6316 		return (ii->ipsec_in_ah_sa != NULL ||
6317 		    ii->ipsec_in_esp_sa != NULL ||
6318 		    ii->ipsec_in_decaps);
6319 	}
6320 }
6321 
6322 /*
6323  * Handle protocols with which IP is less intimate.  There
6324  * can be more than one stream bound to a particular
6325  * protocol.  When this is the case, normally each one gets a copy
6326  * of any incoming packets.
6327  *
6328  * IPsec NOTE :
6329  *
6330  * Don't allow a secure packet going up a non-secure connection.
6331  * We don't allow this because
6332  *
6333  * 1) Reply might go out in clear which will be dropped at
6334  *    the sending side.
6335  * 2) If the reply goes out in clear it will give the
6336  *    adversary enough information for getting the key in
6337  *    most of the cases.
6338  *
6339  * Moreover getting a secure packet when we expect clear
6340  * implies that SA's were added without checking for
6341  * policy on both ends. This should not happen once ISAKMP
6342  * is used to negotiate SAs as SAs will be added only after
6343  * verifying the policy.
6344  *
6345  * IPQoS Notes:
6346  * Once we have determined the client, invoke IPPF processing.
6347  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6348  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6349  * ip_policy will be false.
6350  *
6351  * Zones notes:
6352  * Currently only applications in the global zone can create raw sockets for
6353  * protocols other than ICMP. So unlike the broadcast / multicast case of
6354  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6355  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6356  */
6357 static void
6358 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6359     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6360     zoneid_t zoneid)
6361 {
6362 	queue_t	*rq;
6363 	mblk_t	*mp1, *first_mp1;
6364 	uint_t	protocol = ipha->ipha_protocol;
6365 	ipaddr_t dst;
6366 	mblk_t *first_mp = mp;
6367 	boolean_t secure;
6368 	uint32_t ill_index;
6369 	conn_t	*connp, *first_connp, *next_connp;
6370 	connf_t	*connfp;
6371 	boolean_t shared_addr;
6372 	mib2_ipIfStatsEntry_t *mibptr;
6373 	ip_stack_t *ipst = recv_ill->ill_ipst;
6374 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6375 
6376 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6377 	if (mctl_present) {
6378 		mp = first_mp->b_cont;
6379 		secure = ipsec_in_is_secure(first_mp);
6380 		ASSERT(mp != NULL);
6381 	} else {
6382 		secure = B_FALSE;
6383 	}
6384 	dst = ipha->ipha_dst;
6385 	shared_addr = (zoneid == ALL_ZONES);
6386 	if (shared_addr) {
6387 		/*
6388 		 * We don't allow multilevel ports for raw IP, so no need to
6389 		 * check for that here.
6390 		 */
6391 		zoneid = tsol_packet_to_zoneid(mp);
6392 	}
6393 
6394 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6395 	mutex_enter(&connfp->connf_lock);
6396 	connp = connfp->connf_head;
6397 	for (connp = connfp->connf_head; connp != NULL;
6398 	    connp = connp->conn_next) {
6399 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6400 		    zoneid) &&
6401 		    (!is_system_labeled() ||
6402 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6403 		    connp))) {
6404 			break;
6405 		}
6406 	}
6407 
6408 	if (connp == NULL) {
6409 		/*
6410 		 * No one bound to these addresses.  Is
6411 		 * there a client that wants all
6412 		 * unclaimed datagrams?
6413 		 */
6414 		mutex_exit(&connfp->connf_lock);
6415 		/*
6416 		 * Check for IPPROTO_ENCAP...
6417 		 */
6418 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6419 			/*
6420 			 * If an IPsec mblk is here on a multicast
6421 			 * tunnel (using ip_mroute stuff), check policy here,
6422 			 * THEN ship off to ip_mroute_decap().
6423 			 *
6424 			 * BTW,  If I match a configured IP-in-IP
6425 			 * tunnel, this path will not be reached, and
6426 			 * ip_mroute_decap will never be called.
6427 			 */
6428 			first_mp = ipsec_check_global_policy(first_mp, connp,
6429 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6430 			if (first_mp != NULL) {
6431 				if (mctl_present)
6432 					freeb(first_mp);
6433 				ip_mroute_decap(q, mp, ill);
6434 			} /* Else we already freed everything! */
6435 		} else {
6436 			/*
6437 			 * Otherwise send an ICMP protocol unreachable.
6438 			 */
6439 			if (ip_fanout_send_icmp(q, first_mp, flags,
6440 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6441 			    mctl_present, zoneid, ipst)) {
6442 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6443 			}
6444 		}
6445 		return;
6446 	}
6447 
6448 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6449 
6450 	CONN_INC_REF(connp);
6451 	first_connp = connp;
6452 	connp = connp->conn_next;
6453 
6454 	for (;;) {
6455 		while (connp != NULL) {
6456 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6457 			    flags, zoneid) &&
6458 			    (!is_system_labeled() ||
6459 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6460 			    shared_addr, connp)))
6461 				break;
6462 			connp = connp->conn_next;
6463 		}
6464 
6465 		/*
6466 		 * Copy the packet.
6467 		 */
6468 		if (connp == NULL ||
6469 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6470 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6471 			/*
6472 			 * No more interested clients or memory
6473 			 * allocation failed
6474 			 */
6475 			connp = first_connp;
6476 			break;
6477 		}
6478 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6479 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6480 		CONN_INC_REF(connp);
6481 		mutex_exit(&connfp->connf_lock);
6482 		rq = connp->conn_rq;
6483 
6484 		/*
6485 		 * Check flow control
6486 		 */
6487 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6488 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6489 			if (flags & IP_FF_RAWIP) {
6490 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6491 			} else {
6492 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6493 			}
6494 
6495 			freemsg(first_mp1);
6496 		} else {
6497 			/*
6498 			 * Enforce policy like any other conn_t.  Note that
6499 			 * IP-in-IP packets don't come through here, but
6500 			 * through ip_iptun_input() or
6501 			 * icmp_inbound_iptun_fanout().  IPsec policy for such
6502 			 * packets is enforced in the iptun module.
6503 			 */
6504 			if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6505 			    secure) {
6506 				first_mp1 = ipsec_check_inbound_policy
6507 				    (first_mp1, connp, ipha, NULL,
6508 				    mctl_present);
6509 			}
6510 			if (first_mp1 != NULL) {
6511 				int in_flags = 0;
6512 				/*
6513 				 * ip_fanout_proto also gets called from
6514 				 * icmp_inbound_error_fanout, in which case
6515 				 * the msg type is M_CTL.  Don't add info
6516 				 * in this case for the time being. In future
6517 				 * when there is a need for knowing the
6518 				 * inbound iface index for ICMP error msgs,
6519 				 * then this can be changed.
6520 				 */
6521 				if (connp->conn_recvif)
6522 					in_flags = IPF_RECVIF;
6523 				/*
6524 				 * The ULP may support IP_RECVPKTINFO for both
6525 				 * IP v4 and v6 so pass the appropriate argument
6526 				 * based on conn IP version.
6527 				 */
6528 				if (connp->conn_ip_recvpktinfo) {
6529 					if (connp->conn_af_isv6) {
6530 						/*
6531 						 * V6 only needs index
6532 						 */
6533 						in_flags |= IPF_RECVIF;
6534 					} else {
6535 						/*
6536 						 * V4 needs index +
6537 						 * matching address.
6538 						 */
6539 						in_flags |= IPF_RECVADDR;
6540 					}
6541 				}
6542 				if ((in_flags != 0) &&
6543 				    (mp->b_datap->db_type != M_CTL)) {
6544 					/*
6545 					 * the actual data will be
6546 					 * contained in b_cont upon
6547 					 * successful return of the
6548 					 * following call else
6549 					 * original mblk is returned
6550 					 */
6551 					ASSERT(recv_ill != NULL);
6552 					mp1 = ip_add_info(mp1, recv_ill,
6553 					    in_flags, IPCL_ZONEID(connp), ipst);
6554 				}
6555 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6556 				if (mctl_present)
6557 					freeb(first_mp1);
6558 				(connp->conn_recv)(connp, mp1, NULL);
6559 			}
6560 		}
6561 		mutex_enter(&connfp->connf_lock);
6562 		/* Follow the next pointer before releasing the conn. */
6563 		next_connp = connp->conn_next;
6564 		CONN_DEC_REF(connp);
6565 		connp = next_connp;
6566 	}
6567 
6568 	/* Last one.  Send it upstream. */
6569 	mutex_exit(&connfp->connf_lock);
6570 
6571 	/*
6572 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6573 	 * will be set to false.
6574 	 */
6575 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6576 		ill_index = ill->ill_phyint->phyint_ifindex;
6577 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6578 		if (mp == NULL) {
6579 			CONN_DEC_REF(connp);
6580 			if (mctl_present) {
6581 				freeb(first_mp);
6582 			}
6583 			return;
6584 		}
6585 	}
6586 
6587 	rq = connp->conn_rq;
6588 	/*
6589 	 * Check flow control
6590 	 */
6591 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6592 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6593 		if (flags & IP_FF_RAWIP) {
6594 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6595 		} else {
6596 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6597 		}
6598 
6599 		freemsg(first_mp);
6600 	} else {
6601 		ASSERT(!IPCL_IS_IPTUN(connp));
6602 
6603 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6604 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6605 			    ipha, NULL, mctl_present);
6606 		}
6607 
6608 		if (first_mp != NULL) {
6609 			int in_flags = 0;
6610 
6611 			/*
6612 			 * ip_fanout_proto also gets called
6613 			 * from icmp_inbound_error_fanout, in
6614 			 * which case the msg type is M_CTL.
6615 			 * Don't add info in this case for time
6616 			 * being. In future when there is a
6617 			 * need for knowing the inbound iface
6618 			 * index for ICMP error msgs, then this
6619 			 * can be changed
6620 			 */
6621 			if (connp->conn_recvif)
6622 				in_flags = IPF_RECVIF;
6623 			if (connp->conn_ip_recvpktinfo) {
6624 				if (connp->conn_af_isv6) {
6625 					/*
6626 					 * V6 only needs index
6627 					 */
6628 					in_flags |= IPF_RECVIF;
6629 				} else {
6630 					/*
6631 					 * V4 needs index +
6632 					 * matching address.
6633 					 */
6634 					in_flags |= IPF_RECVADDR;
6635 				}
6636 			}
6637 			if ((in_flags != 0) &&
6638 			    (mp->b_datap->db_type != M_CTL)) {
6639 
6640 				/*
6641 				 * the actual data will be contained in
6642 				 * b_cont upon successful return
6643 				 * of the following call else original
6644 				 * mblk is returned
6645 				 */
6646 				ASSERT(recv_ill != NULL);
6647 				mp = ip_add_info(mp, recv_ill,
6648 				    in_flags, IPCL_ZONEID(connp), ipst);
6649 			}
6650 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6651 			(connp->conn_recv)(connp, mp, NULL);
6652 			if (mctl_present)
6653 				freeb(first_mp);
6654 		}
6655 	}
6656 	CONN_DEC_REF(connp);
6657 }
6658 
6659 /*
6660  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6661  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6662  * the correct squeue, in this case the same squeue as a valid listener with
6663  * no current connection state for the packet we are processing. The function
6664  * is called for synchronizing both IPv4 and IPv6.
6665  */
6666 void
6667 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6668     tcp_stack_t *tcps, conn_t *connp)
6669 {
6670 	mblk_t *rst_mp;
6671 	tcp_xmit_reset_event_t *eventp;
6672 
6673 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6674 
6675 	if (rst_mp == NULL) {
6676 		freemsg(mp);
6677 		return;
6678 	}
6679 
6680 	rst_mp->b_datap->db_type = M_PROTO;
6681 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6682 
6683 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6684 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6685 	eventp->tcp_xre_iphdrlen = hdrlen;
6686 	eventp->tcp_xre_zoneid = zoneid;
6687 	eventp->tcp_xre_tcps = tcps;
6688 
6689 	rst_mp->b_cont = mp;
6690 	mp = rst_mp;
6691 
6692 	/*
6693 	 * Increment the connref, this ref will be released by the squeue
6694 	 * framework.
6695 	 */
6696 	CONN_INC_REF(connp);
6697 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6698 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6699 }
6700 
6701 /*
6702  * Fanout for TCP packets
6703  * The caller puts <fport, lport> in the ports parameter.
6704  *
6705  * IPQoS Notes
6706  * Before sending it to the client, invoke IPPF processing.
6707  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6708  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6709  * ip_policy is false.
6710  */
6711 static void
6712 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6713     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6714 {
6715 	mblk_t  *first_mp;
6716 	boolean_t secure;
6717 	uint32_t ill_index;
6718 	int	ip_hdr_len;
6719 	tcph_t	*tcph;
6720 	boolean_t syn_present = B_FALSE;
6721 	conn_t	*connp;
6722 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6723 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6724 
6725 	ASSERT(recv_ill != NULL);
6726 
6727 	first_mp = mp;
6728 	if (mctl_present) {
6729 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6730 		mp = first_mp->b_cont;
6731 		secure = ipsec_in_is_secure(first_mp);
6732 		ASSERT(mp != NULL);
6733 	} else {
6734 		secure = B_FALSE;
6735 	}
6736 
6737 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6738 
6739 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6740 	    zoneid, ipst)) == NULL) {
6741 		/*
6742 		 * No connected connection or listener. Send a
6743 		 * TH_RST via tcp_xmit_listeners_reset.
6744 		 */
6745 
6746 		/* Initiate IPPf processing, if needed. */
6747 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6748 			uint32_t ill_index;
6749 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6750 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6751 			if (first_mp == NULL)
6752 				return;
6753 		}
6754 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6755 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6756 		    zoneid));
6757 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6758 		    ipst->ips_netstack->netstack_tcp, NULL);
6759 		return;
6760 	}
6761 
6762 	/*
6763 	 * Allocate the SYN for the TCP connection here itself
6764 	 */
6765 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6766 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6767 		if (IPCL_IS_TCP(connp)) {
6768 			squeue_t *sqp;
6769 
6770 			/*
6771 			 * If the queue belongs to a conn, and fused tcp
6772 			 * loopback is enabled, assign the eager's squeue
6773 			 * to be that of the active connect's. Note that
6774 			 * we don't check for IP_FF_LOOPBACK here since this
6775 			 * routine gets called only for loopback (unlike the
6776 			 * IPv6 counterpart).
6777 			 */
6778 			if (do_tcp_fusion &&
6779 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6780 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6781 			    !secure &&
6782 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6783 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6784 				sqp = Q_TO_CONN(q)->conn_sqp;
6785 			} else {
6786 				sqp = IP_SQUEUE_GET(lbolt);
6787 			}
6788 
6789 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6790 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6791 			syn_present = B_TRUE;
6792 		}
6793 	}
6794 
6795 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6796 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6797 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6798 		if ((flags & TH_RST) || (flags & TH_URG)) {
6799 			CONN_DEC_REF(connp);
6800 			freemsg(first_mp);
6801 			return;
6802 		}
6803 		if (flags & TH_ACK) {
6804 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6805 			    ipst->ips_netstack->netstack_tcp, connp);
6806 			CONN_DEC_REF(connp);
6807 			return;
6808 		}
6809 
6810 		CONN_DEC_REF(connp);
6811 		freemsg(first_mp);
6812 		return;
6813 	}
6814 
6815 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6816 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6817 		    NULL, mctl_present);
6818 		if (first_mp == NULL) {
6819 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6820 			CONN_DEC_REF(connp);
6821 			return;
6822 		}
6823 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6824 			ASSERT(syn_present);
6825 			if (mctl_present) {
6826 				ASSERT(first_mp != mp);
6827 				first_mp->b_datap->db_struioflag |=
6828 				    STRUIO_POLICY;
6829 			} else {
6830 				ASSERT(first_mp == mp);
6831 				mp->b_datap->db_struioflag &=
6832 				    ~STRUIO_EAGER;
6833 				mp->b_datap->db_struioflag |=
6834 				    STRUIO_POLICY;
6835 			}
6836 		} else {
6837 			/*
6838 			 * Discard first_mp early since we're dealing with a
6839 			 * fully-connected conn_t and tcp doesn't do policy in
6840 			 * this case.
6841 			 */
6842 			if (mctl_present) {
6843 				freeb(first_mp);
6844 				mctl_present = B_FALSE;
6845 			}
6846 			first_mp = mp;
6847 		}
6848 	}
6849 
6850 	/*
6851 	 * Initiate policy processing here if needed. If we get here from
6852 	 * icmp_inbound_error_fanout, ip_policy is false.
6853 	 */
6854 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6855 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6856 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6857 		if (mp == NULL) {
6858 			CONN_DEC_REF(connp);
6859 			if (mctl_present)
6860 				freeb(first_mp);
6861 			return;
6862 		} else if (mctl_present) {
6863 			ASSERT(first_mp != mp);
6864 			first_mp->b_cont = mp;
6865 		} else {
6866 			first_mp = mp;
6867 		}
6868 	}
6869 
6870 	/* Handle socket options. */
6871 	if (!syn_present &&
6872 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6873 		/* Add header */
6874 		ASSERT(recv_ill != NULL);
6875 		/*
6876 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6877 		 * IPF_RECVIF.
6878 		 */
6879 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6880 		    ipst);
6881 		if (mp == NULL) {
6882 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6883 			CONN_DEC_REF(connp);
6884 			if (mctl_present)
6885 				freeb(first_mp);
6886 			return;
6887 		} else if (mctl_present) {
6888 			/*
6889 			 * ip_add_info might return a new mp.
6890 			 */
6891 			ASSERT(first_mp != mp);
6892 			first_mp->b_cont = mp;
6893 		} else {
6894 			first_mp = mp;
6895 		}
6896 	}
6897 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6898 	if (IPCL_IS_TCP(connp)) {
6899 		/* do not drain, certain use cases can blow the stack */
6900 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6901 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
6902 	} else {
6903 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6904 		(connp->conn_recv)(connp, first_mp, NULL);
6905 		CONN_DEC_REF(connp);
6906 	}
6907 }
6908 
6909 /*
6910  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6911  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6912  * is not consumed.
6913  *
6914  * One of four things can happen, all of which affect the passed-in mblk:
6915  *
6916  * 1.) ICMP messages that go through here just get returned TRUE.
6917  *
6918  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6919  *
6920  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6921  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6922  *
6923  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6924  */
6925 static boolean_t
6926 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6927     ipsec_stack_t *ipss)
6928 {
6929 	int shift, plen, iph_len;
6930 	ipha_t *ipha;
6931 	udpha_t *udpha;
6932 	uint32_t *spi;
6933 	uint32_t esp_ports;
6934 	uint8_t *orptr;
6935 	boolean_t free_ire;
6936 
6937 	if (DB_TYPE(mp) == M_CTL) {
6938 		/*
6939 		 * ICMP message with UDP inside.  Don't bother stripping, just
6940 		 * send it up.
6941 		 *
6942 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6943 		 * to ignore errors set by ICMP anyway ('cause they might be
6944 		 * forged), but that's the app's decision, not ours.
6945 		 */
6946 
6947 		/* Bunch of reality checks for DEBUG kernels... */
6948 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6949 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6950 
6951 		return (B_TRUE);
6952 	}
6953 
6954 	ipha = (ipha_t *)mp->b_rptr;
6955 	iph_len = IPH_HDR_LENGTH(ipha);
6956 	plen = ntohs(ipha->ipha_length);
6957 
6958 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6959 		/*
6960 		 * Most likely a keepalive for the benefit of an intervening
6961 		 * NAT.  These aren't for us, per se, so drop it.
6962 		 *
6963 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6964 		 * byte packets (keepalives are 1-byte), but we'll drop them
6965 		 * also.
6966 		 */
6967 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6968 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6969 		return (B_FALSE);
6970 	}
6971 
6972 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6973 		/* might as well pull it all up - it might be ESP. */
6974 		if (!pullupmsg(mp, -1)) {
6975 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6976 			    DROPPER(ipss, ipds_esp_nomem),
6977 			    &ipss->ipsec_dropper);
6978 			return (B_FALSE);
6979 		}
6980 
6981 		ipha = (ipha_t *)mp->b_rptr;
6982 	}
6983 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6984 	if (*spi == 0) {
6985 		/* UDP packet - remove 0-spi. */
6986 		shift = sizeof (uint32_t);
6987 	} else {
6988 		/* ESP-in-UDP packet - reduce to ESP. */
6989 		ipha->ipha_protocol = IPPROTO_ESP;
6990 		shift = sizeof (udpha_t);
6991 	}
6992 
6993 	/* Fix IP header */
6994 	ipha->ipha_length = htons(plen - shift);
6995 	ipha->ipha_hdr_checksum = 0;
6996 
6997 	orptr = mp->b_rptr;
6998 	mp->b_rptr += shift;
6999 
7000 	udpha = (udpha_t *)(orptr + iph_len);
7001 	if (*spi == 0) {
7002 		ASSERT((uint8_t *)ipha == orptr);
7003 		udpha->uha_length = htons(plen - shift - iph_len);
7004 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7005 		esp_ports = 0;
7006 	} else {
7007 		esp_ports = *((uint32_t *)udpha);
7008 		ASSERT(esp_ports != 0);
7009 	}
7010 	ovbcopy(orptr, orptr + shift, iph_len);
7011 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7012 		ipha = (ipha_t *)(orptr + shift);
7013 
7014 		free_ire = (ire == NULL);
7015 		if (free_ire) {
7016 			/* Re-acquire ire. */
7017 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7018 			    ipss->ipsec_netstack->netstack_ip);
7019 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7020 				if (ire != NULL)
7021 					ire_refrele(ire);
7022 				/*
7023 				 * Do a regular freemsg(), as this is an IP
7024 				 * error (no local route) not an IPsec one.
7025 				 */
7026 				freemsg(mp);
7027 			}
7028 		}
7029 
7030 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7031 		if (free_ire)
7032 			ire_refrele(ire);
7033 	}
7034 
7035 	return (esp_ports == 0);
7036 }
7037 
7038 /*
7039  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7040  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7041  * Caller is responsible for dropping references to the conn, and freeing
7042  * first_mp.
7043  *
7044  * IPQoS Notes
7045  * Before sending it to the client, invoke IPPF processing. Policy processing
7046  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7047  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7048  * ip_wput_local, ip_policy is false.
7049  */
7050 static void
7051 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7052     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7053     boolean_t ip_policy)
7054 {
7055 	boolean_t	mctl_present = (first_mp != NULL);
7056 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7057 	uint32_t	ill_index;
7058 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7059 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7060 
7061 	ASSERT(ill != NULL);
7062 
7063 	if (mctl_present)
7064 		first_mp->b_cont = mp;
7065 	else
7066 		first_mp = mp;
7067 
7068 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7069 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7070 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7071 		freemsg(first_mp);
7072 		return;
7073 	}
7074 
7075 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7076 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7077 		    NULL, mctl_present);
7078 		/* Freed by ipsec_check_inbound_policy(). */
7079 		if (first_mp == NULL) {
7080 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7081 			return;
7082 		}
7083 	}
7084 	if (mctl_present)
7085 		freeb(first_mp);
7086 
7087 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7088 	if (connp->conn_udp->udp_nat_t_endpoint) {
7089 		if (mctl_present) {
7090 			/* mctl_present *shouldn't* happen. */
7091 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7092 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7093 			    &ipss->ipsec_dropper);
7094 			return;
7095 		}
7096 
7097 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7098 			return;
7099 	}
7100 
7101 	/* Handle options. */
7102 	if (connp->conn_recvif)
7103 		in_flags = IPF_RECVIF;
7104 	/*
7105 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7106 	 * passed to ip_add_info is based on IP version of connp.
7107 	 */
7108 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7109 		if (connp->conn_af_isv6) {
7110 			/*
7111 			 * V6 only needs index
7112 			 */
7113 			in_flags |= IPF_RECVIF;
7114 		} else {
7115 			/*
7116 			 * V4 needs index + matching address.
7117 			 */
7118 			in_flags |= IPF_RECVADDR;
7119 		}
7120 	}
7121 
7122 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7123 		in_flags |= IPF_RECVSLLA;
7124 
7125 	/*
7126 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7127 	 * freed if the packet is dropped. The caller will do so.
7128 	 */
7129 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7130 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7131 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7132 		if (mp == NULL) {
7133 			return;
7134 		}
7135 	}
7136 	if ((in_flags != 0) &&
7137 	    (mp->b_datap->db_type != M_CTL)) {
7138 		/*
7139 		 * The actual data will be contained in b_cont
7140 		 * upon successful return of the following call
7141 		 * else original mblk is returned
7142 		 */
7143 		ASSERT(recv_ill != NULL);
7144 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7145 		    ipst);
7146 	}
7147 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7148 	/* Send it upstream */
7149 	(connp->conn_recv)(connp, mp, NULL);
7150 }
7151 
7152 /*
7153  * Fanout for UDP packets.
7154  * The caller puts <fport, lport> in the ports parameter.
7155  *
7156  * If SO_REUSEADDR is set all multicast and broadcast packets
7157  * will be delivered to all streams bound to the same port.
7158  *
7159  * Zones notes:
7160  * Multicast and broadcast packets will be distributed to streams in all zones.
7161  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7162  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7163  * packets. To maintain this behavior with multiple zones, the conns are grouped
7164  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7165  * each zone. If unset, all the following conns in the same zone are skipped.
7166  */
7167 static void
7168 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7169     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7170     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7171 {
7172 	uint32_t	dstport, srcport;
7173 	ipaddr_t	dst;
7174 	mblk_t		*first_mp;
7175 	boolean_t	secure;
7176 	in6_addr_t	v6src;
7177 	conn_t		*connp;
7178 	connf_t		*connfp;
7179 	conn_t		*first_connp;
7180 	conn_t		*next_connp;
7181 	mblk_t		*mp1, *first_mp1;
7182 	ipaddr_t	src;
7183 	zoneid_t	last_zoneid;
7184 	boolean_t	reuseaddr;
7185 	boolean_t	shared_addr;
7186 	boolean_t	unlabeled;
7187 	ip_stack_t	*ipst;
7188 
7189 	ASSERT(recv_ill != NULL);
7190 	ipst = recv_ill->ill_ipst;
7191 
7192 	first_mp = mp;
7193 	if (mctl_present) {
7194 		mp = first_mp->b_cont;
7195 		first_mp->b_cont = NULL;
7196 		secure = ipsec_in_is_secure(first_mp);
7197 		ASSERT(mp != NULL);
7198 	} else {
7199 		first_mp = NULL;
7200 		secure = B_FALSE;
7201 	}
7202 
7203 	/* Extract ports in net byte order */
7204 	dstport = htons(ntohl(ports) & 0xFFFF);
7205 	srcport = htons(ntohl(ports) >> 16);
7206 	dst = ipha->ipha_dst;
7207 	src = ipha->ipha_src;
7208 
7209 	unlabeled = B_FALSE;
7210 	if (is_system_labeled())
7211 		/* Cred cannot be null on IPv4 */
7212 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7213 		    TSLF_UNLABELED) != 0;
7214 	shared_addr = (zoneid == ALL_ZONES);
7215 	if (shared_addr) {
7216 		/*
7217 		 * No need to handle exclusive-stack zones since ALL_ZONES
7218 		 * only applies to the shared stack.
7219 		 */
7220 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7221 		/*
7222 		 * If no shared MLP is found, tsol_mlp_findzone returns
7223 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7224 		 * search for the zone based on the packet label.
7225 		 *
7226 		 * If there is such a zone, we prefer to find a
7227 		 * connection in it.  Otherwise, we look for a
7228 		 * MAC-exempt connection in any zone whose label
7229 		 * dominates the default label on the packet.
7230 		 */
7231 		if (zoneid == ALL_ZONES)
7232 			zoneid = tsol_packet_to_zoneid(mp);
7233 		else
7234 			unlabeled = B_FALSE;
7235 	}
7236 
7237 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7238 	mutex_enter(&connfp->connf_lock);
7239 	connp = connfp->connf_head;
7240 	if (!broadcast && !CLASSD(dst)) {
7241 		/*
7242 		 * Not broadcast or multicast. Send to the one (first)
7243 		 * client we find. No need to check conn_wantpacket()
7244 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7245 		 * IPv4 unicast packets.
7246 		 */
7247 		while ((connp != NULL) &&
7248 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7249 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7250 		    !(unlabeled && connp->conn_mac_exempt && shared_addr)))) {
7251 			/*
7252 			 * We keep searching since the conn did not match,
7253 			 * or its zone did not match and it is not either
7254 			 * an allzones conn or a mac exempt conn (if the
7255 			 * sender is unlabeled.)
7256 			 */
7257 			connp = connp->conn_next;
7258 		}
7259 
7260 		if (connp == NULL ||
7261 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7262 			goto notfound;
7263 
7264 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7265 
7266 		if (is_system_labeled() &&
7267 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7268 		    connp))
7269 			goto notfound;
7270 
7271 		CONN_INC_REF(connp);
7272 		mutex_exit(&connfp->connf_lock);
7273 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7274 		    flags, recv_ill, ip_policy);
7275 		IP_STAT(ipst, ip_udp_fannorm);
7276 		CONN_DEC_REF(connp);
7277 		return;
7278 	}
7279 
7280 	/*
7281 	 * Broadcast and multicast case
7282 	 *
7283 	 * Need to check conn_wantpacket().
7284 	 * If SO_REUSEADDR has been set on the first we send the
7285 	 * packet to all clients that have joined the group and
7286 	 * match the port.
7287 	 */
7288 
7289 	while (connp != NULL) {
7290 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7291 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7292 		    (!is_system_labeled() ||
7293 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7294 		    connp)))
7295 			break;
7296 		connp = connp->conn_next;
7297 	}
7298 
7299 	if (connp == NULL ||
7300 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7301 		goto notfound;
7302 
7303 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7304 
7305 	first_connp = connp;
7306 	/*
7307 	 * When SO_REUSEADDR is not set, send the packet only to the first
7308 	 * matching connection in its zone by keeping track of the zoneid.
7309 	 */
7310 	reuseaddr = first_connp->conn_reuseaddr;
7311 	last_zoneid = first_connp->conn_zoneid;
7312 
7313 	CONN_INC_REF(connp);
7314 	connp = connp->conn_next;
7315 	for (;;) {
7316 		while (connp != NULL) {
7317 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7318 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7319 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7320 			    (!is_system_labeled() ||
7321 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7322 			    shared_addr, connp)))
7323 				break;
7324 			connp = connp->conn_next;
7325 		}
7326 		/*
7327 		 * Just copy the data part alone. The mctl part is
7328 		 * needed just for verifying policy and it is never
7329 		 * sent up.
7330 		 */
7331 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7332 		    ((mp1 = copymsg(mp)) == NULL))) {
7333 			/*
7334 			 * No more interested clients or memory
7335 			 * allocation failed
7336 			 */
7337 			connp = first_connp;
7338 			break;
7339 		}
7340 		if (connp->conn_zoneid != last_zoneid) {
7341 			/*
7342 			 * Update the zoneid so that the packet isn't sent to
7343 			 * any more conns in the same zone unless SO_REUSEADDR
7344 			 * is set.
7345 			 */
7346 			reuseaddr = connp->conn_reuseaddr;
7347 			last_zoneid = connp->conn_zoneid;
7348 		}
7349 		if (first_mp != NULL) {
7350 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7351 			    ipsec_info_type == IPSEC_IN);
7352 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7353 			    ipst->ips_netstack);
7354 			if (first_mp1 == NULL) {
7355 				freemsg(mp1);
7356 				connp = first_connp;
7357 				break;
7358 			}
7359 		} else {
7360 			first_mp1 = NULL;
7361 		}
7362 		CONN_INC_REF(connp);
7363 		mutex_exit(&connfp->connf_lock);
7364 		/*
7365 		 * IPQoS notes: We don't send the packet for policy
7366 		 * processing here, will do it for the last one (below).
7367 		 * i.e. we do it per-packet now, but if we do policy
7368 		 * processing per-conn, then we would need to do it
7369 		 * here too.
7370 		 */
7371 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7372 		    ipha, flags, recv_ill, B_FALSE);
7373 		mutex_enter(&connfp->connf_lock);
7374 		/* Follow the next pointer before releasing the conn. */
7375 		next_connp = connp->conn_next;
7376 		IP_STAT(ipst, ip_udp_fanmb);
7377 		CONN_DEC_REF(connp);
7378 		connp = next_connp;
7379 	}
7380 
7381 	/* Last one.  Send it upstream. */
7382 	mutex_exit(&connfp->connf_lock);
7383 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7384 	    recv_ill, ip_policy);
7385 	IP_STAT(ipst, ip_udp_fanmb);
7386 	CONN_DEC_REF(connp);
7387 	return;
7388 
7389 notfound:
7390 
7391 	mutex_exit(&connfp->connf_lock);
7392 	IP_STAT(ipst, ip_udp_fanothers);
7393 	/*
7394 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7395 	 * have already been matched above, since they live in the IPv4
7396 	 * fanout tables. This implies we only need to
7397 	 * check for IPv6 in6addr_any endpoints here.
7398 	 * Thus we compare using ipv6_all_zeros instead of the destination
7399 	 * address, except for the multicast group membership lookup which
7400 	 * uses the IPv4 destination.
7401 	 */
7402 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7403 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7404 	mutex_enter(&connfp->connf_lock);
7405 	connp = connfp->connf_head;
7406 	if (!broadcast && !CLASSD(dst)) {
7407 		while (connp != NULL) {
7408 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7409 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7410 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7411 			    !connp->conn_ipv6_v6only)
7412 				break;
7413 			connp = connp->conn_next;
7414 		}
7415 
7416 		if (connp != NULL && is_system_labeled() &&
7417 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7418 		    connp))
7419 			connp = NULL;
7420 
7421 		if (connp == NULL ||
7422 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7423 			/*
7424 			 * No one bound to this port.  Is
7425 			 * there a client that wants all
7426 			 * unclaimed datagrams?
7427 			 */
7428 			mutex_exit(&connfp->connf_lock);
7429 
7430 			if (mctl_present)
7431 				first_mp->b_cont = mp;
7432 			else
7433 				first_mp = mp;
7434 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7435 			    connf_head != NULL) {
7436 				ip_fanout_proto(q, first_mp, ill, ipha,
7437 				    flags | IP_FF_RAWIP, mctl_present,
7438 				    ip_policy, recv_ill, zoneid);
7439 			} else {
7440 				if (ip_fanout_send_icmp(q, first_mp, flags,
7441 				    ICMP_DEST_UNREACHABLE,
7442 				    ICMP_PORT_UNREACHABLE,
7443 				    mctl_present, zoneid, ipst)) {
7444 					BUMP_MIB(ill->ill_ip_mib,
7445 					    udpIfStatsNoPorts);
7446 				}
7447 			}
7448 			return;
7449 		}
7450 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7451 
7452 		CONN_INC_REF(connp);
7453 		mutex_exit(&connfp->connf_lock);
7454 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7455 		    flags, recv_ill, ip_policy);
7456 		CONN_DEC_REF(connp);
7457 		return;
7458 	}
7459 	/*
7460 	 * IPv4 multicast packet being delivered to an AF_INET6
7461 	 * in6addr_any endpoint.
7462 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7463 	 * and not conn_wantpacket_v6() since any multicast membership is
7464 	 * for an IPv4-mapped multicast address.
7465 	 * The packet is sent to all clients in all zones that have joined the
7466 	 * group and match the port.
7467 	 */
7468 	while (connp != NULL) {
7469 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7470 		    srcport, v6src) &&
7471 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7472 		    (!is_system_labeled() ||
7473 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7474 		    connp)))
7475 			break;
7476 		connp = connp->conn_next;
7477 	}
7478 
7479 	if (connp == NULL ||
7480 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7481 		/*
7482 		 * No one bound to this port.  Is
7483 		 * there a client that wants all
7484 		 * unclaimed datagrams?
7485 		 */
7486 		mutex_exit(&connfp->connf_lock);
7487 
7488 		if (mctl_present)
7489 			first_mp->b_cont = mp;
7490 		else
7491 			first_mp = mp;
7492 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7493 		    NULL) {
7494 			ip_fanout_proto(q, first_mp, ill, ipha,
7495 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7496 			    recv_ill, zoneid);
7497 		} else {
7498 			/*
7499 			 * We used to attempt to send an icmp error here, but
7500 			 * since this is known to be a multicast packet
7501 			 * and we don't send icmp errors in response to
7502 			 * multicast, just drop the packet and give up sooner.
7503 			 */
7504 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7505 			freemsg(first_mp);
7506 		}
7507 		return;
7508 	}
7509 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7510 
7511 	first_connp = connp;
7512 
7513 	CONN_INC_REF(connp);
7514 	connp = connp->conn_next;
7515 	for (;;) {
7516 		while (connp != NULL) {
7517 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7518 			    ipv6_all_zeros, srcport, v6src) &&
7519 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7520 			    (!is_system_labeled() ||
7521 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7522 			    shared_addr, connp)))
7523 				break;
7524 			connp = connp->conn_next;
7525 		}
7526 		/*
7527 		 * Just copy the data part alone. The mctl part is
7528 		 * needed just for verifying policy and it is never
7529 		 * sent up.
7530 		 */
7531 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7532 		    ((mp1 = copymsg(mp)) == NULL))) {
7533 			/*
7534 			 * No more intested clients or memory
7535 			 * allocation failed
7536 			 */
7537 			connp = first_connp;
7538 			break;
7539 		}
7540 		if (first_mp != NULL) {
7541 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7542 			    ipsec_info_type == IPSEC_IN);
7543 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7544 			    ipst->ips_netstack);
7545 			if (first_mp1 == NULL) {
7546 				freemsg(mp1);
7547 				connp = first_connp;
7548 				break;
7549 			}
7550 		} else {
7551 			first_mp1 = NULL;
7552 		}
7553 		CONN_INC_REF(connp);
7554 		mutex_exit(&connfp->connf_lock);
7555 		/*
7556 		 * IPQoS notes: We don't send the packet for policy
7557 		 * processing here, will do it for the last one (below).
7558 		 * i.e. we do it per-packet now, but if we do policy
7559 		 * processing per-conn, then we would need to do it
7560 		 * here too.
7561 		 */
7562 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7563 		    ipha, flags, recv_ill, B_FALSE);
7564 		mutex_enter(&connfp->connf_lock);
7565 		/* Follow the next pointer before releasing the conn. */
7566 		next_connp = connp->conn_next;
7567 		CONN_DEC_REF(connp);
7568 		connp = next_connp;
7569 	}
7570 
7571 	/* Last one.  Send it upstream. */
7572 	mutex_exit(&connfp->connf_lock);
7573 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7574 	    recv_ill, ip_policy);
7575 	CONN_DEC_REF(connp);
7576 }
7577 
7578 /*
7579  * Complete the ip_wput header so that it
7580  * is possible to generate ICMP
7581  * errors.
7582  */
7583 int
7584 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7585 {
7586 	ire_t *ire;
7587 
7588 	if (ipha->ipha_src == INADDR_ANY) {
7589 		ire = ire_lookup_local(zoneid, ipst);
7590 		if (ire == NULL) {
7591 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7592 			return (1);
7593 		}
7594 		ipha->ipha_src = ire->ire_addr;
7595 		ire_refrele(ire);
7596 	}
7597 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7598 	ipha->ipha_hdr_checksum = 0;
7599 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7600 	return (0);
7601 }
7602 
7603 /*
7604  * Nobody should be sending
7605  * packets up this stream
7606  */
7607 static void
7608 ip_lrput(queue_t *q, mblk_t *mp)
7609 {
7610 	mblk_t *mp1;
7611 
7612 	switch (mp->b_datap->db_type) {
7613 	case M_FLUSH:
7614 		/* Turn around */
7615 		if (*mp->b_rptr & FLUSHW) {
7616 			*mp->b_rptr &= ~FLUSHR;
7617 			qreply(q, mp);
7618 			return;
7619 		}
7620 		break;
7621 	}
7622 	/* Could receive messages that passed through ar_rput */
7623 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7624 		mp1->b_prev = mp1->b_next = NULL;
7625 	freemsg(mp);
7626 }
7627 
7628 /* Nobody should be sending packets down this stream */
7629 /* ARGSUSED */
7630 void
7631 ip_lwput(queue_t *q, mblk_t *mp)
7632 {
7633 	freemsg(mp);
7634 }
7635 
7636 /*
7637  * Move the first hop in any source route to ipha_dst and remove that part of
7638  * the source route.  Called by other protocols.  Errors in option formatting
7639  * are ignored - will be handled by ip_wput_options Return the final
7640  * destination (either ipha_dst or the last entry in a source route.)
7641  */
7642 ipaddr_t
7643 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7644 {
7645 	ipoptp_t	opts;
7646 	uchar_t		*opt;
7647 	uint8_t		optval;
7648 	uint8_t		optlen;
7649 	ipaddr_t	dst;
7650 	int		i;
7651 	ire_t		*ire;
7652 	ip_stack_t	*ipst = ns->netstack_ip;
7653 
7654 	ip2dbg(("ip_massage_options\n"));
7655 	dst = ipha->ipha_dst;
7656 	for (optval = ipoptp_first(&opts, ipha);
7657 	    optval != IPOPT_EOL;
7658 	    optval = ipoptp_next(&opts)) {
7659 		opt = opts.ipoptp_cur;
7660 		switch (optval) {
7661 			uint8_t off;
7662 		case IPOPT_SSRR:
7663 		case IPOPT_LSRR:
7664 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7665 				ip1dbg(("ip_massage_options: bad src route\n"));
7666 				break;
7667 			}
7668 			optlen = opts.ipoptp_len;
7669 			off = opt[IPOPT_OFFSET];
7670 			off--;
7671 		redo_srr:
7672 			if (optlen < IP_ADDR_LEN ||
7673 			    off > optlen - IP_ADDR_LEN) {
7674 				/* End of source route */
7675 				ip1dbg(("ip_massage_options: end of SR\n"));
7676 				break;
7677 			}
7678 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7679 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7680 			    ntohl(dst)));
7681 			/*
7682 			 * Check if our address is present more than
7683 			 * once as consecutive hops in source route.
7684 			 * XXX verify per-interface ip_forwarding
7685 			 * for source route?
7686 			 */
7687 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7688 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7689 			if (ire != NULL) {
7690 				ire_refrele(ire);
7691 				off += IP_ADDR_LEN;
7692 				goto redo_srr;
7693 			}
7694 			if (dst == htonl(INADDR_LOOPBACK)) {
7695 				ip1dbg(("ip_massage_options: loopback addr in "
7696 				    "source route!\n"));
7697 				break;
7698 			}
7699 			/*
7700 			 * Update ipha_dst to be the first hop and remove the
7701 			 * first hop from the source route (by overwriting
7702 			 * part of the option with NOP options).
7703 			 */
7704 			ipha->ipha_dst = dst;
7705 			/* Put the last entry in dst */
7706 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7707 			    3;
7708 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7709 
7710 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7711 			    ntohl(dst)));
7712 			/* Move down and overwrite */
7713 			opt[IP_ADDR_LEN] = opt[0];
7714 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7715 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7716 			for (i = 0; i < IP_ADDR_LEN; i++)
7717 				opt[i] = IPOPT_NOP;
7718 			break;
7719 		}
7720 	}
7721 	return (dst);
7722 }
7723 
7724 /*
7725  * Return the network mask
7726  * associated with the specified address.
7727  */
7728 ipaddr_t
7729 ip_net_mask(ipaddr_t addr)
7730 {
7731 	uchar_t	*up = (uchar_t *)&addr;
7732 	ipaddr_t mask = 0;
7733 	uchar_t	*maskp = (uchar_t *)&mask;
7734 
7735 #if defined(__i386) || defined(__amd64)
7736 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7737 #endif
7738 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7739 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7740 #endif
7741 	if (CLASSD(addr)) {
7742 		maskp[0] = 0xF0;
7743 		return (mask);
7744 	}
7745 
7746 	/* We assume Class E default netmask to be 32 */
7747 	if (CLASSE(addr))
7748 		return (0xffffffffU);
7749 
7750 	if (addr == 0)
7751 		return (0);
7752 	maskp[0] = 0xFF;
7753 	if ((up[0] & 0x80) == 0)
7754 		return (mask);
7755 
7756 	maskp[1] = 0xFF;
7757 	if ((up[0] & 0xC0) == 0x80)
7758 		return (mask);
7759 
7760 	maskp[2] = 0xFF;
7761 	if ((up[0] & 0xE0) == 0xC0)
7762 		return (mask);
7763 
7764 	/* Otherwise return no mask */
7765 	return ((ipaddr_t)0);
7766 }
7767 
7768 /*
7769  * Helper ill lookup function used by IPsec.
7770  */
7771 ill_t *
7772 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7773 {
7774 	ill_t *ret_ill;
7775 
7776 	ASSERT(ifindex != 0);
7777 
7778 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7779 	    ipst);
7780 	if (ret_ill == NULL) {
7781 		if (isv6) {
7782 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7783 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7784 			    ifindex));
7785 		} else {
7786 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7787 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7788 			    ifindex));
7789 		}
7790 		freemsg(first_mp);
7791 		return (NULL);
7792 	}
7793 	return (ret_ill);
7794 }
7795 
7796 /*
7797  * IPv4 -
7798  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7799  * out a packet to a destination address for which we do not have specific
7800  * (or sufficient) routing information.
7801  *
7802  * NOTE : These are the scopes of some of the variables that point at IRE,
7803  *	  which needs to be followed while making any future modifications
7804  *	  to avoid memory leaks.
7805  *
7806  *	- ire and sire are the entries looked up initially by
7807  *	  ire_ftable_lookup.
7808  *	- ipif_ire is used to hold the interface ire associated with
7809  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7810  *	  it before branching out to error paths.
7811  *	- save_ire is initialized before ire_create, so that ire returned
7812  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7813  *	  before breaking out of the switch.
7814  *
7815  *	Thus on failures, we have to REFRELE only ire and sire, if they
7816  *	are not NULL.
7817  */
7818 void
7819 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7820     zoneid_t zoneid, ip_stack_t *ipst)
7821 {
7822 	areq_t	*areq;
7823 	ipaddr_t gw = 0;
7824 	ire_t	*ire = NULL;
7825 	mblk_t	*res_mp;
7826 	ipaddr_t *addrp;
7827 	ipaddr_t nexthop_addr;
7828 	ipif_t  *src_ipif = NULL;
7829 	ill_t	*dst_ill = NULL;
7830 	ipha_t  *ipha;
7831 	ire_t	*sire = NULL;
7832 	mblk_t	*first_mp;
7833 	ire_t	*save_ire;
7834 	ushort_t ire_marks = 0;
7835 	boolean_t mctl_present;
7836 	ipsec_out_t *io;
7837 	mblk_t	*saved_mp;
7838 	mblk_t	*copy_mp = NULL;
7839 	mblk_t	*xmit_mp = NULL;
7840 	ipaddr_t save_dst;
7841 	uint32_t multirt_flags =
7842 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7843 	boolean_t multirt_is_resolvable;
7844 	boolean_t multirt_resolve_next;
7845 	boolean_t unspec_src;
7846 	boolean_t ip_nexthop = B_FALSE;
7847 	tsol_ire_gw_secattr_t *attrp = NULL;
7848 	tsol_gcgrp_t *gcgrp = NULL;
7849 	tsol_gcgrp_addr_t ga;
7850 	int multirt_res_failures = 0;
7851 	int multirt_res_attempts = 0;
7852 	int multirt_already_resolved = 0;
7853 	boolean_t multirt_no_icmp_error = B_FALSE;
7854 
7855 	if (ip_debug > 2) {
7856 		/* ip1dbg */
7857 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7858 	}
7859 
7860 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7861 	if (mctl_present) {
7862 		io = (ipsec_out_t *)first_mp->b_rptr;
7863 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7864 		ASSERT(zoneid == io->ipsec_out_zoneid);
7865 		ASSERT(zoneid != ALL_ZONES);
7866 	}
7867 
7868 	ipha = (ipha_t *)mp->b_rptr;
7869 
7870 	/* All multicast lookups come through ip_newroute_ipif() */
7871 	if (CLASSD(dst)) {
7872 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7873 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7874 		freemsg(first_mp);
7875 		return;
7876 	}
7877 
7878 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7879 		ip_nexthop = B_TRUE;
7880 		nexthop_addr = io->ipsec_out_nexthop_addr;
7881 	}
7882 	/*
7883 	 * If this IRE is created for forwarding or it is not for
7884 	 * traffic for congestion controlled protocols, mark it as temporary.
7885 	 */
7886 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7887 		ire_marks |= IRE_MARK_TEMPORARY;
7888 
7889 	/*
7890 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7891 	 * chain until it gets the most specific information available.
7892 	 * For example, we know that there is no IRE_CACHE for this dest,
7893 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7894 	 * ire_ftable_lookup will look up the gateway, etc.
7895 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7896 	 * to the destination, of equal netmask length in the forward table,
7897 	 * will be recursively explored. If no information is available
7898 	 * for the final gateway of that route, we force the returned ire
7899 	 * to be equal to sire using MATCH_IRE_PARENT.
7900 	 * At least, in this case we have a starting point (in the buckets)
7901 	 * to look for other routes to the destination in the forward table.
7902 	 * This is actually used only for multirouting, where a list
7903 	 * of routes has to be processed in sequence.
7904 	 *
7905 	 * In the process of coming up with the most specific information,
7906 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7907 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7908 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7909 	 * Two caveats when handling incomplete ire's in ip_newroute:
7910 	 * - we should be careful when accessing its ire_nce (specifically
7911 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7912 	 * - not all legacy code path callers are prepared to handle
7913 	 *   incomplete ire's, so we should not create/add incomplete
7914 	 *   ire_cache entries here. (See discussion about temporary solution
7915 	 *   further below).
7916 	 *
7917 	 * In order to minimize packet dropping, and to preserve existing
7918 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7919 	 * gateway, and instead use the IF_RESOLVER ire to send out
7920 	 * another request to ARP (this is achieved by passing the
7921 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7922 	 * arp response comes back in ip_wput_nondata, we will create
7923 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7924 	 *
7925 	 * Note that this is a temporary solution; the correct solution is
7926 	 * to create an incomplete  per-dst ire_cache entry, and send the
7927 	 * packet out when the gw's nce is resolved. In order to achieve this,
7928 	 * all packet processing must have been completed prior to calling
7929 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7930 	 * to be modified to accomodate this solution.
7931 	 */
7932 	if (ip_nexthop) {
7933 		/*
7934 		 * The first time we come here, we look for an IRE_INTERFACE
7935 		 * entry for the specified nexthop, set the dst to be the
7936 		 * nexthop address and create an IRE_CACHE entry for the
7937 		 * nexthop. The next time around, we are able to find an
7938 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7939 		 * nexthop address and create an IRE_CACHE entry for the
7940 		 * destination address via the specified nexthop.
7941 		 */
7942 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7943 		    msg_getlabel(mp), ipst);
7944 		if (ire != NULL) {
7945 			gw = nexthop_addr;
7946 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7947 		} else {
7948 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7949 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7950 			    msg_getlabel(mp),
7951 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7952 			    ipst);
7953 			if (ire != NULL) {
7954 				dst = nexthop_addr;
7955 			}
7956 		}
7957 	} else {
7958 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7959 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
7960 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7961 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7962 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7963 		    ipst);
7964 	}
7965 
7966 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7967 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7968 
7969 	/*
7970 	 * This loop is run only once in most cases.
7971 	 * We loop to resolve further routes only when the destination
7972 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7973 	 */
7974 	do {
7975 		/* Clear the previous iteration's values */
7976 		if (src_ipif != NULL) {
7977 			ipif_refrele(src_ipif);
7978 			src_ipif = NULL;
7979 		}
7980 		if (dst_ill != NULL) {
7981 			ill_refrele(dst_ill);
7982 			dst_ill = NULL;
7983 		}
7984 
7985 		multirt_resolve_next = B_FALSE;
7986 		/*
7987 		 * We check if packets have to be multirouted.
7988 		 * In this case, given the current <ire, sire> couple,
7989 		 * we look for the next suitable <ire, sire>.
7990 		 * This check is done in ire_multirt_lookup(),
7991 		 * which applies various criteria to find the next route
7992 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7993 		 * unchanged if it detects it has not been tried yet.
7994 		 */
7995 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7996 			ip3dbg(("ip_newroute: starting next_resolution "
7997 			    "with first_mp %p, tag %d\n",
7998 			    (void *)first_mp,
7999 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8000 
8001 			ASSERT(sire != NULL);
8002 			multirt_is_resolvable =
8003 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8004 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
8005 
8006 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8007 			    "multirt_already_resolved %d, "
8008 			    "multirt_res_attempts %d, multirt_res_failures %d, "
8009 			    "ire %p, sire %p\n", multirt_is_resolvable,
8010 			    multirt_already_resolved, multirt_res_attempts,
8011 			    multirt_res_failures, (void *)ire, (void *)sire));
8012 
8013 			if (!multirt_is_resolvable) {
8014 				/*
8015 				 * No more multirt route to resolve; give up
8016 				 * (all routes resolved or no more
8017 				 * resolvable routes).
8018 				 */
8019 				if (ire != NULL) {
8020 					ire_refrele(ire);
8021 					ire = NULL;
8022 				}
8023 				/*
8024 				 * Generate ICMP error only if all attempts to
8025 				 * resolve multirt route failed and there is no
8026 				 * already resolved one.  Don't generate ICMP
8027 				 * error when:
8028 				 *
8029 				 *  1) there was no attempt to resolve
8030 				 *  2) at least one attempt passed
8031 				 *  3) a multirt route is already resolved
8032 				 *
8033 				 *  Case 1) may occur due to multiple
8034 				 *    resolution attempts during single
8035 				 *    ip_multirt_resolution_interval.
8036 				 *
8037 				 *  Case 2-3) means that CGTP destination is
8038 				 *    reachable via one link so we don't want to
8039 				 *    generate ICMP host unreachable error.
8040 				 */
8041 				if (multirt_res_attempts == 0 ||
8042 				    multirt_res_failures <
8043 				    multirt_res_attempts ||
8044 				    multirt_already_resolved > 0)
8045 					multirt_no_icmp_error = B_TRUE;
8046 			} else {
8047 				ASSERT(sire != NULL);
8048 				ASSERT(ire != NULL);
8049 
8050 				multirt_res_attempts++;
8051 			}
8052 		}
8053 
8054 		if (ire == NULL) {
8055 			if (ip_debug > 3) {
8056 				/* ip2dbg */
8057 				pr_addr_dbg("ip_newroute: "
8058 				    "can't resolve %s\n", AF_INET, &dst);
8059 			}
8060 			ip3dbg(("ip_newroute: "
8061 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8062 			    (void *)ire, (void *)sire,
8063 			    (int)multirt_no_icmp_error));
8064 
8065 			if (sire != NULL) {
8066 				ire_refrele(sire);
8067 				sire = NULL;
8068 			}
8069 
8070 			if (multirt_no_icmp_error) {
8071 				/* There is no need to report an ICMP error. */
8072 				MULTIRT_DEBUG_UNTAG(first_mp);
8073 				freemsg(first_mp);
8074 				return;
8075 			}
8076 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8077 			    RTA_DST, ipst);
8078 			goto icmp_err_ret;
8079 		}
8080 
8081 		/*
8082 		 * Verify that the returned IRE does not have either
8083 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8084 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8085 		 */
8086 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8087 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8088 			goto icmp_err_ret;
8089 		}
8090 		/*
8091 		 * Increment the ire_ob_pkt_count field for ire if it is an
8092 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8093 		 * increment the same for the parent IRE, sire, if it is some
8094 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8095 		 */
8096 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8097 			UPDATE_OB_PKT_COUNT(ire);
8098 			ire->ire_last_used_time = lbolt;
8099 		}
8100 
8101 		if (sire != NULL) {
8102 			gw = sire->ire_gateway_addr;
8103 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8104 			    IRE_INTERFACE)) == 0);
8105 			UPDATE_OB_PKT_COUNT(sire);
8106 			sire->ire_last_used_time = lbolt;
8107 		}
8108 		/*
8109 		 * We have a route to reach the destination.  Find the
8110 		 * appropriate ill, then get a source address using
8111 		 * ipif_select_source().
8112 		 *
8113 		 * If we are here trying to create an IRE_CACHE for an offlink
8114 		 * destination and have an IRE_CACHE entry for VNI, then use
8115 		 * ire_stq instead since VNI's queue is a black hole.
8116 		 */
8117 		if ((ire->ire_type == IRE_CACHE) &&
8118 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8119 			dst_ill = ire->ire_stq->q_ptr;
8120 			ill_refhold(dst_ill);
8121 		} else {
8122 			ill_t *ill = ire->ire_ipif->ipif_ill;
8123 
8124 			if (IS_IPMP(ill)) {
8125 				dst_ill =
8126 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8127 			} else {
8128 				dst_ill = ill;
8129 				ill_refhold(dst_ill);
8130 			}
8131 		}
8132 
8133 		if (dst_ill == NULL) {
8134 			if (ip_debug > 2) {
8135 				pr_addr_dbg("ip_newroute: no dst "
8136 				    "ill for dst %s\n", AF_INET, &dst);
8137 			}
8138 			goto icmp_err_ret;
8139 		}
8140 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8141 
8142 		/*
8143 		 * Pick the best source address from dst_ill.
8144 		 *
8145 		 * 1) Try to pick the source address from the destination
8146 		 *    route. Clustering assumes that when we have multiple
8147 		 *    prefixes hosted on an interface, the prefix of the
8148 		 *    source address matches the prefix of the destination
8149 		 *    route. We do this only if the address is not
8150 		 *    DEPRECATED.
8151 		 *
8152 		 * 2) If the conn is in a different zone than the ire, we
8153 		 *    need to pick a source address from the right zone.
8154 		 */
8155 		ASSERT(src_ipif == NULL);
8156 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8157 			/*
8158 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8159 			 * Check that the ipif matching the requested source
8160 			 * address still exists.
8161 			 */
8162 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8163 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8164 		}
8165 
8166 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8167 
8168 		if (src_ipif == NULL &&
8169 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8170 			ire_marks |= IRE_MARK_USESRC_CHECK;
8171 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8172 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8173 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8174 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8175 			    ire->ire_zoneid != ALL_ZONES) ||
8176 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8177 				/*
8178 				 * If the destination is reachable via a
8179 				 * given gateway, the selected source address
8180 				 * should be in the same subnet as the gateway.
8181 				 * Otherwise, the destination is not reachable.
8182 				 *
8183 				 * If there are no interfaces on the same subnet
8184 				 * as the destination, ipif_select_source gives
8185 				 * first non-deprecated interface which might be
8186 				 * on a different subnet than the gateway.
8187 				 * This is not desirable. Hence pass the dst_ire
8188 				 * source address to ipif_select_source.
8189 				 * It is sure that the destination is reachable
8190 				 * with the dst_ire source address subnet.
8191 				 * So passing dst_ire source address to
8192 				 * ipif_select_source will make sure that the
8193 				 * selected source will be on the same subnet
8194 				 * as dst_ire source address.
8195 				 */
8196 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8197 
8198 				src_ipif = ipif_select_source(dst_ill, saddr,
8199 				    zoneid);
8200 				if (src_ipif == NULL) {
8201 					/*
8202 					 * In the case of multirouting, it may
8203 					 * happen that ipif_select_source fails
8204 					 * as DAD may disallow use of the
8205 					 * particular source interface.  Anyway,
8206 					 * we need to continue and attempt to
8207 					 * resolve other multirt routes.
8208 					 */
8209 					if ((sire != NULL) &&
8210 					    (sire->ire_flags & RTF_MULTIRT)) {
8211 						ire_refrele(ire);
8212 						ire = NULL;
8213 						multirt_resolve_next = B_TRUE;
8214 						multirt_res_failures++;
8215 						continue;
8216 					}
8217 
8218 					if (ip_debug > 2) {
8219 						pr_addr_dbg("ip_newroute: "
8220 						    "no src for dst %s ",
8221 						    AF_INET, &dst);
8222 						printf("on interface %s\n",
8223 						    dst_ill->ill_name);
8224 					}
8225 					goto icmp_err_ret;
8226 				}
8227 			} else {
8228 				src_ipif = ire->ire_ipif;
8229 				ASSERT(src_ipif != NULL);
8230 				/* hold src_ipif for uniformity */
8231 				ipif_refhold(src_ipif);
8232 			}
8233 		}
8234 
8235 		/*
8236 		 * Assign a source address while we have the conn.
8237 		 * We can't have ip_wput_ire pick a source address when the
8238 		 * packet returns from arp since we need to look at
8239 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8240 		 * going through arp.
8241 		 *
8242 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8243 		 *	  it uses ip6i to store this information.
8244 		 */
8245 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8246 			ipha->ipha_src = src_ipif->ipif_src_addr;
8247 
8248 		if (ip_debug > 3) {
8249 			/* ip2dbg */
8250 			pr_addr_dbg("ip_newroute: first hop %s\n",
8251 			    AF_INET, &gw);
8252 		}
8253 		ip2dbg(("\tire type %s (%d)\n",
8254 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8255 
8256 		/*
8257 		 * The TTL of multirouted packets is bounded by the
8258 		 * ip_multirt_ttl ndd variable.
8259 		 */
8260 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8261 			/* Force TTL of multirouted packets */
8262 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8263 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8264 				ip2dbg(("ip_newroute: forcing multirt TTL "
8265 				    "to %d (was %d), dst 0x%08x\n",
8266 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8267 				    ntohl(sire->ire_addr)));
8268 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8269 			}
8270 		}
8271 		/*
8272 		 * At this point in ip_newroute(), ire is either the
8273 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8274 		 * destination or an IRE_INTERFACE type that should be used
8275 		 * to resolve an on-subnet destination or an on-subnet
8276 		 * next-hop gateway.
8277 		 *
8278 		 * In the IRE_CACHE case, we have the following :
8279 		 *
8280 		 * 1) src_ipif - used for getting a source address.
8281 		 *
8282 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8283 		 *    means packets using this IRE_CACHE will go out on
8284 		 *    dst_ill.
8285 		 *
8286 		 * 3) The IRE sire will point to the prefix that is the
8287 		 *    longest  matching route for the destination. These
8288 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8289 		 *
8290 		 *    The newly created IRE_CACHE entry for the off-subnet
8291 		 *    destination is tied to both the prefix route and the
8292 		 *    interface route used to resolve the next-hop gateway
8293 		 *    via the ire_phandle and ire_ihandle fields,
8294 		 *    respectively.
8295 		 *
8296 		 * In the IRE_INTERFACE case, we have the following :
8297 		 *
8298 		 * 1) src_ipif - used for getting a source address.
8299 		 *
8300 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8301 		 *    means packets using the IRE_CACHE that we will build
8302 		 *    here will go out on dst_ill.
8303 		 *
8304 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8305 		 *    to be created will only be tied to the IRE_INTERFACE
8306 		 *    that was derived from the ire_ihandle field.
8307 		 *
8308 		 *    If sire is non-NULL, it means the destination is
8309 		 *    off-link and we will first create the IRE_CACHE for the
8310 		 *    gateway. Next time through ip_newroute, we will create
8311 		 *    the IRE_CACHE for the final destination as described
8312 		 *    above.
8313 		 *
8314 		 * In both cases, after the current resolution has been
8315 		 * completed (or possibly initialised, in the IRE_INTERFACE
8316 		 * case), the loop may be re-entered to attempt the resolution
8317 		 * of another RTF_MULTIRT route.
8318 		 *
8319 		 * When an IRE_CACHE entry for the off-subnet destination is
8320 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8321 		 * for further processing in emission loops.
8322 		 */
8323 		save_ire = ire;
8324 		switch (ire->ire_type) {
8325 		case IRE_CACHE: {
8326 			ire_t	*ipif_ire;
8327 
8328 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8329 			if (gw == 0)
8330 				gw = ire->ire_gateway_addr;
8331 			/*
8332 			 * We need 3 ire's to create a new cache ire for an
8333 			 * off-link destination from the cache ire of the
8334 			 * gateway.
8335 			 *
8336 			 *	1. The prefix ire 'sire' (Note that this does
8337 			 *	   not apply to the conn_nexthop_set case)
8338 			 *	2. The cache ire of the gateway 'ire'
8339 			 *	3. The interface ire 'ipif_ire'
8340 			 *
8341 			 * We have (1) and (2). We lookup (3) below.
8342 			 *
8343 			 * If there is no interface route to the gateway,
8344 			 * it is a race condition, where we found the cache
8345 			 * but the interface route has been deleted.
8346 			 */
8347 			if (ip_nexthop) {
8348 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8349 			} else {
8350 				ipif_ire =
8351 				    ire_ihandle_lookup_offlink(ire, sire);
8352 			}
8353 			if (ipif_ire == NULL) {
8354 				ip1dbg(("ip_newroute: "
8355 				    "ire_ihandle_lookup_offlink failed\n"));
8356 				goto icmp_err_ret;
8357 			}
8358 
8359 			/*
8360 			 * Check cached gateway IRE for any security
8361 			 * attributes; if found, associate the gateway
8362 			 * credentials group to the destination IRE.
8363 			 */
8364 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8365 				mutex_enter(&attrp->igsa_lock);
8366 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8367 					GCGRP_REFHOLD(gcgrp);
8368 				mutex_exit(&attrp->igsa_lock);
8369 			}
8370 
8371 			/*
8372 			 * XXX For the source of the resolver mp,
8373 			 * we are using the same DL_UNITDATA_REQ
8374 			 * (from save_ire->ire_nce->nce_res_mp)
8375 			 * though the save_ire is not pointing at the same ill.
8376 			 * This is incorrect. We need to send it up to the
8377 			 * resolver to get the right res_mp. For ethernets
8378 			 * this may be okay (ill_type == DL_ETHER).
8379 			 */
8380 
8381 			ire = ire_create(
8382 			    (uchar_t *)&dst,		/* dest address */
8383 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8384 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8385 			    (uchar_t *)&gw,		/* gateway address */
8386 			    &save_ire->ire_max_frag,
8387 			    save_ire->ire_nce,		/* src nce */
8388 			    dst_ill->ill_rq,		/* recv-from queue */
8389 			    dst_ill->ill_wq,		/* send-to queue */
8390 			    IRE_CACHE,			/* IRE type */
8391 			    src_ipif,
8392 			    (sire != NULL) ?
8393 			    sire->ire_mask : 0, 	/* Parent mask */
8394 			    (sire != NULL) ?
8395 			    sire->ire_phandle : 0,	/* Parent handle */
8396 			    ipif_ire->ire_ihandle,	/* Interface handle */
8397 			    (sire != NULL) ? (sire->ire_flags &
8398 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8399 			    (sire != NULL) ?
8400 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8401 			    NULL,
8402 			    gcgrp,
8403 			    ipst);
8404 
8405 			if (ire == NULL) {
8406 				if (gcgrp != NULL) {
8407 					GCGRP_REFRELE(gcgrp);
8408 					gcgrp = NULL;
8409 				}
8410 				ire_refrele(ipif_ire);
8411 				ire_refrele(save_ire);
8412 				break;
8413 			}
8414 
8415 			/* reference now held by IRE */
8416 			gcgrp = NULL;
8417 
8418 			ire->ire_marks |= ire_marks;
8419 
8420 			/*
8421 			 * Prevent sire and ipif_ire from getting deleted.
8422 			 * The newly created ire is tied to both of them via
8423 			 * the phandle and ihandle respectively.
8424 			 */
8425 			if (sire != NULL) {
8426 				IRB_REFHOLD(sire->ire_bucket);
8427 				/* Has it been removed already ? */
8428 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8429 					IRB_REFRELE(sire->ire_bucket);
8430 					ire_refrele(ipif_ire);
8431 					ire_refrele(save_ire);
8432 					break;
8433 				}
8434 			}
8435 
8436 			IRB_REFHOLD(ipif_ire->ire_bucket);
8437 			/* Has it been removed already ? */
8438 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8439 				IRB_REFRELE(ipif_ire->ire_bucket);
8440 				if (sire != NULL)
8441 					IRB_REFRELE(sire->ire_bucket);
8442 				ire_refrele(ipif_ire);
8443 				ire_refrele(save_ire);
8444 				break;
8445 			}
8446 
8447 			xmit_mp = first_mp;
8448 			/*
8449 			 * In the case of multirouting, a copy
8450 			 * of the packet is done before its sending.
8451 			 * The copy is used to attempt another
8452 			 * route resolution, in a next loop.
8453 			 */
8454 			if (ire->ire_flags & RTF_MULTIRT) {
8455 				copy_mp = copymsg(first_mp);
8456 				if (copy_mp != NULL) {
8457 					xmit_mp = copy_mp;
8458 					MULTIRT_DEBUG_TAG(first_mp);
8459 				}
8460 			}
8461 
8462 			ire_add_then_send(q, ire, xmit_mp);
8463 			ire_refrele(save_ire);
8464 
8465 			/* Assert that sire is not deleted yet. */
8466 			if (sire != NULL) {
8467 				ASSERT(sire->ire_ptpn != NULL);
8468 				IRB_REFRELE(sire->ire_bucket);
8469 			}
8470 
8471 			/* Assert that ipif_ire is not deleted yet. */
8472 			ASSERT(ipif_ire->ire_ptpn != NULL);
8473 			IRB_REFRELE(ipif_ire->ire_bucket);
8474 			ire_refrele(ipif_ire);
8475 
8476 			/*
8477 			 * If copy_mp is not NULL, multirouting was
8478 			 * requested. We loop to initiate a next
8479 			 * route resolution attempt, starting from sire.
8480 			 */
8481 			if (copy_mp != NULL) {
8482 				/*
8483 				 * Search for the next unresolved
8484 				 * multirt route.
8485 				 */
8486 				copy_mp = NULL;
8487 				ipif_ire = NULL;
8488 				ire = NULL;
8489 				multirt_resolve_next = B_TRUE;
8490 				continue;
8491 			}
8492 			if (sire != NULL)
8493 				ire_refrele(sire);
8494 			ipif_refrele(src_ipif);
8495 			ill_refrele(dst_ill);
8496 			return;
8497 		}
8498 		case IRE_IF_NORESOLVER: {
8499 			if (dst_ill->ill_resolver_mp == NULL) {
8500 				ip1dbg(("ip_newroute: dst_ill %p "
8501 				    "for IRE_IF_NORESOLVER ire %p has "
8502 				    "no ill_resolver_mp\n",
8503 				    (void *)dst_ill, (void *)ire));
8504 				break;
8505 			}
8506 
8507 			/*
8508 			 * TSol note: We are creating the ire cache for the
8509 			 * destination 'dst'. If 'dst' is offlink, going
8510 			 * through the first hop 'gw', the security attributes
8511 			 * of 'dst' must be set to point to the gateway
8512 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8513 			 * is possible that 'dst' is a potential gateway that is
8514 			 * referenced by some route that has some security
8515 			 * attributes. Thus in the former case, we need to do a
8516 			 * gcgrp_lookup of 'gw' while in the latter case we
8517 			 * need to do gcgrp_lookup of 'dst' itself.
8518 			 */
8519 			ga.ga_af = AF_INET;
8520 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8521 			    &ga.ga_addr);
8522 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8523 
8524 			ire = ire_create(
8525 			    (uchar_t *)&dst,		/* dest address */
8526 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8527 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8528 			    (uchar_t *)&gw,		/* gateway address */
8529 			    &save_ire->ire_max_frag,
8530 			    NULL,			/* no src nce */
8531 			    dst_ill->ill_rq,		/* recv-from queue */
8532 			    dst_ill->ill_wq,		/* send-to queue */
8533 			    IRE_CACHE,
8534 			    src_ipif,
8535 			    save_ire->ire_mask,		/* Parent mask */
8536 			    (sire != NULL) ?		/* Parent handle */
8537 			    sire->ire_phandle : 0,
8538 			    save_ire->ire_ihandle,	/* Interface handle */
8539 			    (sire != NULL) ? sire->ire_flags &
8540 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8541 			    &(save_ire->ire_uinfo),
8542 			    NULL,
8543 			    gcgrp,
8544 			    ipst);
8545 
8546 			if (ire == NULL) {
8547 				if (gcgrp != NULL) {
8548 					GCGRP_REFRELE(gcgrp);
8549 					gcgrp = NULL;
8550 				}
8551 				ire_refrele(save_ire);
8552 				break;
8553 			}
8554 
8555 			/* reference now held by IRE */
8556 			gcgrp = NULL;
8557 
8558 			ire->ire_marks |= ire_marks;
8559 
8560 			/* Prevent save_ire from getting deleted */
8561 			IRB_REFHOLD(save_ire->ire_bucket);
8562 			/* Has it been removed already ? */
8563 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8564 				IRB_REFRELE(save_ire->ire_bucket);
8565 				ire_refrele(save_ire);
8566 				break;
8567 			}
8568 
8569 			/*
8570 			 * In the case of multirouting, a copy
8571 			 * of the packet is made before it is sent.
8572 			 * The copy is used in the next
8573 			 * loop to attempt another resolution.
8574 			 */
8575 			xmit_mp = first_mp;
8576 			if ((sire != NULL) &&
8577 			    (sire->ire_flags & RTF_MULTIRT)) {
8578 				copy_mp = copymsg(first_mp);
8579 				if (copy_mp != NULL) {
8580 					xmit_mp = copy_mp;
8581 					MULTIRT_DEBUG_TAG(first_mp);
8582 				}
8583 			}
8584 			ire_add_then_send(q, ire, xmit_mp);
8585 
8586 			/* Assert that it is not deleted yet. */
8587 			ASSERT(save_ire->ire_ptpn != NULL);
8588 			IRB_REFRELE(save_ire->ire_bucket);
8589 			ire_refrele(save_ire);
8590 
8591 			if (copy_mp != NULL) {
8592 				/*
8593 				 * If we found a (no)resolver, we ignore any
8594 				 * trailing top priority IRE_CACHE in further
8595 				 * loops. This ensures that we do not omit any
8596 				 * (no)resolver.
8597 				 * This IRE_CACHE, if any, will be processed
8598 				 * by another thread entering ip_newroute().
8599 				 * IRE_CACHE entries, if any, will be processed
8600 				 * by another thread entering ip_newroute(),
8601 				 * (upon resolver response, for instance).
8602 				 * This aims to force parallel multirt
8603 				 * resolutions as soon as a packet must be sent.
8604 				 * In the best case, after the tx of only one
8605 				 * packet, all reachable routes are resolved.
8606 				 * Otherwise, the resolution of all RTF_MULTIRT
8607 				 * routes would require several emissions.
8608 				 */
8609 				multirt_flags &= ~MULTIRT_CACHEGW;
8610 
8611 				/*
8612 				 * Search for the next unresolved multirt
8613 				 * route.
8614 				 */
8615 				copy_mp = NULL;
8616 				save_ire = NULL;
8617 				ire = NULL;
8618 				multirt_resolve_next = B_TRUE;
8619 				continue;
8620 			}
8621 
8622 			/*
8623 			 * Don't need sire anymore
8624 			 */
8625 			if (sire != NULL)
8626 				ire_refrele(sire);
8627 
8628 			ipif_refrele(src_ipif);
8629 			ill_refrele(dst_ill);
8630 			return;
8631 		}
8632 		case IRE_IF_RESOLVER:
8633 			/*
8634 			 * We can't build an IRE_CACHE yet, but at least we
8635 			 * found a resolver that can help.
8636 			 */
8637 			res_mp = dst_ill->ill_resolver_mp;
8638 			if (!OK_RESOLVER_MP(res_mp))
8639 				break;
8640 
8641 			/*
8642 			 * To be at this point in the code with a non-zero gw
8643 			 * means that dst is reachable through a gateway that
8644 			 * we have never resolved.  By changing dst to the gw
8645 			 * addr we resolve the gateway first.
8646 			 * When ire_add_then_send() tries to put the IP dg
8647 			 * to dst, it will reenter ip_newroute() at which
8648 			 * time we will find the IRE_CACHE for the gw and
8649 			 * create another IRE_CACHE in case IRE_CACHE above.
8650 			 */
8651 			if (gw != INADDR_ANY) {
8652 				/*
8653 				 * The source ipif that was determined above was
8654 				 * relative to the destination address, not the
8655 				 * gateway's. If src_ipif was not taken out of
8656 				 * the IRE_IF_RESOLVER entry, we'll need to call
8657 				 * ipif_select_source() again.
8658 				 */
8659 				if (src_ipif != ire->ire_ipif) {
8660 					ipif_refrele(src_ipif);
8661 					src_ipif = ipif_select_source(dst_ill,
8662 					    gw, zoneid);
8663 					/*
8664 					 * In the case of multirouting, it may
8665 					 * happen that ipif_select_source fails
8666 					 * as DAD may disallow use of the
8667 					 * particular source interface.  Anyway,
8668 					 * we need to continue and attempt to
8669 					 * resolve other multirt routes.
8670 					 */
8671 					if (src_ipif == NULL) {
8672 						if (sire != NULL &&
8673 						    (sire->ire_flags &
8674 						    RTF_MULTIRT)) {
8675 							ire_refrele(ire);
8676 							ire = NULL;
8677 							multirt_resolve_next =
8678 							    B_TRUE;
8679 							multirt_res_failures++;
8680 							continue;
8681 						}
8682 						if (ip_debug > 2) {
8683 							pr_addr_dbg(
8684 							    "ip_newroute: no "
8685 							    "src for gw %s ",
8686 							    AF_INET, &gw);
8687 							printf("on "
8688 							    "interface %s\n",
8689 							    dst_ill->ill_name);
8690 						}
8691 						goto icmp_err_ret;
8692 					}
8693 				}
8694 				save_dst = dst;
8695 				dst = gw;
8696 				gw = INADDR_ANY;
8697 			}
8698 
8699 			/*
8700 			 * We obtain a partial IRE_CACHE which we will pass
8701 			 * along with the resolver query.  When the response
8702 			 * comes back it will be there ready for us to add.
8703 			 * The ire_max_frag is atomically set under the
8704 			 * irebucket lock in ire_add_v[46].
8705 			 */
8706 
8707 			ire = ire_create_mp(
8708 			    (uchar_t *)&dst,		/* dest address */
8709 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8710 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8711 			    (uchar_t *)&gw,		/* gateway address */
8712 			    NULL,			/* ire_max_frag */
8713 			    NULL,			/* no src nce */
8714 			    dst_ill->ill_rq,		/* recv-from queue */
8715 			    dst_ill->ill_wq,		/* send-to queue */
8716 			    IRE_CACHE,
8717 			    src_ipif,			/* Interface ipif */
8718 			    save_ire->ire_mask,		/* Parent mask */
8719 			    0,
8720 			    save_ire->ire_ihandle,	/* Interface handle */
8721 			    0,				/* flags if any */
8722 			    &(save_ire->ire_uinfo),
8723 			    NULL,
8724 			    NULL,
8725 			    ipst);
8726 
8727 			if (ire == NULL) {
8728 				ire_refrele(save_ire);
8729 				break;
8730 			}
8731 
8732 			if ((sire != NULL) &&
8733 			    (sire->ire_flags & RTF_MULTIRT)) {
8734 				copy_mp = copymsg(first_mp);
8735 				if (copy_mp != NULL)
8736 					MULTIRT_DEBUG_TAG(copy_mp);
8737 			}
8738 
8739 			ire->ire_marks |= ire_marks;
8740 
8741 			/*
8742 			 * Construct message chain for the resolver
8743 			 * of the form:
8744 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8745 			 * Packet could contain a IPSEC_OUT mp.
8746 			 *
8747 			 * NOTE : ire will be added later when the response
8748 			 * comes back from ARP. If the response does not
8749 			 * come back, ARP frees the packet. For this reason,
8750 			 * we can't REFHOLD the bucket of save_ire to prevent
8751 			 * deletions. We may not be able to REFRELE the bucket
8752 			 * if the response never comes back. Thus, before
8753 			 * adding the ire, ire_add_v4 will make sure that the
8754 			 * interface route does not get deleted. This is the
8755 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8756 			 * where we can always prevent deletions because of
8757 			 * the synchronous nature of adding IRES i.e
8758 			 * ire_add_then_send is called after creating the IRE.
8759 			 */
8760 			ASSERT(ire->ire_mp != NULL);
8761 			ire->ire_mp->b_cont = first_mp;
8762 			/* Have saved_mp handy, for cleanup if canput fails */
8763 			saved_mp = mp;
8764 			mp = copyb(res_mp);
8765 			if (mp == NULL) {
8766 				/* Prepare for cleanup */
8767 				mp = saved_mp; /* pkt */
8768 				ire_delete(ire); /* ire_mp */
8769 				ire = NULL;
8770 				ire_refrele(save_ire);
8771 				if (copy_mp != NULL) {
8772 					MULTIRT_DEBUG_UNTAG(copy_mp);
8773 					freemsg(copy_mp);
8774 					copy_mp = NULL;
8775 				}
8776 				break;
8777 			}
8778 			linkb(mp, ire->ire_mp);
8779 
8780 			/*
8781 			 * Fill in the source and dest addrs for the resolver.
8782 			 * NOTE: this depends on memory layouts imposed by
8783 			 * ill_init().
8784 			 */
8785 			areq = (areq_t *)mp->b_rptr;
8786 			addrp = (ipaddr_t *)((char *)areq +
8787 			    areq->areq_sender_addr_offset);
8788 			*addrp = save_ire->ire_src_addr;
8789 
8790 			ire_refrele(save_ire);
8791 			addrp = (ipaddr_t *)((char *)areq +
8792 			    areq->areq_target_addr_offset);
8793 			*addrp = dst;
8794 			/* Up to the resolver. */
8795 			if (canputnext(dst_ill->ill_rq) &&
8796 			    !(dst_ill->ill_arp_closing)) {
8797 				putnext(dst_ill->ill_rq, mp);
8798 				ire = NULL;
8799 				if (copy_mp != NULL) {
8800 					/*
8801 					 * If we found a resolver, we ignore
8802 					 * any trailing top priority IRE_CACHE
8803 					 * in the further loops. This ensures
8804 					 * that we do not omit any resolver.
8805 					 * IRE_CACHE entries, if any, will be
8806 					 * processed next time we enter
8807 					 * ip_newroute().
8808 					 */
8809 					multirt_flags &= ~MULTIRT_CACHEGW;
8810 					/*
8811 					 * Search for the next unresolved
8812 					 * multirt route.
8813 					 */
8814 					first_mp = copy_mp;
8815 					copy_mp = NULL;
8816 					/* Prepare the next resolution loop. */
8817 					mp = first_mp;
8818 					EXTRACT_PKT_MP(mp, first_mp,
8819 					    mctl_present);
8820 					if (mctl_present)
8821 						io = (ipsec_out_t *)
8822 						    first_mp->b_rptr;
8823 					ipha = (ipha_t *)mp->b_rptr;
8824 
8825 					ASSERT(sire != NULL);
8826 
8827 					dst = save_dst;
8828 					multirt_resolve_next = B_TRUE;
8829 					continue;
8830 				}
8831 
8832 				if (sire != NULL)
8833 					ire_refrele(sire);
8834 
8835 				/*
8836 				 * The response will come back in ip_wput
8837 				 * with db_type IRE_DB_TYPE.
8838 				 */
8839 				ipif_refrele(src_ipif);
8840 				ill_refrele(dst_ill);
8841 				return;
8842 			} else {
8843 				/* Prepare for cleanup */
8844 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8845 				    mp);
8846 				mp->b_cont = NULL;
8847 				freeb(mp); /* areq */
8848 				/*
8849 				 * this is an ire that is not added to the
8850 				 * cache. ire_freemblk will handle the release
8851 				 * of any resources associated with the ire.
8852 				 */
8853 				ire_delete(ire); /* ire_mp */
8854 				mp = saved_mp; /* pkt */
8855 				ire = NULL;
8856 				if (copy_mp != NULL) {
8857 					MULTIRT_DEBUG_UNTAG(copy_mp);
8858 					freemsg(copy_mp);
8859 					copy_mp = NULL;
8860 				}
8861 				break;
8862 			}
8863 		default:
8864 			break;
8865 		}
8866 	} while (multirt_resolve_next);
8867 
8868 	ip1dbg(("ip_newroute: dropped\n"));
8869 	/* Did this packet originate externally? */
8870 	if (mp->b_prev) {
8871 		mp->b_next = NULL;
8872 		mp->b_prev = NULL;
8873 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8874 	} else {
8875 		if (dst_ill != NULL) {
8876 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8877 		} else {
8878 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8879 		}
8880 	}
8881 	ASSERT(copy_mp == NULL);
8882 	MULTIRT_DEBUG_UNTAG(first_mp);
8883 	freemsg(first_mp);
8884 	if (ire != NULL)
8885 		ire_refrele(ire);
8886 	if (sire != NULL)
8887 		ire_refrele(sire);
8888 	if (src_ipif != NULL)
8889 		ipif_refrele(src_ipif);
8890 	if (dst_ill != NULL)
8891 		ill_refrele(dst_ill);
8892 	return;
8893 
8894 icmp_err_ret:
8895 	ip1dbg(("ip_newroute: no route\n"));
8896 	if (src_ipif != NULL)
8897 		ipif_refrele(src_ipif);
8898 	if (dst_ill != NULL)
8899 		ill_refrele(dst_ill);
8900 	if (sire != NULL)
8901 		ire_refrele(sire);
8902 	/* Did this packet originate externally? */
8903 	if (mp->b_prev) {
8904 		mp->b_next = NULL;
8905 		mp->b_prev = NULL;
8906 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8907 		q = WR(q);
8908 	} else {
8909 		/*
8910 		 * There is no outgoing ill, so just increment the
8911 		 * system MIB.
8912 		 */
8913 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8914 		/*
8915 		 * Since ip_wput() isn't close to finished, we fill
8916 		 * in enough of the header for credible error reporting.
8917 		 */
8918 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8919 			/* Failed */
8920 			MULTIRT_DEBUG_UNTAG(first_mp);
8921 			freemsg(first_mp);
8922 			if (ire != NULL)
8923 				ire_refrele(ire);
8924 			return;
8925 		}
8926 	}
8927 
8928 	/*
8929 	 * At this point we will have ire only if RTF_BLACKHOLE
8930 	 * or RTF_REJECT flags are set on the IRE. It will not
8931 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8932 	 */
8933 	if (ire != NULL) {
8934 		if (ire->ire_flags & RTF_BLACKHOLE) {
8935 			ire_refrele(ire);
8936 			MULTIRT_DEBUG_UNTAG(first_mp);
8937 			freemsg(first_mp);
8938 			return;
8939 		}
8940 		ire_refrele(ire);
8941 	}
8942 	if (ip_source_routed(ipha, ipst)) {
8943 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8944 		    zoneid, ipst);
8945 		return;
8946 	}
8947 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8948 }
8949 
8950 ip_opt_info_t zero_info;
8951 
8952 /*
8953  * IPv4 -
8954  * ip_newroute_ipif is called by ip_wput_multicast and
8955  * ip_rput_forward_multicast whenever we need to send
8956  * out a packet to a destination address for which we do not have specific
8957  * routing information. It is used when the packet will be sent out
8958  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8959  * socket option is set or icmp error message wants to go out on a particular
8960  * interface for a unicast packet.
8961  *
8962  * In most cases, the destination address is resolved thanks to the ipif
8963  * intrinsic resolver. However, there are some cases where the call to
8964  * ip_newroute_ipif must take into account the potential presence of
8965  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8966  * that uses the interface. This is specified through flags,
8967  * which can be a combination of:
8968  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8969  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8970  *   and flags. Additionally, the packet source address has to be set to
8971  *   the specified address. The caller is thus expected to set this flag
8972  *   if the packet has no specific source address yet.
8973  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8974  *   flag, the resulting ire will inherit the flag. All unresolved routes
8975  *   to the destination must be explored in the same call to
8976  *   ip_newroute_ipif().
8977  */
8978 static void
8979 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8980     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8981 {
8982 	areq_t	*areq;
8983 	ire_t	*ire = NULL;
8984 	mblk_t	*res_mp;
8985 	ipaddr_t *addrp;
8986 	mblk_t *first_mp;
8987 	ire_t	*save_ire = NULL;
8988 	ipif_t	*src_ipif = NULL;
8989 	ushort_t ire_marks = 0;
8990 	ill_t	*dst_ill = NULL;
8991 	ipha_t *ipha;
8992 	mblk_t	*saved_mp;
8993 	ire_t   *fire = NULL;
8994 	mblk_t  *copy_mp = NULL;
8995 	boolean_t multirt_resolve_next;
8996 	boolean_t unspec_src;
8997 	ipaddr_t ipha_dst;
8998 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8999 
9000 	/*
9001 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9002 	 * here for uniformity
9003 	 */
9004 	ipif_refhold(ipif);
9005 
9006 	/*
9007 	 * This loop is run only once in most cases.
9008 	 * We loop to resolve further routes only when the destination
9009 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9010 	 */
9011 	do {
9012 		if (dst_ill != NULL) {
9013 			ill_refrele(dst_ill);
9014 			dst_ill = NULL;
9015 		}
9016 		if (src_ipif != NULL) {
9017 			ipif_refrele(src_ipif);
9018 			src_ipif = NULL;
9019 		}
9020 		multirt_resolve_next = B_FALSE;
9021 
9022 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9023 		    ipif->ipif_ill->ill_name));
9024 
9025 		first_mp = mp;
9026 		if (DB_TYPE(mp) == M_CTL)
9027 			mp = mp->b_cont;
9028 		ipha = (ipha_t *)mp->b_rptr;
9029 
9030 		/*
9031 		 * Save the packet destination address, we may need it after
9032 		 * the packet has been consumed.
9033 		 */
9034 		ipha_dst = ipha->ipha_dst;
9035 
9036 		/*
9037 		 * If the interface is a pt-pt interface we look for an
9038 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9039 		 * local_address and the pt-pt destination address. Otherwise
9040 		 * we just match the local address.
9041 		 * NOTE: dst could be different than ipha->ipha_dst in case
9042 		 * of sending igmp multicast packets over a point-to-point
9043 		 * connection.
9044 		 * Thus we must be careful enough to check ipha_dst to be a
9045 		 * multicast address, otherwise it will take xmit_if path for
9046 		 * multicast packets resulting into kernel stack overflow by
9047 		 * repeated calls to ip_newroute_ipif from ire_send().
9048 		 */
9049 		if (CLASSD(ipha_dst) &&
9050 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9051 			goto err_ret;
9052 		}
9053 
9054 		/*
9055 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9056 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9057 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9058 		 * propagate its flags to the new ire.
9059 		 */
9060 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9061 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9062 			ip2dbg(("ip_newroute_ipif: "
9063 			    "ipif_lookup_multi_ire("
9064 			    "ipif %p, dst %08x) = fire %p\n",
9065 			    (void *)ipif, ntohl(dst), (void *)fire));
9066 		}
9067 
9068 		/*
9069 		 * Note: While we pick a dst_ill we are really only
9070 		 * interested in the ill for load spreading. The source
9071 		 * ipif is determined by source address selection below.
9072 		 */
9073 		if (IS_IPMP(ipif->ipif_ill)) {
9074 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9075 
9076 			if (CLASSD(ipha_dst))
9077 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9078 			else
9079 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9080 		} else {
9081 			dst_ill = ipif->ipif_ill;
9082 			ill_refhold(dst_ill);
9083 		}
9084 
9085 		if (dst_ill == NULL) {
9086 			if (ip_debug > 2) {
9087 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9088 				    "for dst %s\n", AF_INET, &dst);
9089 			}
9090 			goto err_ret;
9091 		}
9092 
9093 		/*
9094 		 * Pick a source address preferring non-deprecated ones.
9095 		 * Unlike ip_newroute, we don't do any source address
9096 		 * selection here since for multicast it really does not help
9097 		 * in inbound load spreading as in the unicast case.
9098 		 */
9099 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9100 		    (fire->ire_flags & RTF_SETSRC)) {
9101 			/*
9102 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9103 			 * on that interface. This ire has RTF_SETSRC flag, so
9104 			 * the source address of the packet must be changed.
9105 			 * Check that the ipif matching the requested source
9106 			 * address still exists.
9107 			 */
9108 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9109 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9110 		}
9111 
9112 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9113 
9114 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9115 		    (IS_IPMP(ipif->ipif_ill) ||
9116 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9117 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9118 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9119 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9120 		    (src_ipif == NULL) &&
9121 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9122 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9123 			if (src_ipif == NULL) {
9124 				if (ip_debug > 2) {
9125 					/* ip1dbg */
9126 					pr_addr_dbg("ip_newroute_ipif: "
9127 					    "no src for dst %s",
9128 					    AF_INET, &dst);
9129 				}
9130 				ip1dbg((" on interface %s\n",
9131 				    dst_ill->ill_name));
9132 				goto err_ret;
9133 			}
9134 			ipif_refrele(ipif);
9135 			ipif = src_ipif;
9136 			ipif_refhold(ipif);
9137 		}
9138 		if (src_ipif == NULL) {
9139 			src_ipif = ipif;
9140 			ipif_refhold(src_ipif);
9141 		}
9142 
9143 		/*
9144 		 * Assign a source address while we have the conn.
9145 		 * We can't have ip_wput_ire pick a source address when the
9146 		 * packet returns from arp since conn_unspec_src might be set
9147 		 * and we lose the conn when going through arp.
9148 		 */
9149 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9150 			ipha->ipha_src = src_ipif->ipif_src_addr;
9151 
9152 		/*
9153 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9154 		 * that the outgoing interface does not have an interface ire.
9155 		 */
9156 		if (CLASSD(ipha_dst) && (connp == NULL ||
9157 		    connp->conn_outgoing_ill == NULL) &&
9158 		    infop->ip_opt_ill_index == 0) {
9159 			/* ipif_to_ire returns an held ire */
9160 			ire = ipif_to_ire(ipif);
9161 			if (ire == NULL)
9162 				goto err_ret;
9163 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9164 				goto err_ret;
9165 			save_ire = ire;
9166 
9167 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9168 			    "flags %04x\n",
9169 			    (void *)ire, (void *)ipif, flags));
9170 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9171 			    (fire->ire_flags & RTF_MULTIRT)) {
9172 				/*
9173 				 * As requested by flags, an IRE_OFFSUBNET was
9174 				 * looked up on that interface. This ire has
9175 				 * RTF_MULTIRT flag, so the resolution loop will
9176 				 * be re-entered to resolve additional routes on
9177 				 * other interfaces. For that purpose, a copy of
9178 				 * the packet is performed at this point.
9179 				 */
9180 				fire->ire_last_used_time = lbolt;
9181 				copy_mp = copymsg(first_mp);
9182 				if (copy_mp) {
9183 					MULTIRT_DEBUG_TAG(copy_mp);
9184 				}
9185 			}
9186 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9187 			    (fire->ire_flags & RTF_SETSRC)) {
9188 				/*
9189 				 * As requested by flags, an IRE_OFFSUBET was
9190 				 * looked up on that interface. This ire has
9191 				 * RTF_SETSRC flag, so the source address of the
9192 				 * packet must be changed.
9193 				 */
9194 				ipha->ipha_src = fire->ire_src_addr;
9195 			}
9196 		} else {
9197 			/*
9198 			 * The only ways we can come here are:
9199 			 * 1) IP_BOUND_IF socket option is set
9200 			 * 2) SO_DONTROUTE socket option is set
9201 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9202 			 * In all cases, the new ire will not be added
9203 			 * into cache table.
9204 			 */
9205 			ASSERT(connp == NULL || connp->conn_dontroute ||
9206 			    connp->conn_outgoing_ill != NULL ||
9207 			    infop->ip_opt_ill_index != 0);
9208 			ire_marks |= IRE_MARK_NOADD;
9209 		}
9210 
9211 		switch (ipif->ipif_net_type) {
9212 		case IRE_IF_NORESOLVER: {
9213 			/* We have what we need to build an IRE_CACHE. */
9214 
9215 			if (dst_ill->ill_resolver_mp == NULL) {
9216 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9217 				    "for IRE_IF_NORESOLVER ire %p has "
9218 				    "no ill_resolver_mp\n",
9219 				    (void *)dst_ill, (void *)ire));
9220 				break;
9221 			}
9222 
9223 			/*
9224 			 * The new ire inherits the IRE_OFFSUBNET flags
9225 			 * and source address, if this was requested.
9226 			 */
9227 			ire = ire_create(
9228 			    (uchar_t *)&dst,		/* dest address */
9229 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9230 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9231 			    NULL,			/* gateway address */
9232 			    &ipif->ipif_mtu,
9233 			    NULL,			/* no src nce */
9234 			    dst_ill->ill_rq,		/* recv-from queue */
9235 			    dst_ill->ill_wq,		/* send-to queue */
9236 			    IRE_CACHE,
9237 			    src_ipif,
9238 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9239 			    (fire != NULL) ?		/* Parent handle */
9240 			    fire->ire_phandle : 0,
9241 			    (save_ire != NULL) ?	/* Interface handle */
9242 			    save_ire->ire_ihandle : 0,
9243 			    (fire != NULL) ?
9244 			    (fire->ire_flags &
9245 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9246 			    (save_ire == NULL ? &ire_uinfo_null :
9247 			    &save_ire->ire_uinfo),
9248 			    NULL,
9249 			    NULL,
9250 			    ipst);
9251 
9252 			if (ire == NULL) {
9253 				if (save_ire != NULL)
9254 					ire_refrele(save_ire);
9255 				break;
9256 			}
9257 
9258 			ire->ire_marks |= ire_marks;
9259 
9260 			/*
9261 			 * If IRE_MARK_NOADD is set then we need to convert
9262 			 * the max_fragp to a useable value now. This is
9263 			 * normally done in ire_add_v[46]. We also need to
9264 			 * associate the ire with an nce (normally would be
9265 			 * done in ip_wput_nondata()).
9266 			 *
9267 			 * Note that IRE_MARK_NOADD packets created here
9268 			 * do not have a non-null ire_mp pointer. The null
9269 			 * value of ire_bucket indicates that they were
9270 			 * never added.
9271 			 */
9272 			if (ire->ire_marks & IRE_MARK_NOADD) {
9273 				uint_t  max_frag;
9274 
9275 				max_frag = *ire->ire_max_fragp;
9276 				ire->ire_max_fragp = NULL;
9277 				ire->ire_max_frag = max_frag;
9278 
9279 				if ((ire->ire_nce = ndp_lookup_v4(
9280 				    ire_to_ill(ire),
9281 				    (ire->ire_gateway_addr != INADDR_ANY ?
9282 				    &ire->ire_gateway_addr : &ire->ire_addr),
9283 				    B_FALSE)) == NULL) {
9284 					if (save_ire != NULL)
9285 						ire_refrele(save_ire);
9286 					break;
9287 				}
9288 				ASSERT(ire->ire_nce->nce_state ==
9289 				    ND_REACHABLE);
9290 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9291 			}
9292 
9293 			/* Prevent save_ire from getting deleted */
9294 			if (save_ire != NULL) {
9295 				IRB_REFHOLD(save_ire->ire_bucket);
9296 				/* Has it been removed already ? */
9297 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9298 					IRB_REFRELE(save_ire->ire_bucket);
9299 					ire_refrele(save_ire);
9300 					break;
9301 				}
9302 			}
9303 
9304 			ire_add_then_send(q, ire, first_mp);
9305 
9306 			/* Assert that save_ire is not deleted yet. */
9307 			if (save_ire != NULL) {
9308 				ASSERT(save_ire->ire_ptpn != NULL);
9309 				IRB_REFRELE(save_ire->ire_bucket);
9310 				ire_refrele(save_ire);
9311 				save_ire = NULL;
9312 			}
9313 			if (fire != NULL) {
9314 				ire_refrele(fire);
9315 				fire = NULL;
9316 			}
9317 
9318 			/*
9319 			 * the resolution loop is re-entered if this
9320 			 * was requested through flags and if we
9321 			 * actually are in a multirouting case.
9322 			 */
9323 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9324 				boolean_t need_resolve =
9325 				    ire_multirt_need_resolve(ipha_dst,
9326 				    msg_getlabel(copy_mp), ipst);
9327 				if (!need_resolve) {
9328 					MULTIRT_DEBUG_UNTAG(copy_mp);
9329 					freemsg(copy_mp);
9330 					copy_mp = NULL;
9331 				} else {
9332 					/*
9333 					 * ipif_lookup_group() calls
9334 					 * ire_lookup_multi() that uses
9335 					 * ire_ftable_lookup() to find
9336 					 * an IRE_INTERFACE for the group.
9337 					 * In the multirt case,
9338 					 * ire_lookup_multi() then invokes
9339 					 * ire_multirt_lookup() to find
9340 					 * the next resolvable ire.
9341 					 * As a result, we obtain an new
9342 					 * interface, derived from the
9343 					 * next ire.
9344 					 */
9345 					ipif_refrele(ipif);
9346 					ipif = ipif_lookup_group(ipha_dst,
9347 					    zoneid, ipst);
9348 					ip2dbg(("ip_newroute_ipif: "
9349 					    "multirt dst %08x, ipif %p\n",
9350 					    htonl(dst), (void *)ipif));
9351 					if (ipif != NULL) {
9352 						mp = copy_mp;
9353 						copy_mp = NULL;
9354 						multirt_resolve_next = B_TRUE;
9355 						continue;
9356 					} else {
9357 						freemsg(copy_mp);
9358 					}
9359 				}
9360 			}
9361 			if (ipif != NULL)
9362 				ipif_refrele(ipif);
9363 			ill_refrele(dst_ill);
9364 			ipif_refrele(src_ipif);
9365 			return;
9366 		}
9367 		case IRE_IF_RESOLVER:
9368 			/*
9369 			 * We can't build an IRE_CACHE yet, but at least
9370 			 * we found a resolver that can help.
9371 			 */
9372 			res_mp = dst_ill->ill_resolver_mp;
9373 			if (!OK_RESOLVER_MP(res_mp))
9374 				break;
9375 
9376 			/*
9377 			 * We obtain a partial IRE_CACHE which we will pass
9378 			 * along with the resolver query.  When the response
9379 			 * comes back it will be there ready for us to add.
9380 			 * The new ire inherits the IRE_OFFSUBNET flags
9381 			 * and source address, if this was requested.
9382 			 * The ire_max_frag is atomically set under the
9383 			 * irebucket lock in ire_add_v[46]. Only in the
9384 			 * case of IRE_MARK_NOADD, we set it here itself.
9385 			 */
9386 			ire = ire_create_mp(
9387 			    (uchar_t *)&dst,		/* dest address */
9388 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9389 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9390 			    NULL,			/* gateway address */
9391 			    (ire_marks & IRE_MARK_NOADD) ?
9392 			    ipif->ipif_mtu : 0,		/* max_frag */
9393 			    NULL,			/* no src nce */
9394 			    dst_ill->ill_rq,		/* recv-from queue */
9395 			    dst_ill->ill_wq,		/* send-to queue */
9396 			    IRE_CACHE,
9397 			    src_ipif,
9398 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9399 			    (fire != NULL) ?		/* Parent handle */
9400 			    fire->ire_phandle : 0,
9401 			    (save_ire != NULL) ?	/* Interface handle */
9402 			    save_ire->ire_ihandle : 0,
9403 			    (fire != NULL) ?		/* flags if any */
9404 			    (fire->ire_flags &
9405 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9406 			    (save_ire == NULL ? &ire_uinfo_null :
9407 			    &save_ire->ire_uinfo),
9408 			    NULL,
9409 			    NULL,
9410 			    ipst);
9411 
9412 			if (save_ire != NULL) {
9413 				ire_refrele(save_ire);
9414 				save_ire = NULL;
9415 			}
9416 			if (ire == NULL)
9417 				break;
9418 
9419 			ire->ire_marks |= ire_marks;
9420 			/*
9421 			 * Construct message chain for the resolver of the
9422 			 * form:
9423 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9424 			 *
9425 			 * NOTE : ire will be added later when the response
9426 			 * comes back from ARP. If the response does not
9427 			 * come back, ARP frees the packet. For this reason,
9428 			 * we can't REFHOLD the bucket of save_ire to prevent
9429 			 * deletions. We may not be able to REFRELE the
9430 			 * bucket if the response never comes back.
9431 			 * Thus, before adding the ire, ire_add_v4 will make
9432 			 * sure that the interface route does not get deleted.
9433 			 * This is the only case unlike ip_newroute_v6,
9434 			 * ip_newroute_ipif_v6 where we can always prevent
9435 			 * deletions because ire_add_then_send is called after
9436 			 * creating the IRE.
9437 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9438 			 * does not add this IRE into the IRE CACHE.
9439 			 */
9440 			ASSERT(ire->ire_mp != NULL);
9441 			ire->ire_mp->b_cont = first_mp;
9442 			/* Have saved_mp handy, for cleanup if canput fails */
9443 			saved_mp = mp;
9444 			mp = copyb(res_mp);
9445 			if (mp == NULL) {
9446 				/* Prepare for cleanup */
9447 				mp = saved_mp; /* pkt */
9448 				ire_delete(ire); /* ire_mp */
9449 				ire = NULL;
9450 				if (copy_mp != NULL) {
9451 					MULTIRT_DEBUG_UNTAG(copy_mp);
9452 					freemsg(copy_mp);
9453 					copy_mp = NULL;
9454 				}
9455 				break;
9456 			}
9457 			linkb(mp, ire->ire_mp);
9458 
9459 			/*
9460 			 * Fill in the source and dest addrs for the resolver.
9461 			 * NOTE: this depends on memory layouts imposed by
9462 			 * ill_init().  There are corner cases above where we
9463 			 * might've created the IRE with an INADDR_ANY source
9464 			 * address (e.g., if the zeroth ipif on an underlying
9465 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9466 			 * on the ill has a usable test address).  If so, tell
9467 			 * ARP to use ipha_src as its sender address.
9468 			 */
9469 			areq = (areq_t *)mp->b_rptr;
9470 			addrp = (ipaddr_t *)((char *)areq +
9471 			    areq->areq_sender_addr_offset);
9472 			if (ire->ire_src_addr != INADDR_ANY)
9473 				*addrp = ire->ire_src_addr;
9474 			else
9475 				*addrp = ipha->ipha_src;
9476 			addrp = (ipaddr_t *)((char *)areq +
9477 			    areq->areq_target_addr_offset);
9478 			*addrp = dst;
9479 			/* Up to the resolver. */
9480 			if (canputnext(dst_ill->ill_rq) &&
9481 			    !(dst_ill->ill_arp_closing)) {
9482 				putnext(dst_ill->ill_rq, mp);
9483 				/*
9484 				 * The response will come back in ip_wput
9485 				 * with db_type IRE_DB_TYPE.
9486 				 */
9487 			} else {
9488 				mp->b_cont = NULL;
9489 				freeb(mp); /* areq */
9490 				ire_delete(ire); /* ire_mp */
9491 				saved_mp->b_next = NULL;
9492 				saved_mp->b_prev = NULL;
9493 				freemsg(first_mp); /* pkt */
9494 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9495 			}
9496 
9497 			if (fire != NULL) {
9498 				ire_refrele(fire);
9499 				fire = NULL;
9500 			}
9501 
9502 			/*
9503 			 * The resolution loop is re-entered if this was
9504 			 * requested through flags and we actually are
9505 			 * in a multirouting case.
9506 			 */
9507 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9508 				boolean_t need_resolve =
9509 				    ire_multirt_need_resolve(ipha_dst,
9510 				    msg_getlabel(copy_mp), ipst);
9511 				if (!need_resolve) {
9512 					MULTIRT_DEBUG_UNTAG(copy_mp);
9513 					freemsg(copy_mp);
9514 					copy_mp = NULL;
9515 				} else {
9516 					/*
9517 					 * ipif_lookup_group() calls
9518 					 * ire_lookup_multi() that uses
9519 					 * ire_ftable_lookup() to find
9520 					 * an IRE_INTERFACE for the group.
9521 					 * In the multirt case,
9522 					 * ire_lookup_multi() then invokes
9523 					 * ire_multirt_lookup() to find
9524 					 * the next resolvable ire.
9525 					 * As a result, we obtain an new
9526 					 * interface, derived from the
9527 					 * next ire.
9528 					 */
9529 					ipif_refrele(ipif);
9530 					ipif = ipif_lookup_group(ipha_dst,
9531 					    zoneid, ipst);
9532 					if (ipif != NULL) {
9533 						mp = copy_mp;
9534 						copy_mp = NULL;
9535 						multirt_resolve_next = B_TRUE;
9536 						continue;
9537 					} else {
9538 						freemsg(copy_mp);
9539 					}
9540 				}
9541 			}
9542 			if (ipif != NULL)
9543 				ipif_refrele(ipif);
9544 			ill_refrele(dst_ill);
9545 			ipif_refrele(src_ipif);
9546 			return;
9547 		default:
9548 			break;
9549 		}
9550 	} while (multirt_resolve_next);
9551 
9552 err_ret:
9553 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9554 	if (fire != NULL)
9555 		ire_refrele(fire);
9556 	ipif_refrele(ipif);
9557 	/* Did this packet originate externally? */
9558 	if (dst_ill != NULL)
9559 		ill_refrele(dst_ill);
9560 	if (src_ipif != NULL)
9561 		ipif_refrele(src_ipif);
9562 	if (mp->b_prev || mp->b_next) {
9563 		mp->b_next = NULL;
9564 		mp->b_prev = NULL;
9565 	} else {
9566 		/*
9567 		 * Since ip_wput() isn't close to finished, we fill
9568 		 * in enough of the header for credible error reporting.
9569 		 */
9570 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9571 			/* Failed */
9572 			freemsg(first_mp);
9573 			if (ire != NULL)
9574 				ire_refrele(ire);
9575 			return;
9576 		}
9577 	}
9578 	/*
9579 	 * At this point we will have ire only if RTF_BLACKHOLE
9580 	 * or RTF_REJECT flags are set on the IRE. It will not
9581 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9582 	 */
9583 	if (ire != NULL) {
9584 		if (ire->ire_flags & RTF_BLACKHOLE) {
9585 			ire_refrele(ire);
9586 			freemsg(first_mp);
9587 			return;
9588 		}
9589 		ire_refrele(ire);
9590 	}
9591 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9592 }
9593 
9594 /* Name/Value Table Lookup Routine */
9595 char *
9596 ip_nv_lookup(nv_t *nv, int value)
9597 {
9598 	if (!nv)
9599 		return (NULL);
9600 	for (; nv->nv_name; nv++) {
9601 		if (nv->nv_value == value)
9602 			return (nv->nv_name);
9603 	}
9604 	return ("unknown");
9605 }
9606 
9607 /*
9608  * This is a module open, i.e. this is a control stream for access
9609  * to a DLPI device.  We allocate an ill_t as the instance data in
9610  * this case.
9611  */
9612 int
9613 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9614 {
9615 	ill_t	*ill;
9616 	int	err;
9617 	zoneid_t zoneid;
9618 	netstack_t *ns;
9619 	ip_stack_t *ipst;
9620 
9621 	/*
9622 	 * Prevent unprivileged processes from pushing IP so that
9623 	 * they can't send raw IP.
9624 	 */
9625 	if (secpolicy_net_rawaccess(credp) != 0)
9626 		return (EPERM);
9627 
9628 	ns = netstack_find_by_cred(credp);
9629 	ASSERT(ns != NULL);
9630 	ipst = ns->netstack_ip;
9631 	ASSERT(ipst != NULL);
9632 
9633 	/*
9634 	 * For exclusive stacks we set the zoneid to zero
9635 	 * to make IP operate as if in the global zone.
9636 	 */
9637 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9638 		zoneid = GLOBAL_ZONEID;
9639 	else
9640 		zoneid = crgetzoneid(credp);
9641 
9642 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9643 	q->q_ptr = WR(q)->q_ptr = ill;
9644 	ill->ill_ipst = ipst;
9645 	ill->ill_zoneid = zoneid;
9646 
9647 	/*
9648 	 * ill_init initializes the ill fields and then sends down
9649 	 * down a DL_INFO_REQ after calling qprocson.
9650 	 */
9651 	err = ill_init(q, ill);
9652 	if (err != 0) {
9653 		mi_free(ill);
9654 		netstack_rele(ipst->ips_netstack);
9655 		q->q_ptr = NULL;
9656 		WR(q)->q_ptr = NULL;
9657 		return (err);
9658 	}
9659 
9660 	/* ill_init initializes the ipsq marking this thread as writer */
9661 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9662 	/* Wait for the DL_INFO_ACK */
9663 	mutex_enter(&ill->ill_lock);
9664 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9665 		/*
9666 		 * Return value of 0 indicates a pending signal.
9667 		 */
9668 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9669 		if (err == 0) {
9670 			mutex_exit(&ill->ill_lock);
9671 			(void) ip_close(q, 0);
9672 			return (EINTR);
9673 		}
9674 	}
9675 	mutex_exit(&ill->ill_lock);
9676 
9677 	/*
9678 	 * ip_rput_other could have set an error  in ill_error on
9679 	 * receipt of M_ERROR.
9680 	 */
9681 
9682 	err = ill->ill_error;
9683 	if (err != 0) {
9684 		(void) ip_close(q, 0);
9685 		return (err);
9686 	}
9687 
9688 	ill->ill_credp = credp;
9689 	crhold(credp);
9690 
9691 	mutex_enter(&ipst->ips_ip_mi_lock);
9692 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9693 	    credp);
9694 	mutex_exit(&ipst->ips_ip_mi_lock);
9695 	if (err) {
9696 		(void) ip_close(q, 0);
9697 		return (err);
9698 	}
9699 	return (0);
9700 }
9701 
9702 /* For /dev/ip aka AF_INET open */
9703 int
9704 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9705 {
9706 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9707 }
9708 
9709 /* For /dev/ip6 aka AF_INET6 open */
9710 int
9711 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9712 {
9713 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9714 }
9715 
9716 /* IP open routine. */
9717 int
9718 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9719     boolean_t isv6)
9720 {
9721 	conn_t 		*connp;
9722 	major_t		maj;
9723 	zoneid_t	zoneid;
9724 	netstack_t	*ns;
9725 	ip_stack_t	*ipst;
9726 
9727 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9728 
9729 	/* Allow reopen. */
9730 	if (q->q_ptr != NULL)
9731 		return (0);
9732 
9733 	if (sflag & MODOPEN) {
9734 		/* This is a module open */
9735 		return (ip_modopen(q, devp, flag, sflag, credp));
9736 	}
9737 
9738 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9739 		/*
9740 		 * Non streams based socket looking for a stream
9741 		 * to access IP
9742 		 */
9743 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9744 		    credp, isv6));
9745 	}
9746 
9747 	ns = netstack_find_by_cred(credp);
9748 	ASSERT(ns != NULL);
9749 	ipst = ns->netstack_ip;
9750 	ASSERT(ipst != NULL);
9751 
9752 	/*
9753 	 * For exclusive stacks we set the zoneid to zero
9754 	 * to make IP operate as if in the global zone.
9755 	 */
9756 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9757 		zoneid = GLOBAL_ZONEID;
9758 	else
9759 		zoneid = crgetzoneid(credp);
9760 
9761 	/*
9762 	 * We are opening as a device. This is an IP client stream, and we
9763 	 * allocate an conn_t as the instance data.
9764 	 */
9765 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9766 
9767 	/*
9768 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9769 	 * done by netstack_find_by_cred()
9770 	 */
9771 	netstack_rele(ipst->ips_netstack);
9772 
9773 	connp->conn_zoneid = zoneid;
9774 	connp->conn_sqp = NULL;
9775 	connp->conn_initial_sqp = NULL;
9776 	connp->conn_final_sqp = NULL;
9777 
9778 	connp->conn_upq = q;
9779 	q->q_ptr = WR(q)->q_ptr = connp;
9780 
9781 	if (flag & SO_SOCKSTR)
9782 		connp->conn_flags |= IPCL_SOCKET;
9783 
9784 	/* Minor tells us which /dev entry was opened */
9785 	if (isv6) {
9786 		connp->conn_af_isv6 = B_TRUE;
9787 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9788 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9789 	} else {
9790 		connp->conn_af_isv6 = B_FALSE;
9791 		connp->conn_pkt_isv6 = B_FALSE;
9792 	}
9793 
9794 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9795 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9796 		connp->conn_minor_arena = ip_minor_arena_la;
9797 	} else {
9798 		/*
9799 		 * Either minor numbers in the large arena were exhausted
9800 		 * or a non socket application is doing the open.
9801 		 * Try to allocate from the small arena.
9802 		 */
9803 		if ((connp->conn_dev =
9804 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9805 			/* CONN_DEC_REF takes care of netstack_rele() */
9806 			q->q_ptr = WR(q)->q_ptr = NULL;
9807 			CONN_DEC_REF(connp);
9808 			return (EBUSY);
9809 		}
9810 		connp->conn_minor_arena = ip_minor_arena_sa;
9811 	}
9812 
9813 	maj = getemajor(*devp);
9814 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9815 
9816 	/*
9817 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9818 	 */
9819 	connp->conn_cred = credp;
9820 
9821 	/*
9822 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9823 	 */
9824 	connp->conn_recv = ip_conn_input;
9825 
9826 	crhold(connp->conn_cred);
9827 
9828 	/*
9829 	 * If the caller has the process-wide flag set, then default to MAC
9830 	 * exempt mode.  This allows read-down to unlabeled hosts.
9831 	 */
9832 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9833 		connp->conn_mac_exempt = B_TRUE;
9834 
9835 	connp->conn_rq = q;
9836 	connp->conn_wq = WR(q);
9837 
9838 	/* Non-zero default values */
9839 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9840 
9841 	/*
9842 	 * Make the conn globally visible to walkers
9843 	 */
9844 	ASSERT(connp->conn_ref == 1);
9845 	mutex_enter(&connp->conn_lock);
9846 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9847 	mutex_exit(&connp->conn_lock);
9848 
9849 	qprocson(q);
9850 
9851 	return (0);
9852 }
9853 
9854 /*
9855  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9856  * Note that there is no race since either ip_output function works - it
9857  * is just an optimization to enter the best ip_output routine directly.
9858  */
9859 void
9860 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9861     ip_stack_t *ipst)
9862 {
9863 	if (isv6)  {
9864 		if (bump_mib) {
9865 			BUMP_MIB(&ipst->ips_ip6_mib,
9866 			    ipIfStatsOutSwitchIPVersion);
9867 		}
9868 		connp->conn_send = ip_output_v6;
9869 		connp->conn_pkt_isv6 = B_TRUE;
9870 	} else {
9871 		if (bump_mib) {
9872 			BUMP_MIB(&ipst->ips_ip_mib,
9873 			    ipIfStatsOutSwitchIPVersion);
9874 		}
9875 		connp->conn_send = ip_output;
9876 		connp->conn_pkt_isv6 = B_FALSE;
9877 	}
9878 
9879 }
9880 
9881 /*
9882  * See if IPsec needs loading because of the options in mp.
9883  */
9884 static boolean_t
9885 ipsec_opt_present(mblk_t *mp)
9886 {
9887 	uint8_t *optcp, *next_optcp, *opt_endcp;
9888 	struct opthdr *opt;
9889 	struct T_opthdr *topt;
9890 	int opthdr_len;
9891 	t_uscalar_t optname, optlevel;
9892 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9893 	ipsec_req_t *ipsr;
9894 
9895 	/*
9896 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9897 	 * return TRUE.
9898 	 */
9899 
9900 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9901 	opt_endcp = optcp + tor->OPT_length;
9902 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9903 		opthdr_len = sizeof (struct T_opthdr);
9904 	} else {		/* O_OPTMGMT_REQ */
9905 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9906 		opthdr_len = sizeof (struct opthdr);
9907 	}
9908 	for (; optcp < opt_endcp; optcp = next_optcp) {
9909 		if (optcp + opthdr_len > opt_endcp)
9910 			return (B_FALSE);	/* Not enough option header. */
9911 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9912 			topt = (struct T_opthdr *)optcp;
9913 			optlevel = topt->level;
9914 			optname = topt->name;
9915 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9916 		} else {
9917 			opt = (struct opthdr *)optcp;
9918 			optlevel = opt->level;
9919 			optname = opt->name;
9920 			next_optcp = optcp + opthdr_len +
9921 			    _TPI_ALIGN_OPT(opt->len);
9922 		}
9923 		if ((next_optcp < optcp) || /* wraparound pointer space */
9924 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9925 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9926 			return (B_FALSE); /* bad option buffer */
9927 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9928 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9929 			/*
9930 			 * Check to see if it's an all-bypass or all-zeroes
9931 			 * IPsec request.  Don't bother loading IPsec if
9932 			 * the socket doesn't want to use it.  (A good example
9933 			 * is a bypass request.)
9934 			 *
9935 			 * Basically, if any of the non-NEVER bits are set,
9936 			 * load IPsec.
9937 			 */
9938 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9939 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9940 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9941 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9942 			    != 0)
9943 				return (B_TRUE);
9944 		}
9945 	}
9946 	return (B_FALSE);
9947 }
9948 
9949 /*
9950  * If conn is is waiting for ipsec to finish loading, kick it.
9951  */
9952 /* ARGSUSED */
9953 static void
9954 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9955 {
9956 	t_scalar_t	optreq_prim;
9957 	mblk_t		*mp;
9958 	cred_t		*cr;
9959 	int		err = 0;
9960 
9961 	/*
9962 	 * This function is called, after ipsec loading is complete.
9963 	 * Since IP checks exclusively and atomically (i.e it prevents
9964 	 * ipsec load from completing until ip_optcom_req completes)
9965 	 * whether ipsec load is complete, there cannot be a race with IP
9966 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9967 	 */
9968 	mutex_enter(&connp->conn_lock);
9969 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9970 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9971 		mp = connp->conn_ipsec_opt_mp;
9972 		connp->conn_ipsec_opt_mp = NULL;
9973 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9974 		mutex_exit(&connp->conn_lock);
9975 
9976 		/*
9977 		 * All Solaris components should pass a db_credp
9978 		 * for this TPI message, hence we ASSERT.
9979 		 * But in case there is some other M_PROTO that looks
9980 		 * like a TPI message sent by some other kernel
9981 		 * component, we check and return an error.
9982 		 */
9983 		cr = msg_getcred(mp, NULL);
9984 		ASSERT(cr != NULL);
9985 		if (cr == NULL) {
9986 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
9987 			if (mp != NULL)
9988 				qreply(connp->conn_wq, mp);
9989 			return;
9990 		}
9991 
9992 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9993 
9994 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9995 		if (optreq_prim == T_OPTMGMT_REQ) {
9996 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9997 			    &ip_opt_obj, B_FALSE);
9998 		} else {
9999 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10000 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10001 			    &ip_opt_obj, B_FALSE);
10002 		}
10003 		if (err != EINPROGRESS)
10004 			CONN_OPER_PENDING_DONE(connp);
10005 		return;
10006 	}
10007 	mutex_exit(&connp->conn_lock);
10008 }
10009 
10010 /*
10011  * Called from the ipsec_loader thread, outside any perimeter, to tell
10012  * ip qenable any of the queues waiting for the ipsec loader to
10013  * complete.
10014  */
10015 void
10016 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10017 {
10018 	netstack_t *ns = ipss->ipsec_netstack;
10019 
10020 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10021 }
10022 
10023 /*
10024  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10025  * determines the grp on which it has to become exclusive, queues the mp
10026  * and IPSQ draining restarts the optmgmt
10027  */
10028 static boolean_t
10029 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10030 {
10031 	conn_t *connp = Q_TO_CONN(q);
10032 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10033 
10034 	/*
10035 	 * Take IPsec requests and treat them special.
10036 	 */
10037 	if (ipsec_opt_present(mp)) {
10038 		/* First check if IPsec is loaded. */
10039 		mutex_enter(&ipss->ipsec_loader_lock);
10040 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10041 			mutex_exit(&ipss->ipsec_loader_lock);
10042 			return (B_FALSE);
10043 		}
10044 		mutex_enter(&connp->conn_lock);
10045 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10046 
10047 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10048 		connp->conn_ipsec_opt_mp = mp;
10049 		mutex_exit(&connp->conn_lock);
10050 		mutex_exit(&ipss->ipsec_loader_lock);
10051 
10052 		ipsec_loader_loadnow(ipss);
10053 		return (B_TRUE);
10054 	}
10055 	return (B_FALSE);
10056 }
10057 
10058 /*
10059  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10060  * all of them are copied to the conn_t. If the req is "zero", the policy is
10061  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10062  * fields.
10063  * We keep only the latest setting of the policy and thus policy setting
10064  * is not incremental/cumulative.
10065  *
10066  * Requests to set policies with multiple alternative actions will
10067  * go through a different API.
10068  */
10069 int
10070 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10071 {
10072 	uint_t ah_req = 0;
10073 	uint_t esp_req = 0;
10074 	uint_t se_req = 0;
10075 	ipsec_act_t *actp = NULL;
10076 	uint_t nact;
10077 	ipsec_policy_head_t *ph;
10078 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
10079 	int error = 0;
10080 	netstack_t	*ns = connp->conn_netstack;
10081 	ip_stack_t	*ipst = ns->netstack_ip;
10082 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10083 
10084 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10085 
10086 	/*
10087 	 * The IP_SEC_OPT option does not allow variable length parameters,
10088 	 * hence a request cannot be NULL.
10089 	 */
10090 	if (req == NULL)
10091 		return (EINVAL);
10092 
10093 	ah_req = req->ipsr_ah_req;
10094 	esp_req = req->ipsr_esp_req;
10095 	se_req = req->ipsr_self_encap_req;
10096 
10097 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10098 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10099 		return (EINVAL);
10100 
10101 	/*
10102 	 * Are we dealing with a request to reset the policy (i.e.
10103 	 * zero requests).
10104 	 */
10105 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10106 	    (esp_req & REQ_MASK) == 0 &&
10107 	    (se_req & REQ_MASK) == 0);
10108 
10109 	if (!is_pol_reset) {
10110 		/*
10111 		 * If we couldn't load IPsec, fail with "protocol
10112 		 * not supported".
10113 		 * IPsec may not have been loaded for a request with zero
10114 		 * policies, so we don't fail in this case.
10115 		 */
10116 		mutex_enter(&ipss->ipsec_loader_lock);
10117 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10118 			mutex_exit(&ipss->ipsec_loader_lock);
10119 			return (EPROTONOSUPPORT);
10120 		}
10121 		mutex_exit(&ipss->ipsec_loader_lock);
10122 
10123 		/*
10124 		 * Test for valid requests. Invalid algorithms
10125 		 * need to be tested by IPsec code because new
10126 		 * algorithms can be added dynamically.
10127 		 */
10128 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10129 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10130 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10131 			return (EINVAL);
10132 		}
10133 
10134 		/*
10135 		 * Only privileged users can issue these
10136 		 * requests.
10137 		 */
10138 		if (((ah_req & IPSEC_PREF_NEVER) ||
10139 		    (esp_req & IPSEC_PREF_NEVER) ||
10140 		    (se_req & IPSEC_PREF_NEVER)) &&
10141 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10142 			return (EPERM);
10143 		}
10144 
10145 		/*
10146 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10147 		 * are mutually exclusive.
10148 		 */
10149 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10150 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10151 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10152 			/* Both of them are set */
10153 			return (EINVAL);
10154 		}
10155 	}
10156 
10157 	mutex_enter(&connp->conn_lock);
10158 
10159 	/*
10160 	 * If we have already cached policies in ip_bind_connected*(), don't
10161 	 * let them change now. We cache policies for connections
10162 	 * whose src,dst [addr, port] is known.
10163 	 */
10164 	if (connp->conn_policy_cached) {
10165 		mutex_exit(&connp->conn_lock);
10166 		return (EINVAL);
10167 	}
10168 
10169 	/*
10170 	 * We have a zero policies, reset the connection policy if already
10171 	 * set. This will cause the connection to inherit the
10172 	 * global policy, if any.
10173 	 */
10174 	if (is_pol_reset) {
10175 		if (connp->conn_policy != NULL) {
10176 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10177 			connp->conn_policy = NULL;
10178 		}
10179 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10180 		connp->conn_in_enforce_policy = B_FALSE;
10181 		connp->conn_out_enforce_policy = B_FALSE;
10182 		mutex_exit(&connp->conn_lock);
10183 		return (0);
10184 	}
10185 
10186 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10187 	    ipst->ips_netstack);
10188 	if (ph == NULL)
10189 		goto enomem;
10190 
10191 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10192 	if (actp == NULL)
10193 		goto enomem;
10194 
10195 	/*
10196 	 * Always insert IPv4 policy entries, since they can also apply to
10197 	 * ipv6 sockets being used in ipv4-compat mode.
10198 	 */
10199 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10200 	    IPSEC_TYPE_INBOUND, ns))
10201 		goto enomem;
10202 	is_pol_inserted = B_TRUE;
10203 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10204 	    IPSEC_TYPE_OUTBOUND, ns))
10205 		goto enomem;
10206 
10207 	/*
10208 	 * We're looking at a v6 socket, also insert the v6-specific
10209 	 * entries.
10210 	 */
10211 	if (connp->conn_af_isv6) {
10212 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10213 		    IPSEC_TYPE_INBOUND, ns))
10214 			goto enomem;
10215 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10216 		    IPSEC_TYPE_OUTBOUND, ns))
10217 			goto enomem;
10218 	}
10219 
10220 	ipsec_actvec_free(actp, nact);
10221 
10222 	/*
10223 	 * If the requests need security, set enforce_policy.
10224 	 * If the requests are IPSEC_PREF_NEVER, one should
10225 	 * still set conn_out_enforce_policy so that an ipsec_out
10226 	 * gets attached in ip_wput. This is needed so that
10227 	 * for connections that we don't cache policy in ip_bind,
10228 	 * if global policy matches in ip_wput_attach_policy, we
10229 	 * don't wrongly inherit global policy. Similarly, we need
10230 	 * to set conn_in_enforce_policy also so that we don't verify
10231 	 * policy wrongly.
10232 	 */
10233 	if ((ah_req & REQ_MASK) != 0 ||
10234 	    (esp_req & REQ_MASK) != 0 ||
10235 	    (se_req & REQ_MASK) != 0) {
10236 		connp->conn_in_enforce_policy = B_TRUE;
10237 		connp->conn_out_enforce_policy = B_TRUE;
10238 		connp->conn_flags |= IPCL_CHECK_POLICY;
10239 	}
10240 
10241 	mutex_exit(&connp->conn_lock);
10242 	return (error);
10243 #undef REQ_MASK
10244 
10245 	/*
10246 	 * Common memory-allocation-failure exit path.
10247 	 */
10248 enomem:
10249 	mutex_exit(&connp->conn_lock);
10250 	if (actp != NULL)
10251 		ipsec_actvec_free(actp, nact);
10252 	if (is_pol_inserted)
10253 		ipsec_polhead_flush(ph, ns);
10254 	return (ENOMEM);
10255 }
10256 
10257 /*
10258  * Only for options that pass in an IP addr. Currently only V4 options
10259  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10260  * So this function assumes level is IPPROTO_IP
10261  */
10262 int
10263 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10264     mblk_t *first_mp)
10265 {
10266 	ipif_t *ipif = NULL;
10267 	int error;
10268 	ill_t *ill;
10269 	int zoneid;
10270 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10271 
10272 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10273 
10274 	if (addr != INADDR_ANY || checkonly) {
10275 		ASSERT(connp != NULL);
10276 		zoneid = IPCL_ZONEID(connp);
10277 		if (option == IP_NEXTHOP) {
10278 			ipif = ipif_lookup_onlink_addr(addr,
10279 			    connp->conn_zoneid, ipst);
10280 		} else {
10281 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10282 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10283 			    &error, ipst);
10284 		}
10285 		if (ipif == NULL) {
10286 			if (error == EINPROGRESS)
10287 				return (error);
10288 			if ((option == IP_MULTICAST_IF) ||
10289 			    (option == IP_NEXTHOP))
10290 				return (EHOSTUNREACH);
10291 			else
10292 				return (EINVAL);
10293 		} else if (checkonly) {
10294 			if (option == IP_MULTICAST_IF) {
10295 				ill = ipif->ipif_ill;
10296 				/* not supported by the virtual network iface */
10297 				if (IS_VNI(ill)) {
10298 					ipif_refrele(ipif);
10299 					return (EINVAL);
10300 				}
10301 			}
10302 			ipif_refrele(ipif);
10303 			return (0);
10304 		}
10305 		ill = ipif->ipif_ill;
10306 		mutex_enter(&connp->conn_lock);
10307 		mutex_enter(&ill->ill_lock);
10308 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10309 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10310 			mutex_exit(&ill->ill_lock);
10311 			mutex_exit(&connp->conn_lock);
10312 			ipif_refrele(ipif);
10313 			return (option == IP_MULTICAST_IF ?
10314 			    EHOSTUNREACH : EINVAL);
10315 		}
10316 	} else {
10317 		mutex_enter(&connp->conn_lock);
10318 	}
10319 
10320 	/* None of the options below are supported on the VNI */
10321 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10322 		mutex_exit(&ill->ill_lock);
10323 		mutex_exit(&connp->conn_lock);
10324 		ipif_refrele(ipif);
10325 		return (EINVAL);
10326 	}
10327 
10328 	switch (option) {
10329 	case IP_MULTICAST_IF:
10330 		connp->conn_multicast_ipif = ipif;
10331 		break;
10332 	case IP_NEXTHOP:
10333 		connp->conn_nexthop_v4 = addr;
10334 		connp->conn_nexthop_set = B_TRUE;
10335 		break;
10336 	}
10337 
10338 	if (ipif != NULL) {
10339 		mutex_exit(&ill->ill_lock);
10340 		mutex_exit(&connp->conn_lock);
10341 		ipif_refrele(ipif);
10342 		return (0);
10343 	}
10344 	mutex_exit(&connp->conn_lock);
10345 	/* We succeded in cleared the option */
10346 	return (0);
10347 }
10348 
10349 /*
10350  * For options that pass in an ifindex specifying the ill. V6 options always
10351  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10352  */
10353 int
10354 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10355     int level, int option, mblk_t *first_mp)
10356 {
10357 	ill_t *ill = NULL;
10358 	int error = 0;
10359 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10360 
10361 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10362 	if (ifindex != 0) {
10363 		ASSERT(connp != NULL);
10364 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10365 		    first_mp, ip_restart_optmgmt, &error, ipst);
10366 		if (ill != NULL) {
10367 			if (checkonly) {
10368 				/* not supported by the virtual network iface */
10369 				if (IS_VNI(ill)) {
10370 					ill_refrele(ill);
10371 					return (EINVAL);
10372 				}
10373 				ill_refrele(ill);
10374 				return (0);
10375 			}
10376 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10377 			    0, NULL)) {
10378 				ill_refrele(ill);
10379 				ill = NULL;
10380 				mutex_enter(&connp->conn_lock);
10381 				goto setit;
10382 			}
10383 			mutex_enter(&connp->conn_lock);
10384 			mutex_enter(&ill->ill_lock);
10385 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10386 				mutex_exit(&ill->ill_lock);
10387 				mutex_exit(&connp->conn_lock);
10388 				ill_refrele(ill);
10389 				ill = NULL;
10390 				mutex_enter(&connp->conn_lock);
10391 			}
10392 			goto setit;
10393 		} else if (error == EINPROGRESS) {
10394 			return (error);
10395 		} else {
10396 			error = 0;
10397 		}
10398 	}
10399 	mutex_enter(&connp->conn_lock);
10400 setit:
10401 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10402 
10403 	/*
10404 	 * The options below assume that the ILL (if any) transmits and/or
10405 	 * receives traffic. Neither of which is true for the virtual network
10406 	 * interface, so fail setting these on a VNI.
10407 	 */
10408 	if (IS_VNI(ill)) {
10409 		ASSERT(ill != NULL);
10410 		mutex_exit(&ill->ill_lock);
10411 		mutex_exit(&connp->conn_lock);
10412 		ill_refrele(ill);
10413 		return (EINVAL);
10414 	}
10415 
10416 	if (level == IPPROTO_IP) {
10417 		switch (option) {
10418 		case IP_BOUND_IF:
10419 			connp->conn_incoming_ill = ill;
10420 			connp->conn_outgoing_ill = ill;
10421 			break;
10422 
10423 		case IP_MULTICAST_IF:
10424 			/*
10425 			 * This option is an internal special. The socket
10426 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10427 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10428 			 * specifies an ifindex and we try first on V6 ill's.
10429 			 * If we don't find one, we they try using on v4 ill's
10430 			 * intenally and we come here.
10431 			 */
10432 			if (!checkonly && ill != NULL) {
10433 				ipif_t	*ipif;
10434 				ipif = ill->ill_ipif;
10435 
10436 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10437 					mutex_exit(&ill->ill_lock);
10438 					mutex_exit(&connp->conn_lock);
10439 					ill_refrele(ill);
10440 					ill = NULL;
10441 					mutex_enter(&connp->conn_lock);
10442 				} else {
10443 					connp->conn_multicast_ipif = ipif;
10444 				}
10445 			}
10446 			break;
10447 
10448 		case IP_DHCPINIT_IF:
10449 			if (connp->conn_dhcpinit_ill != NULL) {
10450 				/*
10451 				 * We've locked the conn so conn_cleanup_ill()
10452 				 * cannot clear conn_dhcpinit_ill -- so it's
10453 				 * safe to access the ill.
10454 				 */
10455 				ill_t *oill = connp->conn_dhcpinit_ill;
10456 
10457 				ASSERT(oill->ill_dhcpinit != 0);
10458 				atomic_dec_32(&oill->ill_dhcpinit);
10459 				connp->conn_dhcpinit_ill = NULL;
10460 			}
10461 
10462 			if (ill != NULL) {
10463 				connp->conn_dhcpinit_ill = ill;
10464 				atomic_inc_32(&ill->ill_dhcpinit);
10465 			}
10466 			break;
10467 		}
10468 	} else {
10469 		switch (option) {
10470 		case IPV6_BOUND_IF:
10471 			connp->conn_incoming_ill = ill;
10472 			connp->conn_outgoing_ill = ill;
10473 			break;
10474 
10475 		case IPV6_MULTICAST_IF:
10476 			/*
10477 			 * Set conn_multicast_ill to be the IPv6 ill.
10478 			 * Set conn_multicast_ipif to be an IPv4 ipif
10479 			 * for ifindex to make IPv4 mapped addresses
10480 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10481 			 * Even if no IPv6 ill exists for the ifindex
10482 			 * we need to check for an IPv4 ifindex in order
10483 			 * for this to work with mapped addresses. In that
10484 			 * case only set conn_multicast_ipif.
10485 			 */
10486 			if (!checkonly) {
10487 				if (ifindex == 0) {
10488 					connp->conn_multicast_ill = NULL;
10489 					connp->conn_multicast_ipif = NULL;
10490 				} else if (ill != NULL) {
10491 					connp->conn_multicast_ill = ill;
10492 				}
10493 			}
10494 			break;
10495 		}
10496 	}
10497 
10498 	if (ill != NULL) {
10499 		mutex_exit(&ill->ill_lock);
10500 		mutex_exit(&connp->conn_lock);
10501 		ill_refrele(ill);
10502 		return (0);
10503 	}
10504 	mutex_exit(&connp->conn_lock);
10505 	/*
10506 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10507 	 * locate the ill and could not set the option (ifindex != 0)
10508 	 */
10509 	return (ifindex == 0 ? 0 : EINVAL);
10510 }
10511 
10512 /* This routine sets socket options. */
10513 /* ARGSUSED */
10514 int
10515 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10516     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10517     void *dummy, cred_t *cr, mblk_t *first_mp)
10518 {
10519 	int		*i1 = (int *)invalp;
10520 	conn_t		*connp = Q_TO_CONN(q);
10521 	int		error = 0;
10522 	boolean_t	checkonly;
10523 	ire_t		*ire;
10524 	boolean_t	found;
10525 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10526 
10527 	switch (optset_context) {
10528 
10529 	case SETFN_OPTCOM_CHECKONLY:
10530 		checkonly = B_TRUE;
10531 		/*
10532 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10533 		 * inlen != 0 implies value supplied and
10534 		 * 	we have to "pretend" to set it.
10535 		 * inlen == 0 implies that there is no
10536 		 * 	value part in T_CHECK request and just validation
10537 		 * done elsewhere should be enough, we just return here.
10538 		 */
10539 		if (inlen == 0) {
10540 			*outlenp = 0;
10541 			return (0);
10542 		}
10543 		break;
10544 	case SETFN_OPTCOM_NEGOTIATE:
10545 	case SETFN_UD_NEGOTIATE:
10546 	case SETFN_CONN_NEGOTIATE:
10547 		checkonly = B_FALSE;
10548 		break;
10549 	default:
10550 		/*
10551 		 * We should never get here
10552 		 */
10553 		*outlenp = 0;
10554 		return (EINVAL);
10555 	}
10556 
10557 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10558 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10559 
10560 	/*
10561 	 * For fixed length options, no sanity check
10562 	 * of passed in length is done. It is assumed *_optcom_req()
10563 	 * routines do the right thing.
10564 	 */
10565 
10566 	switch (level) {
10567 	case SOL_SOCKET:
10568 		/*
10569 		 * conn_lock protects the bitfields, and is used to
10570 		 * set the fields atomically.
10571 		 */
10572 		switch (name) {
10573 		case SO_BROADCAST:
10574 			if (!checkonly) {
10575 				/* TODO: use value someplace? */
10576 				mutex_enter(&connp->conn_lock);
10577 				connp->conn_broadcast = *i1 ? 1 : 0;
10578 				mutex_exit(&connp->conn_lock);
10579 			}
10580 			break;	/* goto sizeof (int) option return */
10581 		case SO_USELOOPBACK:
10582 			if (!checkonly) {
10583 				/* TODO: use value someplace? */
10584 				mutex_enter(&connp->conn_lock);
10585 				connp->conn_loopback = *i1 ? 1 : 0;
10586 				mutex_exit(&connp->conn_lock);
10587 			}
10588 			break;	/* goto sizeof (int) option return */
10589 		case SO_DONTROUTE:
10590 			if (!checkonly) {
10591 				mutex_enter(&connp->conn_lock);
10592 				connp->conn_dontroute = *i1 ? 1 : 0;
10593 				mutex_exit(&connp->conn_lock);
10594 			}
10595 			break;	/* goto sizeof (int) option return */
10596 		case SO_REUSEADDR:
10597 			if (!checkonly) {
10598 				mutex_enter(&connp->conn_lock);
10599 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10600 				mutex_exit(&connp->conn_lock);
10601 			}
10602 			break;	/* goto sizeof (int) option return */
10603 		case SO_PROTOTYPE:
10604 			if (!checkonly) {
10605 				mutex_enter(&connp->conn_lock);
10606 				connp->conn_proto = *i1;
10607 				mutex_exit(&connp->conn_lock);
10608 			}
10609 			break;	/* goto sizeof (int) option return */
10610 		case SO_ALLZONES:
10611 			if (!checkonly) {
10612 				mutex_enter(&connp->conn_lock);
10613 				if (IPCL_IS_BOUND(connp)) {
10614 					mutex_exit(&connp->conn_lock);
10615 					return (EINVAL);
10616 				}
10617 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10618 				mutex_exit(&connp->conn_lock);
10619 			}
10620 			break;	/* goto sizeof (int) option return */
10621 		case SO_ANON_MLP:
10622 			if (!checkonly) {
10623 				mutex_enter(&connp->conn_lock);
10624 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10625 				mutex_exit(&connp->conn_lock);
10626 			}
10627 			break;	/* goto sizeof (int) option return */
10628 		case SO_MAC_EXEMPT:
10629 			if (secpolicy_net_mac_aware(cr) != 0 ||
10630 			    IPCL_IS_BOUND(connp))
10631 				return (EACCES);
10632 			if (!checkonly) {
10633 				mutex_enter(&connp->conn_lock);
10634 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10635 				mutex_exit(&connp->conn_lock);
10636 			}
10637 			break;	/* goto sizeof (int) option return */
10638 		default:
10639 			/*
10640 			 * "soft" error (negative)
10641 			 * option not handled at this level
10642 			 * Note: Do not modify *outlenp
10643 			 */
10644 			return (-EINVAL);
10645 		}
10646 		break;
10647 	case IPPROTO_IP:
10648 		switch (name) {
10649 		case IP_NEXTHOP:
10650 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10651 				return (EPERM);
10652 			/* FALLTHRU */
10653 		case IP_MULTICAST_IF: {
10654 			ipaddr_t addr = *i1;
10655 
10656 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10657 			    first_mp);
10658 			if (error != 0)
10659 				return (error);
10660 			break;	/* goto sizeof (int) option return */
10661 		}
10662 
10663 		case IP_MULTICAST_TTL:
10664 			/* Recorded in transport above IP */
10665 			*outvalp = *invalp;
10666 			*outlenp = sizeof (uchar_t);
10667 			return (0);
10668 		case IP_MULTICAST_LOOP:
10669 			if (!checkonly) {
10670 				mutex_enter(&connp->conn_lock);
10671 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10672 				mutex_exit(&connp->conn_lock);
10673 			}
10674 			*outvalp = *invalp;
10675 			*outlenp = sizeof (uchar_t);
10676 			return (0);
10677 		case IP_ADD_MEMBERSHIP:
10678 		case MCAST_JOIN_GROUP:
10679 		case IP_DROP_MEMBERSHIP:
10680 		case MCAST_LEAVE_GROUP: {
10681 			struct ip_mreq *mreqp;
10682 			struct group_req *greqp;
10683 			ire_t *ire;
10684 			boolean_t done = B_FALSE;
10685 			ipaddr_t group, ifaddr;
10686 			struct sockaddr_in *sin;
10687 			uint32_t *ifindexp;
10688 			boolean_t mcast_opt = B_TRUE;
10689 			mcast_record_t fmode;
10690 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10691 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10692 
10693 			switch (name) {
10694 			case IP_ADD_MEMBERSHIP:
10695 				mcast_opt = B_FALSE;
10696 				/* FALLTHRU */
10697 			case MCAST_JOIN_GROUP:
10698 				fmode = MODE_IS_EXCLUDE;
10699 				optfn = ip_opt_add_group;
10700 				break;
10701 
10702 			case IP_DROP_MEMBERSHIP:
10703 				mcast_opt = B_FALSE;
10704 				/* FALLTHRU */
10705 			case MCAST_LEAVE_GROUP:
10706 				fmode = MODE_IS_INCLUDE;
10707 				optfn = ip_opt_delete_group;
10708 				break;
10709 			}
10710 
10711 			if (mcast_opt) {
10712 				greqp = (struct group_req *)i1;
10713 				sin = (struct sockaddr_in *)&greqp->gr_group;
10714 				if (sin->sin_family != AF_INET) {
10715 					*outlenp = 0;
10716 					return (ENOPROTOOPT);
10717 				}
10718 				group = (ipaddr_t)sin->sin_addr.s_addr;
10719 				ifaddr = INADDR_ANY;
10720 				ifindexp = &greqp->gr_interface;
10721 			} else {
10722 				mreqp = (struct ip_mreq *)i1;
10723 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10724 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10725 				ifindexp = NULL;
10726 			}
10727 
10728 			/*
10729 			 * In the multirouting case, we need to replicate
10730 			 * the request on all interfaces that will take part
10731 			 * in replication.  We do so because multirouting is
10732 			 * reflective, thus we will probably receive multi-
10733 			 * casts on those interfaces.
10734 			 * The ip_multirt_apply_membership() succeeds if the
10735 			 * operation succeeds on at least one interface.
10736 			 */
10737 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10738 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10739 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10740 			if (ire != NULL) {
10741 				if (ire->ire_flags & RTF_MULTIRT) {
10742 					error = ip_multirt_apply_membership(
10743 					    optfn, ire, connp, checkonly, group,
10744 					    fmode, INADDR_ANY, first_mp);
10745 					done = B_TRUE;
10746 				}
10747 				ire_refrele(ire);
10748 			}
10749 			if (!done) {
10750 				error = optfn(connp, checkonly, group, ifaddr,
10751 				    ifindexp, fmode, INADDR_ANY, first_mp);
10752 			}
10753 			if (error) {
10754 				/*
10755 				 * EINPROGRESS is a soft error, needs retry
10756 				 * so don't make *outlenp zero.
10757 				 */
10758 				if (error != EINPROGRESS)
10759 					*outlenp = 0;
10760 				return (error);
10761 			}
10762 			/* OK return - copy input buffer into output buffer */
10763 			if (invalp != outvalp) {
10764 				/* don't trust bcopy for identical src/dst */
10765 				bcopy(invalp, outvalp, inlen);
10766 			}
10767 			*outlenp = inlen;
10768 			return (0);
10769 		}
10770 		case IP_BLOCK_SOURCE:
10771 		case IP_UNBLOCK_SOURCE:
10772 		case IP_ADD_SOURCE_MEMBERSHIP:
10773 		case IP_DROP_SOURCE_MEMBERSHIP:
10774 		case MCAST_BLOCK_SOURCE:
10775 		case MCAST_UNBLOCK_SOURCE:
10776 		case MCAST_JOIN_SOURCE_GROUP:
10777 		case MCAST_LEAVE_SOURCE_GROUP: {
10778 			struct ip_mreq_source *imreqp;
10779 			struct group_source_req *gsreqp;
10780 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10781 			uint32_t ifindex = 0;
10782 			mcast_record_t fmode;
10783 			struct sockaddr_in *sin;
10784 			ire_t *ire;
10785 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10786 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10787 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10788 
10789 			switch (name) {
10790 			case IP_BLOCK_SOURCE:
10791 				mcast_opt = B_FALSE;
10792 				/* FALLTHRU */
10793 			case MCAST_BLOCK_SOURCE:
10794 				fmode = MODE_IS_EXCLUDE;
10795 				optfn = ip_opt_add_group;
10796 				break;
10797 
10798 			case IP_UNBLOCK_SOURCE:
10799 				mcast_opt = B_FALSE;
10800 				/* FALLTHRU */
10801 			case MCAST_UNBLOCK_SOURCE:
10802 				fmode = MODE_IS_EXCLUDE;
10803 				optfn = ip_opt_delete_group;
10804 				break;
10805 
10806 			case IP_ADD_SOURCE_MEMBERSHIP:
10807 				mcast_opt = B_FALSE;
10808 				/* FALLTHRU */
10809 			case MCAST_JOIN_SOURCE_GROUP:
10810 				fmode = MODE_IS_INCLUDE;
10811 				optfn = ip_opt_add_group;
10812 				break;
10813 
10814 			case IP_DROP_SOURCE_MEMBERSHIP:
10815 				mcast_opt = B_FALSE;
10816 				/* FALLTHRU */
10817 			case MCAST_LEAVE_SOURCE_GROUP:
10818 				fmode = MODE_IS_INCLUDE;
10819 				optfn = ip_opt_delete_group;
10820 				break;
10821 			}
10822 
10823 			if (mcast_opt) {
10824 				gsreqp = (struct group_source_req *)i1;
10825 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10826 					*outlenp = 0;
10827 					return (ENOPROTOOPT);
10828 				}
10829 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10830 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10831 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10832 				src = (ipaddr_t)sin->sin_addr.s_addr;
10833 				ifindex = gsreqp->gsr_interface;
10834 			} else {
10835 				imreqp = (struct ip_mreq_source *)i1;
10836 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10837 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10838 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10839 			}
10840 
10841 			/*
10842 			 * In the multirouting case, we need to replicate
10843 			 * the request as noted in the mcast cases above.
10844 			 */
10845 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10846 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10847 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10848 			if (ire != NULL) {
10849 				if (ire->ire_flags & RTF_MULTIRT) {
10850 					error = ip_multirt_apply_membership(
10851 					    optfn, ire, connp, checkonly, grp,
10852 					    fmode, src, first_mp);
10853 					done = B_TRUE;
10854 				}
10855 				ire_refrele(ire);
10856 			}
10857 			if (!done) {
10858 				error = optfn(connp, checkonly, grp, ifaddr,
10859 				    &ifindex, fmode, src, first_mp);
10860 			}
10861 			if (error != 0) {
10862 				/*
10863 				 * EINPROGRESS is a soft error, needs retry
10864 				 * so don't make *outlenp zero.
10865 				 */
10866 				if (error != EINPROGRESS)
10867 					*outlenp = 0;
10868 				return (error);
10869 			}
10870 			/* OK return - copy input buffer into output buffer */
10871 			if (invalp != outvalp) {
10872 				bcopy(invalp, outvalp, inlen);
10873 			}
10874 			*outlenp = inlen;
10875 			return (0);
10876 		}
10877 		case IP_SEC_OPT:
10878 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10879 			if (error != 0) {
10880 				*outlenp = 0;
10881 				return (error);
10882 			}
10883 			break;
10884 		case IP_HDRINCL:
10885 		case IP_OPTIONS:
10886 		case T_IP_OPTIONS:
10887 		case IP_TOS:
10888 		case T_IP_TOS:
10889 		case IP_TTL:
10890 		case IP_RECVDSTADDR:
10891 		case IP_RECVOPTS:
10892 			/* OK return - copy input buffer into output buffer */
10893 			if (invalp != outvalp) {
10894 				/* don't trust bcopy for identical src/dst */
10895 				bcopy(invalp, outvalp, inlen);
10896 			}
10897 			*outlenp = inlen;
10898 			return (0);
10899 		case IP_RECVIF:
10900 			/* Retrieve the inbound interface index */
10901 			if (!checkonly) {
10902 				mutex_enter(&connp->conn_lock);
10903 				connp->conn_recvif = *i1 ? 1 : 0;
10904 				mutex_exit(&connp->conn_lock);
10905 			}
10906 			break;	/* goto sizeof (int) option return */
10907 		case IP_RECVPKTINFO:
10908 			if (!checkonly) {
10909 				mutex_enter(&connp->conn_lock);
10910 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10911 				mutex_exit(&connp->conn_lock);
10912 			}
10913 			break;	/* goto sizeof (int) option return */
10914 		case IP_RECVSLLA:
10915 			/* Retrieve the source link layer address */
10916 			if (!checkonly) {
10917 				mutex_enter(&connp->conn_lock);
10918 				connp->conn_recvslla = *i1 ? 1 : 0;
10919 				mutex_exit(&connp->conn_lock);
10920 			}
10921 			break;	/* goto sizeof (int) option return */
10922 		case MRT_INIT:
10923 		case MRT_DONE:
10924 		case MRT_ADD_VIF:
10925 		case MRT_DEL_VIF:
10926 		case MRT_ADD_MFC:
10927 		case MRT_DEL_MFC:
10928 		case MRT_ASSERT:
10929 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10930 				*outlenp = 0;
10931 				return (error);
10932 			}
10933 			error = ip_mrouter_set((int)name, q, checkonly,
10934 			    (uchar_t *)invalp, inlen, first_mp);
10935 			if (error) {
10936 				*outlenp = 0;
10937 				return (error);
10938 			}
10939 			/* OK return - copy input buffer into output buffer */
10940 			if (invalp != outvalp) {
10941 				/* don't trust bcopy for identical src/dst */
10942 				bcopy(invalp, outvalp, inlen);
10943 			}
10944 			*outlenp = inlen;
10945 			return (0);
10946 		case IP_BOUND_IF:
10947 		case IP_DHCPINIT_IF:
10948 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10949 			    level, name, first_mp);
10950 			if (error != 0)
10951 				return (error);
10952 			break; 		/* goto sizeof (int) option return */
10953 
10954 		case IP_UNSPEC_SRC:
10955 			/* Allow sending with a zero source address */
10956 			if (!checkonly) {
10957 				mutex_enter(&connp->conn_lock);
10958 				connp->conn_unspec_src = *i1 ? 1 : 0;
10959 				mutex_exit(&connp->conn_lock);
10960 			}
10961 			break;	/* goto sizeof (int) option return */
10962 		default:
10963 			/*
10964 			 * "soft" error (negative)
10965 			 * option not handled at this level
10966 			 * Note: Do not modify *outlenp
10967 			 */
10968 			return (-EINVAL);
10969 		}
10970 		break;
10971 	case IPPROTO_IPV6:
10972 		switch (name) {
10973 		case IPV6_BOUND_IF:
10974 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10975 			    level, name, first_mp);
10976 			if (error != 0)
10977 				return (error);
10978 			break; 		/* goto sizeof (int) option return */
10979 
10980 		case IPV6_MULTICAST_IF:
10981 			/*
10982 			 * The only possible errors are EINPROGRESS and
10983 			 * EINVAL. EINPROGRESS will be restarted and is not
10984 			 * a hard error. We call this option on both V4 and V6
10985 			 * If both return EINVAL, then this call returns
10986 			 * EINVAL. If at least one of them succeeds we
10987 			 * return success.
10988 			 */
10989 			found = B_FALSE;
10990 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10991 			    level, name, first_mp);
10992 			if (error == EINPROGRESS)
10993 				return (error);
10994 			if (error == 0)
10995 				found = B_TRUE;
10996 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10997 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10998 			if (error == 0)
10999 				found = B_TRUE;
11000 			if (!found)
11001 				return (error);
11002 			break; 		/* goto sizeof (int) option return */
11003 
11004 		case IPV6_MULTICAST_HOPS:
11005 			/* Recorded in transport above IP */
11006 			break;	/* goto sizeof (int) option return */
11007 		case IPV6_MULTICAST_LOOP:
11008 			if (!checkonly) {
11009 				mutex_enter(&connp->conn_lock);
11010 				connp->conn_multicast_loop = *i1;
11011 				mutex_exit(&connp->conn_lock);
11012 			}
11013 			break;	/* goto sizeof (int) option return */
11014 		case IPV6_JOIN_GROUP:
11015 		case MCAST_JOIN_GROUP:
11016 		case IPV6_LEAVE_GROUP:
11017 		case MCAST_LEAVE_GROUP: {
11018 			struct ipv6_mreq *ip_mreqp;
11019 			struct group_req *greqp;
11020 			ire_t *ire;
11021 			boolean_t done = B_FALSE;
11022 			in6_addr_t groupv6;
11023 			uint32_t ifindex;
11024 			boolean_t mcast_opt = B_TRUE;
11025 			mcast_record_t fmode;
11026 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11027 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11028 
11029 			switch (name) {
11030 			case IPV6_JOIN_GROUP:
11031 				mcast_opt = B_FALSE;
11032 				/* FALLTHRU */
11033 			case MCAST_JOIN_GROUP:
11034 				fmode = MODE_IS_EXCLUDE;
11035 				optfn = ip_opt_add_group_v6;
11036 				break;
11037 
11038 			case IPV6_LEAVE_GROUP:
11039 				mcast_opt = B_FALSE;
11040 				/* FALLTHRU */
11041 			case MCAST_LEAVE_GROUP:
11042 				fmode = MODE_IS_INCLUDE;
11043 				optfn = ip_opt_delete_group_v6;
11044 				break;
11045 			}
11046 
11047 			if (mcast_opt) {
11048 				struct sockaddr_in *sin;
11049 				struct sockaddr_in6 *sin6;
11050 				greqp = (struct group_req *)i1;
11051 				if (greqp->gr_group.ss_family == AF_INET) {
11052 					sin = (struct sockaddr_in *)
11053 					    &(greqp->gr_group);
11054 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11055 					    &groupv6);
11056 				} else {
11057 					sin6 = (struct sockaddr_in6 *)
11058 					    &(greqp->gr_group);
11059 					groupv6 = sin6->sin6_addr;
11060 				}
11061 				ifindex = greqp->gr_interface;
11062 			} else {
11063 				ip_mreqp = (struct ipv6_mreq *)i1;
11064 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11065 				ifindex = ip_mreqp->ipv6mr_interface;
11066 			}
11067 			/*
11068 			 * In the multirouting case, we need to replicate
11069 			 * the request on all interfaces that will take part
11070 			 * in replication.  We do so because multirouting is
11071 			 * reflective, thus we will probably receive multi-
11072 			 * casts on those interfaces.
11073 			 * The ip_multirt_apply_membership_v6() succeeds if
11074 			 * the operation succeeds on at least one interface.
11075 			 */
11076 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11077 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11078 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11079 			if (ire != NULL) {
11080 				if (ire->ire_flags & RTF_MULTIRT) {
11081 					error = ip_multirt_apply_membership_v6(
11082 					    optfn, ire, connp, checkonly,
11083 					    &groupv6, fmode, &ipv6_all_zeros,
11084 					    first_mp);
11085 					done = B_TRUE;
11086 				}
11087 				ire_refrele(ire);
11088 			}
11089 			if (!done) {
11090 				error = optfn(connp, checkonly, &groupv6,
11091 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11092 			}
11093 			if (error) {
11094 				/*
11095 				 * EINPROGRESS is a soft error, needs retry
11096 				 * so don't make *outlenp zero.
11097 				 */
11098 				if (error != EINPROGRESS)
11099 					*outlenp = 0;
11100 				return (error);
11101 			}
11102 			/* OK return - copy input buffer into output buffer */
11103 			if (invalp != outvalp) {
11104 				/* don't trust bcopy for identical src/dst */
11105 				bcopy(invalp, outvalp, inlen);
11106 			}
11107 			*outlenp = inlen;
11108 			return (0);
11109 		}
11110 		case MCAST_BLOCK_SOURCE:
11111 		case MCAST_UNBLOCK_SOURCE:
11112 		case MCAST_JOIN_SOURCE_GROUP:
11113 		case MCAST_LEAVE_SOURCE_GROUP: {
11114 			struct group_source_req *gsreqp;
11115 			in6_addr_t v6grp, v6src;
11116 			uint32_t ifindex;
11117 			mcast_record_t fmode;
11118 			ire_t *ire;
11119 			boolean_t done = B_FALSE;
11120 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11121 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11122 
11123 			switch (name) {
11124 			case MCAST_BLOCK_SOURCE:
11125 				fmode = MODE_IS_EXCLUDE;
11126 				optfn = ip_opt_add_group_v6;
11127 				break;
11128 			case MCAST_UNBLOCK_SOURCE:
11129 				fmode = MODE_IS_EXCLUDE;
11130 				optfn = ip_opt_delete_group_v6;
11131 				break;
11132 			case MCAST_JOIN_SOURCE_GROUP:
11133 				fmode = MODE_IS_INCLUDE;
11134 				optfn = ip_opt_add_group_v6;
11135 				break;
11136 			case MCAST_LEAVE_SOURCE_GROUP:
11137 				fmode = MODE_IS_INCLUDE;
11138 				optfn = ip_opt_delete_group_v6;
11139 				break;
11140 			}
11141 
11142 			gsreqp = (struct group_source_req *)i1;
11143 			ifindex = gsreqp->gsr_interface;
11144 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11145 				struct sockaddr_in *s;
11146 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11147 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11148 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11149 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11150 			} else {
11151 				struct sockaddr_in6 *s6;
11152 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11153 				v6grp = s6->sin6_addr;
11154 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11155 				v6src = s6->sin6_addr;
11156 			}
11157 
11158 			/*
11159 			 * In the multirouting case, we need to replicate
11160 			 * the request as noted in the mcast cases above.
11161 			 */
11162 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11163 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11164 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11165 			if (ire != NULL) {
11166 				if (ire->ire_flags & RTF_MULTIRT) {
11167 					error = ip_multirt_apply_membership_v6(
11168 					    optfn, ire, connp, checkonly,
11169 					    &v6grp, fmode, &v6src, first_mp);
11170 					done = B_TRUE;
11171 				}
11172 				ire_refrele(ire);
11173 			}
11174 			if (!done) {
11175 				error = optfn(connp, checkonly, &v6grp,
11176 				    ifindex, fmode, &v6src, first_mp);
11177 			}
11178 			if (error != 0) {
11179 				/*
11180 				 * EINPROGRESS is a soft error, needs retry
11181 				 * so don't make *outlenp zero.
11182 				 */
11183 				if (error != EINPROGRESS)
11184 					*outlenp = 0;
11185 				return (error);
11186 			}
11187 			/* OK return - copy input buffer into output buffer */
11188 			if (invalp != outvalp) {
11189 				bcopy(invalp, outvalp, inlen);
11190 			}
11191 			*outlenp = inlen;
11192 			return (0);
11193 		}
11194 		case IPV6_UNICAST_HOPS:
11195 			/* Recorded in transport above IP */
11196 			break;	/* goto sizeof (int) option return */
11197 		case IPV6_UNSPEC_SRC:
11198 			/* Allow sending with a zero source address */
11199 			if (!checkonly) {
11200 				mutex_enter(&connp->conn_lock);
11201 				connp->conn_unspec_src = *i1 ? 1 : 0;
11202 				mutex_exit(&connp->conn_lock);
11203 			}
11204 			break;	/* goto sizeof (int) option return */
11205 		case IPV6_RECVPKTINFO:
11206 			if (!checkonly) {
11207 				mutex_enter(&connp->conn_lock);
11208 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11209 				mutex_exit(&connp->conn_lock);
11210 			}
11211 			break;	/* goto sizeof (int) option return */
11212 		case IPV6_RECVTCLASS:
11213 			if (!checkonly) {
11214 				if (*i1 < 0 || *i1 > 1) {
11215 					return (EINVAL);
11216 				}
11217 				mutex_enter(&connp->conn_lock);
11218 				connp->conn_ipv6_recvtclass = *i1;
11219 				mutex_exit(&connp->conn_lock);
11220 			}
11221 			break;
11222 		case IPV6_RECVPATHMTU:
11223 			if (!checkonly) {
11224 				if (*i1 < 0 || *i1 > 1) {
11225 					return (EINVAL);
11226 				}
11227 				mutex_enter(&connp->conn_lock);
11228 				connp->conn_ipv6_recvpathmtu = *i1;
11229 				mutex_exit(&connp->conn_lock);
11230 			}
11231 			break;
11232 		case IPV6_RECVHOPLIMIT:
11233 			if (!checkonly) {
11234 				mutex_enter(&connp->conn_lock);
11235 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11236 				mutex_exit(&connp->conn_lock);
11237 			}
11238 			break;	/* goto sizeof (int) option return */
11239 		case IPV6_RECVHOPOPTS:
11240 			if (!checkonly) {
11241 				mutex_enter(&connp->conn_lock);
11242 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11243 				mutex_exit(&connp->conn_lock);
11244 			}
11245 			break;	/* goto sizeof (int) option return */
11246 		case IPV6_RECVDSTOPTS:
11247 			if (!checkonly) {
11248 				mutex_enter(&connp->conn_lock);
11249 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11250 				mutex_exit(&connp->conn_lock);
11251 			}
11252 			break;	/* goto sizeof (int) option return */
11253 		case IPV6_RECVRTHDR:
11254 			if (!checkonly) {
11255 				mutex_enter(&connp->conn_lock);
11256 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11257 				mutex_exit(&connp->conn_lock);
11258 			}
11259 			break;	/* goto sizeof (int) option return */
11260 		case IPV6_RECVRTHDRDSTOPTS:
11261 			if (!checkonly) {
11262 				mutex_enter(&connp->conn_lock);
11263 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11264 				mutex_exit(&connp->conn_lock);
11265 			}
11266 			break;	/* goto sizeof (int) option return */
11267 		case IPV6_PKTINFO:
11268 			if (inlen == 0)
11269 				return (-EINVAL);	/* clearing option */
11270 			error = ip6_set_pktinfo(cr, connp,
11271 			    (struct in6_pktinfo *)invalp);
11272 			if (error != 0)
11273 				*outlenp = 0;
11274 			else
11275 				*outlenp = inlen;
11276 			return (error);
11277 		case IPV6_NEXTHOP: {
11278 			struct sockaddr_in6 *sin6;
11279 
11280 			/* Verify that the nexthop is reachable */
11281 			if (inlen == 0)
11282 				return (-EINVAL);	/* clearing option */
11283 
11284 			sin6 = (struct sockaddr_in6 *)invalp;
11285 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11286 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11287 			    NULL, MATCH_IRE_DEFAULT, ipst);
11288 
11289 			if (ire == NULL) {
11290 				*outlenp = 0;
11291 				return (EHOSTUNREACH);
11292 			}
11293 			ire_refrele(ire);
11294 			return (-EINVAL);
11295 		}
11296 		case IPV6_SEC_OPT:
11297 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11298 			if (error != 0) {
11299 				*outlenp = 0;
11300 				return (error);
11301 			}
11302 			break;
11303 		case IPV6_SRC_PREFERENCES: {
11304 			/*
11305 			 * This is implemented strictly in the ip module
11306 			 * (here and in tcp_opt_*() to accomodate tcp
11307 			 * sockets).  Modules above ip pass this option
11308 			 * down here since ip is the only one that needs to
11309 			 * be aware of source address preferences.
11310 			 *
11311 			 * This socket option only affects connected
11312 			 * sockets that haven't already bound to a specific
11313 			 * IPv6 address.  In other words, sockets that
11314 			 * don't call bind() with an address other than the
11315 			 * unspecified address and that call connect().
11316 			 * ip_bind_connected_v6() passes these preferences
11317 			 * to the ipif_select_source_v6() function.
11318 			 */
11319 			if (inlen != sizeof (uint32_t))
11320 				return (EINVAL);
11321 			error = ip6_set_src_preferences(connp,
11322 			    *(uint32_t *)invalp);
11323 			if (error != 0) {
11324 				*outlenp = 0;
11325 				return (error);
11326 			} else {
11327 				*outlenp = sizeof (uint32_t);
11328 			}
11329 			break;
11330 		}
11331 		case IPV6_V6ONLY:
11332 			if (*i1 < 0 || *i1 > 1) {
11333 				return (EINVAL);
11334 			}
11335 			mutex_enter(&connp->conn_lock);
11336 			connp->conn_ipv6_v6only = *i1;
11337 			mutex_exit(&connp->conn_lock);
11338 			break;
11339 		default:
11340 			return (-EINVAL);
11341 		}
11342 		break;
11343 	default:
11344 		/*
11345 		 * "soft" error (negative)
11346 		 * option not handled at this level
11347 		 * Note: Do not modify *outlenp
11348 		 */
11349 		return (-EINVAL);
11350 	}
11351 	/*
11352 	 * Common case of return from an option that is sizeof (int)
11353 	 */
11354 	*(int *)outvalp = *i1;
11355 	*outlenp = sizeof (int);
11356 	return (0);
11357 }
11358 
11359 /*
11360  * This routine gets default values of certain options whose default
11361  * values are maintained by protocol specific code
11362  */
11363 /* ARGSUSED */
11364 int
11365 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11366 {
11367 	int *i1 = (int *)ptr;
11368 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11369 
11370 	switch (level) {
11371 	case IPPROTO_IP:
11372 		switch (name) {
11373 		case IP_MULTICAST_TTL:
11374 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11375 			return (sizeof (uchar_t));
11376 		case IP_MULTICAST_LOOP:
11377 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11378 			return (sizeof (uchar_t));
11379 		default:
11380 			return (-1);
11381 		}
11382 	case IPPROTO_IPV6:
11383 		switch (name) {
11384 		case IPV6_UNICAST_HOPS:
11385 			*i1 = ipst->ips_ipv6_def_hops;
11386 			return (sizeof (int));
11387 		case IPV6_MULTICAST_HOPS:
11388 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11389 			return (sizeof (int));
11390 		case IPV6_MULTICAST_LOOP:
11391 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11392 			return (sizeof (int));
11393 		case IPV6_V6ONLY:
11394 			*i1 = 1;
11395 			return (sizeof (int));
11396 		default:
11397 			return (-1);
11398 		}
11399 	default:
11400 		return (-1);
11401 	}
11402 	/* NOTREACHED */
11403 }
11404 
11405 /*
11406  * Given a destination address and a pointer to where to put the information
11407  * this routine fills in the mtuinfo.
11408  */
11409 int
11410 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11411     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11412 {
11413 	ire_t *ire;
11414 	ip_stack_t	*ipst = ns->netstack_ip;
11415 
11416 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11417 		return (-1);
11418 
11419 	bzero(mtuinfo, sizeof (*mtuinfo));
11420 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11421 	mtuinfo->ip6m_addr.sin6_port = port;
11422 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11423 
11424 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11425 	if (ire != NULL) {
11426 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11427 		ire_refrele(ire);
11428 	} else {
11429 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11430 	}
11431 	return (sizeof (struct ip6_mtuinfo));
11432 }
11433 
11434 /*
11435  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11436  * checking of cred and that ip_g_mrouter is set should be done and
11437  * isn't.  This doesn't matter as the error checking is done properly for the
11438  * other MRT options coming in through ip_opt_set.
11439  */
11440 int
11441 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11442 {
11443 	conn_t		*connp = Q_TO_CONN(q);
11444 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11445 
11446 	switch (level) {
11447 	case IPPROTO_IP:
11448 		switch (name) {
11449 		case MRT_VERSION:
11450 		case MRT_ASSERT:
11451 			(void) ip_mrouter_get(name, q, ptr);
11452 			return (sizeof (int));
11453 		case IP_SEC_OPT:
11454 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11455 		case IP_NEXTHOP:
11456 			if (connp->conn_nexthop_set) {
11457 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11458 				return (sizeof (ipaddr_t));
11459 			} else
11460 				return (0);
11461 		case IP_RECVPKTINFO:
11462 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11463 			return (sizeof (int));
11464 		default:
11465 			break;
11466 		}
11467 		break;
11468 	case IPPROTO_IPV6:
11469 		switch (name) {
11470 		case IPV6_SEC_OPT:
11471 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11472 		case IPV6_SRC_PREFERENCES: {
11473 			return (ip6_get_src_preferences(connp,
11474 			    (uint32_t *)ptr));
11475 		}
11476 		case IPV6_V6ONLY:
11477 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11478 			return (sizeof (int));
11479 		case IPV6_PATHMTU:
11480 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11481 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11482 		default:
11483 			break;
11484 		}
11485 		break;
11486 	default:
11487 		break;
11488 	}
11489 	return (-1);
11490 }
11491 /* Named Dispatch routine to get a current value out of our parameter table. */
11492 /* ARGSUSED */
11493 static int
11494 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11495 {
11496 	ipparam_t *ippa = (ipparam_t *)cp;
11497 
11498 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11499 	return (0);
11500 }
11501 
11502 /* ARGSUSED */
11503 static int
11504 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11505 {
11506 
11507 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11508 	return (0);
11509 }
11510 
11511 /*
11512  * Set ip{,6}_forwarding values.  This means walking through all of the
11513  * ill's and toggling their forwarding values.
11514  */
11515 /* ARGSUSED */
11516 static int
11517 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11518 {
11519 	long new_value;
11520 	int *forwarding_value = (int *)cp;
11521 	ill_t *ill;
11522 	boolean_t isv6;
11523 	ill_walk_context_t ctx;
11524 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11525 
11526 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11527 
11528 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11529 	    new_value < 0 || new_value > 1) {
11530 		return (EINVAL);
11531 	}
11532 
11533 	*forwarding_value = new_value;
11534 
11535 	/*
11536 	 * Regardless of the current value of ip_forwarding, set all per-ill
11537 	 * values of ip_forwarding to the value being set.
11538 	 *
11539 	 * Bring all the ill's up to date with the new global value.
11540 	 */
11541 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11542 
11543 	if (isv6)
11544 		ill = ILL_START_WALK_V6(&ctx, ipst);
11545 	else
11546 		ill = ILL_START_WALK_V4(&ctx, ipst);
11547 
11548 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11549 		(void) ill_forward_set(ill, new_value != 0);
11550 
11551 	rw_exit(&ipst->ips_ill_g_lock);
11552 	return (0);
11553 }
11554 
11555 /*
11556  * Walk through the param array specified registering each element with the
11557  * Named Dispatch handler. This is called only during init. So it is ok
11558  * not to acquire any locks
11559  */
11560 static boolean_t
11561 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11562     ipndp_t *ipnd, size_t ipnd_cnt)
11563 {
11564 	for (; ippa_cnt-- > 0; ippa++) {
11565 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11566 			if (!nd_load(ndp, ippa->ip_param_name,
11567 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11568 				nd_free(ndp);
11569 				return (B_FALSE);
11570 			}
11571 		}
11572 	}
11573 
11574 	for (; ipnd_cnt-- > 0; ipnd++) {
11575 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11576 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11577 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11578 			    ipnd->ip_ndp_data)) {
11579 				nd_free(ndp);
11580 				return (B_FALSE);
11581 			}
11582 		}
11583 	}
11584 
11585 	return (B_TRUE);
11586 }
11587 
11588 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11589 /* ARGSUSED */
11590 static int
11591 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11592 {
11593 	long		new_value;
11594 	ipparam_t	*ippa = (ipparam_t *)cp;
11595 
11596 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11597 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11598 		return (EINVAL);
11599 	}
11600 	ippa->ip_param_value = new_value;
11601 	return (0);
11602 }
11603 
11604 /*
11605  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11606  * When an ipf is passed here for the first time, if
11607  * we already have in-order fragments on the queue, we convert from the fast-
11608  * path reassembly scheme to the hard-case scheme.  From then on, additional
11609  * fragments are reassembled here.  We keep track of the start and end offsets
11610  * of each piece, and the number of holes in the chain.  When the hole count
11611  * goes to zero, we are done!
11612  *
11613  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11614  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11615  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11616  * after the call to ip_reassemble().
11617  */
11618 int
11619 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11620     size_t msg_len)
11621 {
11622 	uint_t	end;
11623 	mblk_t	*next_mp;
11624 	mblk_t	*mp1;
11625 	uint_t	offset;
11626 	boolean_t incr_dups = B_TRUE;
11627 	boolean_t offset_zero_seen = B_FALSE;
11628 	boolean_t pkt_boundary_checked = B_FALSE;
11629 
11630 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11631 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11632 
11633 	/* Add in byte count */
11634 	ipf->ipf_count += msg_len;
11635 	if (ipf->ipf_end) {
11636 		/*
11637 		 * We were part way through in-order reassembly, but now there
11638 		 * is a hole.  We walk through messages already queued, and
11639 		 * mark them for hard case reassembly.  We know that up till
11640 		 * now they were in order starting from offset zero.
11641 		 */
11642 		offset = 0;
11643 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11644 			IP_REASS_SET_START(mp1, offset);
11645 			if (offset == 0) {
11646 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11647 				offset = -ipf->ipf_nf_hdr_len;
11648 			}
11649 			offset += mp1->b_wptr - mp1->b_rptr;
11650 			IP_REASS_SET_END(mp1, offset);
11651 		}
11652 		/* One hole at the end. */
11653 		ipf->ipf_hole_cnt = 1;
11654 		/* Brand it as a hard case, forever. */
11655 		ipf->ipf_end = 0;
11656 	}
11657 	/* Walk through all the new pieces. */
11658 	do {
11659 		end = start + (mp->b_wptr - mp->b_rptr);
11660 		/*
11661 		 * If start is 0, decrease 'end' only for the first mblk of
11662 		 * the fragment. Otherwise 'end' can get wrong value in the
11663 		 * second pass of the loop if first mblk is exactly the
11664 		 * size of ipf_nf_hdr_len.
11665 		 */
11666 		if (start == 0 && !offset_zero_seen) {
11667 			/* First segment */
11668 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11669 			end -= ipf->ipf_nf_hdr_len;
11670 			offset_zero_seen = B_TRUE;
11671 		}
11672 		next_mp = mp->b_cont;
11673 		/*
11674 		 * We are checking to see if there is any interesing data
11675 		 * to process.  If there isn't and the mblk isn't the
11676 		 * one which carries the unfragmentable header then we
11677 		 * drop it.  It's possible to have just the unfragmentable
11678 		 * header come through without any data.  That needs to be
11679 		 * saved.
11680 		 *
11681 		 * If the assert at the top of this function holds then the
11682 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11683 		 * is infrequently traveled enough that the test is left in
11684 		 * to protect against future code changes which break that
11685 		 * invariant.
11686 		 */
11687 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11688 			/* Empty.  Blast it. */
11689 			IP_REASS_SET_START(mp, 0);
11690 			IP_REASS_SET_END(mp, 0);
11691 			/*
11692 			 * If the ipf points to the mblk we are about to free,
11693 			 * update ipf to point to the next mblk (or NULL
11694 			 * if none).
11695 			 */
11696 			if (ipf->ipf_mp->b_cont == mp)
11697 				ipf->ipf_mp->b_cont = next_mp;
11698 			freeb(mp);
11699 			continue;
11700 		}
11701 		mp->b_cont = NULL;
11702 		IP_REASS_SET_START(mp, start);
11703 		IP_REASS_SET_END(mp, end);
11704 		if (!ipf->ipf_tail_mp) {
11705 			ipf->ipf_tail_mp = mp;
11706 			ipf->ipf_mp->b_cont = mp;
11707 			if (start == 0 || !more) {
11708 				ipf->ipf_hole_cnt = 1;
11709 				/*
11710 				 * if the first fragment comes in more than one
11711 				 * mblk, this loop will be executed for each
11712 				 * mblk. Need to adjust hole count so exiting
11713 				 * this routine will leave hole count at 1.
11714 				 */
11715 				if (next_mp)
11716 					ipf->ipf_hole_cnt++;
11717 			} else
11718 				ipf->ipf_hole_cnt = 2;
11719 			continue;
11720 		} else if (ipf->ipf_last_frag_seen && !more &&
11721 		    !pkt_boundary_checked) {
11722 			/*
11723 			 * We check datagram boundary only if this fragment
11724 			 * claims to be the last fragment and we have seen a
11725 			 * last fragment in the past too. We do this only
11726 			 * once for a given fragment.
11727 			 *
11728 			 * start cannot be 0 here as fragments with start=0
11729 			 * and MF=0 gets handled as a complete packet. These
11730 			 * fragments should not reach here.
11731 			 */
11732 
11733 			if (start + msgdsize(mp) !=
11734 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11735 				/*
11736 				 * We have two fragments both of which claim
11737 				 * to be the last fragment but gives conflicting
11738 				 * information about the whole datagram size.
11739 				 * Something fishy is going on. Drop the
11740 				 * fragment and free up the reassembly list.
11741 				 */
11742 				return (IP_REASS_FAILED);
11743 			}
11744 
11745 			/*
11746 			 * We shouldn't come to this code block again for this
11747 			 * particular fragment.
11748 			 */
11749 			pkt_boundary_checked = B_TRUE;
11750 		}
11751 
11752 		/* New stuff at or beyond tail? */
11753 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11754 		if (start >= offset) {
11755 			if (ipf->ipf_last_frag_seen) {
11756 				/* current fragment is beyond last fragment */
11757 				return (IP_REASS_FAILED);
11758 			}
11759 			/* Link it on end. */
11760 			ipf->ipf_tail_mp->b_cont = mp;
11761 			ipf->ipf_tail_mp = mp;
11762 			if (more) {
11763 				if (start != offset)
11764 					ipf->ipf_hole_cnt++;
11765 			} else if (start == offset && next_mp == NULL)
11766 					ipf->ipf_hole_cnt--;
11767 			continue;
11768 		}
11769 		mp1 = ipf->ipf_mp->b_cont;
11770 		offset = IP_REASS_START(mp1);
11771 		/* New stuff at the front? */
11772 		if (start < offset) {
11773 			if (start == 0) {
11774 				if (end >= offset) {
11775 					/* Nailed the hole at the begining. */
11776 					ipf->ipf_hole_cnt--;
11777 				}
11778 			} else if (end < offset) {
11779 				/*
11780 				 * A hole, stuff, and a hole where there used
11781 				 * to be just a hole.
11782 				 */
11783 				ipf->ipf_hole_cnt++;
11784 			}
11785 			mp->b_cont = mp1;
11786 			/* Check for overlap. */
11787 			while (end > offset) {
11788 				if (end < IP_REASS_END(mp1)) {
11789 					mp->b_wptr -= end - offset;
11790 					IP_REASS_SET_END(mp, offset);
11791 					BUMP_MIB(ill->ill_ip_mib,
11792 					    ipIfStatsReasmPartDups);
11793 					break;
11794 				}
11795 				/* Did we cover another hole? */
11796 				if ((mp1->b_cont &&
11797 				    IP_REASS_END(mp1) !=
11798 				    IP_REASS_START(mp1->b_cont) &&
11799 				    end >= IP_REASS_START(mp1->b_cont)) ||
11800 				    (!ipf->ipf_last_frag_seen && !more)) {
11801 					ipf->ipf_hole_cnt--;
11802 				}
11803 				/* Clip out mp1. */
11804 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11805 					/*
11806 					 * After clipping out mp1, this guy
11807 					 * is now hanging off the end.
11808 					 */
11809 					ipf->ipf_tail_mp = mp;
11810 				}
11811 				IP_REASS_SET_START(mp1, 0);
11812 				IP_REASS_SET_END(mp1, 0);
11813 				/* Subtract byte count */
11814 				ipf->ipf_count -= mp1->b_datap->db_lim -
11815 				    mp1->b_datap->db_base;
11816 				freeb(mp1);
11817 				BUMP_MIB(ill->ill_ip_mib,
11818 				    ipIfStatsReasmPartDups);
11819 				mp1 = mp->b_cont;
11820 				if (!mp1)
11821 					break;
11822 				offset = IP_REASS_START(mp1);
11823 			}
11824 			ipf->ipf_mp->b_cont = mp;
11825 			continue;
11826 		}
11827 		/*
11828 		 * The new piece starts somewhere between the start of the head
11829 		 * and before the end of the tail.
11830 		 */
11831 		for (; mp1; mp1 = mp1->b_cont) {
11832 			offset = IP_REASS_END(mp1);
11833 			if (start < offset) {
11834 				if (end <= offset) {
11835 					/* Nothing new. */
11836 					IP_REASS_SET_START(mp, 0);
11837 					IP_REASS_SET_END(mp, 0);
11838 					/* Subtract byte count */
11839 					ipf->ipf_count -= mp->b_datap->db_lim -
11840 					    mp->b_datap->db_base;
11841 					if (incr_dups) {
11842 						ipf->ipf_num_dups++;
11843 						incr_dups = B_FALSE;
11844 					}
11845 					freeb(mp);
11846 					BUMP_MIB(ill->ill_ip_mib,
11847 					    ipIfStatsReasmDuplicates);
11848 					break;
11849 				}
11850 				/*
11851 				 * Trim redundant stuff off beginning of new
11852 				 * piece.
11853 				 */
11854 				IP_REASS_SET_START(mp, offset);
11855 				mp->b_rptr += offset - start;
11856 				BUMP_MIB(ill->ill_ip_mib,
11857 				    ipIfStatsReasmPartDups);
11858 				start = offset;
11859 				if (!mp1->b_cont) {
11860 					/*
11861 					 * After trimming, this guy is now
11862 					 * hanging off the end.
11863 					 */
11864 					mp1->b_cont = mp;
11865 					ipf->ipf_tail_mp = mp;
11866 					if (!more) {
11867 						ipf->ipf_hole_cnt--;
11868 					}
11869 					break;
11870 				}
11871 			}
11872 			if (start >= IP_REASS_START(mp1->b_cont))
11873 				continue;
11874 			/* Fill a hole */
11875 			if (start > offset)
11876 				ipf->ipf_hole_cnt++;
11877 			mp->b_cont = mp1->b_cont;
11878 			mp1->b_cont = mp;
11879 			mp1 = mp->b_cont;
11880 			offset = IP_REASS_START(mp1);
11881 			if (end >= offset) {
11882 				ipf->ipf_hole_cnt--;
11883 				/* Check for overlap. */
11884 				while (end > offset) {
11885 					if (end < IP_REASS_END(mp1)) {
11886 						mp->b_wptr -= end - offset;
11887 						IP_REASS_SET_END(mp, offset);
11888 						/*
11889 						 * TODO we might bump
11890 						 * this up twice if there is
11891 						 * overlap at both ends.
11892 						 */
11893 						BUMP_MIB(ill->ill_ip_mib,
11894 						    ipIfStatsReasmPartDups);
11895 						break;
11896 					}
11897 					/* Did we cover another hole? */
11898 					if ((mp1->b_cont &&
11899 					    IP_REASS_END(mp1)
11900 					    != IP_REASS_START(mp1->b_cont) &&
11901 					    end >=
11902 					    IP_REASS_START(mp1->b_cont)) ||
11903 					    (!ipf->ipf_last_frag_seen &&
11904 					    !more)) {
11905 						ipf->ipf_hole_cnt--;
11906 					}
11907 					/* Clip out mp1. */
11908 					if ((mp->b_cont = mp1->b_cont) ==
11909 					    NULL) {
11910 						/*
11911 						 * After clipping out mp1,
11912 						 * this guy is now hanging
11913 						 * off the end.
11914 						 */
11915 						ipf->ipf_tail_mp = mp;
11916 					}
11917 					IP_REASS_SET_START(mp1, 0);
11918 					IP_REASS_SET_END(mp1, 0);
11919 					/* Subtract byte count */
11920 					ipf->ipf_count -=
11921 					    mp1->b_datap->db_lim -
11922 					    mp1->b_datap->db_base;
11923 					freeb(mp1);
11924 					BUMP_MIB(ill->ill_ip_mib,
11925 					    ipIfStatsReasmPartDups);
11926 					mp1 = mp->b_cont;
11927 					if (!mp1)
11928 						break;
11929 					offset = IP_REASS_START(mp1);
11930 				}
11931 			}
11932 			break;
11933 		}
11934 	} while (start = end, mp = next_mp);
11935 
11936 	/* Fragment just processed could be the last one. Remember this fact */
11937 	if (!more)
11938 		ipf->ipf_last_frag_seen = B_TRUE;
11939 
11940 	/* Still got holes? */
11941 	if (ipf->ipf_hole_cnt)
11942 		return (IP_REASS_PARTIAL);
11943 	/* Clean up overloaded fields to avoid upstream disasters. */
11944 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11945 		IP_REASS_SET_START(mp1, 0);
11946 		IP_REASS_SET_END(mp1, 0);
11947 	}
11948 	return (IP_REASS_COMPLETE);
11949 }
11950 
11951 /*
11952  * ipsec processing for the fast path, used for input UDP Packets
11953  * Returns true if ready for passup to UDP.
11954  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11955  * was an ESP-in-UDP packet, etc.).
11956  */
11957 static boolean_t
11958 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11959     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11960 {
11961 	uint32_t	ill_index;
11962 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11963 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11964 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11965 	udp_t		*udp = connp->conn_udp;
11966 
11967 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11968 	/* The ill_index of the incoming ILL */
11969 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11970 
11971 	/* pass packet up to the transport */
11972 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11973 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11974 		    NULL, mctl_present);
11975 		if (*first_mpp == NULL) {
11976 			return (B_FALSE);
11977 		}
11978 	}
11979 
11980 	/* Initiate IPPF processing for fastpath UDP */
11981 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11982 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11983 		if (*mpp == NULL) {
11984 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11985 			    "deferred/dropped during IPPF processing\n"));
11986 			return (B_FALSE);
11987 		}
11988 	}
11989 	/*
11990 	 * Remove 0-spi if it's 0, or move everything behind
11991 	 * the UDP header over it and forward to ESP via
11992 	 * ip_proto_input().
11993 	 */
11994 	if (udp->udp_nat_t_endpoint) {
11995 		if (mctl_present) {
11996 			/* mctl_present *shouldn't* happen. */
11997 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
11998 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
11999 			    &ipss->ipsec_dropper);
12000 			*first_mpp = NULL;
12001 			return (B_FALSE);
12002 		}
12003 
12004 		/* "ill" is "recv_ill" in actuality. */
12005 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12006 			return (B_FALSE);
12007 
12008 		/* Else continue like a normal UDP packet. */
12009 	}
12010 
12011 	/*
12012 	 * We make the checks as below since we are in the fast path
12013 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12014 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12015 	 */
12016 	if (connp->conn_recvif || connp->conn_recvslla ||
12017 	    connp->conn_ip_recvpktinfo) {
12018 		if (connp->conn_recvif) {
12019 			in_flags = IPF_RECVIF;
12020 		}
12021 		/*
12022 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12023 		 * so the flag passed to ip_add_info is based on IP version
12024 		 * of connp.
12025 		 */
12026 		if (connp->conn_ip_recvpktinfo) {
12027 			if (connp->conn_af_isv6) {
12028 				/*
12029 				 * V6 only needs index
12030 				 */
12031 				in_flags |= IPF_RECVIF;
12032 			} else {
12033 				/*
12034 				 * V4 needs index + matching address.
12035 				 */
12036 				in_flags |= IPF_RECVADDR;
12037 			}
12038 		}
12039 		if (connp->conn_recvslla) {
12040 			in_flags |= IPF_RECVSLLA;
12041 		}
12042 		/*
12043 		 * since in_flags are being set ill will be
12044 		 * referenced in ip_add_info, so it better not
12045 		 * be NULL.
12046 		 */
12047 		/*
12048 		 * the actual data will be contained in b_cont
12049 		 * upon successful return of the following call.
12050 		 * If the call fails then the original mblk is
12051 		 * returned.
12052 		 */
12053 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12054 		    ipst);
12055 	}
12056 
12057 	return (B_TRUE);
12058 }
12059 
12060 /*
12061  * Fragmentation reassembly.  Each ILL has a hash table for
12062  * queuing packets undergoing reassembly for all IPIFs
12063  * associated with the ILL.  The hash is based on the packet
12064  * IP ident field.  The ILL frag hash table was allocated
12065  * as a timer block at the time the ILL was created.  Whenever
12066  * there is anything on the reassembly queue, the timer will
12067  * be running.  Returns B_TRUE if successful else B_FALSE;
12068  * frees mp on failure.
12069  */
12070 static boolean_t
12071 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12072     uint32_t *cksum_val, uint16_t *cksum_flags)
12073 {
12074 	uint32_t	frag_offset_flags;
12075 	mblk_t		*mp = *mpp;
12076 	mblk_t		*t_mp;
12077 	ipaddr_t	dst;
12078 	uint8_t		proto = ipha->ipha_protocol;
12079 	uint32_t	sum_val;
12080 	uint16_t	sum_flags;
12081 	ipf_t		*ipf;
12082 	ipf_t		**ipfp;
12083 	ipfb_t		*ipfb;
12084 	uint16_t	ident;
12085 	uint32_t	offset;
12086 	ipaddr_t	src;
12087 	uint_t		hdr_length;
12088 	uint32_t	end;
12089 	mblk_t		*mp1;
12090 	mblk_t		*tail_mp;
12091 	size_t		count;
12092 	size_t		msg_len;
12093 	uint8_t		ecn_info = 0;
12094 	uint32_t	packet_size;
12095 	boolean_t	pruned = B_FALSE;
12096 	ip_stack_t *ipst = ill->ill_ipst;
12097 
12098 	if (cksum_val != NULL)
12099 		*cksum_val = 0;
12100 	if (cksum_flags != NULL)
12101 		*cksum_flags = 0;
12102 
12103 	/*
12104 	 * Drop the fragmented as early as possible, if
12105 	 * we don't have resource(s) to re-assemble.
12106 	 */
12107 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12108 		freemsg(mp);
12109 		return (B_FALSE);
12110 	}
12111 
12112 	/* Check for fragmentation offset; return if there's none */
12113 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12114 	    (IPH_MF | IPH_OFFSET)) == 0)
12115 		return (B_TRUE);
12116 
12117 	/*
12118 	 * We utilize hardware computed checksum info only for UDP since
12119 	 * IP fragmentation is a normal occurrence for the protocol.  In
12120 	 * addition, checksum offload support for IP fragments carrying
12121 	 * UDP payload is commonly implemented across network adapters.
12122 	 */
12123 	ASSERT(recv_ill != NULL);
12124 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12125 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12126 		mblk_t *mp1 = mp->b_cont;
12127 		int32_t len;
12128 
12129 		/* Record checksum information from the packet */
12130 		sum_val = (uint32_t)DB_CKSUM16(mp);
12131 		sum_flags = DB_CKSUMFLAGS(mp);
12132 
12133 		/* IP payload offset from beginning of mblk */
12134 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12135 
12136 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12137 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12138 		    offset >= DB_CKSUMSTART(mp) &&
12139 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12140 			uint32_t adj;
12141 			/*
12142 			 * Partial checksum has been calculated by hardware
12143 			 * and attached to the packet; in addition, any
12144 			 * prepended extraneous data is even byte aligned.
12145 			 * If any such data exists, we adjust the checksum;
12146 			 * this would also handle any postpended data.
12147 			 */
12148 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12149 			    mp, mp1, len, adj);
12150 
12151 			/* One's complement subtract extraneous checksum */
12152 			if (adj >= sum_val)
12153 				sum_val = ~(adj - sum_val) & 0xFFFF;
12154 			else
12155 				sum_val -= adj;
12156 		}
12157 	} else {
12158 		sum_val = 0;
12159 		sum_flags = 0;
12160 	}
12161 
12162 	/* Clear hardware checksumming flag */
12163 	DB_CKSUMFLAGS(mp) = 0;
12164 
12165 	ident = ipha->ipha_ident;
12166 	offset = (frag_offset_flags << 3) & 0xFFFF;
12167 	src = ipha->ipha_src;
12168 	dst = ipha->ipha_dst;
12169 	hdr_length = IPH_HDR_LENGTH(ipha);
12170 	end = ntohs(ipha->ipha_length) - hdr_length;
12171 
12172 	/* If end == 0 then we have a packet with no data, so just free it */
12173 	if (end == 0) {
12174 		freemsg(mp);
12175 		return (B_FALSE);
12176 	}
12177 
12178 	/* Record the ECN field info. */
12179 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12180 	if (offset != 0) {
12181 		/*
12182 		 * If this isn't the first piece, strip the header, and
12183 		 * add the offset to the end value.
12184 		 */
12185 		mp->b_rptr += hdr_length;
12186 		end += offset;
12187 	}
12188 
12189 	msg_len = MBLKSIZE(mp);
12190 	tail_mp = mp;
12191 	while (tail_mp->b_cont != NULL) {
12192 		tail_mp = tail_mp->b_cont;
12193 		msg_len += MBLKSIZE(tail_mp);
12194 	}
12195 
12196 	/* If the reassembly list for this ILL will get too big, prune it */
12197 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12198 	    ipst->ips_ip_reass_queue_bytes) {
12199 		ill_frag_prune(ill,
12200 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12201 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12202 		pruned = B_TRUE;
12203 	}
12204 
12205 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12206 	mutex_enter(&ipfb->ipfb_lock);
12207 
12208 	ipfp = &ipfb->ipfb_ipf;
12209 	/* Try to find an existing fragment queue for this packet. */
12210 	for (;;) {
12211 		ipf = ipfp[0];
12212 		if (ipf != NULL) {
12213 			/*
12214 			 * It has to match on ident and src/dst address.
12215 			 */
12216 			if (ipf->ipf_ident == ident &&
12217 			    ipf->ipf_src == src &&
12218 			    ipf->ipf_dst == dst &&
12219 			    ipf->ipf_protocol == proto) {
12220 				/*
12221 				 * If we have received too many
12222 				 * duplicate fragments for this packet
12223 				 * free it.
12224 				 */
12225 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12226 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12227 					freemsg(mp);
12228 					mutex_exit(&ipfb->ipfb_lock);
12229 					return (B_FALSE);
12230 				}
12231 				/* Found it. */
12232 				break;
12233 			}
12234 			ipfp = &ipf->ipf_hash_next;
12235 			continue;
12236 		}
12237 
12238 		/*
12239 		 * If we pruned the list, do we want to store this new
12240 		 * fragment?. We apply an optimization here based on the
12241 		 * fact that most fragments will be received in order.
12242 		 * So if the offset of this incoming fragment is zero,
12243 		 * it is the first fragment of a new packet. We will
12244 		 * keep it.  Otherwise drop the fragment, as we have
12245 		 * probably pruned the packet already (since the
12246 		 * packet cannot be found).
12247 		 */
12248 		if (pruned && offset != 0) {
12249 			mutex_exit(&ipfb->ipfb_lock);
12250 			freemsg(mp);
12251 			return (B_FALSE);
12252 		}
12253 
12254 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12255 			/*
12256 			 * Too many fragmented packets in this hash
12257 			 * bucket. Free the oldest.
12258 			 */
12259 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12260 		}
12261 
12262 		/* New guy.  Allocate a frag message. */
12263 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12264 		if (mp1 == NULL) {
12265 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12266 			freemsg(mp);
12267 reass_done:
12268 			mutex_exit(&ipfb->ipfb_lock);
12269 			return (B_FALSE);
12270 		}
12271 
12272 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12273 		mp1->b_cont = mp;
12274 
12275 		/* Initialize the fragment header. */
12276 		ipf = (ipf_t *)mp1->b_rptr;
12277 		ipf->ipf_mp = mp1;
12278 		ipf->ipf_ptphn = ipfp;
12279 		ipfp[0] = ipf;
12280 		ipf->ipf_hash_next = NULL;
12281 		ipf->ipf_ident = ident;
12282 		ipf->ipf_protocol = proto;
12283 		ipf->ipf_src = src;
12284 		ipf->ipf_dst = dst;
12285 		ipf->ipf_nf_hdr_len = 0;
12286 		/* Record reassembly start time. */
12287 		ipf->ipf_timestamp = gethrestime_sec();
12288 		/* Record ipf generation and account for frag header */
12289 		ipf->ipf_gen = ill->ill_ipf_gen++;
12290 		ipf->ipf_count = MBLKSIZE(mp1);
12291 		ipf->ipf_last_frag_seen = B_FALSE;
12292 		ipf->ipf_ecn = ecn_info;
12293 		ipf->ipf_num_dups = 0;
12294 		ipfb->ipfb_frag_pkts++;
12295 		ipf->ipf_checksum = 0;
12296 		ipf->ipf_checksum_flags = 0;
12297 
12298 		/* Store checksum value in fragment header */
12299 		if (sum_flags != 0) {
12300 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12301 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12302 			ipf->ipf_checksum = sum_val;
12303 			ipf->ipf_checksum_flags = sum_flags;
12304 		}
12305 
12306 		/*
12307 		 * We handle reassembly two ways.  In the easy case,
12308 		 * where all the fragments show up in order, we do
12309 		 * minimal bookkeeping, and just clip new pieces on
12310 		 * the end.  If we ever see a hole, then we go off
12311 		 * to ip_reassemble which has to mark the pieces and
12312 		 * keep track of the number of holes, etc.  Obviously,
12313 		 * the point of having both mechanisms is so we can
12314 		 * handle the easy case as efficiently as possible.
12315 		 */
12316 		if (offset == 0) {
12317 			/* Easy case, in-order reassembly so far. */
12318 			ipf->ipf_count += msg_len;
12319 			ipf->ipf_tail_mp = tail_mp;
12320 			/*
12321 			 * Keep track of next expected offset in
12322 			 * ipf_end.
12323 			 */
12324 			ipf->ipf_end = end;
12325 			ipf->ipf_nf_hdr_len = hdr_length;
12326 		} else {
12327 			/* Hard case, hole at the beginning. */
12328 			ipf->ipf_tail_mp = NULL;
12329 			/*
12330 			 * ipf_end == 0 means that we have given up
12331 			 * on easy reassembly.
12332 			 */
12333 			ipf->ipf_end = 0;
12334 
12335 			/* Forget checksum offload from now on */
12336 			ipf->ipf_checksum_flags = 0;
12337 
12338 			/*
12339 			 * ipf_hole_cnt is set by ip_reassemble.
12340 			 * ipf_count is updated by ip_reassemble.
12341 			 * No need to check for return value here
12342 			 * as we don't expect reassembly to complete
12343 			 * or fail for the first fragment itself.
12344 			 */
12345 			(void) ip_reassemble(mp, ipf,
12346 			    (frag_offset_flags & IPH_OFFSET) << 3,
12347 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12348 		}
12349 		/* Update per ipfb and ill byte counts */
12350 		ipfb->ipfb_count += ipf->ipf_count;
12351 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12352 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12353 		/* If the frag timer wasn't already going, start it. */
12354 		mutex_enter(&ill->ill_lock);
12355 		ill_frag_timer_start(ill);
12356 		mutex_exit(&ill->ill_lock);
12357 		goto reass_done;
12358 	}
12359 
12360 	/*
12361 	 * If the packet's flag has changed (it could be coming up
12362 	 * from an interface different than the previous, therefore
12363 	 * possibly different checksum capability), then forget about
12364 	 * any stored checksum states.  Otherwise add the value to
12365 	 * the existing one stored in the fragment header.
12366 	 */
12367 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12368 		sum_val += ipf->ipf_checksum;
12369 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12370 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12371 		ipf->ipf_checksum = sum_val;
12372 	} else if (ipf->ipf_checksum_flags != 0) {
12373 		/* Forget checksum offload from now on */
12374 		ipf->ipf_checksum_flags = 0;
12375 	}
12376 
12377 	/*
12378 	 * We have a new piece of a datagram which is already being
12379 	 * reassembled.  Update the ECN info if all IP fragments
12380 	 * are ECN capable.  If there is one which is not, clear
12381 	 * all the info.  If there is at least one which has CE
12382 	 * code point, IP needs to report that up to transport.
12383 	 */
12384 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12385 		if (ecn_info == IPH_ECN_CE)
12386 			ipf->ipf_ecn = IPH_ECN_CE;
12387 	} else {
12388 		ipf->ipf_ecn = IPH_ECN_NECT;
12389 	}
12390 	if (offset && ipf->ipf_end == offset) {
12391 		/* The new fragment fits at the end */
12392 		ipf->ipf_tail_mp->b_cont = mp;
12393 		/* Update the byte count */
12394 		ipf->ipf_count += msg_len;
12395 		/* Update per ipfb and ill byte counts */
12396 		ipfb->ipfb_count += msg_len;
12397 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12398 		atomic_add_32(&ill->ill_frag_count, msg_len);
12399 		if (frag_offset_flags & IPH_MF) {
12400 			/* More to come. */
12401 			ipf->ipf_end = end;
12402 			ipf->ipf_tail_mp = tail_mp;
12403 			goto reass_done;
12404 		}
12405 	} else {
12406 		/* Go do the hard cases. */
12407 		int ret;
12408 
12409 		if (offset == 0)
12410 			ipf->ipf_nf_hdr_len = hdr_length;
12411 
12412 		/* Save current byte count */
12413 		count = ipf->ipf_count;
12414 		ret = ip_reassemble(mp, ipf,
12415 		    (frag_offset_flags & IPH_OFFSET) << 3,
12416 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12417 		/* Count of bytes added and subtracted (freeb()ed) */
12418 		count = ipf->ipf_count - count;
12419 		if (count) {
12420 			/* Update per ipfb and ill byte counts */
12421 			ipfb->ipfb_count += count;
12422 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12423 			atomic_add_32(&ill->ill_frag_count, count);
12424 		}
12425 		if (ret == IP_REASS_PARTIAL) {
12426 			goto reass_done;
12427 		} else if (ret == IP_REASS_FAILED) {
12428 			/* Reassembly failed. Free up all resources */
12429 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12430 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12431 				IP_REASS_SET_START(t_mp, 0);
12432 				IP_REASS_SET_END(t_mp, 0);
12433 			}
12434 			freemsg(mp);
12435 			goto reass_done;
12436 		}
12437 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12438 	}
12439 	/*
12440 	 * We have completed reassembly.  Unhook the frag header from
12441 	 * the reassembly list.
12442 	 *
12443 	 * Before we free the frag header, record the ECN info
12444 	 * to report back to the transport.
12445 	 */
12446 	ecn_info = ipf->ipf_ecn;
12447 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12448 	ipfp = ipf->ipf_ptphn;
12449 
12450 	/* We need to supply these to caller */
12451 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12452 		sum_val = ipf->ipf_checksum;
12453 	else
12454 		sum_val = 0;
12455 
12456 	mp1 = ipf->ipf_mp;
12457 	count = ipf->ipf_count;
12458 	ipf = ipf->ipf_hash_next;
12459 	if (ipf != NULL)
12460 		ipf->ipf_ptphn = ipfp;
12461 	ipfp[0] = ipf;
12462 	atomic_add_32(&ill->ill_frag_count, -count);
12463 	ASSERT(ipfb->ipfb_count >= count);
12464 	ipfb->ipfb_count -= count;
12465 	ipfb->ipfb_frag_pkts--;
12466 	mutex_exit(&ipfb->ipfb_lock);
12467 	/* Ditch the frag header. */
12468 	mp = mp1->b_cont;
12469 
12470 	freeb(mp1);
12471 
12472 	/* Restore original IP length in header. */
12473 	packet_size = (uint32_t)msgdsize(mp);
12474 	if (packet_size > IP_MAXPACKET) {
12475 		freemsg(mp);
12476 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12477 		return (B_FALSE);
12478 	}
12479 
12480 	if (DB_REF(mp) > 1) {
12481 		mblk_t *mp2 = copymsg(mp);
12482 
12483 		freemsg(mp);
12484 		if (mp2 == NULL) {
12485 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12486 			return (B_FALSE);
12487 		}
12488 		mp = mp2;
12489 	}
12490 	ipha = (ipha_t *)mp->b_rptr;
12491 
12492 	ipha->ipha_length = htons((uint16_t)packet_size);
12493 	/* We're now complete, zip the frag state */
12494 	ipha->ipha_fragment_offset_and_flags = 0;
12495 	/* Record the ECN info. */
12496 	ipha->ipha_type_of_service &= 0xFC;
12497 	ipha->ipha_type_of_service |= ecn_info;
12498 	*mpp = mp;
12499 
12500 	/* Reassembly is successful; return checksum information if needed */
12501 	if (cksum_val != NULL)
12502 		*cksum_val = sum_val;
12503 	if (cksum_flags != NULL)
12504 		*cksum_flags = sum_flags;
12505 
12506 	return (B_TRUE);
12507 }
12508 
12509 /*
12510  * Perform ip header check sum update local options.
12511  * return B_TRUE if all is well, else return B_FALSE and release
12512  * the mp. caller is responsible for decrementing ire ref cnt.
12513  */
12514 static boolean_t
12515 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12516     ip_stack_t *ipst)
12517 {
12518 	mblk_t		*first_mp;
12519 	boolean_t	mctl_present;
12520 	uint16_t	sum;
12521 
12522 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12523 	/*
12524 	 * Don't do the checksum if it has gone through AH/ESP
12525 	 * processing.
12526 	 */
12527 	if (!mctl_present) {
12528 		sum = ip_csum_hdr(ipha);
12529 		if (sum != 0) {
12530 			if (ill != NULL) {
12531 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12532 			} else {
12533 				BUMP_MIB(&ipst->ips_ip_mib,
12534 				    ipIfStatsInCksumErrs);
12535 			}
12536 			freemsg(first_mp);
12537 			return (B_FALSE);
12538 		}
12539 	}
12540 
12541 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12542 		if (mctl_present)
12543 			freeb(first_mp);
12544 		return (B_FALSE);
12545 	}
12546 
12547 	return (B_TRUE);
12548 }
12549 
12550 /*
12551  * All udp packet are delivered to the local host via this routine.
12552  */
12553 void
12554 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12555     ill_t *recv_ill)
12556 {
12557 	uint32_t	sum;
12558 	uint32_t	u1;
12559 	boolean_t	mctl_present;
12560 	conn_t		*connp;
12561 	mblk_t		*first_mp;
12562 	uint16_t	*up;
12563 	ill_t		*ill = (ill_t *)q->q_ptr;
12564 	uint16_t	reass_hck_flags = 0;
12565 	ip_stack_t	*ipst;
12566 
12567 	ASSERT(recv_ill != NULL);
12568 	ipst = recv_ill->ill_ipst;
12569 
12570 #define	rptr    ((uchar_t *)ipha)
12571 
12572 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12573 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12574 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12575 	ASSERT(ill != NULL);
12576 
12577 	/*
12578 	 * FAST PATH for udp packets
12579 	 */
12580 
12581 	/* u1 is # words of IP options */
12582 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12583 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12584 
12585 	/* IP options present */
12586 	if (u1 != 0)
12587 		goto ipoptions;
12588 
12589 	/* Check the IP header checksum.  */
12590 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12591 		/* Clear the IP header h/w cksum flag */
12592 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12593 	} else if (!mctl_present) {
12594 		/*
12595 		 * Don't verify header checksum if this packet is coming
12596 		 * back from AH/ESP as we already did it.
12597 		 */
12598 #define	uph	((uint16_t *)ipha)
12599 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12600 		    uph[6] + uph[7] + uph[8] + uph[9];
12601 #undef	uph
12602 		/* finish doing IP checksum */
12603 		sum = (sum & 0xFFFF) + (sum >> 16);
12604 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12605 		if (sum != 0 && sum != 0xFFFF) {
12606 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12607 			freemsg(first_mp);
12608 			return;
12609 		}
12610 	}
12611 
12612 	/*
12613 	 * Count for SNMP of inbound packets for ire.
12614 	 * if mctl is present this might be a secure packet and
12615 	 * has already been counted for in ip_proto_input().
12616 	 */
12617 	if (!mctl_present) {
12618 		UPDATE_IB_PKT_COUNT(ire);
12619 		ire->ire_last_used_time = lbolt;
12620 	}
12621 
12622 	/* packet part of fragmented IP packet? */
12623 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12624 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12625 		goto fragmented;
12626 	}
12627 
12628 	/* u1 = IP header length (20 bytes) */
12629 	u1 = IP_SIMPLE_HDR_LENGTH;
12630 
12631 	/* packet does not contain complete IP & UDP headers */
12632 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12633 		goto udppullup;
12634 
12635 	/* up points to UDP header */
12636 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12637 #define	iphs    ((uint16_t *)ipha)
12638 
12639 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12640 	if (up[3] != 0) {
12641 		mblk_t *mp1 = mp->b_cont;
12642 		boolean_t cksum_err;
12643 		uint16_t hck_flags = 0;
12644 
12645 		/* Pseudo-header checksum */
12646 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12647 		    iphs[9] + up[2];
12648 
12649 		/*
12650 		 * Revert to software checksum calculation if the interface
12651 		 * isn't capable of checksum offload or if IPsec is present.
12652 		 */
12653 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12654 			hck_flags = DB_CKSUMFLAGS(mp);
12655 
12656 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12657 			IP_STAT(ipst, ip_in_sw_cksum);
12658 
12659 		IP_CKSUM_RECV(hck_flags, u1,
12660 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12661 		    (int32_t)((uchar_t *)up - rptr),
12662 		    mp, mp1, cksum_err);
12663 
12664 		if (cksum_err) {
12665 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12666 			if (hck_flags & HCK_FULLCKSUM)
12667 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12668 			else if (hck_flags & HCK_PARTIALCKSUM)
12669 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12670 			else
12671 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12672 
12673 			freemsg(first_mp);
12674 			return;
12675 		}
12676 	}
12677 
12678 	/* Non-fragmented broadcast or multicast packet? */
12679 	if (ire->ire_type == IRE_BROADCAST)
12680 		goto udpslowpath;
12681 
12682 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12683 	    ire->ire_zoneid, ipst)) != NULL) {
12684 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12685 		IP_STAT(ipst, ip_udp_fast_path);
12686 
12687 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12688 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12689 			freemsg(mp);
12690 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12691 		} else {
12692 			if (!mctl_present) {
12693 				BUMP_MIB(ill->ill_ip_mib,
12694 				    ipIfStatsHCInDelivers);
12695 			}
12696 			/*
12697 			 * mp and first_mp can change.
12698 			 */
12699 			if (ip_udp_check(q, connp, recv_ill,
12700 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12701 				/* Send it upstream */
12702 				(connp->conn_recv)(connp, mp, NULL);
12703 			}
12704 		}
12705 		/*
12706 		 * freeb() cannot deal with null mblk being passed
12707 		 * in and first_mp can be set to null in the call
12708 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12709 		 */
12710 		if (mctl_present && first_mp != NULL) {
12711 			freeb(first_mp);
12712 		}
12713 		CONN_DEC_REF(connp);
12714 		return;
12715 	}
12716 
12717 	/*
12718 	 * if we got here we know the packet is not fragmented and
12719 	 * has no options. The classifier could not find a conn_t and
12720 	 * most likely its an icmp packet so send it through slow path.
12721 	 */
12722 
12723 	goto udpslowpath;
12724 
12725 ipoptions:
12726 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12727 		goto slow_done;
12728 	}
12729 
12730 	UPDATE_IB_PKT_COUNT(ire);
12731 	ire->ire_last_used_time = lbolt;
12732 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12733 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12734 fragmented:
12735 		/*
12736 		 * "sum" and "reass_hck_flags" are non-zero if the
12737 		 * reassembled packet has a valid hardware computed
12738 		 * checksum information associated with it.
12739 		 */
12740 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12741 		    &reass_hck_flags)) {
12742 			goto slow_done;
12743 		}
12744 
12745 		/*
12746 		 * Make sure that first_mp points back to mp as
12747 		 * the mp we came in with could have changed in
12748 		 * ip_rput_fragment().
12749 		 */
12750 		ASSERT(!mctl_present);
12751 		ipha = (ipha_t *)mp->b_rptr;
12752 		first_mp = mp;
12753 	}
12754 
12755 	/* Now we have a complete datagram, destined for this machine. */
12756 	u1 = IPH_HDR_LENGTH(ipha);
12757 	/* Pull up the UDP header, if necessary. */
12758 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12759 udppullup:
12760 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12761 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12762 			freemsg(first_mp);
12763 			goto slow_done;
12764 		}
12765 		ipha = (ipha_t *)mp->b_rptr;
12766 	}
12767 
12768 	/*
12769 	 * Validate the checksum for the reassembled packet; for the
12770 	 * pullup case we calculate the payload checksum in software.
12771 	 */
12772 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12773 	if (up[3] != 0) {
12774 		boolean_t cksum_err;
12775 
12776 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12777 			IP_STAT(ipst, ip_in_sw_cksum);
12778 
12779 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12780 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12781 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12782 		    iphs[9] + up[2], sum, cksum_err);
12783 
12784 		if (cksum_err) {
12785 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12786 
12787 			if (reass_hck_flags & HCK_FULLCKSUM)
12788 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12789 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12790 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12791 			else
12792 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12793 
12794 			freemsg(first_mp);
12795 			goto slow_done;
12796 		}
12797 	}
12798 udpslowpath:
12799 
12800 	/* Clear hardware checksum flag to be safe */
12801 	DB_CKSUMFLAGS(mp) = 0;
12802 
12803 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12804 	    (ire->ire_type == IRE_BROADCAST),
12805 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12806 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12807 
12808 slow_done:
12809 	IP_STAT(ipst, ip_udp_slow_path);
12810 	return;
12811 
12812 #undef  iphs
12813 #undef  rptr
12814 }
12815 
12816 static boolean_t
12817 ip_iptun_input(mblk_t *ipsec_mp, mblk_t *data_mp, ipha_t *ipha, ill_t *ill,
12818     ire_t *ire, ip_stack_t *ipst)
12819 {
12820 	conn_t	*connp;
12821 
12822 	ASSERT(ipsec_mp == NULL || ipsec_mp->b_cont == data_mp);
12823 
12824 	if ((connp = ipcl_classify_v4(data_mp, ipha->ipha_protocol,
12825 	    IP_SIMPLE_HDR_LENGTH, ire->ire_zoneid, ipst)) != NULL) {
12826 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12827 		connp->conn_recv(connp, ipsec_mp != NULL ? ipsec_mp : data_mp,
12828 		    NULL);
12829 		CONN_DEC_REF(connp);
12830 		return (B_TRUE);
12831 	}
12832 	return (B_FALSE);
12833 }
12834 
12835 /* ARGSUSED */
12836 static mblk_t *
12837 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12838     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12839     ill_rx_ring_t *ill_ring)
12840 {
12841 	conn_t		*connp;
12842 	uint32_t	sum;
12843 	uint32_t	u1;
12844 	uint16_t	*up;
12845 	int		offset;
12846 	ssize_t		len;
12847 	mblk_t		*mp1;
12848 	boolean_t	syn_present = B_FALSE;
12849 	tcph_t		*tcph;
12850 	uint_t		tcph_flags;
12851 	uint_t		ip_hdr_len;
12852 	ill_t		*ill = (ill_t *)q->q_ptr;
12853 	zoneid_t	zoneid = ire->ire_zoneid;
12854 	boolean_t	cksum_err;
12855 	uint16_t	hck_flags = 0;
12856 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12857 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12858 
12859 #define	rptr	((uchar_t *)ipha)
12860 
12861 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12862 	ASSERT(ill != NULL);
12863 
12864 	/*
12865 	 * FAST PATH for tcp packets
12866 	 */
12867 
12868 	/* u1 is # words of IP options */
12869 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12870 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12871 
12872 	/* IP options present */
12873 	if (u1) {
12874 		goto ipoptions;
12875 	} else if (!mctl_present) {
12876 		/* Check the IP header checksum.  */
12877 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12878 			/* Clear the IP header h/w cksum flag */
12879 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12880 		} else if (!mctl_present) {
12881 			/*
12882 			 * Don't verify header checksum if this packet
12883 			 * is coming back from AH/ESP as we already did it.
12884 			 */
12885 #define	uph	((uint16_t *)ipha)
12886 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12887 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12888 #undef	uph
12889 			/* finish doing IP checksum */
12890 			sum = (sum & 0xFFFF) + (sum >> 16);
12891 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12892 			if (sum != 0 && sum != 0xFFFF) {
12893 				BUMP_MIB(ill->ill_ip_mib,
12894 				    ipIfStatsInCksumErrs);
12895 				goto error;
12896 			}
12897 		}
12898 	}
12899 
12900 	if (!mctl_present) {
12901 		UPDATE_IB_PKT_COUNT(ire);
12902 		ire->ire_last_used_time = lbolt;
12903 	}
12904 
12905 	/* packet part of fragmented IP packet? */
12906 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12907 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12908 		goto fragmented;
12909 	}
12910 
12911 	/* u1 = IP header length (20 bytes) */
12912 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12913 
12914 	/* does packet contain IP+TCP headers? */
12915 	len = mp->b_wptr - rptr;
12916 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12917 		IP_STAT(ipst, ip_tcppullup);
12918 		goto tcppullup;
12919 	}
12920 
12921 	/* TCP options present? */
12922 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12923 
12924 	/*
12925 	 * If options need to be pulled up, then goto tcpoptions.
12926 	 * otherwise we are still in the fast path
12927 	 */
12928 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12929 		IP_STAT(ipst, ip_tcpoptions);
12930 		goto tcpoptions;
12931 	}
12932 
12933 	/* multiple mblks of tcp data? */
12934 	if ((mp1 = mp->b_cont) != NULL) {
12935 		IP_STAT(ipst, ip_multipkttcp);
12936 		len += msgdsize(mp1);
12937 	}
12938 
12939 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12940 
12941 	/* part of pseudo checksum */
12942 
12943 	/* TCP datagram length */
12944 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12945 
12946 #define	iphs    ((uint16_t *)ipha)
12947 
12948 #ifdef	_BIG_ENDIAN
12949 	u1 += IPPROTO_TCP;
12950 #else
12951 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12952 #endif
12953 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12954 
12955 	/*
12956 	 * Revert to software checksum calculation if the interface
12957 	 * isn't capable of checksum offload or if IPsec is present.
12958 	 */
12959 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12960 		hck_flags = DB_CKSUMFLAGS(mp);
12961 
12962 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12963 		IP_STAT(ipst, ip_in_sw_cksum);
12964 
12965 	IP_CKSUM_RECV(hck_flags, u1,
12966 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12967 	    (int32_t)((uchar_t *)up - rptr),
12968 	    mp, mp1, cksum_err);
12969 
12970 	if (cksum_err) {
12971 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12972 
12973 		if (hck_flags & HCK_FULLCKSUM)
12974 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12975 		else if (hck_flags & HCK_PARTIALCKSUM)
12976 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12977 		else
12978 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12979 
12980 		goto error;
12981 	}
12982 
12983 try_again:
12984 
12985 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12986 	    zoneid, ipst)) == NULL) {
12987 		/* Send the TH_RST */
12988 		goto no_conn;
12989 	}
12990 
12991 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12992 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12993 
12994 	/*
12995 	 * TCP FAST PATH for AF_INET socket.
12996 	 *
12997 	 * TCP fast path to avoid extra work. An AF_INET socket type
12998 	 * does not have facility to receive extra information via
12999 	 * ip_process or ip_add_info. Also, when the connection was
13000 	 * established, we made a check if this connection is impacted
13001 	 * by any global IPsec policy or per connection policy (a
13002 	 * policy that comes in effect later will not apply to this
13003 	 * connection). Since all this can be determined at the
13004 	 * connection establishment time, a quick check of flags
13005 	 * can avoid extra work.
13006 	 */
13007 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13008 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13009 		ASSERT(first_mp == mp);
13010 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13011 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13012 			SET_SQUEUE(mp, tcp_rput_data, connp);
13013 			return (mp);
13014 		}
13015 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13016 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13017 		SET_SQUEUE(mp, tcp_input, connp);
13018 		return (mp);
13019 	}
13020 
13021 	if (tcph_flags == TH_SYN) {
13022 		if (IPCL_IS_TCP(connp)) {
13023 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13024 			DB_CKSUMSTART(mp) =
13025 			    (intptr_t)ip_squeue_get(ill_ring);
13026 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13027 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13028 				BUMP_MIB(ill->ill_ip_mib,
13029 				    ipIfStatsHCInDelivers);
13030 				SET_SQUEUE(mp, connp->conn_recv, connp);
13031 				return (mp);
13032 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13033 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13034 				BUMP_MIB(ill->ill_ip_mib,
13035 				    ipIfStatsHCInDelivers);
13036 				ip_squeue_enter_unbound++;
13037 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13038 				    connp);
13039 				return (mp);
13040 			}
13041 			syn_present = B_TRUE;
13042 		}
13043 	}
13044 
13045 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13046 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13047 
13048 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13049 		/* No need to send this packet to TCP */
13050 		if ((flags & TH_RST) || (flags & TH_URG)) {
13051 			CONN_DEC_REF(connp);
13052 			freemsg(first_mp);
13053 			return (NULL);
13054 		}
13055 		if (flags & TH_ACK) {
13056 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13057 			    ipst->ips_netstack->netstack_tcp, connp);
13058 			CONN_DEC_REF(connp);
13059 			return (NULL);
13060 		}
13061 
13062 		CONN_DEC_REF(connp);
13063 		freemsg(first_mp);
13064 		return (NULL);
13065 	}
13066 
13067 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13068 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13069 		    ipha, NULL, mctl_present);
13070 		if (first_mp == NULL) {
13071 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13072 			CONN_DEC_REF(connp);
13073 			return (NULL);
13074 		}
13075 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13076 			ASSERT(syn_present);
13077 			if (mctl_present) {
13078 				ASSERT(first_mp != mp);
13079 				first_mp->b_datap->db_struioflag |=
13080 				    STRUIO_POLICY;
13081 			} else {
13082 				ASSERT(first_mp == mp);
13083 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13084 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13085 			}
13086 		} else {
13087 			/*
13088 			 * Discard first_mp early since we're dealing with a
13089 			 * fully-connected conn_t and tcp doesn't do policy in
13090 			 * this case.
13091 			 */
13092 			if (mctl_present) {
13093 				freeb(first_mp);
13094 				mctl_present = B_FALSE;
13095 			}
13096 			first_mp = mp;
13097 		}
13098 	}
13099 
13100 	/* Initiate IPPF processing for fastpath */
13101 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13102 		uint32_t	ill_index;
13103 
13104 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13105 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13106 		if (mp == NULL) {
13107 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13108 			    "deferred/dropped during IPPF processing\n"));
13109 			CONN_DEC_REF(connp);
13110 			if (mctl_present)
13111 				freeb(first_mp);
13112 			return (NULL);
13113 		} else if (mctl_present) {
13114 			/*
13115 			 * ip_process might return a new mp.
13116 			 */
13117 			ASSERT(first_mp != mp);
13118 			first_mp->b_cont = mp;
13119 		} else {
13120 			first_mp = mp;
13121 		}
13122 
13123 	}
13124 
13125 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13126 		/*
13127 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13128 		 * make sure IPF_RECVIF is passed to ip_add_info.
13129 		 */
13130 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13131 		    IPCL_ZONEID(connp), ipst);
13132 		if (mp == NULL) {
13133 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13134 			CONN_DEC_REF(connp);
13135 			if (mctl_present)
13136 				freeb(first_mp);
13137 			return (NULL);
13138 		} else if (mctl_present) {
13139 			/*
13140 			 * ip_add_info might return a new mp.
13141 			 */
13142 			ASSERT(first_mp != mp);
13143 			first_mp->b_cont = mp;
13144 		} else {
13145 			first_mp = mp;
13146 		}
13147 	}
13148 
13149 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13150 	if (IPCL_IS_TCP(connp)) {
13151 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13152 		return (first_mp);
13153 	} else {
13154 		/* SOCK_RAW, IPPROTO_TCP case */
13155 		(connp->conn_recv)(connp, first_mp, NULL);
13156 		CONN_DEC_REF(connp);
13157 		return (NULL);
13158 	}
13159 
13160 no_conn:
13161 	/* Initiate IPPf processing, if needed. */
13162 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13163 		uint32_t ill_index;
13164 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13165 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13166 		if (first_mp == NULL) {
13167 			return (NULL);
13168 		}
13169 	}
13170 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13171 
13172 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13173 	    ipst->ips_netstack->netstack_tcp, NULL);
13174 	return (NULL);
13175 ipoptions:
13176 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13177 		goto slow_done;
13178 	}
13179 
13180 	UPDATE_IB_PKT_COUNT(ire);
13181 	ire->ire_last_used_time = lbolt;
13182 
13183 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13184 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13185 fragmented:
13186 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13187 			if (mctl_present)
13188 				freeb(first_mp);
13189 			goto slow_done;
13190 		}
13191 		/*
13192 		 * Make sure that first_mp points back to mp as
13193 		 * the mp we came in with could have changed in
13194 		 * ip_rput_fragment().
13195 		 */
13196 		ASSERT(!mctl_present);
13197 		ipha = (ipha_t *)mp->b_rptr;
13198 		first_mp = mp;
13199 	}
13200 
13201 	/* Now we have a complete datagram, destined for this machine. */
13202 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13203 
13204 	len = mp->b_wptr - mp->b_rptr;
13205 	/* Pull up a minimal TCP header, if necessary. */
13206 	if (len < (u1 + 20)) {
13207 tcppullup:
13208 		if (!pullupmsg(mp, u1 + 20)) {
13209 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13210 			goto error;
13211 		}
13212 		ipha = (ipha_t *)mp->b_rptr;
13213 		len = mp->b_wptr - mp->b_rptr;
13214 	}
13215 
13216 	/*
13217 	 * Extract the offset field from the TCP header.  As usual, we
13218 	 * try to help the compiler more than the reader.
13219 	 */
13220 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13221 	if (offset != 5) {
13222 tcpoptions:
13223 		if (offset < 5) {
13224 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13225 			goto error;
13226 		}
13227 		/*
13228 		 * There must be TCP options.
13229 		 * Make sure we can grab them.
13230 		 */
13231 		offset <<= 2;
13232 		offset += u1;
13233 		if (len < offset) {
13234 			if (!pullupmsg(mp, offset)) {
13235 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13236 				goto error;
13237 			}
13238 			ipha = (ipha_t *)mp->b_rptr;
13239 			len = mp->b_wptr - rptr;
13240 		}
13241 	}
13242 
13243 	/* Get the total packet length in len, including headers. */
13244 	if (mp->b_cont)
13245 		len = msgdsize(mp);
13246 
13247 	/*
13248 	 * Check the TCP checksum by pulling together the pseudo-
13249 	 * header checksum, and passing it to ip_csum to be added in
13250 	 * with the TCP datagram.
13251 	 *
13252 	 * Since we are not using the hwcksum if available we must
13253 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13254 	 * If either of these fails along the way the mblk is freed.
13255 	 * If this logic ever changes and mblk is reused to say send
13256 	 * ICMP's back, then this flag may need to be cleared in
13257 	 * other places as well.
13258 	 */
13259 	DB_CKSUMFLAGS(mp) = 0;
13260 
13261 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13262 
13263 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13264 #ifdef	_BIG_ENDIAN
13265 	u1 += IPPROTO_TCP;
13266 #else
13267 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13268 #endif
13269 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13270 	/*
13271 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13272 	 */
13273 	IP_STAT(ipst, ip_in_sw_cksum);
13274 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13275 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13276 		goto error;
13277 	}
13278 
13279 	IP_STAT(ipst, ip_tcp_slow_path);
13280 	goto try_again;
13281 #undef  iphs
13282 #undef  rptr
13283 
13284 error:
13285 	freemsg(first_mp);
13286 slow_done:
13287 	return (NULL);
13288 }
13289 
13290 /* ARGSUSED */
13291 static void
13292 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13293     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13294 {
13295 	conn_t		*connp;
13296 	uint32_t	sum;
13297 	uint32_t	u1;
13298 	ssize_t		len;
13299 	sctp_hdr_t	*sctph;
13300 	zoneid_t	zoneid = ire->ire_zoneid;
13301 	uint32_t	pktsum;
13302 	uint32_t	calcsum;
13303 	uint32_t	ports;
13304 	in6_addr_t	map_src, map_dst;
13305 	ill_t		*ill = (ill_t *)q->q_ptr;
13306 	ip_stack_t	*ipst;
13307 	sctp_stack_t	*sctps;
13308 	boolean_t	sctp_csum_err = B_FALSE;
13309 
13310 	ASSERT(recv_ill != NULL);
13311 	ipst = recv_ill->ill_ipst;
13312 	sctps = ipst->ips_netstack->netstack_sctp;
13313 
13314 #define	rptr	((uchar_t *)ipha)
13315 
13316 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13317 	ASSERT(ill != NULL);
13318 
13319 	/* u1 is # words of IP options */
13320 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13321 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13322 
13323 	/* IP options present */
13324 	if (u1 > 0) {
13325 		goto ipoptions;
13326 	} else {
13327 		/* Check the IP header checksum.  */
13328 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13329 		    !mctl_present) {
13330 #define	uph	((uint16_t *)ipha)
13331 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13332 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13333 #undef	uph
13334 			/* finish doing IP checksum */
13335 			sum = (sum & 0xFFFF) + (sum >> 16);
13336 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13337 			/*
13338 			 * Don't verify header checksum if this packet
13339 			 * is coming back from AH/ESP as we already did it.
13340 			 */
13341 			if (sum != 0 && sum != 0xFFFF) {
13342 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13343 				goto error;
13344 			}
13345 		}
13346 		/*
13347 		 * Since there is no SCTP h/w cksum support yet, just
13348 		 * clear the flag.
13349 		 */
13350 		DB_CKSUMFLAGS(mp) = 0;
13351 	}
13352 
13353 	/*
13354 	 * Don't verify header checksum if this packet is coming
13355 	 * back from AH/ESP as we already did it.
13356 	 */
13357 	if (!mctl_present) {
13358 		UPDATE_IB_PKT_COUNT(ire);
13359 		ire->ire_last_used_time = lbolt;
13360 	}
13361 
13362 	/* packet part of fragmented IP packet? */
13363 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13364 	if (u1 & (IPH_MF | IPH_OFFSET))
13365 		goto fragmented;
13366 
13367 	/* u1 = IP header length (20 bytes) */
13368 	u1 = IP_SIMPLE_HDR_LENGTH;
13369 
13370 find_sctp_client:
13371 	/* Pullup if we don't have the sctp common header. */
13372 	len = MBLKL(mp);
13373 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13374 		if (mp->b_cont == NULL ||
13375 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13376 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13377 			goto error;
13378 		}
13379 		ipha = (ipha_t *)mp->b_rptr;
13380 		len = MBLKL(mp);
13381 	}
13382 
13383 	sctph = (sctp_hdr_t *)(rptr + u1);
13384 #ifdef	DEBUG
13385 	if (!skip_sctp_cksum) {
13386 #endif
13387 		pktsum = sctph->sh_chksum;
13388 		sctph->sh_chksum = 0;
13389 		calcsum = sctp_cksum(mp, u1);
13390 		sctph->sh_chksum = pktsum;
13391 		if (calcsum != pktsum)
13392 			sctp_csum_err = B_TRUE;
13393 #ifdef	DEBUG	/* skip_sctp_cksum */
13394 	}
13395 #endif
13396 	/* get the ports */
13397 	ports = *(uint32_t *)&sctph->sh_sport;
13398 
13399 	IRE_REFRELE(ire);
13400 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13401 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13402 	if (sctp_csum_err) {
13403 		/*
13404 		 * No potential sctp checksum errors go to the Sun
13405 		 * sctp stack however they might be Adler-32 summed
13406 		 * packets a userland stack bound to a raw IP socket
13407 		 * could reasonably use. Note though that Adler-32 is
13408 		 * a long deprecated algorithm and customer sctp
13409 		 * networks should eventually migrate to CRC-32 at
13410 		 * which time this facility should be removed.
13411 		 */
13412 		flags |= IP_FF_SCTP_CSUM_ERR;
13413 		goto no_conn;
13414 	}
13415 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13416 	    sctps)) == NULL) {
13417 		/* Check for raw socket or OOTB handling */
13418 		goto no_conn;
13419 	}
13420 
13421 	/* Found a client; up it goes */
13422 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13423 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13424 	return;
13425 
13426 no_conn:
13427 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13428 	    ports, mctl_present, flags, B_TRUE, zoneid);
13429 	return;
13430 
13431 ipoptions:
13432 	DB_CKSUMFLAGS(mp) = 0;
13433 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13434 		goto slow_done;
13435 
13436 	UPDATE_IB_PKT_COUNT(ire);
13437 	ire->ire_last_used_time = lbolt;
13438 
13439 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13440 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13441 fragmented:
13442 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13443 			goto slow_done;
13444 		/*
13445 		 * Make sure that first_mp points back to mp as
13446 		 * the mp we came in with could have changed in
13447 		 * ip_rput_fragment().
13448 		 */
13449 		ASSERT(!mctl_present);
13450 		ipha = (ipha_t *)mp->b_rptr;
13451 		first_mp = mp;
13452 	}
13453 
13454 	/* Now we have a complete datagram, destined for this machine. */
13455 	u1 = IPH_HDR_LENGTH(ipha);
13456 	goto find_sctp_client;
13457 #undef  iphs
13458 #undef  rptr
13459 
13460 error:
13461 	freemsg(first_mp);
13462 slow_done:
13463 	IRE_REFRELE(ire);
13464 }
13465 
13466 #define	VER_BITS	0xF0
13467 #define	VERSION_6	0x60
13468 
13469 static boolean_t
13470 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13471     ipaddr_t *dstp, ip_stack_t *ipst)
13472 {
13473 	uint_t	opt_len;
13474 	ipha_t *ipha;
13475 	ssize_t len;
13476 	uint_t	pkt_len;
13477 
13478 	ASSERT(ill != NULL);
13479 	IP_STAT(ipst, ip_ipoptions);
13480 	ipha = *iphapp;
13481 
13482 #define	rptr    ((uchar_t *)ipha)
13483 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13484 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13485 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13486 		freemsg(mp);
13487 		return (B_FALSE);
13488 	}
13489 
13490 	/* multiple mblk or too short */
13491 	pkt_len = ntohs(ipha->ipha_length);
13492 
13493 	/* Get the number of words of IP options in the IP header. */
13494 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13495 	if (opt_len) {
13496 		/* IP Options present!  Validate and process. */
13497 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13498 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13499 			goto done;
13500 		}
13501 		/*
13502 		 * Recompute complete header length and make sure we
13503 		 * have access to all of it.
13504 		 */
13505 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13506 		if (len > (mp->b_wptr - rptr)) {
13507 			if (len > pkt_len) {
13508 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13509 				goto done;
13510 			}
13511 			if (!pullupmsg(mp, len)) {
13512 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13513 				goto done;
13514 			}
13515 			ipha = (ipha_t *)mp->b_rptr;
13516 		}
13517 		/*
13518 		 * Go off to ip_rput_options which returns the next hop
13519 		 * destination address, which may have been affected
13520 		 * by source routing.
13521 		 */
13522 		IP_STAT(ipst, ip_opt);
13523 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13524 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13525 			return (B_FALSE);
13526 		}
13527 	}
13528 	*iphapp = ipha;
13529 	return (B_TRUE);
13530 done:
13531 	/* clear b_prev - used by ip_mroute_decap */
13532 	mp->b_prev = NULL;
13533 	freemsg(mp);
13534 	return (B_FALSE);
13535 #undef  rptr
13536 }
13537 
13538 /*
13539  * Deal with the fact that there is no ire for the destination.
13540  */
13541 static ire_t *
13542 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13543 {
13544 	ipha_t	*ipha;
13545 	ill_t	*ill;
13546 	ire_t	*ire;
13547 	ip_stack_t *ipst;
13548 	enum	ire_forward_action ret_action;
13549 
13550 	ipha = (ipha_t *)mp->b_rptr;
13551 	ill = (ill_t *)q->q_ptr;
13552 
13553 	ASSERT(ill != NULL);
13554 	ipst = ill->ill_ipst;
13555 
13556 	/*
13557 	 * No IRE for this destination, so it can't be for us.
13558 	 * Unless we are forwarding, drop the packet.
13559 	 * We have to let source routed packets through
13560 	 * since we don't yet know if they are 'ping -l'
13561 	 * packets i.e. if they will go out over the
13562 	 * same interface as they came in on.
13563 	 */
13564 	if (ll_multicast) {
13565 		freemsg(mp);
13566 		return (NULL);
13567 	}
13568 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13569 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13570 		freemsg(mp);
13571 		return (NULL);
13572 	}
13573 
13574 	/*
13575 	 * Mark this packet as having originated externally.
13576 	 *
13577 	 * For non-forwarding code path, ire_send later double
13578 	 * checks this interface to see if it is still exists
13579 	 * post-ARP resolution.
13580 	 *
13581 	 * Also, IPQOS uses this to differentiate between
13582 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13583 	 * QOS packet processing in ip_wput_attach_llhdr().
13584 	 * The QoS module can mark the b_band for a fastpath message
13585 	 * or the dl_priority field in a unitdata_req header for
13586 	 * CoS marking. This info can only be found in
13587 	 * ip_wput_attach_llhdr().
13588 	 */
13589 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13590 	/*
13591 	 * Clear the indication that this may have a hardware checksum
13592 	 * as we are not using it
13593 	 */
13594 	DB_CKSUMFLAGS(mp) = 0;
13595 
13596 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13597 	    msg_getlabel(mp), ipst);
13598 
13599 	if (ire == NULL && ret_action == Forward_check_multirt) {
13600 		/* Let ip_newroute handle CGTP  */
13601 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13602 		return (NULL);
13603 	}
13604 
13605 	if (ire != NULL)
13606 		return (ire);
13607 
13608 	mp->b_prev = mp->b_next = 0;
13609 
13610 	if (ret_action == Forward_blackhole) {
13611 		freemsg(mp);
13612 		return (NULL);
13613 	}
13614 	/* send icmp unreachable */
13615 	q = WR(q);
13616 	/* Sent by forwarding path, and router is global zone */
13617 	if (ip_source_routed(ipha, ipst)) {
13618 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13619 		    GLOBAL_ZONEID, ipst);
13620 	} else {
13621 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13622 		    ipst);
13623 	}
13624 
13625 	return (NULL);
13626 
13627 }
13628 
13629 /*
13630  * check ip header length and align it.
13631  */
13632 static boolean_t
13633 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13634 {
13635 	ssize_t len;
13636 	ill_t *ill;
13637 	ipha_t	*ipha;
13638 
13639 	len = MBLKL(mp);
13640 
13641 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13642 		ill = (ill_t *)q->q_ptr;
13643 
13644 		if (!OK_32PTR(mp->b_rptr))
13645 			IP_STAT(ipst, ip_notaligned1);
13646 		else
13647 			IP_STAT(ipst, ip_notaligned2);
13648 		/* Guard against bogus device drivers */
13649 		if (len < 0) {
13650 			/* clear b_prev - used by ip_mroute_decap */
13651 			mp->b_prev = NULL;
13652 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13653 			freemsg(mp);
13654 			return (B_FALSE);
13655 		}
13656 
13657 		if (ip_rput_pullups++ == 0) {
13658 			ipha = (ipha_t *)mp->b_rptr;
13659 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13660 			    "ip_check_and_align_header: %s forced us to "
13661 			    " pullup pkt, hdr len %ld, hdr addr %p",
13662 			    ill->ill_name, len, (void *)ipha);
13663 		}
13664 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13665 			/* clear b_prev - used by ip_mroute_decap */
13666 			mp->b_prev = NULL;
13667 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13668 			freemsg(mp);
13669 			return (B_FALSE);
13670 		}
13671 	}
13672 	return (B_TRUE);
13673 }
13674 
13675 /*
13676  * Handle the situation where a packet came in on `ill' but matched an IRE
13677  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13678  * for interface statistics.
13679  */
13680 ire_t *
13681 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13682 {
13683 	ire_t		*new_ire;
13684 	ill_t		*ire_ill;
13685 	uint_t		ifindex;
13686 	ip_stack_t	*ipst = ill->ill_ipst;
13687 	boolean_t	strict_check = B_FALSE;
13688 
13689 	/*
13690 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13691 	 * issue (e.g. packet received on an underlying interface matched an
13692 	 * IRE_LOCAL on its associated group interface).
13693 	 */
13694 	if (ire->ire_rfq != NULL &&
13695 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13696 		return (ire);
13697 	}
13698 
13699 	/*
13700 	 * Do another ire lookup here, using the ingress ill, to see if the
13701 	 * interface is in a usesrc group.
13702 	 * As long as the ills belong to the same group, we don't consider
13703 	 * them to be arriving on the wrong interface. Thus, if the switch
13704 	 * is doing inbound load spreading, we won't drop packets when the
13705 	 * ip*_strict_dst_multihoming switch is on.
13706 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13707 	 * where the local address may not be unique. In this case we were
13708 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13709 	 * actually returned. The new lookup, which is more specific, should
13710 	 * only find the IRE_LOCAL associated with the ingress ill if one
13711 	 * exists.
13712 	 */
13713 
13714 	if (ire->ire_ipversion == IPV4_VERSION) {
13715 		if (ipst->ips_ip_strict_dst_multihoming)
13716 			strict_check = B_TRUE;
13717 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13718 		    ill->ill_ipif, ALL_ZONES, NULL,
13719 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13720 	} else {
13721 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13722 		if (ipst->ips_ipv6_strict_dst_multihoming)
13723 			strict_check = B_TRUE;
13724 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13725 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13726 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13727 	}
13728 	/*
13729 	 * If the same ire that was returned in ip_input() is found then this
13730 	 * is an indication that usesrc groups are in use. The packet
13731 	 * arrived on a different ill in the group than the one associated with
13732 	 * the destination address.  If a different ire was found then the same
13733 	 * IP address must be hosted on multiple ills. This is possible with
13734 	 * unnumbered point2point interfaces. We switch to use this new ire in
13735 	 * order to have accurate interface statistics.
13736 	 */
13737 	if (new_ire != NULL) {
13738 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13739 			ire_refrele(ire);
13740 			ire = new_ire;
13741 		} else {
13742 			ire_refrele(new_ire);
13743 		}
13744 		return (ire);
13745 	} else if ((ire->ire_rfq == NULL) &&
13746 	    (ire->ire_ipversion == IPV4_VERSION)) {
13747 		/*
13748 		 * The best match could have been the original ire which
13749 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13750 		 * the strict multihoming checks are irrelevant as we consider
13751 		 * local addresses hosted on lo0 to be interface agnostic. We
13752 		 * only expect a null ire_rfq on IREs which are associated with
13753 		 * lo0 hence we can return now.
13754 		 */
13755 		return (ire);
13756 	}
13757 
13758 	/*
13759 	 * Chase pointers once and store locally.
13760 	 */
13761 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13762 	    (ill_t *)(ire->ire_rfq->q_ptr);
13763 	ifindex = ill->ill_usesrc_ifindex;
13764 
13765 	/*
13766 	 * Check if it's a legal address on the 'usesrc' interface.
13767 	 */
13768 	if ((ifindex != 0) && (ire_ill != NULL) &&
13769 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13770 		return (ire);
13771 	}
13772 
13773 	/*
13774 	 * If the ip*_strict_dst_multihoming switch is on then we can
13775 	 * only accept this packet if the interface is marked as routing.
13776 	 */
13777 	if (!(strict_check))
13778 		return (ire);
13779 
13780 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13781 	    ILLF_ROUTER) != 0) {
13782 		return (ire);
13783 	}
13784 
13785 	ire_refrele(ire);
13786 	return (NULL);
13787 }
13788 
13789 /*
13790  *
13791  * This is the fast forward path. If we are here, we dont need to
13792  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13793  * needed to find the nexthop in this case is much simpler
13794  */
13795 ire_t *
13796 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13797 {
13798 	ipha_t	*ipha;
13799 	ire_t	*src_ire;
13800 	ill_t	*stq_ill;
13801 	uint_t	hlen;
13802 	uint_t	pkt_len;
13803 	uint32_t sum;
13804 	queue_t	*dev_q;
13805 	ip_stack_t *ipst = ill->ill_ipst;
13806 	mblk_t *fpmp;
13807 	enum	ire_forward_action ret_action;
13808 
13809 	ipha = (ipha_t *)mp->b_rptr;
13810 
13811 	if (ire != NULL &&
13812 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13813 	    ire->ire_zoneid != ALL_ZONES) {
13814 		/*
13815 		 * Should only use IREs that are visible to the global
13816 		 * zone for forwarding.
13817 		 */
13818 		ire_refrele(ire);
13819 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13820 		/*
13821 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13822 		 * transient cases. In such case, just drop the packet
13823 		 */
13824 		if (ire != NULL && ire->ire_type != IRE_CACHE)
13825 			goto indiscard;
13826 	}
13827 
13828 	/*
13829 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13830 	 * The loopback address check for both src and dst has already
13831 	 * been checked in ip_input
13832 	 */
13833 
13834 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13835 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13836 		goto drop;
13837 	}
13838 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13839 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13840 
13841 	if (src_ire != NULL) {
13842 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13843 		ire_refrele(src_ire);
13844 		goto drop;
13845 	}
13846 
13847 	/* No ire cache of nexthop. So first create one  */
13848 	if (ire == NULL) {
13849 
13850 		ire = ire_forward_simple(dst, &ret_action, ipst);
13851 
13852 		/*
13853 		 * We only come to ip_fast_forward if ip_cgtp_filter
13854 		 * is not set. So ire_forward() should not return with
13855 		 * Forward_check_multirt as the next action.
13856 		 */
13857 		ASSERT(ret_action != Forward_check_multirt);
13858 		if (ire == NULL) {
13859 			/* An attempt was made to forward the packet */
13860 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13861 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13862 			mp->b_prev = mp->b_next = 0;
13863 			/* send icmp unreachable */
13864 			/* Sent by forwarding path, and router is global zone */
13865 			if (ret_action == Forward_ret_icmp_err) {
13866 				if (ip_source_routed(ipha, ipst)) {
13867 					icmp_unreachable(ill->ill_wq, mp,
13868 					    ICMP_SOURCE_ROUTE_FAILED,
13869 					    GLOBAL_ZONEID, ipst);
13870 				} else {
13871 					icmp_unreachable(ill->ill_wq, mp,
13872 					    ICMP_HOST_UNREACHABLE,
13873 					    GLOBAL_ZONEID, ipst);
13874 				}
13875 			} else {
13876 				freemsg(mp);
13877 			}
13878 			return (NULL);
13879 		}
13880 	}
13881 
13882 	/*
13883 	 * Forwarding fastpath exception case:
13884 	 * If any of the following are true, we take the slowpath:
13885 	 *	o forwarding is not enabled
13886 	 *	o incoming and outgoing interface are the same, or in the same
13887 	 *	  IPMP group.
13888 	 *	o corresponding ire is in incomplete state
13889 	 *	o packet needs fragmentation
13890 	 *	o ARP cache is not resolved
13891 	 *
13892 	 * The codeflow from here on is thus:
13893 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13894 	 */
13895 	pkt_len = ntohs(ipha->ipha_length);
13896 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13897 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13898 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13899 	    (ire->ire_nce == NULL) ||
13900 	    (pkt_len > ire->ire_max_frag) ||
13901 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13902 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13903 	    ipha->ipha_ttl <= 1) {
13904 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13905 		    ipha, ill, B_FALSE, B_TRUE);
13906 		return (ire);
13907 	}
13908 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13909 
13910 	DTRACE_PROBE4(ip4__forwarding__start,
13911 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13912 
13913 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13914 	    ipst->ips_ipv4firewall_forwarding,
13915 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13916 
13917 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13918 
13919 	if (mp == NULL)
13920 		goto drop;
13921 
13922 	mp->b_datap->db_struioun.cksum.flags = 0;
13923 	/* Adjust the checksum to reflect the ttl decrement. */
13924 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13925 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13926 	ipha->ipha_ttl--;
13927 
13928 	/*
13929 	 * Write the link layer header.  We can do this safely here,
13930 	 * because we have already tested to make sure that the IP
13931 	 * policy is not set, and that we have a fast path destination
13932 	 * header.
13933 	 */
13934 	mp->b_rptr -= hlen;
13935 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13936 
13937 	UPDATE_IB_PKT_COUNT(ire);
13938 	ire->ire_last_used_time = lbolt;
13939 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13940 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13941 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13942 
13943 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13944 		dev_q = ire->ire_stq->q_next;
13945 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13946 			goto indiscard;
13947 	}
13948 
13949 	DTRACE_PROBE4(ip4__physical__out__start,
13950 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13951 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13952 	    ipst->ips_ipv4firewall_physical_out,
13953 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13954 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13955 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13956 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13957 	    ip6_t *, NULL, int, 0);
13958 
13959 	if (mp != NULL) {
13960 		if (ipst->ips_ip4_observe.he_interested) {
13961 			zoneid_t szone;
13962 
13963 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13964 			    ipst, ALL_ZONES);
13965 			/*
13966 			 * The IP observability hook expects b_rptr to be
13967 			 * where the IP header starts, so advance past the
13968 			 * link layer header.
13969 			 */
13970 			mp->b_rptr += hlen;
13971 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13972 			    ALL_ZONES, ill, ipst);
13973 			mp->b_rptr -= hlen;
13974 		}
13975 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
13976 	}
13977 	return (ire);
13978 
13979 indiscard:
13980 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13981 drop:
13982 	if (mp != NULL)
13983 		freemsg(mp);
13984 	return (ire);
13985 
13986 }
13987 
13988 /*
13989  * This function is called in the forwarding slowpath, when
13990  * either the ire lacks the link-layer address, or the packet needs
13991  * further processing(eg. fragmentation), before transmission.
13992  */
13993 
13994 static void
13995 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13996     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
13997 {
13998 	queue_t		*dev_q;
13999 	ire_t		*src_ire;
14000 	ip_stack_t	*ipst = ill->ill_ipst;
14001 	boolean_t	same_illgrp = B_FALSE;
14002 
14003 	ASSERT(ire->ire_stq != NULL);
14004 
14005 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14006 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14007 
14008 	/*
14009 	 * If the caller of this function is ip_fast_forward() skip the
14010 	 * next three checks as it does not apply.
14011 	 */
14012 	if (from_ip_fast_forward)
14013 		goto skip;
14014 
14015 	if (ll_multicast != 0) {
14016 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14017 		goto drop_pkt;
14018 	}
14019 
14020 	/*
14021 	 * check if ipha_src is a broadcast address. Note that this
14022 	 * check is redundant when we get here from ip_fast_forward()
14023 	 * which has already done this check. However, since we can
14024 	 * also get here from ip_rput_process_broadcast() or, for
14025 	 * for the slow path through ip_fast_forward(), we perform
14026 	 * the check again for code-reusability
14027 	 */
14028 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14029 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14030 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14031 		if (src_ire != NULL)
14032 			ire_refrele(src_ire);
14033 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14034 		ip2dbg(("ip_rput_process_forward: Received packet with"
14035 		    " bad src/dst address on %s\n", ill->ill_name));
14036 		goto drop_pkt;
14037 	}
14038 
14039 	/*
14040 	 * Check if we want to forward this one at this time.
14041 	 * We allow source routed packets on a host provided that
14042 	 * they go out the same ill or illgrp as they came in on.
14043 	 *
14044 	 * XXX To be quicker, we may wish to not chase pointers to
14045 	 * get the ILLF_ROUTER flag and instead store the
14046 	 * forwarding policy in the ire.  An unfortunate
14047 	 * side-effect of that would be requiring an ire flush
14048 	 * whenever the ILLF_ROUTER flag changes.
14049 	 */
14050 skip:
14051 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14052 
14053 	if (((ill->ill_flags &
14054 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14055 	    !(ip_source_routed(ipha, ipst) &&
14056 	    (ire->ire_rfq == q || same_illgrp))) {
14057 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14058 		if (ip_source_routed(ipha, ipst)) {
14059 			q = WR(q);
14060 			/*
14061 			 * Clear the indication that this may have
14062 			 * hardware checksum as we are not using it.
14063 			 */
14064 			DB_CKSUMFLAGS(mp) = 0;
14065 			/* Sent by forwarding path, and router is global zone */
14066 			icmp_unreachable(q, mp,
14067 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14068 			return;
14069 		}
14070 		goto drop_pkt;
14071 	}
14072 
14073 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14074 
14075 	/* Packet is being forwarded. Turning off hwcksum flag. */
14076 	DB_CKSUMFLAGS(mp) = 0;
14077 	if (ipst->ips_ip_g_send_redirects) {
14078 		/*
14079 		 * Check whether the incoming interface and outgoing
14080 		 * interface is part of the same group. If so,
14081 		 * send redirects.
14082 		 *
14083 		 * Check the source address to see if it originated
14084 		 * on the same logical subnet it is going back out on.
14085 		 * If so, we should be able to send it a redirect.
14086 		 * Avoid sending a redirect if the destination
14087 		 * is directly connected (i.e., ipha_dst is the same
14088 		 * as ire_gateway_addr or the ire_addr of the
14089 		 * nexthop IRE_CACHE ), or if the packet was source
14090 		 * routed out this interface.
14091 		 */
14092 		ipaddr_t src, nhop;
14093 		mblk_t	*mp1;
14094 		ire_t	*nhop_ire = NULL;
14095 
14096 		/*
14097 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14098 		 * If so, send redirects.
14099 		 */
14100 		if ((ire->ire_rfq == q || same_illgrp) &&
14101 		    !ip_source_routed(ipha, ipst)) {
14102 
14103 			nhop = (ire->ire_gateway_addr != 0 ?
14104 			    ire->ire_gateway_addr : ire->ire_addr);
14105 
14106 			if (ipha->ipha_dst == nhop) {
14107 				/*
14108 				 * We avoid sending a redirect if the
14109 				 * destination is directly connected
14110 				 * because it is possible that multiple
14111 				 * IP subnets may have been configured on
14112 				 * the link, and the source may not
14113 				 * be on the same subnet as ip destination,
14114 				 * even though they are on the same
14115 				 * physical link.
14116 				 */
14117 				goto sendit;
14118 			}
14119 
14120 			src = ipha->ipha_src;
14121 
14122 			/*
14123 			 * We look up the interface ire for the nexthop,
14124 			 * to see if ipha_src is in the same subnet
14125 			 * as the nexthop.
14126 			 *
14127 			 * Note that, if, in the future, IRE_CACHE entries
14128 			 * are obsoleted,  this lookup will not be needed,
14129 			 * as the ire passed to this function will be the
14130 			 * same as the nhop_ire computed below.
14131 			 */
14132 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14133 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14134 			    0, NULL, MATCH_IRE_TYPE, ipst);
14135 
14136 			if (nhop_ire != NULL) {
14137 				if ((src & nhop_ire->ire_mask) ==
14138 				    (nhop & nhop_ire->ire_mask)) {
14139 					/*
14140 					 * The source is directly connected.
14141 					 * Just copy the ip header (which is
14142 					 * in the first mblk)
14143 					 */
14144 					mp1 = copyb(mp);
14145 					if (mp1 != NULL) {
14146 						icmp_send_redirect(WR(q), mp1,
14147 						    nhop, ipst);
14148 					}
14149 				}
14150 				ire_refrele(nhop_ire);
14151 			}
14152 		}
14153 	}
14154 sendit:
14155 	dev_q = ire->ire_stq->q_next;
14156 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14157 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14158 		freemsg(mp);
14159 		return;
14160 	}
14161 
14162 	ip_rput_forward(ire, ipha, mp, ill);
14163 	return;
14164 
14165 drop_pkt:
14166 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14167 	freemsg(mp);
14168 }
14169 
14170 ire_t *
14171 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14172     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14173 {
14174 	queue_t		*q;
14175 	uint16_t	hcksumflags;
14176 	ip_stack_t	*ipst = ill->ill_ipst;
14177 
14178 	q = *qp;
14179 
14180 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14181 
14182 	/*
14183 	 * Clear the indication that this may have hardware
14184 	 * checksum as we are not using it for forwarding.
14185 	 */
14186 	hcksumflags = DB_CKSUMFLAGS(mp);
14187 	DB_CKSUMFLAGS(mp) = 0;
14188 
14189 	/*
14190 	 * Directed broadcast forwarding: if the packet came in over a
14191 	 * different interface then it is routed out over we can forward it.
14192 	 */
14193 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14194 		ire_refrele(ire);
14195 		freemsg(mp);
14196 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14197 		return (NULL);
14198 	}
14199 	/*
14200 	 * For multicast we have set dst to be INADDR_BROADCAST
14201 	 * for delivering to all STREAMS.
14202 	 */
14203 	if (!CLASSD(ipha->ipha_dst)) {
14204 		ire_t *new_ire;
14205 		ipif_t *ipif;
14206 
14207 		ipif = ipif_get_next_ipif(NULL, ill);
14208 		if (ipif == NULL) {
14209 discard:		ire_refrele(ire);
14210 			freemsg(mp);
14211 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14212 			return (NULL);
14213 		}
14214 		new_ire = ire_ctable_lookup(dst, 0, 0,
14215 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14216 		ipif_refrele(ipif);
14217 
14218 		if (new_ire != NULL) {
14219 			/*
14220 			 * If the matching IRE_BROADCAST is part of an IPMP
14221 			 * group, then drop the packet unless our ill has been
14222 			 * nominated to receive for the group.
14223 			 */
14224 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14225 			    new_ire->ire_rfq != q) {
14226 				ire_refrele(new_ire);
14227 				goto discard;
14228 			}
14229 
14230 			/*
14231 			 * In the special case of multirouted broadcast
14232 			 * packets, we unconditionally need to "gateway"
14233 			 * them to the appropriate interface here.
14234 			 * In the normal case, this cannot happen, because
14235 			 * there is no broadcast IRE tagged with the
14236 			 * RTF_MULTIRT flag.
14237 			 */
14238 			if (new_ire->ire_flags & RTF_MULTIRT) {
14239 				ire_refrele(new_ire);
14240 				if (ire->ire_rfq != NULL) {
14241 					q = ire->ire_rfq;
14242 					*qp = q;
14243 				}
14244 			} else {
14245 				ire_refrele(ire);
14246 				ire = new_ire;
14247 			}
14248 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14249 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14250 				/*
14251 				 * Free the message if
14252 				 * ip_g_forward_directed_bcast is turned
14253 				 * off for non-local broadcast.
14254 				 */
14255 				ire_refrele(ire);
14256 				freemsg(mp);
14257 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14258 				return (NULL);
14259 			}
14260 		} else {
14261 			/*
14262 			 * This CGTP packet successfully passed the
14263 			 * CGTP filter, but the related CGTP
14264 			 * broadcast IRE has not been found,
14265 			 * meaning that the redundant ipif is
14266 			 * probably down. However, if we discarded
14267 			 * this packet, its duplicate would be
14268 			 * filtered out by the CGTP filter so none
14269 			 * of them would get through. So we keep
14270 			 * going with this one.
14271 			 */
14272 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14273 			if (ire->ire_rfq != NULL) {
14274 				q = ire->ire_rfq;
14275 				*qp = q;
14276 			}
14277 		}
14278 	}
14279 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14280 		/*
14281 		 * Verify that there are not more then one
14282 		 * IRE_BROADCAST with this broadcast address which
14283 		 * has ire_stq set.
14284 		 * TODO: simplify, loop over all IRE's
14285 		 */
14286 		ire_t	*ire1;
14287 		int	num_stq = 0;
14288 		mblk_t	*mp1;
14289 
14290 		/* Find the first one with ire_stq set */
14291 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14292 		for (ire1 = ire; ire1 &&
14293 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14294 		    ire1 = ire1->ire_next)
14295 			;
14296 		if (ire1) {
14297 			ire_refrele(ire);
14298 			ire = ire1;
14299 			IRE_REFHOLD(ire);
14300 		}
14301 
14302 		/* Check if there are additional ones with stq set */
14303 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14304 			if (ire->ire_addr != ire1->ire_addr)
14305 				break;
14306 			if (ire1->ire_stq) {
14307 				num_stq++;
14308 				break;
14309 			}
14310 		}
14311 		rw_exit(&ire->ire_bucket->irb_lock);
14312 		if (num_stq == 1 && ire->ire_stq != NULL) {
14313 			ip1dbg(("ip_rput_process_broadcast: directed "
14314 			    "broadcast to 0x%x\n",
14315 			    ntohl(ire->ire_addr)));
14316 			mp1 = copymsg(mp);
14317 			if (mp1) {
14318 				switch (ipha->ipha_protocol) {
14319 				case IPPROTO_UDP:
14320 					ip_udp_input(q, mp1, ipha, ire, ill);
14321 					break;
14322 				default:
14323 					ip_proto_input(q, mp1, ipha, ire, ill,
14324 					    0);
14325 					break;
14326 				}
14327 			}
14328 			/*
14329 			 * Adjust ttl to 2 (1+1 - the forward engine
14330 			 * will decrement it by one.
14331 			 */
14332 			if (ip_csum_hdr(ipha)) {
14333 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14334 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14335 				freemsg(mp);
14336 				ire_refrele(ire);
14337 				return (NULL);
14338 			}
14339 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14340 			ipha->ipha_hdr_checksum = 0;
14341 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14342 			ip_rput_process_forward(q, mp, ire, ipha,
14343 			    ill, ll_multicast, B_FALSE);
14344 			ire_refrele(ire);
14345 			return (NULL);
14346 		}
14347 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14348 		    ntohl(ire->ire_addr)));
14349 	}
14350 
14351 	/* Restore any hardware checksum flags */
14352 	DB_CKSUMFLAGS(mp) = hcksumflags;
14353 	return (ire);
14354 }
14355 
14356 /* ARGSUSED */
14357 static boolean_t
14358 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14359     int *ll_multicast, ipaddr_t *dstp)
14360 {
14361 	ip_stack_t	*ipst = ill->ill_ipst;
14362 
14363 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14364 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14365 	    ntohs(ipha->ipha_length));
14366 
14367 	/*
14368 	 * So that we don't end up with dups, only one ill in an IPMP group is
14369 	 * nominated to receive multicast traffic.
14370 	 */
14371 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14372 		goto drop_pkt;
14373 
14374 	/*
14375 	 * Forward packets only if we have joined the allmulti
14376 	 * group on this interface.
14377 	 */
14378 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14379 		int retval;
14380 
14381 		/*
14382 		 * Clear the indication that this may have hardware
14383 		 * checksum as we are not using it.
14384 		 */
14385 		DB_CKSUMFLAGS(mp) = 0;
14386 		retval = ip_mforward(ill, ipha, mp);
14387 		/* ip_mforward updates mib variables if needed */
14388 		/* clear b_prev - used by ip_mroute_decap */
14389 		mp->b_prev = NULL;
14390 
14391 		switch (retval) {
14392 		case 0:
14393 			/*
14394 			 * pkt is okay and arrived on phyint.
14395 			 *
14396 			 * If we are running as a multicast router
14397 			 * we need to see all IGMP and/or PIM packets.
14398 			 */
14399 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14400 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14401 				goto done;
14402 			}
14403 			break;
14404 		case -1:
14405 			/* pkt is mal-formed, toss it */
14406 			goto drop_pkt;
14407 		case 1:
14408 			/* pkt is okay and arrived on a tunnel */
14409 			/*
14410 			 * If we are running a multicast router
14411 			 *  we need to see all igmp packets.
14412 			 */
14413 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14414 				*dstp = INADDR_BROADCAST;
14415 				*ll_multicast = 1;
14416 				return (B_FALSE);
14417 			}
14418 
14419 			goto drop_pkt;
14420 		}
14421 	}
14422 
14423 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14424 		/*
14425 		 * This might just be caused by the fact that
14426 		 * multiple IP Multicast addresses map to the same
14427 		 * link layer multicast - no need to increment counter!
14428 		 */
14429 		freemsg(mp);
14430 		return (B_TRUE);
14431 	}
14432 done:
14433 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14434 	/*
14435 	 * This assumes the we deliver to all streams for multicast
14436 	 * and broadcast packets.
14437 	 */
14438 	*dstp = INADDR_BROADCAST;
14439 	*ll_multicast = 1;
14440 	return (B_FALSE);
14441 drop_pkt:
14442 	ip2dbg(("ip_rput: drop pkt\n"));
14443 	freemsg(mp);
14444 	return (B_TRUE);
14445 }
14446 
14447 /*
14448  * This function is used to both return an indication of whether or not
14449  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14450  * and in doing so, determine whether or not it is broadcast vs multicast.
14451  * For it to be a broadcast packet, we must have the appropriate mblk_t
14452  * hanging off the ill_t.  If this is either not present or doesn't match
14453  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14454  * to be multicast.  Thus NICs that have no broadcast address (or no
14455  * capability for one, such as point to point links) cannot return as
14456  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14457  * the return values simplifies the current use of the return value of this
14458  * function, which is to pass through the multicast/broadcast characteristic
14459  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14460  * changing the return value to some other symbol demands the appropriate
14461  * "translation" when hpe_flags is set prior to calling hook_run() for
14462  * packet events.
14463  */
14464 int
14465 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14466 {
14467 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14468 	mblk_t *bmp;
14469 
14470 	if (ind->dl_group_address) {
14471 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14472 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14473 		    MBLKL(mb) &&
14474 		    (bmp = ill->ill_bcast_mp) != NULL) {
14475 			dl_unitdata_req_t *dlur;
14476 			uint8_t *bphys_addr;
14477 
14478 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14479 			if (ill->ill_sap_length < 0)
14480 				bphys_addr = (uchar_t *)dlur +
14481 				    dlur->dl_dest_addr_offset;
14482 			else
14483 				bphys_addr = (uchar_t *)dlur +
14484 				    dlur->dl_dest_addr_offset +
14485 				    ill->ill_sap_length;
14486 
14487 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14488 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14489 				return (HPE_BROADCAST);
14490 			}
14491 			return (HPE_MULTICAST);
14492 		}
14493 		return (HPE_MULTICAST);
14494 	}
14495 	return (0);
14496 }
14497 
14498 static boolean_t
14499 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14500     int *ll_multicast, mblk_t **mpp)
14501 {
14502 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14503 	boolean_t must_copy = B_FALSE;
14504 	struct iocblk   *iocp;
14505 	ipha_t		*ipha;
14506 	ip_stack_t	*ipst = ill->ill_ipst;
14507 
14508 #define	rptr    ((uchar_t *)ipha)
14509 
14510 	first_mp = *first_mpp;
14511 	mp = *mpp;
14512 
14513 	ASSERT(first_mp == mp);
14514 
14515 	/*
14516 	 * if db_ref > 1 then copymsg and free original. Packet may be
14517 	 * changed and do not want other entity who has a reference to this
14518 	 * message to trip over the changes. This is a blind change because
14519 	 * trying to catch all places that might change packet is too
14520 	 * difficult (since it may be a module above this one)
14521 	 *
14522 	 * This corresponds to the non-fast path case. We walk down the full
14523 	 * chain in this case, and check the db_ref count of all the dblks,
14524 	 * and do a copymsg if required. It is possible that the db_ref counts
14525 	 * of the data blocks in the mblk chain can be different.
14526 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14527 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14528 	 * 'snoop' is running.
14529 	 */
14530 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14531 		if (mp1->b_datap->db_ref > 1) {
14532 			must_copy = B_TRUE;
14533 			break;
14534 		}
14535 	}
14536 
14537 	if (must_copy) {
14538 		mp1 = copymsg(mp);
14539 		if (mp1 == NULL) {
14540 			for (mp1 = mp; mp1 != NULL;
14541 			    mp1 = mp1->b_cont) {
14542 				mp1->b_next = NULL;
14543 				mp1->b_prev = NULL;
14544 			}
14545 			freemsg(mp);
14546 			if (ill != NULL) {
14547 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14548 			} else {
14549 				BUMP_MIB(&ipst->ips_ip_mib,
14550 				    ipIfStatsInDiscards);
14551 			}
14552 			return (B_TRUE);
14553 		}
14554 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14555 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14556 			/* Copy b_prev - used by ip_mroute_decap */
14557 			to_mp->b_prev = from_mp->b_prev;
14558 			from_mp->b_prev = NULL;
14559 		}
14560 		*first_mpp = first_mp = mp1;
14561 		freemsg(mp);
14562 		mp = mp1;
14563 		*mpp = mp1;
14564 	}
14565 
14566 	ipha = (ipha_t *)mp->b_rptr;
14567 
14568 	/*
14569 	 * previous code has a case for M_DATA.
14570 	 * We want to check how that happens.
14571 	 */
14572 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14573 	switch (first_mp->b_datap->db_type) {
14574 	case M_PROTO:
14575 	case M_PCPROTO:
14576 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14577 		    DL_UNITDATA_IND) {
14578 			/* Go handle anything other than data elsewhere. */
14579 			ip_rput_dlpi(q, mp);
14580 			return (B_TRUE);
14581 		}
14582 
14583 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14584 		/* Ditch the DLPI header. */
14585 		mp1 = mp->b_cont;
14586 		ASSERT(first_mp == mp);
14587 		*first_mpp = mp1;
14588 		freeb(mp);
14589 		*mpp = mp1;
14590 		return (B_FALSE);
14591 	case M_IOCACK:
14592 		ip1dbg(("got iocack "));
14593 		iocp = (struct iocblk *)mp->b_rptr;
14594 		switch (iocp->ioc_cmd) {
14595 		case DL_IOC_HDR_INFO:
14596 			ill = (ill_t *)q->q_ptr;
14597 			ill_fastpath_ack(ill, mp);
14598 			return (B_TRUE);
14599 		default:
14600 			putnext(q, mp);
14601 			return (B_TRUE);
14602 		}
14603 		/* FALLTHRU */
14604 	case M_ERROR:
14605 	case M_HANGUP:
14606 		/*
14607 		 * Since this is on the ill stream we unconditionally
14608 		 * bump up the refcount
14609 		 */
14610 		ill_refhold(ill);
14611 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14612 		return (B_TRUE);
14613 	case M_CTL:
14614 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14615 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14616 		    IPHADA_M_CTL)) {
14617 			/*
14618 			 * It's an IPsec accelerated packet.
14619 			 * Make sure that the ill from which we received the
14620 			 * packet has enabled IPsec hardware acceleration.
14621 			 */
14622 			if (!(ill->ill_capabilities &
14623 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14624 				/* IPsec kstats: bean counter */
14625 				freemsg(mp);
14626 				return (B_TRUE);
14627 			}
14628 
14629 			/*
14630 			 * Make mp point to the mblk following the M_CTL,
14631 			 * then process according to type of mp.
14632 			 * After this processing, first_mp will point to
14633 			 * the data-attributes and mp to the pkt following
14634 			 * the M_CTL.
14635 			 */
14636 			mp = first_mp->b_cont;
14637 			if (mp == NULL) {
14638 				freemsg(first_mp);
14639 				return (B_TRUE);
14640 			}
14641 			/*
14642 			 * A Hardware Accelerated packet can only be M_DATA
14643 			 * ESP or AH packet.
14644 			 */
14645 			if (mp->b_datap->db_type != M_DATA) {
14646 				/* non-M_DATA IPsec accelerated packet */
14647 				IPSECHW_DEBUG(IPSECHW_PKT,
14648 				    ("non-M_DATA IPsec accelerated pkt\n"));
14649 				freemsg(first_mp);
14650 				return (B_TRUE);
14651 			}
14652 			ipha = (ipha_t *)mp->b_rptr;
14653 			if (ipha->ipha_protocol != IPPROTO_AH &&
14654 			    ipha->ipha_protocol != IPPROTO_ESP) {
14655 				IPSECHW_DEBUG(IPSECHW_PKT,
14656 				    ("non-M_DATA IPsec accelerated pkt\n"));
14657 				freemsg(first_mp);
14658 				return (B_TRUE);
14659 			}
14660 			*mpp = mp;
14661 			return (B_FALSE);
14662 		}
14663 		putnext(q, mp);
14664 		return (B_TRUE);
14665 	case M_IOCNAK:
14666 		ip1dbg(("got iocnak "));
14667 		iocp = (struct iocblk *)mp->b_rptr;
14668 		switch (iocp->ioc_cmd) {
14669 		case DL_IOC_HDR_INFO:
14670 			ip_rput_other(NULL, q, mp, NULL);
14671 			return (B_TRUE);
14672 		default:
14673 			break;
14674 		}
14675 		/* FALLTHRU */
14676 	default:
14677 		putnext(q, mp);
14678 		return (B_TRUE);
14679 	}
14680 }
14681 
14682 /* Read side put procedure.  Packets coming from the wire arrive here. */
14683 void
14684 ip_rput(queue_t *q, mblk_t *mp)
14685 {
14686 	ill_t	*ill;
14687 	union DL_primitives *dl;
14688 
14689 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14690 
14691 	ill = (ill_t *)q->q_ptr;
14692 
14693 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14694 		/*
14695 		 * If things are opening or closing, only accept high-priority
14696 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14697 		 * created; on close, things hanging off the ill may have been
14698 		 * freed already.)
14699 		 */
14700 		dl = (union DL_primitives *)mp->b_rptr;
14701 		if (DB_TYPE(mp) != M_PCPROTO ||
14702 		    dl->dl_primitive == DL_UNITDATA_IND) {
14703 			inet_freemsg(mp);
14704 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14705 			    "ip_rput_end: q %p (%S)", q, "uninit");
14706 			return;
14707 		}
14708 	}
14709 
14710 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14711 	    "ip_rput_end: q %p (%S)", q, "end");
14712 
14713 	ip_input(ill, NULL, mp, NULL);
14714 }
14715 
14716 static mblk_t *
14717 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14718 {
14719 	mblk_t *mp1;
14720 	boolean_t adjusted = B_FALSE;
14721 	ip_stack_t *ipst = ill->ill_ipst;
14722 
14723 	IP_STAT(ipst, ip_db_ref);
14724 	/*
14725 	 * The IP_RECVSLLA option depends on having the
14726 	 * link layer header. First check that:
14727 	 * a> the underlying device is of type ether,
14728 	 * since this option is currently supported only
14729 	 * over ethernet.
14730 	 * b> there is enough room to copy over the link
14731 	 * layer header.
14732 	 *
14733 	 * Once the checks are done, adjust rptr so that
14734 	 * the link layer header will be copied via
14735 	 * copymsg. Note that, IFT_ETHER may be returned
14736 	 * by some non-ethernet drivers but in this case
14737 	 * the second check will fail.
14738 	 */
14739 	if (ill->ill_type == IFT_ETHER &&
14740 	    (mp->b_rptr - mp->b_datap->db_base) >=
14741 	    sizeof (struct ether_header)) {
14742 		mp->b_rptr -= sizeof (struct ether_header);
14743 		adjusted = B_TRUE;
14744 	}
14745 	mp1 = copymsg(mp);
14746 
14747 	if (mp1 == NULL) {
14748 		mp->b_next = NULL;
14749 		/* clear b_prev - used by ip_mroute_decap */
14750 		mp->b_prev = NULL;
14751 		freemsg(mp);
14752 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14753 		return (NULL);
14754 	}
14755 
14756 	if (adjusted) {
14757 		/*
14758 		 * Copy is done. Restore the pointer in
14759 		 * the _new_ mblk
14760 		 */
14761 		mp1->b_rptr += sizeof (struct ether_header);
14762 	}
14763 
14764 	/* Copy b_prev - used by ip_mroute_decap */
14765 	mp1->b_prev = mp->b_prev;
14766 	mp->b_prev = NULL;
14767 
14768 	/* preserve the hardware checksum flags and data, if present */
14769 	if (DB_CKSUMFLAGS(mp) != 0) {
14770 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14771 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14772 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14773 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14774 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14775 	}
14776 
14777 	freemsg(mp);
14778 	return (mp1);
14779 }
14780 
14781 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14782 	if (tail != NULL)					\
14783 		tail->b_next = mp;				\
14784 	else							\
14785 		head = mp;					\
14786 	tail = mp;						\
14787 	cnt++;							\
14788 }
14789 
14790 /*
14791  * Direct read side procedure capable of dealing with chains. GLDv3 based
14792  * drivers call this function directly with mblk chains while STREAMS
14793  * read side procedure ip_rput() calls this for single packet with ip_ring
14794  * set to NULL to process one packet at a time.
14795  *
14796  * The ill will always be valid if this function is called directly from
14797  * the driver.
14798  *
14799  * If ip_input() is called from GLDv3:
14800  *
14801  *   - This must be a non-VLAN IP stream.
14802  *   - 'mp' is either an untagged or a special priority-tagged packet.
14803  *   - Any VLAN tag that was in the MAC header has been stripped.
14804  *
14805  * If the IP header in packet is not 32-bit aligned, every message in the
14806  * chain will be aligned before further operations. This is required on SPARC
14807  * platform.
14808  */
14809 /* ARGSUSED */
14810 void
14811 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14812     struct mac_header_info_s *mhip)
14813 {
14814 	ipaddr_t		dst = NULL;
14815 	ipaddr_t		prev_dst;
14816 	ire_t			*ire = NULL;
14817 	ipha_t			*ipha;
14818 	uint_t			pkt_len;
14819 	ssize_t			len;
14820 	uint_t			opt_len;
14821 	int			ll_multicast;
14822 	int			cgtp_flt_pkt;
14823 	queue_t			*q = ill->ill_rq;
14824 	squeue_t		*curr_sqp = NULL;
14825 	mblk_t 			*head = NULL;
14826 	mblk_t			*tail = NULL;
14827 	mblk_t			*first_mp;
14828 	int			cnt = 0;
14829 	ip_stack_t		*ipst = ill->ill_ipst;
14830 	mblk_t			*mp;
14831 	mblk_t			*dmp;
14832 	uint8_t			tag;
14833 
14834 	ASSERT(mp_chain != NULL);
14835 	ASSERT(ill != NULL);
14836 
14837 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14838 
14839 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14840 
14841 #define	rptr	((uchar_t *)ipha)
14842 
14843 	while (mp_chain != NULL) {
14844 		mp = mp_chain;
14845 		mp_chain = mp_chain->b_next;
14846 		mp->b_next = NULL;
14847 		ll_multicast = 0;
14848 
14849 		/*
14850 		 * We do ire caching from one iteration to
14851 		 * another. In the event the packet chain contains
14852 		 * all packets from the same dst, this caching saves
14853 		 * an ire_cache_lookup for each of the succeeding
14854 		 * packets in a packet chain.
14855 		 */
14856 		prev_dst = dst;
14857 
14858 		/*
14859 		 * if db_ref > 1 then copymsg and free original. Packet
14860 		 * may be changed and we do not want the other entity
14861 		 * who has a reference to this message to trip over the
14862 		 * changes. This is a blind change because trying to
14863 		 * catch all places that might change the packet is too
14864 		 * difficult.
14865 		 *
14866 		 * This corresponds to the fast path case, where we have
14867 		 * a chain of M_DATA mblks.  We check the db_ref count
14868 		 * of only the 1st data block in the mblk chain. There
14869 		 * doesn't seem to be a reason why a device driver would
14870 		 * send up data with varying db_ref counts in the mblk
14871 		 * chain. In any case the Fast path is a private
14872 		 * interface, and our drivers don't do such a thing.
14873 		 * Given the above assumption, there is no need to walk
14874 		 * down the entire mblk chain (which could have a
14875 		 * potential performance problem)
14876 		 *
14877 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14878 		 * to here because of exclusive ip stacks and vnics.
14879 		 * Packets transmitted from exclusive stack over vnic
14880 		 * can have db_ref > 1 and when it gets looped back to
14881 		 * another vnic in a different zone, you have ip_input()
14882 		 * getting dblks with db_ref > 1. So if someone
14883 		 * complains of TCP performance under this scenario,
14884 		 * take a serious look here on the impact of copymsg().
14885 		 */
14886 
14887 		if (DB_REF(mp) > 1) {
14888 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14889 				continue;
14890 		}
14891 
14892 		/*
14893 		 * Check and align the IP header.
14894 		 */
14895 		first_mp = mp;
14896 		if (DB_TYPE(mp) == M_DATA) {
14897 			dmp = mp;
14898 		} else if (DB_TYPE(mp) == M_PROTO &&
14899 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14900 			dmp = mp->b_cont;
14901 		} else {
14902 			dmp = NULL;
14903 		}
14904 		if (dmp != NULL) {
14905 			/*
14906 			 * IP header ptr not aligned?
14907 			 * OR IP header not complete in first mblk
14908 			 */
14909 			if (!OK_32PTR(dmp->b_rptr) ||
14910 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14911 				if (!ip_check_and_align_header(q, dmp, ipst))
14912 					continue;
14913 			}
14914 		}
14915 
14916 		/*
14917 		 * ip_input fast path
14918 		 */
14919 
14920 		/* mblk type is not M_DATA */
14921 		if (DB_TYPE(mp) != M_DATA) {
14922 			if (ip_rput_process_notdata(q, &first_mp, ill,
14923 			    &ll_multicast, &mp))
14924 				continue;
14925 
14926 			/*
14927 			 * The only way we can get here is if we had a
14928 			 * packet that was either a DL_UNITDATA_IND or
14929 			 * an M_CTL for an IPsec accelerated packet.
14930 			 *
14931 			 * In either case, the first_mp will point to
14932 			 * the leading M_PROTO or M_CTL.
14933 			 */
14934 			ASSERT(first_mp != NULL);
14935 		} else if (mhip != NULL) {
14936 			/*
14937 			 * ll_multicast is set here so that it is ready
14938 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14939 			 * manipulates ll_multicast in the same fashion when
14940 			 * called from ip_rput_process_notdata.
14941 			 */
14942 			switch (mhip->mhi_dsttype) {
14943 			case MAC_ADDRTYPE_MULTICAST :
14944 				ll_multicast = HPE_MULTICAST;
14945 				break;
14946 			case MAC_ADDRTYPE_BROADCAST :
14947 				ll_multicast = HPE_BROADCAST;
14948 				break;
14949 			default :
14950 				break;
14951 			}
14952 		}
14953 
14954 		/* Only M_DATA can come here and it is always aligned */
14955 		ASSERT(DB_TYPE(mp) == M_DATA);
14956 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14957 
14958 		ipha = (ipha_t *)mp->b_rptr;
14959 		len = mp->b_wptr - rptr;
14960 		pkt_len = ntohs(ipha->ipha_length);
14961 
14962 		/*
14963 		 * We must count all incoming packets, even if they end
14964 		 * up being dropped later on.
14965 		 */
14966 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14967 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14968 
14969 		/* multiple mblk or too short */
14970 		len -= pkt_len;
14971 		if (len != 0) {
14972 			/*
14973 			 * Make sure we have data length consistent
14974 			 * with the IP header.
14975 			 */
14976 			if (mp->b_cont == NULL) {
14977 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14978 					BUMP_MIB(ill->ill_ip_mib,
14979 					    ipIfStatsInHdrErrors);
14980 					ip2dbg(("ip_input: drop pkt\n"));
14981 					freemsg(mp);
14982 					continue;
14983 				}
14984 				mp->b_wptr = rptr + pkt_len;
14985 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14986 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14987 					BUMP_MIB(ill->ill_ip_mib,
14988 					    ipIfStatsInHdrErrors);
14989 					ip2dbg(("ip_input: drop pkt\n"));
14990 					freemsg(mp);
14991 					continue;
14992 				}
14993 				(void) adjmsg(mp, -len);
14994 				/*
14995 				 * adjmsg may have freed an mblk from the chain,
14996 				 * hence invalidate any hw checksum here. This
14997 				 * will force IP to calculate the checksum in
14998 				 * sw, but only for this packet.
14999 				 */
15000 				DB_CKSUMFLAGS(mp) = 0;
15001 				IP_STAT(ipst, ip_multimblk3);
15002 			}
15003 		}
15004 
15005 		/* Obtain the dst of the current packet */
15006 		dst = ipha->ipha_dst;
15007 
15008 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15009 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15010 		    ipha, ip6_t *, NULL, int, 0);
15011 
15012 		/*
15013 		 * The following test for loopback is faster than
15014 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15015 		 * operations.
15016 		 * Note that these addresses are always in network byte order
15017 		 */
15018 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15019 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15020 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15021 			freemsg(mp);
15022 			continue;
15023 		}
15024 
15025 		/*
15026 		 * The event for packets being received from a 'physical'
15027 		 * interface is placed after validation of the source and/or
15028 		 * destination address as being local so that packets can be
15029 		 * redirected to loopback addresses using ipnat.
15030 		 */
15031 		DTRACE_PROBE4(ip4__physical__in__start,
15032 		    ill_t *, ill, ill_t *, NULL,
15033 		    ipha_t *, ipha, mblk_t *, first_mp);
15034 
15035 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15036 		    ipst->ips_ipv4firewall_physical_in,
15037 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15038 
15039 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15040 
15041 		if (first_mp == NULL) {
15042 			continue;
15043 		}
15044 		dst = ipha->ipha_dst;
15045 		/*
15046 		 * Attach any necessary label information to
15047 		 * this packet
15048 		 */
15049 		if (is_system_labeled() &&
15050 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15051 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15052 			freemsg(mp);
15053 			continue;
15054 		}
15055 
15056 		if (ipst->ips_ip4_observe.he_interested) {
15057 			zoneid_t dzone;
15058 
15059 			/*
15060 			 * On the inbound path the src zone will be unknown as
15061 			 * this packet has come from the wire.
15062 			 */
15063 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15064 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15065 			    ill, ipst);
15066 		}
15067 
15068 		/*
15069 		 * Reuse the cached ire only if the ipha_dst of the previous
15070 		 * packet is the same as the current packet AND it is not
15071 		 * INADDR_ANY.
15072 		 */
15073 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15074 		    (ire != NULL)) {
15075 			ire_refrele(ire);
15076 			ire = NULL;
15077 		}
15078 
15079 		opt_len = ipha->ipha_version_and_hdr_length -
15080 		    IP_SIMPLE_HDR_VERSION;
15081 
15082 		/*
15083 		 * Check to see if we can take the fastpath.
15084 		 * That is possible if the following conditions are met
15085 		 *	o Tsol disabled
15086 		 *	o CGTP disabled
15087 		 *	o ipp_action_count is 0
15088 		 *	o no options in the packet
15089 		 *	o not a RSVP packet
15090 		 * 	o not a multicast packet
15091 		 *	o ill not in IP_DHCPINIT_IF mode
15092 		 */
15093 		if (!is_system_labeled() &&
15094 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15095 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15096 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15097 			if (ire == NULL)
15098 				ire = ire_cache_lookup_simple(dst, ipst);
15099 			/*
15100 			 * Unless forwarding is enabled, dont call
15101 			 * ip_fast_forward(). Incoming packet is for forwarding
15102 			 */
15103 			if ((ill->ill_flags & ILLF_ROUTER) &&
15104 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15105 				ire = ip_fast_forward(ire, dst, ill, mp);
15106 				continue;
15107 			}
15108 			/* incoming packet is for local consumption */
15109 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15110 				goto local;
15111 		}
15112 
15113 		/*
15114 		 * Disable ire caching for anything more complex
15115 		 * than the simple fast path case we checked for above.
15116 		 */
15117 		if (ire != NULL) {
15118 			ire_refrele(ire);
15119 			ire = NULL;
15120 		}
15121 
15122 		/*
15123 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15124 		 * server to unicast DHCP packets to a DHCP client using the
15125 		 * IP address it is offering to the client.  This can be
15126 		 * disabled through the "broadcast bit", but not all DHCP
15127 		 * servers honor that bit.  Therefore, to interoperate with as
15128 		 * many DHCP servers as possible, the DHCP client allows the
15129 		 * server to unicast, but we treat those packets as broadcast
15130 		 * here.  Note that we don't rewrite the packet itself since
15131 		 * (a) that would mess up the checksums and (b) the DHCP
15132 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15133 		 * hand it the packet regardless.
15134 		 */
15135 		if (ill->ill_dhcpinit != 0 &&
15136 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15137 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15138 			udpha_t *udpha;
15139 
15140 			/*
15141 			 * Reload ipha since pullupmsg() can change b_rptr.
15142 			 */
15143 			ipha = (ipha_t *)mp->b_rptr;
15144 			udpha = (udpha_t *)&ipha[1];
15145 
15146 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15147 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15148 				    mblk_t *, mp);
15149 				dst = INADDR_BROADCAST;
15150 			}
15151 		}
15152 
15153 		/* Full-blown slow path */
15154 		if (opt_len != 0) {
15155 			if (len != 0)
15156 				IP_STAT(ipst, ip_multimblk4);
15157 			else
15158 				IP_STAT(ipst, ip_ipoptions);
15159 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15160 			    &dst, ipst))
15161 				continue;
15162 		}
15163 
15164 		/*
15165 		 * Invoke the CGTP (multirouting) filtering module to process
15166 		 * the incoming packet. Packets identified as duplicates
15167 		 * must be discarded. Filtering is active only if the
15168 		 * the ip_cgtp_filter ndd variable is non-zero.
15169 		 */
15170 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15171 		if (ipst->ips_ip_cgtp_filter &&
15172 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15173 			netstackid_t stackid;
15174 
15175 			stackid = ipst->ips_netstack->netstack_stackid;
15176 			cgtp_flt_pkt =
15177 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15178 			    ill->ill_phyint->phyint_ifindex, mp);
15179 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15180 				freemsg(first_mp);
15181 				continue;
15182 			}
15183 		}
15184 
15185 		/*
15186 		 * If rsvpd is running, let RSVP daemon handle its processing
15187 		 * and forwarding of RSVP multicast/unicast packets.
15188 		 * If rsvpd is not running but mrouted is running, RSVP
15189 		 * multicast packets are forwarded as multicast traffic
15190 		 * and RSVP unicast packets are forwarded by unicast router.
15191 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15192 		 * packets are not forwarded, but the unicast packets are
15193 		 * forwarded like unicast traffic.
15194 		 */
15195 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15196 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15197 		    NULL) {
15198 			/* RSVP packet and rsvpd running. Treat as ours */
15199 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15200 			/*
15201 			 * This assumes that we deliver to all streams for
15202 			 * multicast and broadcast packets.
15203 			 * We have to force ll_multicast to 1 to handle the
15204 			 * M_DATA messages passed in from ip_mroute_decap.
15205 			 */
15206 			dst = INADDR_BROADCAST;
15207 			ll_multicast = 1;
15208 		} else if (CLASSD(dst)) {
15209 			/* packet is multicast */
15210 			mp->b_next = NULL;
15211 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15212 			    &ll_multicast, &dst))
15213 				continue;
15214 		}
15215 
15216 		if (ire == NULL) {
15217 			ire = ire_cache_lookup(dst, ALL_ZONES,
15218 			    msg_getlabel(mp), ipst);
15219 		}
15220 
15221 		if (ire != NULL && ire->ire_stq != NULL &&
15222 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15223 		    ire->ire_zoneid != ALL_ZONES) {
15224 			/*
15225 			 * Should only use IREs that are visible from the
15226 			 * global zone for forwarding.
15227 			 */
15228 			ire_refrele(ire);
15229 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15230 			    msg_getlabel(mp), ipst);
15231 		}
15232 
15233 		if (ire == NULL) {
15234 			/*
15235 			 * No IRE for this destination, so it can't be for us.
15236 			 * Unless we are forwarding, drop the packet.
15237 			 * We have to let source routed packets through
15238 			 * since we don't yet know if they are 'ping -l'
15239 			 * packets i.e. if they will go out over the
15240 			 * same interface as they came in on.
15241 			 */
15242 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15243 			if (ire == NULL)
15244 				continue;
15245 		}
15246 
15247 		/*
15248 		 * Broadcast IRE may indicate either broadcast or
15249 		 * multicast packet
15250 		 */
15251 		if (ire->ire_type == IRE_BROADCAST) {
15252 			/*
15253 			 * Skip broadcast checks if packet is UDP multicast;
15254 			 * we'd rather not enter ip_rput_process_broadcast()
15255 			 * unless the packet is broadcast for real, since
15256 			 * that routine is a no-op for multicast.
15257 			 */
15258 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15259 			    !CLASSD(ipha->ipha_dst)) {
15260 				ire = ip_rput_process_broadcast(&q, mp,
15261 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15262 				    ll_multicast);
15263 				if (ire == NULL)
15264 					continue;
15265 			}
15266 		} else if (ire->ire_stq != NULL) {
15267 			/* fowarding? */
15268 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15269 			    ll_multicast, B_FALSE);
15270 			/* ip_rput_process_forward consumed the packet */
15271 			continue;
15272 		}
15273 
15274 local:
15275 		/*
15276 		 * If the queue in the ire is different to the ingress queue
15277 		 * then we need to check to see if we can accept the packet.
15278 		 * Note that for multicast packets and broadcast packets sent
15279 		 * to a broadcast address which is shared between multiple
15280 		 * interfaces we should not do this since we just got a random
15281 		 * broadcast ire.
15282 		 */
15283 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15284 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15285 			if (ire == NULL) {
15286 				/* Drop packet */
15287 				BUMP_MIB(ill->ill_ip_mib,
15288 				    ipIfStatsForwProhibits);
15289 				freemsg(mp);
15290 				continue;
15291 			}
15292 			if (ire->ire_rfq != NULL)
15293 				q = ire->ire_rfq;
15294 		}
15295 
15296 		switch (ipha->ipha_protocol) {
15297 		case IPPROTO_TCP:
15298 			ASSERT(first_mp == mp);
15299 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15300 			    mp, 0, q, ip_ring)) != NULL) {
15301 				if (curr_sqp == NULL) {
15302 					curr_sqp = GET_SQUEUE(mp);
15303 					ASSERT(cnt == 0);
15304 					cnt++;
15305 					head = tail = mp;
15306 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15307 					ASSERT(tail != NULL);
15308 					cnt++;
15309 					tail->b_next = mp;
15310 					tail = mp;
15311 				} else {
15312 					/*
15313 					 * A different squeue. Send the
15314 					 * chain for the previous squeue on
15315 					 * its way. This shouldn't happen
15316 					 * often unless interrupt binding
15317 					 * changes.
15318 					 */
15319 					IP_STAT(ipst, ip_input_multi_squeue);
15320 					SQUEUE_ENTER(curr_sqp, head,
15321 					    tail, cnt, SQ_PROCESS, tag);
15322 					curr_sqp = GET_SQUEUE(mp);
15323 					head = mp;
15324 					tail = mp;
15325 					cnt = 1;
15326 				}
15327 			}
15328 			continue;
15329 		case IPPROTO_UDP:
15330 			ASSERT(first_mp == mp);
15331 			ip_udp_input(q, mp, ipha, ire, ill);
15332 			continue;
15333 		case IPPROTO_SCTP:
15334 			ASSERT(first_mp == mp);
15335 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15336 			    q, dst);
15337 			/* ire has been released by ip_sctp_input */
15338 			ire = NULL;
15339 			continue;
15340 		case IPPROTO_ENCAP:
15341 		case IPPROTO_IPV6:
15342 			ASSERT(first_mp == mp);
15343 			if (ip_iptun_input(NULL, mp, ipha, ill, ire, ipst))
15344 				break;
15345 			/*
15346 			 * If there was no IP tunnel data-link bound to
15347 			 * receive this packet, then we fall through to
15348 			 * allow potential raw sockets bound to either of
15349 			 * these protocols to pick it up.
15350 			 */
15351 		default:
15352 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15353 			continue;
15354 		}
15355 	}
15356 
15357 	if (ire != NULL)
15358 		ire_refrele(ire);
15359 
15360 	if (head != NULL)
15361 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15362 
15363 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15364 	    "ip_input_end: q %p (%S)", q, "end");
15365 #undef  rptr
15366 }
15367 
15368 /*
15369  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15370  * a chain of packets in the poll mode. The packets have gone through the
15371  * data link processing but not IP processing. For performance and latency
15372  * reasons, the squeue wants to process the chain in line instead of feeding
15373  * it back via ip_input path.
15374  *
15375  * So this is a light weight function which checks to see if the packets
15376  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15377  * but we still do the paranoid check) meant for local machine and we don't
15378  * have labels etc enabled. Packets that meet the criterion are returned to
15379  * the squeue and processed inline while the rest go via ip_input path.
15380  */
15381 /*ARGSUSED*/
15382 mblk_t *
15383 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15384     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15385 {
15386 	mblk_t 		*mp;
15387 	ipaddr_t	dst = NULL;
15388 	ipaddr_t	prev_dst;
15389 	ire_t		*ire = NULL;
15390 	ipha_t		*ipha;
15391 	uint_t		pkt_len;
15392 	ssize_t		len;
15393 	uint_t		opt_len;
15394 	queue_t		*q = ill->ill_rq;
15395 	squeue_t	*curr_sqp;
15396 	mblk_t 		*ahead = NULL;	/* Accepted head */
15397 	mblk_t		*atail = NULL;	/* Accepted tail */
15398 	uint_t		acnt = 0;	/* Accepted count */
15399 	mblk_t		*utail = NULL;	/* Unaccepted head */
15400 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15401 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15402 	ip_stack_t	*ipst = ill->ill_ipst;
15403 
15404 	*cnt = 0;
15405 
15406 	ASSERT(ill != NULL);
15407 	ASSERT(ip_ring != NULL);
15408 
15409 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15410 
15411 #define	rptr	((uchar_t *)ipha)
15412 
15413 	while (mp_chain != NULL) {
15414 		mp = mp_chain;
15415 		mp_chain = mp_chain->b_next;
15416 		mp->b_next = NULL;
15417 
15418 		/*
15419 		 * We do ire caching from one iteration to
15420 		 * another. In the event the packet chain contains
15421 		 * all packets from the same dst, this caching saves
15422 		 * an ire_cache_lookup for each of the succeeding
15423 		 * packets in a packet chain.
15424 		 */
15425 		prev_dst = dst;
15426 
15427 		ipha = (ipha_t *)mp->b_rptr;
15428 		len = mp->b_wptr - rptr;
15429 
15430 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15431 
15432 		/*
15433 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15434 		 * or doesn't have min len, reject.
15435 		 */
15436 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15437 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15438 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15439 			continue;
15440 		}
15441 
15442 		pkt_len = ntohs(ipha->ipha_length);
15443 		if (len != pkt_len) {
15444 			if (len > pkt_len) {
15445 				mp->b_wptr = rptr + pkt_len;
15446 			} else {
15447 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15448 				continue;
15449 			}
15450 		}
15451 
15452 		opt_len = ipha->ipha_version_and_hdr_length -
15453 		    IP_SIMPLE_HDR_VERSION;
15454 		dst = ipha->ipha_dst;
15455 
15456 		/* IP version bad or there are IP options */
15457 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15458 		    mp, &ipha, &dst, ipst)))
15459 			continue;
15460 
15461 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15462 		    (ipst->ips_ip_cgtp_filter &&
15463 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15464 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15465 			continue;
15466 		}
15467 
15468 		/*
15469 		 * Reuse the cached ire only if the ipha_dst of the previous
15470 		 * packet is the same as the current packet AND it is not
15471 		 * INADDR_ANY.
15472 		 */
15473 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15474 		    (ire != NULL)) {
15475 			ire_refrele(ire);
15476 			ire = NULL;
15477 		}
15478 
15479 		if (ire == NULL)
15480 			ire = ire_cache_lookup_simple(dst, ipst);
15481 
15482 		/*
15483 		 * Unless forwarding is enabled, dont call
15484 		 * ip_fast_forward(). Incoming packet is for forwarding
15485 		 */
15486 		if ((ill->ill_flags & ILLF_ROUTER) &&
15487 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15488 
15489 			DTRACE_PROBE4(ip4__physical__in__start,
15490 			    ill_t *, ill, ill_t *, NULL,
15491 			    ipha_t *, ipha, mblk_t *, mp);
15492 
15493 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15494 			    ipst->ips_ipv4firewall_physical_in,
15495 			    ill, NULL, ipha, mp, mp, 0, ipst);
15496 
15497 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15498 
15499 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15500 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15501 			    pkt_len);
15502 
15503 			if (mp != NULL)
15504 				ire = ip_fast_forward(ire, dst, ill, mp);
15505 			continue;
15506 		}
15507 
15508 		/* incoming packet is for local consumption */
15509 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15510 			goto local_accept;
15511 
15512 		/*
15513 		 * Disable ire caching for anything more complex
15514 		 * than the simple fast path case we checked for above.
15515 		 */
15516 		if (ire != NULL) {
15517 			ire_refrele(ire);
15518 			ire = NULL;
15519 		}
15520 
15521 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15522 		    ipst);
15523 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15524 		    ire->ire_stq != NULL) {
15525 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15526 			if (ire != NULL) {
15527 				ire_refrele(ire);
15528 				ire = NULL;
15529 			}
15530 			continue;
15531 		}
15532 
15533 local_accept:
15534 
15535 		if (ire->ire_rfq != q) {
15536 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15537 			if (ire != NULL) {
15538 				ire_refrele(ire);
15539 				ire = NULL;
15540 			}
15541 			continue;
15542 		}
15543 
15544 		/*
15545 		 * The event for packets being received from a 'physical'
15546 		 * interface is placed after validation of the source and/or
15547 		 * destination address as being local so that packets can be
15548 		 * redirected to loopback addresses using ipnat.
15549 		 */
15550 		DTRACE_PROBE4(ip4__physical__in__start,
15551 		    ill_t *, ill, ill_t *, NULL,
15552 		    ipha_t *, ipha, mblk_t *, mp);
15553 
15554 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15555 		    ipst->ips_ipv4firewall_physical_in,
15556 		    ill, NULL, ipha, mp, mp, 0, ipst);
15557 
15558 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15559 
15560 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15561 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15562 
15563 		if (mp != NULL &&
15564 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15565 		    0, q, ip_ring)) != NULL) {
15566 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15567 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15568 			} else {
15569 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15570 				    SQ_FILL, SQTAG_IP_INPUT);
15571 			}
15572 		}
15573 	}
15574 
15575 	if (ire != NULL)
15576 		ire_refrele(ire);
15577 
15578 	if (uhead != NULL)
15579 		ip_input(ill, ip_ring, uhead, NULL);
15580 
15581 	if (ahead != NULL) {
15582 		*last = atail;
15583 		*cnt = acnt;
15584 		return (ahead);
15585 	}
15586 
15587 	return (NULL);
15588 #undef  rptr
15589 }
15590 
15591 static void
15592 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15593     t_uscalar_t err)
15594 {
15595 	if (dl_err == DL_SYSERR) {
15596 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15597 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15598 		    ill->ill_name, dl_primstr(prim), err);
15599 		return;
15600 	}
15601 
15602 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15603 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15604 	    dl_errstr(dl_err));
15605 }
15606 
15607 /*
15608  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15609  * than DL_UNITDATA_IND messages. If we need to process this message
15610  * exclusively, we call qwriter_ip, in which case we also need to call
15611  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15612  */
15613 void
15614 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15615 {
15616 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15617 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15618 	ill_t		*ill = q->q_ptr;
15619 	t_uscalar_t	prim = dloa->dl_primitive;
15620 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15621 
15622 	ip1dbg(("ip_rput_dlpi"));
15623 
15624 	/*
15625 	 * If we received an ACK but didn't send a request for it, then it
15626 	 * can't be part of any pending operation; discard up-front.
15627 	 */
15628 	switch (prim) {
15629 	case DL_ERROR_ACK:
15630 		reqprim = dlea->dl_error_primitive;
15631 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15632 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15633 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15634 		    dlea->dl_unix_errno));
15635 		break;
15636 	case DL_OK_ACK:
15637 		reqprim = dloa->dl_correct_primitive;
15638 		break;
15639 	case DL_INFO_ACK:
15640 		reqprim = DL_INFO_REQ;
15641 		break;
15642 	case DL_BIND_ACK:
15643 		reqprim = DL_BIND_REQ;
15644 		break;
15645 	case DL_PHYS_ADDR_ACK:
15646 		reqprim = DL_PHYS_ADDR_REQ;
15647 		break;
15648 	case DL_NOTIFY_ACK:
15649 		reqprim = DL_NOTIFY_REQ;
15650 		break;
15651 	case DL_CONTROL_ACK:
15652 		reqprim = DL_CONTROL_REQ;
15653 		break;
15654 	case DL_CAPABILITY_ACK:
15655 		reqprim = DL_CAPABILITY_REQ;
15656 		break;
15657 	}
15658 
15659 	if (prim != DL_NOTIFY_IND) {
15660 		if (reqprim == DL_PRIM_INVAL ||
15661 		    !ill_dlpi_pending(ill, reqprim)) {
15662 			/* Not a DLPI message we support or expected */
15663 			freemsg(mp);
15664 			return;
15665 		}
15666 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15667 		    dl_primstr(reqprim)));
15668 	}
15669 
15670 	switch (reqprim) {
15671 	case DL_UNBIND_REQ:
15672 		/*
15673 		 * NOTE: we mark the unbind as complete even if we got a
15674 		 * DL_ERROR_ACK, since there's not much else we can do.
15675 		 */
15676 		mutex_enter(&ill->ill_lock);
15677 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15678 		cv_signal(&ill->ill_cv);
15679 		mutex_exit(&ill->ill_lock);
15680 		break;
15681 
15682 	case DL_ENABMULTI_REQ:
15683 		if (prim == DL_OK_ACK) {
15684 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15685 				ill->ill_dlpi_multicast_state = IDS_OK;
15686 		}
15687 		break;
15688 	}
15689 
15690 	/*
15691 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15692 	 * need to become writer to continue to process it.  Because an
15693 	 * exclusive operation doesn't complete until replies to all queued
15694 	 * DLPI messages have been received, we know we're in the middle of an
15695 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15696 	 *
15697 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15698 	 * Since this is on the ill stream we unconditionally bump up the
15699 	 * refcount without doing ILL_CAN_LOOKUP().
15700 	 */
15701 	ill_refhold(ill);
15702 	if (prim == DL_NOTIFY_IND)
15703 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15704 	else
15705 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15706 }
15707 
15708 /*
15709  * Handling of DLPI messages that require exclusive access to the ipsq.
15710  *
15711  * Need to do ill_pending_mp_release on ioctl completion, which could
15712  * happen here. (along with mi_copy_done)
15713  */
15714 /* ARGSUSED */
15715 static void
15716 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15717 {
15718 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15719 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15720 	int		err = 0;
15721 	ill_t		*ill;
15722 	ipif_t		*ipif = NULL;
15723 	mblk_t		*mp1 = NULL;
15724 	conn_t		*connp = NULL;
15725 	t_uscalar_t	paddrreq;
15726 	mblk_t		*mp_hw;
15727 	boolean_t	success;
15728 	boolean_t	ioctl_aborted = B_FALSE;
15729 	boolean_t	log = B_TRUE;
15730 	ip_stack_t		*ipst;
15731 
15732 	ip1dbg(("ip_rput_dlpi_writer .."));
15733 	ill = (ill_t *)q->q_ptr;
15734 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15735 	ASSERT(IAM_WRITER_ILL(ill));
15736 
15737 	ipst = ill->ill_ipst;
15738 
15739 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15740 	/*
15741 	 * The current ioctl could have been aborted by the user and a new
15742 	 * ioctl to bring up another ill could have started. We could still
15743 	 * get a response from the driver later.
15744 	 */
15745 	if (ipif != NULL && ipif->ipif_ill != ill)
15746 		ioctl_aborted = B_TRUE;
15747 
15748 	switch (dloa->dl_primitive) {
15749 	case DL_ERROR_ACK:
15750 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15751 		    dl_primstr(dlea->dl_error_primitive)));
15752 
15753 		switch (dlea->dl_error_primitive) {
15754 		case DL_DISABMULTI_REQ:
15755 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15756 			break;
15757 		case DL_PROMISCON_REQ:
15758 		case DL_PROMISCOFF_REQ:
15759 		case DL_UNBIND_REQ:
15760 		case DL_ATTACH_REQ:
15761 		case DL_INFO_REQ:
15762 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15763 			break;
15764 		case DL_NOTIFY_REQ:
15765 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15766 			log = B_FALSE;
15767 			break;
15768 		case DL_PHYS_ADDR_REQ:
15769 			/*
15770 			 * For IPv6 only, there are two additional
15771 			 * phys_addr_req's sent to the driver to get the
15772 			 * IPv6 token and lla. This allows IP to acquire
15773 			 * the hardware address format for a given interface
15774 			 * without having built in knowledge of the hardware
15775 			 * address. ill_phys_addr_pend keeps track of the last
15776 			 * DL_PAR sent so we know which response we are
15777 			 * dealing with. ill_dlpi_done will update
15778 			 * ill_phys_addr_pend when it sends the next req.
15779 			 * We don't complete the IOCTL until all three DL_PARs
15780 			 * have been attempted, so set *_len to 0 and break.
15781 			 */
15782 			paddrreq = ill->ill_phys_addr_pend;
15783 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15784 			if (paddrreq == DL_IPV6_TOKEN) {
15785 				ill->ill_token_length = 0;
15786 				log = B_FALSE;
15787 				break;
15788 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15789 				ill->ill_nd_lla_len = 0;
15790 				log = B_FALSE;
15791 				break;
15792 			}
15793 			/*
15794 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15795 			 * We presumably have an IOCTL hanging out waiting
15796 			 * for completion. Find it and complete the IOCTL
15797 			 * with the error noted.
15798 			 * However, ill_dl_phys was called on an ill queue
15799 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15800 			 * set. But the ioctl is known to be pending on ill_wq.
15801 			 */
15802 			if (!ill->ill_ifname_pending)
15803 				break;
15804 			ill->ill_ifname_pending = 0;
15805 			if (!ioctl_aborted)
15806 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15807 			if (mp1 != NULL) {
15808 				/*
15809 				 * This operation (SIOCSLIFNAME) must have
15810 				 * happened on the ill. Assert there is no conn
15811 				 */
15812 				ASSERT(connp == NULL);
15813 				q = ill->ill_wq;
15814 			}
15815 			break;
15816 		case DL_BIND_REQ:
15817 			ill_dlpi_done(ill, DL_BIND_REQ);
15818 			if (ill->ill_ifname_pending)
15819 				break;
15820 			/*
15821 			 * Something went wrong with the bind.  We presumably
15822 			 * have an IOCTL hanging out waiting for completion.
15823 			 * Find it, take down the interface that was coming
15824 			 * up, and complete the IOCTL with the error noted.
15825 			 */
15826 			if (!ioctl_aborted)
15827 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15828 			if (mp1 != NULL) {
15829 				/*
15830 				 * This might be a result of a DL_NOTE_REPLUMB
15831 				 * notification. In that case, connp is NULL.
15832 				 */
15833 				if (connp != NULL)
15834 					q = CONNP_TO_WQ(connp);
15835 
15836 				(void) ipif_down(ipif, NULL, NULL);
15837 				/* error is set below the switch */
15838 			}
15839 			break;
15840 		case DL_ENABMULTI_REQ:
15841 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15842 
15843 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15844 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15845 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15846 				ipif_t *ipif;
15847 
15848 				printf("ip: joining multicasts failed (%d)"
15849 				    " on %s - will use link layer "
15850 				    "broadcasts for multicast\n",
15851 				    dlea->dl_errno, ill->ill_name);
15852 
15853 				/*
15854 				 * Set up the multicast mapping alone.
15855 				 * writer, so ok to access ill->ill_ipif
15856 				 * without any lock.
15857 				 */
15858 				ipif = ill->ill_ipif;
15859 				mutex_enter(&ill->ill_phyint->phyint_lock);
15860 				ill->ill_phyint->phyint_flags |=
15861 				    PHYI_MULTI_BCAST;
15862 				mutex_exit(&ill->ill_phyint->phyint_lock);
15863 
15864 				if (!ill->ill_isv6) {
15865 					(void) ipif_arp_setup_multicast(ipif,
15866 					    NULL);
15867 				} else {
15868 					(void) ipif_ndp_setup_multicast(ipif,
15869 					    NULL);
15870 				}
15871 			}
15872 			freemsg(mp);	/* Don't want to pass this up */
15873 			return;
15874 		case DL_CONTROL_REQ:
15875 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15876 			    "DL_CONTROL_REQ\n"));
15877 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15878 			freemsg(mp);
15879 			return;
15880 		case DL_CAPABILITY_REQ:
15881 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15882 			    "DL_CAPABILITY REQ\n"));
15883 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15884 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15885 			ill_capability_done(ill);
15886 			freemsg(mp);
15887 			return;
15888 		}
15889 		/*
15890 		 * Note the error for IOCTL completion (mp1 is set when
15891 		 * ready to complete ioctl). If ill_ifname_pending_err is
15892 		 * set, an error occured during plumbing (ill_ifname_pending),
15893 		 * so we want to report that error.
15894 		 *
15895 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15896 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15897 		 * expected to get errack'd if the driver doesn't support
15898 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15899 		 * if these error conditions are encountered.
15900 		 */
15901 		if (mp1 != NULL) {
15902 			if (ill->ill_ifname_pending_err != 0)  {
15903 				err = ill->ill_ifname_pending_err;
15904 				ill->ill_ifname_pending_err = 0;
15905 			} else {
15906 				err = dlea->dl_unix_errno ?
15907 				    dlea->dl_unix_errno : ENXIO;
15908 			}
15909 		/*
15910 		 * If we're plumbing an interface and an error hasn't already
15911 		 * been saved, set ill_ifname_pending_err to the error passed
15912 		 * up. Ignore the error if log is B_FALSE (see comment above).
15913 		 */
15914 		} else if (log && ill->ill_ifname_pending &&
15915 		    ill->ill_ifname_pending_err == 0) {
15916 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15917 			    dlea->dl_unix_errno : ENXIO;
15918 		}
15919 
15920 		if (log)
15921 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15922 			    dlea->dl_errno, dlea->dl_unix_errno);
15923 		break;
15924 	case DL_CAPABILITY_ACK:
15925 		ill_capability_ack(ill, mp);
15926 		/*
15927 		 * The message has been handed off to ill_capability_ack
15928 		 * and must not be freed below
15929 		 */
15930 		mp = NULL;
15931 		break;
15932 
15933 	case DL_CONTROL_ACK:
15934 		/* We treat all of these as "fire and forget" */
15935 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15936 		break;
15937 	case DL_INFO_ACK:
15938 		/* Call a routine to handle this one. */
15939 		ill_dlpi_done(ill, DL_INFO_REQ);
15940 		ip_ll_subnet_defaults(ill, mp);
15941 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15942 		return;
15943 	case DL_BIND_ACK:
15944 		/*
15945 		 * We should have an IOCTL waiting on this unless
15946 		 * sent by ill_dl_phys, in which case just return
15947 		 */
15948 		ill_dlpi_done(ill, DL_BIND_REQ);
15949 		if (ill->ill_ifname_pending)
15950 			break;
15951 
15952 		if (!ioctl_aborted)
15953 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15954 		if (mp1 == NULL)
15955 			break;
15956 		/*
15957 		 * mp1 was added by ill_dl_up(). if that is a result of
15958 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
15959 		 */
15960 		if (connp != NULL)
15961 			q = CONNP_TO_WQ(connp);
15962 
15963 		/*
15964 		 * We are exclusive. So nothing can change even after
15965 		 * we get the pending mp. If need be we can put it back
15966 		 * and restart, as in calling ipif_arp_up()  below.
15967 		 */
15968 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15969 
15970 		mutex_enter(&ill->ill_lock);
15971 		ill->ill_dl_up = 1;
15972 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15973 		mutex_exit(&ill->ill_lock);
15974 
15975 		/*
15976 		 * Now bring up the resolver; when that is complete, we'll
15977 		 * create IREs.  Note that we intentionally mirror what
15978 		 * ipif_up() would have done, because we got here by way of
15979 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15980 		 */
15981 		if (ill->ill_isv6) {
15982 			if (ill->ill_flags & ILLF_XRESOLV) {
15983 				if (connp != NULL)
15984 					mutex_enter(&connp->conn_lock);
15985 				mutex_enter(&ill->ill_lock);
15986 				success = ipsq_pending_mp_add(connp, ipif, q,
15987 				    mp1, 0);
15988 				mutex_exit(&ill->ill_lock);
15989 				if (connp != NULL)
15990 					mutex_exit(&connp->conn_lock);
15991 				if (success) {
15992 					err = ipif_resolver_up(ipif,
15993 					    Res_act_initial);
15994 					if (err == EINPROGRESS) {
15995 						freemsg(mp);
15996 						return;
15997 					}
15998 					ASSERT(err != 0);
15999 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16000 					ASSERT(mp1 != NULL);
16001 				} else {
16002 					/* conn has started closing */
16003 					err = EINTR;
16004 				}
16005 			} else { /* Non XRESOLV interface */
16006 				(void) ipif_resolver_up(ipif, Res_act_initial);
16007 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16008 					err = ipif_up_done_v6(ipif);
16009 			}
16010 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16011 			/*
16012 			 * ARP and other v4 external resolvers.
16013 			 * Leave the pending mblk intact so that
16014 			 * the ioctl completes in ip_rput().
16015 			 */
16016 			if (connp != NULL)
16017 				mutex_enter(&connp->conn_lock);
16018 			mutex_enter(&ill->ill_lock);
16019 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16020 			mutex_exit(&ill->ill_lock);
16021 			if (connp != NULL)
16022 				mutex_exit(&connp->conn_lock);
16023 			if (success) {
16024 				err = ipif_resolver_up(ipif, Res_act_initial);
16025 				if (err == EINPROGRESS) {
16026 					freemsg(mp);
16027 					return;
16028 				}
16029 				ASSERT(err != 0);
16030 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16031 			} else {
16032 				/* The conn has started closing */
16033 				err = EINTR;
16034 			}
16035 		} else {
16036 			/*
16037 			 * This one is complete. Reply to pending ioctl.
16038 			 */
16039 			(void) ipif_resolver_up(ipif, Res_act_initial);
16040 			err = ipif_up_done(ipif);
16041 		}
16042 
16043 		if ((err == 0) && (ill->ill_up_ipifs)) {
16044 			err = ill_up_ipifs(ill, q, mp1);
16045 			if (err == EINPROGRESS) {
16046 				freemsg(mp);
16047 				return;
16048 			}
16049 		}
16050 
16051 		/*
16052 		 * If we have a moved ipif to bring up, and everything has
16053 		 * succeeded to this point, bring it up on the IPMP ill.
16054 		 * Otherwise, leave it down -- the admin can try to bring it
16055 		 * up by hand if need be.
16056 		 */
16057 		if (ill->ill_move_ipif != NULL) {
16058 			if (err != 0) {
16059 				ill->ill_move_ipif = NULL;
16060 			} else {
16061 				ipif = ill->ill_move_ipif;
16062 				ill->ill_move_ipif = NULL;
16063 				err = ipif_up(ipif, q, mp1);
16064 				if (err == EINPROGRESS) {
16065 					freemsg(mp);
16066 					return;
16067 				}
16068 			}
16069 		}
16070 		break;
16071 
16072 	case DL_NOTIFY_IND: {
16073 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16074 		ire_t *ire;
16075 		uint_t orig_mtu;
16076 		boolean_t need_ire_walk_v4 = B_FALSE;
16077 		boolean_t need_ire_walk_v6 = B_FALSE;
16078 
16079 		switch (notify->dl_notification) {
16080 		case DL_NOTE_PHYS_ADDR:
16081 			err = ill_set_phys_addr(ill, mp);
16082 			break;
16083 
16084 		case DL_NOTE_REPLUMB:
16085 			/*
16086 			 * Directly return after calling ill_replumb().
16087 			 * Note that we should not free mp as it is reused
16088 			 * in the ill_replumb() function.
16089 			 */
16090 			err = ill_replumb(ill, mp);
16091 			return;
16092 
16093 		case DL_NOTE_FASTPATH_FLUSH:
16094 			ill_fastpath_flush(ill);
16095 			break;
16096 
16097 		case DL_NOTE_SDU_SIZE:
16098 			/*
16099 			 * Change the MTU size of the interface, of all
16100 			 * attached ipif's, and of all relevant ire's.  The
16101 			 * new value's a uint32_t at notify->dl_data.
16102 			 * Mtu change Vs. new ire creation - protocol below.
16103 			 *
16104 			 * a Mark the ipif as IPIF_CHANGING.
16105 			 * b Set the new mtu in the ipif.
16106 			 * c Change the ire_max_frag on all affected ires
16107 			 * d Unmark the IPIF_CHANGING
16108 			 *
16109 			 * To see how the protocol works, assume an interface
16110 			 * route is also being added simultaneously by
16111 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16112 			 * the ire. If the ire is created before step a,
16113 			 * it will be cleaned up by step c. If the ire is
16114 			 * created after step d, it will see the new value of
16115 			 * ipif_mtu. Any attempt to create the ire between
16116 			 * steps a to d will fail because of the IPIF_CHANGING
16117 			 * flag. Note that ire_create() is passed a pointer to
16118 			 * the ipif_mtu, and not the value. During ire_add
16119 			 * under the bucket lock, the ire_max_frag of the
16120 			 * new ire being created is set from the ipif/ire from
16121 			 * which it is being derived.
16122 			 */
16123 			mutex_enter(&ill->ill_lock);
16124 
16125 			orig_mtu = ill->ill_max_mtu;
16126 			ill->ill_max_frag = (uint_t)notify->dl_data;
16127 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16128 
16129 			/*
16130 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16131 			 * clamp ill_max_mtu at it.
16132 			 */
16133 			if (ill->ill_user_mtu != 0 &&
16134 			    ill->ill_user_mtu < ill->ill_max_mtu)
16135 				ill->ill_max_mtu = ill->ill_user_mtu;
16136 
16137 			/*
16138 			 * If the MTU is unchanged, we're done.
16139 			 */
16140 			if (orig_mtu == ill->ill_max_mtu) {
16141 				mutex_exit(&ill->ill_lock);
16142 				break;
16143 			}
16144 
16145 			if (ill->ill_isv6) {
16146 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16147 					ill->ill_max_mtu = IPV6_MIN_MTU;
16148 			} else {
16149 				if (ill->ill_max_mtu < IP_MIN_MTU)
16150 					ill->ill_max_mtu = IP_MIN_MTU;
16151 			}
16152 			for (ipif = ill->ill_ipif; ipif != NULL;
16153 			    ipif = ipif->ipif_next) {
16154 				/*
16155 				 * Don't override the mtu if the user
16156 				 * has explicitly set it.
16157 				 */
16158 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16159 					continue;
16160 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16161 				if (ipif->ipif_isv6)
16162 					ire = ipif_to_ire_v6(ipif);
16163 				else
16164 					ire = ipif_to_ire(ipif);
16165 				if (ire != NULL) {
16166 					ire->ire_max_frag = ipif->ipif_mtu;
16167 					ire_refrele(ire);
16168 				}
16169 				if (ipif->ipif_flags & IPIF_UP) {
16170 					if (ill->ill_isv6)
16171 						need_ire_walk_v6 = B_TRUE;
16172 					else
16173 						need_ire_walk_v4 = B_TRUE;
16174 				}
16175 			}
16176 			mutex_exit(&ill->ill_lock);
16177 			if (need_ire_walk_v4)
16178 				ire_walk_v4(ill_mtu_change, (char *)ill,
16179 				    ALL_ZONES, ipst);
16180 			if (need_ire_walk_v6)
16181 				ire_walk_v6(ill_mtu_change, (char *)ill,
16182 				    ALL_ZONES, ipst);
16183 
16184 			/*
16185 			 * Refresh IPMP meta-interface MTU if necessary.
16186 			 */
16187 			if (IS_UNDER_IPMP(ill))
16188 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16189 			break;
16190 
16191 		case DL_NOTE_LINK_UP:
16192 		case DL_NOTE_LINK_DOWN: {
16193 			/*
16194 			 * We are writer. ill / phyint / ipsq assocs stable.
16195 			 * The RUNNING flag reflects the state of the link.
16196 			 */
16197 			phyint_t *phyint = ill->ill_phyint;
16198 			uint64_t new_phyint_flags;
16199 			boolean_t changed = B_FALSE;
16200 			boolean_t went_up;
16201 
16202 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16203 			mutex_enter(&phyint->phyint_lock);
16204 
16205 			new_phyint_flags = went_up ?
16206 			    phyint->phyint_flags | PHYI_RUNNING :
16207 			    phyint->phyint_flags & ~PHYI_RUNNING;
16208 
16209 			if (IS_IPMP(ill)) {
16210 				new_phyint_flags = went_up ?
16211 				    new_phyint_flags & ~PHYI_FAILED :
16212 				    new_phyint_flags | PHYI_FAILED;
16213 			}
16214 
16215 			if (new_phyint_flags != phyint->phyint_flags) {
16216 				phyint->phyint_flags = new_phyint_flags;
16217 				changed = B_TRUE;
16218 			}
16219 			mutex_exit(&phyint->phyint_lock);
16220 			/*
16221 			 * ill_restart_dad handles the DAD restart and routing
16222 			 * socket notification logic.
16223 			 */
16224 			if (changed) {
16225 				ill_restart_dad(phyint->phyint_illv4, went_up);
16226 				ill_restart_dad(phyint->phyint_illv6, went_up);
16227 			}
16228 			break;
16229 		}
16230 		case DL_NOTE_PROMISC_ON_PHYS: {
16231 			phyint_t *phyint = ill->ill_phyint;
16232 
16233 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16234 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16235 			mutex_enter(&phyint->phyint_lock);
16236 			phyint->phyint_flags |= PHYI_PROMISC;
16237 			mutex_exit(&phyint->phyint_lock);
16238 			break;
16239 		}
16240 		case DL_NOTE_PROMISC_OFF_PHYS: {
16241 			phyint_t *phyint = ill->ill_phyint;
16242 
16243 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16244 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16245 			mutex_enter(&phyint->phyint_lock);
16246 			phyint->phyint_flags &= ~PHYI_PROMISC;
16247 			mutex_exit(&phyint->phyint_lock);
16248 			break;
16249 		}
16250 		case DL_NOTE_CAPAB_RENEG:
16251 			/*
16252 			 * Something changed on the driver side.
16253 			 * It wants us to renegotiate the capabilities
16254 			 * on this ill. One possible cause is the aggregation
16255 			 * interface under us where a port got added or
16256 			 * went away.
16257 			 *
16258 			 * If the capability negotiation is already done
16259 			 * or is in progress, reset the capabilities and
16260 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16261 			 * so that when the ack comes back, we can start
16262 			 * the renegotiation process.
16263 			 *
16264 			 * Note that if ill_capab_reneg is already B_TRUE
16265 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16266 			 * the capability resetting request has been sent
16267 			 * and the renegotiation has not been started yet;
16268 			 * nothing needs to be done in this case.
16269 			 */
16270 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16271 			ill_capability_reset(ill, B_TRUE);
16272 			ipsq_current_finish(ipsq);
16273 			break;
16274 		default:
16275 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16276 			    "type 0x%x for DL_NOTIFY_IND\n",
16277 			    notify->dl_notification));
16278 			break;
16279 		}
16280 
16281 		/*
16282 		 * As this is an asynchronous operation, we
16283 		 * should not call ill_dlpi_done
16284 		 */
16285 		break;
16286 	}
16287 	case DL_NOTIFY_ACK: {
16288 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16289 
16290 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16291 			ill->ill_note_link = 1;
16292 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16293 		break;
16294 	}
16295 	case DL_PHYS_ADDR_ACK: {
16296 		/*
16297 		 * As part of plumbing the interface via SIOCSLIFNAME,
16298 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16299 		 * whose answers we receive here.  As each answer is received,
16300 		 * we call ill_dlpi_done() to dispatch the next request as
16301 		 * we're processing the current one.  Once all answers have
16302 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16303 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16304 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16305 		 * available, but we know the ioctl is pending on ill_wq.)
16306 		 */
16307 		uint_t	paddrlen, paddroff;
16308 		uint8_t	*addr;
16309 
16310 		paddrreq = ill->ill_phys_addr_pend;
16311 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16312 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16313 		addr = mp->b_rptr + paddroff;
16314 
16315 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16316 		if (paddrreq == DL_IPV6_TOKEN) {
16317 			/*
16318 			 * bcopy to low-order bits of ill_token
16319 			 *
16320 			 * XXX Temporary hack - currently, all known tokens
16321 			 * are 64 bits, so I'll cheat for the moment.
16322 			 */
16323 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
16324 			ill->ill_token_length = paddrlen;
16325 			break;
16326 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16327 			ASSERT(ill->ill_nd_lla_mp == NULL);
16328 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16329 			mp = NULL;
16330 			break;
16331 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
16332 			ASSERT(ill->ill_dest_addr_mp == NULL);
16333 			ill->ill_dest_addr_mp = mp;
16334 			ill->ill_dest_addr = addr;
16335 			mp = NULL;
16336 			if (ill->ill_isv6) {
16337 				ill_setdesttoken(ill);
16338 				ipif_setdestlinklocal(ill->ill_ipif);
16339 			}
16340 			break;
16341 		}
16342 
16343 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16344 		ASSERT(ill->ill_phys_addr_mp == NULL);
16345 		if (!ill->ill_ifname_pending)
16346 			break;
16347 		ill->ill_ifname_pending = 0;
16348 		if (!ioctl_aborted)
16349 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16350 		if (mp1 != NULL) {
16351 			ASSERT(connp == NULL);
16352 			q = ill->ill_wq;
16353 		}
16354 		/*
16355 		 * If any error acks received during the plumbing sequence,
16356 		 * ill_ifname_pending_err will be set. Break out and send up
16357 		 * the error to the pending ioctl.
16358 		 */
16359 		if (ill->ill_ifname_pending_err != 0) {
16360 			err = ill->ill_ifname_pending_err;
16361 			ill->ill_ifname_pending_err = 0;
16362 			break;
16363 		}
16364 
16365 		ill->ill_phys_addr_mp = mp;
16366 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
16367 		mp = NULL;
16368 
16369 		/*
16370 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
16371 		 * provider doesn't support physical addresses.  We check both
16372 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
16373 		 * not have physical addresses, but historically adversises a
16374 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
16375 		 * its DL_PHYS_ADDR_ACK.
16376 		 */
16377 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
16378 			ill->ill_phys_addr = NULL;
16379 		} else if (paddrlen != ill->ill_phys_addr_length) {
16380 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16381 			    paddrlen, ill->ill_phys_addr_length));
16382 			err = EINVAL;
16383 			break;
16384 		}
16385 
16386 		if (ill->ill_nd_lla_mp == NULL) {
16387 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16388 				err = ENOMEM;
16389 				break;
16390 			}
16391 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16392 		}
16393 
16394 		if (ill->ill_isv6) {
16395 			ill_setdefaulttoken(ill);
16396 			ipif_setlinklocal(ill->ill_ipif);
16397 		}
16398 		break;
16399 	}
16400 	case DL_OK_ACK:
16401 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16402 		    dl_primstr((int)dloa->dl_correct_primitive),
16403 		    dloa->dl_correct_primitive));
16404 		switch (dloa->dl_correct_primitive) {
16405 		case DL_ENABMULTI_REQ:
16406 		case DL_DISABMULTI_REQ:
16407 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16408 			break;
16409 		case DL_PROMISCON_REQ:
16410 		case DL_PROMISCOFF_REQ:
16411 		case DL_UNBIND_REQ:
16412 		case DL_ATTACH_REQ:
16413 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16414 			break;
16415 		}
16416 		break;
16417 	default:
16418 		break;
16419 	}
16420 
16421 	freemsg(mp);
16422 	if (mp1 == NULL)
16423 		return;
16424 
16425 	/*
16426 	 * The operation must complete without EINPROGRESS since
16427 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16428 	 * the operation will be stuck forever inside the IPSQ.
16429 	 */
16430 	ASSERT(err != EINPROGRESS);
16431 
16432 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16433 	case 0:
16434 		ipsq_current_finish(ipsq);
16435 		break;
16436 
16437 	case SIOCSLIFNAME:
16438 	case IF_UNITSEL: {
16439 		ill_t *ill_other = ILL_OTHER(ill);
16440 
16441 		/*
16442 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16443 		 * ill has a peer which is in an IPMP group, then place ill
16444 		 * into the same group.  One catch: although ifconfig plumbs
16445 		 * the appropriate IPMP meta-interface prior to plumbing this
16446 		 * ill, it is possible for multiple ifconfig applications to
16447 		 * race (or for another application to adjust plumbing), in
16448 		 * which case the IPMP meta-interface we need will be missing.
16449 		 * If so, kick the phyint out of the group.
16450 		 */
16451 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16452 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16453 			ipmp_illgrp_t	*illg;
16454 
16455 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16456 			if (illg == NULL)
16457 				ipmp_phyint_leave_grp(ill->ill_phyint);
16458 			else
16459 				ipmp_ill_join_illgrp(ill, illg);
16460 		}
16461 
16462 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16463 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16464 		else
16465 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16466 		break;
16467 	}
16468 	case SIOCLIFADDIF:
16469 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16470 		break;
16471 
16472 	default:
16473 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16474 		break;
16475 	}
16476 }
16477 
16478 /*
16479  * ip_rput_other is called by ip_rput to handle messages modifying the global
16480  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
16481  */
16482 /* ARGSUSED */
16483 void
16484 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16485 {
16486 	ill_t		*ill = q->q_ptr;
16487 	struct iocblk	*iocp;
16488 
16489 	ip1dbg(("ip_rput_other "));
16490 	if (ipsq != NULL) {
16491 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16492 		ASSERT(ipsq->ipsq_xop ==
16493 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16494 	}
16495 
16496 	switch (mp->b_datap->db_type) {
16497 	case M_ERROR:
16498 	case M_HANGUP:
16499 		/*
16500 		 * The device has a problem.  We force the ILL down.  It can
16501 		 * be brought up again manually using SIOCSIFFLAGS (via
16502 		 * ifconfig or equivalent).
16503 		 */
16504 		ASSERT(ipsq != NULL);
16505 		if (mp->b_rptr < mp->b_wptr)
16506 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16507 		if (ill->ill_error == 0)
16508 			ill->ill_error = ENXIO;
16509 		if (!ill_down_start(q, mp))
16510 			return;
16511 		ipif_all_down_tail(ipsq, q, mp, NULL);
16512 		break;
16513 	case M_IOCNAK: {
16514 		iocp = (struct iocblk *)mp->b_rptr;
16515 
16516 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
16517 		/*
16518 		 * If this was the first attempt, turn off the fastpath
16519 		 * probing.
16520 		 */
16521 		mutex_enter(&ill->ill_lock);
16522 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16523 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
16524 			mutex_exit(&ill->ill_lock);
16525 			ill_fastpath_nack(ill);
16526 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
16527 			    ill->ill_name));
16528 		} else {
16529 			mutex_exit(&ill->ill_lock);
16530 		}
16531 		freemsg(mp);
16532 		break;
16533 	}
16534 	default:
16535 		ASSERT(0);
16536 		break;
16537 	}
16538 }
16539 
16540 /*
16541  * NOTE : This function does not ire_refrele the ire argument passed in.
16542  *
16543  * IPQoS notes
16544  * IP policy is invoked twice for a forwarded packet, once on the read side
16545  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16546  * enabled. An additional parameter, in_ill, has been added for this purpose.
16547  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16548  * because ip_mroute drops this information.
16549  *
16550  */
16551 void
16552 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16553 {
16554 	uint32_t	old_pkt_len;
16555 	uint32_t	pkt_len;
16556 	queue_t	*q;
16557 	uint32_t	sum;
16558 #define	rptr	((uchar_t *)ipha)
16559 	uint32_t	max_frag;
16560 	uint32_t	ill_index;
16561 	ill_t		*out_ill;
16562 	mib2_ipIfStatsEntry_t *mibptr;
16563 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16564 
16565 	/* Get the ill_index of the incoming ILL */
16566 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16567 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16568 
16569 	/* Initiate Read side IPPF processing */
16570 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16571 		ip_process(IPP_FWD_IN, &mp, ill_index);
16572 		if (mp == NULL) {
16573 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16574 			    "during IPPF processing\n"));
16575 			return;
16576 		}
16577 	}
16578 
16579 	/* Adjust the checksum to reflect the ttl decrement. */
16580 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16581 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16582 
16583 	if (ipha->ipha_ttl-- <= 1) {
16584 		if (ip_csum_hdr(ipha)) {
16585 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16586 			goto drop_pkt;
16587 		}
16588 		/*
16589 		 * Note: ire_stq this will be NULL for multicast
16590 		 * datagrams using the long path through arp (the IRE
16591 		 * is not an IRE_CACHE). This should not cause
16592 		 * problems since we don't generate ICMP errors for
16593 		 * multicast packets.
16594 		 */
16595 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16596 		q = ire->ire_stq;
16597 		if (q != NULL) {
16598 			/* Sent by forwarding path, and router is global zone */
16599 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16600 			    GLOBAL_ZONEID, ipst);
16601 		} else
16602 			freemsg(mp);
16603 		return;
16604 	}
16605 
16606 	/*
16607 	 * Don't forward if the interface is down
16608 	 */
16609 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16610 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16611 		ip2dbg(("ip_rput_forward:interface is down\n"));
16612 		goto drop_pkt;
16613 	}
16614 
16615 	/* Get the ill_index of the outgoing ILL */
16616 	out_ill = ire_to_ill(ire);
16617 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16618 
16619 	DTRACE_PROBE4(ip4__forwarding__start,
16620 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16621 
16622 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16623 	    ipst->ips_ipv4firewall_forwarding,
16624 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16625 
16626 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16627 
16628 	if (mp == NULL)
16629 		return;
16630 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16631 
16632 	if (is_system_labeled()) {
16633 		mblk_t *mp1;
16634 
16635 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16636 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16637 			goto drop_pkt;
16638 		}
16639 		/* Size may have changed */
16640 		mp = mp1;
16641 		ipha = (ipha_t *)mp->b_rptr;
16642 		pkt_len = ntohs(ipha->ipha_length);
16643 	}
16644 
16645 	/* Check if there are options to update */
16646 	if (!IS_SIMPLE_IPH(ipha)) {
16647 		if (ip_csum_hdr(ipha)) {
16648 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16649 			goto drop_pkt;
16650 		}
16651 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16652 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16653 			return;
16654 		}
16655 
16656 		ipha->ipha_hdr_checksum = 0;
16657 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16658 	}
16659 	max_frag = ire->ire_max_frag;
16660 	if (pkt_len > max_frag) {
16661 		/*
16662 		 * It needs fragging on its way out.  We haven't
16663 		 * verified the header checksum yet.  Since we
16664 		 * are going to put a surely good checksum in the
16665 		 * outgoing header, we have to make sure that it
16666 		 * was good coming in.
16667 		 */
16668 		if (ip_csum_hdr(ipha)) {
16669 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16670 			goto drop_pkt;
16671 		}
16672 		/* Initiate Write side IPPF processing */
16673 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16674 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16675 			if (mp == NULL) {
16676 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16677 				    " during IPPF processing\n"));
16678 				return;
16679 			}
16680 		}
16681 		/*
16682 		 * Handle labeled packet resizing.
16683 		 *
16684 		 * If we have added a label, inform ip_wput_frag() of its
16685 		 * effect on the MTU for ICMP messages.
16686 		 */
16687 		if (pkt_len > old_pkt_len) {
16688 			uint32_t secopt_size;
16689 
16690 			secopt_size = pkt_len - old_pkt_len;
16691 			if (secopt_size < max_frag)
16692 				max_frag -= secopt_size;
16693 		}
16694 
16695 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16696 		    GLOBAL_ZONEID, ipst, NULL);
16697 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16698 		return;
16699 	}
16700 
16701 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16702 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16703 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16704 	    ipst->ips_ipv4firewall_physical_out,
16705 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16706 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16707 	if (mp == NULL)
16708 		return;
16709 
16710 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16711 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16712 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16713 	/* ip_xmit_v4 always consumes the packet */
16714 	return;
16715 
16716 drop_pkt:;
16717 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16718 	freemsg(mp);
16719 #undef	rptr
16720 }
16721 
16722 void
16723 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16724 {
16725 	ire_t	*ire;
16726 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16727 
16728 	ASSERT(!ipif->ipif_isv6);
16729 	/*
16730 	 * Find an IRE which matches the destination and the outgoing
16731 	 * queue in the cache table. All we need is an IRE_CACHE which
16732 	 * is pointing at ipif->ipif_ill.
16733 	 */
16734 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16735 		dst = ipif->ipif_pp_dst_addr;
16736 
16737 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16738 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16739 	if (ire == NULL) {
16740 		/*
16741 		 * Mark this packet to make it be delivered to
16742 		 * ip_rput_forward after the new ire has been
16743 		 * created.
16744 		 */
16745 		mp->b_prev = NULL;
16746 		mp->b_next = mp;
16747 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16748 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16749 	} else {
16750 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16751 		IRE_REFRELE(ire);
16752 	}
16753 }
16754 
16755 /* Update any source route, record route or timestamp options */
16756 static int
16757 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16758 {
16759 	ipoptp_t	opts;
16760 	uchar_t		*opt;
16761 	uint8_t		optval;
16762 	uint8_t		optlen;
16763 	ipaddr_t	dst;
16764 	uint32_t	ts;
16765 	ire_t		*dst_ire = NULL;
16766 	ire_t		*tmp_ire = NULL;
16767 	timestruc_t	now;
16768 
16769 	ip2dbg(("ip_rput_forward_options\n"));
16770 	dst = ipha->ipha_dst;
16771 	for (optval = ipoptp_first(&opts, ipha);
16772 	    optval != IPOPT_EOL;
16773 	    optval = ipoptp_next(&opts)) {
16774 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16775 		opt = opts.ipoptp_cur;
16776 		optlen = opts.ipoptp_len;
16777 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16778 		    optval, opts.ipoptp_len));
16779 		switch (optval) {
16780 			uint32_t off;
16781 		case IPOPT_SSRR:
16782 		case IPOPT_LSRR:
16783 			/* Check if adminstratively disabled */
16784 			if (!ipst->ips_ip_forward_src_routed) {
16785 				if (ire->ire_stq != NULL) {
16786 					/*
16787 					 * Sent by forwarding path, and router
16788 					 * is global zone
16789 					 */
16790 					icmp_unreachable(ire->ire_stq, mp,
16791 					    ICMP_SOURCE_ROUTE_FAILED,
16792 					    GLOBAL_ZONEID, ipst);
16793 				} else {
16794 					ip0dbg(("ip_rput_forward_options: "
16795 					    "unable to send unreach\n"));
16796 					freemsg(mp);
16797 				}
16798 				return (-1);
16799 			}
16800 
16801 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16802 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16803 			if (dst_ire == NULL) {
16804 				/*
16805 				 * Must be partial since ip_rput_options
16806 				 * checked for strict.
16807 				 */
16808 				break;
16809 			}
16810 			off = opt[IPOPT_OFFSET];
16811 			off--;
16812 		redo_srr:
16813 			if (optlen < IP_ADDR_LEN ||
16814 			    off > optlen - IP_ADDR_LEN) {
16815 				/* End of source route */
16816 				ip1dbg((
16817 				    "ip_rput_forward_options: end of SR\n"));
16818 				ire_refrele(dst_ire);
16819 				break;
16820 			}
16821 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16822 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16823 			    IP_ADDR_LEN);
16824 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16825 			    ntohl(dst)));
16826 
16827 			/*
16828 			 * Check if our address is present more than
16829 			 * once as consecutive hops in source route.
16830 			 */
16831 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16832 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16833 			if (tmp_ire != NULL) {
16834 				ire_refrele(tmp_ire);
16835 				off += IP_ADDR_LEN;
16836 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16837 				goto redo_srr;
16838 			}
16839 			ipha->ipha_dst = dst;
16840 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16841 			ire_refrele(dst_ire);
16842 			break;
16843 		case IPOPT_RR:
16844 			off = opt[IPOPT_OFFSET];
16845 			off--;
16846 			if (optlen < IP_ADDR_LEN ||
16847 			    off > optlen - IP_ADDR_LEN) {
16848 				/* No more room - ignore */
16849 				ip1dbg((
16850 				    "ip_rput_forward_options: end of RR\n"));
16851 				break;
16852 			}
16853 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16854 			    IP_ADDR_LEN);
16855 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16856 			break;
16857 		case IPOPT_TS:
16858 			/* Insert timestamp if there is room */
16859 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16860 			case IPOPT_TS_TSONLY:
16861 				off = IPOPT_TS_TIMELEN;
16862 				break;
16863 			case IPOPT_TS_PRESPEC:
16864 			case IPOPT_TS_PRESPEC_RFC791:
16865 				/* Verify that the address matched */
16866 				off = opt[IPOPT_OFFSET] - 1;
16867 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16868 				dst_ire = ire_ctable_lookup(dst, 0,
16869 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16870 				    MATCH_IRE_TYPE, ipst);
16871 				if (dst_ire == NULL) {
16872 					/* Not for us */
16873 					break;
16874 				}
16875 				ire_refrele(dst_ire);
16876 				/* FALLTHRU */
16877 			case IPOPT_TS_TSANDADDR:
16878 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16879 				break;
16880 			default:
16881 				/*
16882 				 * ip_*put_options should have already
16883 				 * dropped this packet.
16884 				 */
16885 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16886 				    "unknown IT - bug in ip_rput_options?\n");
16887 				return (0);	/* Keep "lint" happy */
16888 			}
16889 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16890 				/* Increase overflow counter */
16891 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16892 				opt[IPOPT_POS_OV_FLG] =
16893 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16894 				    (off << 4));
16895 				break;
16896 			}
16897 			off = opt[IPOPT_OFFSET] - 1;
16898 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16899 			case IPOPT_TS_PRESPEC:
16900 			case IPOPT_TS_PRESPEC_RFC791:
16901 			case IPOPT_TS_TSANDADDR:
16902 				bcopy(&ire->ire_src_addr,
16903 				    (char *)opt + off, IP_ADDR_LEN);
16904 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16905 				/* FALLTHRU */
16906 			case IPOPT_TS_TSONLY:
16907 				off = opt[IPOPT_OFFSET] - 1;
16908 				/* Compute # of milliseconds since midnight */
16909 				gethrestime(&now);
16910 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16911 				    now.tv_nsec / (NANOSEC / MILLISEC);
16912 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16913 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16914 				break;
16915 			}
16916 			break;
16917 		}
16918 	}
16919 	return (0);
16920 }
16921 
16922 /*
16923  * This is called after processing at least one of AH/ESP headers.
16924  *
16925  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16926  * the actual, physical interface on which the packet was received,
16927  * but, when ip_strict_dst_multihoming is set to 1, could be the
16928  * interface which had the ipha_dst configured when the packet went
16929  * through ip_rput. The ill_index corresponding to the recv_ill
16930  * is saved in ipsec_in_rill_index
16931  *
16932  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16933  * cannot assume "ire" points to valid data for any IPv6 cases.
16934  */
16935 void
16936 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16937 {
16938 	mblk_t *mp;
16939 	ipaddr_t dst;
16940 	in6_addr_t *v6dstp;
16941 	ipha_t *ipha;
16942 	ip6_t *ip6h;
16943 	ipsec_in_t *ii;
16944 	boolean_t ill_need_rele = B_FALSE;
16945 	boolean_t rill_need_rele = B_FALSE;
16946 	boolean_t ire_need_rele = B_FALSE;
16947 	netstack_t	*ns;
16948 	ip_stack_t	*ipst;
16949 
16950 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16951 	ASSERT(ii->ipsec_in_ill_index != 0);
16952 	ns = ii->ipsec_in_ns;
16953 	ASSERT(ii->ipsec_in_ns != NULL);
16954 	ipst = ns->netstack_ip;
16955 
16956 	mp = ipsec_mp->b_cont;
16957 	ASSERT(mp != NULL);
16958 
16959 	if (ill == NULL) {
16960 		ASSERT(recv_ill == NULL);
16961 		/*
16962 		 * We need to get the original queue on which ip_rput_local
16963 		 * or ip_rput_data_v6 was called.
16964 		 */
16965 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16966 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16967 		ill_need_rele = B_TRUE;
16968 
16969 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16970 			recv_ill = ill_lookup_on_ifindex(
16971 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16972 			    NULL, NULL, NULL, NULL, ipst);
16973 			rill_need_rele = B_TRUE;
16974 		} else {
16975 			recv_ill = ill;
16976 		}
16977 
16978 		if ((ill == NULL) || (recv_ill == NULL)) {
16979 			ip0dbg(("ip_fanout_proto_again: interface "
16980 			    "disappeared\n"));
16981 			if (ill != NULL)
16982 				ill_refrele(ill);
16983 			if (recv_ill != NULL)
16984 				ill_refrele(recv_ill);
16985 			freemsg(ipsec_mp);
16986 			return;
16987 		}
16988 	}
16989 
16990 	ASSERT(ill != NULL && recv_ill != NULL);
16991 
16992 	if (mp->b_datap->db_type == M_CTL) {
16993 		/*
16994 		 * AH/ESP is returning the ICMP message after
16995 		 * removing their headers. Fanout again till
16996 		 * it gets to the right protocol.
16997 		 */
16998 		if (ii->ipsec_in_v4) {
16999 			icmph_t *icmph;
17000 			int iph_hdr_length;
17001 			int hdr_length;
17002 
17003 			ipha = (ipha_t *)mp->b_rptr;
17004 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17005 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17006 			ipha = (ipha_t *)&icmph[1];
17007 			hdr_length = IPH_HDR_LENGTH(ipha);
17008 			/*
17009 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17010 			 * Reset the type to M_DATA.
17011 			 */
17012 			mp->b_datap->db_type = M_DATA;
17013 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17014 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17015 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17016 		} else {
17017 			icmp6_t *icmp6;
17018 			int hdr_length;
17019 
17020 			ip6h = (ip6_t *)mp->b_rptr;
17021 			/* Don't call hdr_length_v6() unless you have to. */
17022 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17023 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17024 			else
17025 				hdr_length = IPV6_HDR_LEN;
17026 
17027 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17028 			/*
17029 			 * icmp_inbound_error_fanout_v6 may need to do
17030 			 * pullupmsg.  Reset the type to M_DATA.
17031 			 */
17032 			mp->b_datap->db_type = M_DATA;
17033 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17034 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17035 			    ii->ipsec_in_zoneid);
17036 		}
17037 		if (ill_need_rele)
17038 			ill_refrele(ill);
17039 		if (rill_need_rele)
17040 			ill_refrele(recv_ill);
17041 		return;
17042 	}
17043 
17044 	if (ii->ipsec_in_v4) {
17045 		ipha = (ipha_t *)mp->b_rptr;
17046 		dst = ipha->ipha_dst;
17047 		if (CLASSD(dst)) {
17048 			/*
17049 			 * Multicast has to be delivered to all streams.
17050 			 */
17051 			dst = INADDR_BROADCAST;
17052 		}
17053 
17054 		if (ire == NULL) {
17055 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17056 			    msg_getlabel(mp), ipst);
17057 			if (ire == NULL) {
17058 				if (ill_need_rele)
17059 					ill_refrele(ill);
17060 				if (rill_need_rele)
17061 					ill_refrele(recv_ill);
17062 				ip1dbg(("ip_fanout_proto_again: "
17063 				    "IRE not found"));
17064 				freemsg(ipsec_mp);
17065 				return;
17066 			}
17067 			ire_need_rele = B_TRUE;
17068 		}
17069 
17070 		switch (ipha->ipha_protocol) {
17071 		case IPPROTO_UDP:
17072 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17073 			    recv_ill);
17074 			if (ire_need_rele)
17075 				ire_refrele(ire);
17076 			break;
17077 		case IPPROTO_TCP:
17078 			if (!ire_need_rele)
17079 				IRE_REFHOLD(ire);
17080 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17081 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17082 			IRE_REFRELE(ire);
17083 			if (mp != NULL) {
17084 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17085 				    mp, 1, SQ_PROCESS,
17086 				    SQTAG_IP_PROTO_AGAIN);
17087 			}
17088 			break;
17089 		case IPPROTO_SCTP:
17090 			if (!ire_need_rele)
17091 				IRE_REFHOLD(ire);
17092 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17093 			    ipsec_mp, 0, ill->ill_rq, dst);
17094 			break;
17095 		case IPPROTO_ENCAP:
17096 		case IPPROTO_IPV6:
17097 			if (ip_iptun_input(ipsec_mp, mp, ipha, ill, ire,
17098 			    ill->ill_ipst)) {
17099 				/*
17100 				 * If we made it here, we don't need to worry
17101 				 * about the raw-socket/protocol fanout.
17102 				 */
17103 				if (ire_need_rele)
17104 					ire_refrele(ire);
17105 				break;
17106 			}
17107 			/* else FALLTHRU */
17108 		default:
17109 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17110 			    recv_ill, 0);
17111 			if (ire_need_rele)
17112 				ire_refrele(ire);
17113 			break;
17114 		}
17115 	} else {
17116 		uint32_t rput_flags = 0;
17117 
17118 		ip6h = (ip6_t *)mp->b_rptr;
17119 		v6dstp = &ip6h->ip6_dst;
17120 		/*
17121 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17122 		 * address.
17123 		 *
17124 		 * Currently, we don't store that state in the IPSEC_IN
17125 		 * message, and we may need to.
17126 		 */
17127 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17128 		    IP6_IN_LLMCAST : 0);
17129 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17130 		    NULL, NULL);
17131 	}
17132 	if (ill_need_rele)
17133 		ill_refrele(ill);
17134 	if (rill_need_rele)
17135 		ill_refrele(recv_ill);
17136 }
17137 
17138 /*
17139  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17140  * returns 'true' if there are still fragments left on the queue, in
17141  * which case we restart the timer.
17142  */
17143 void
17144 ill_frag_timer(void *arg)
17145 {
17146 	ill_t	*ill = (ill_t *)arg;
17147 	boolean_t frag_pending;
17148 	ip_stack_t	*ipst = ill->ill_ipst;
17149 	time_t	timeout;
17150 
17151 	mutex_enter(&ill->ill_lock);
17152 	ASSERT(!ill->ill_fragtimer_executing);
17153 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17154 		ill->ill_frag_timer_id = 0;
17155 		mutex_exit(&ill->ill_lock);
17156 		return;
17157 	}
17158 	ill->ill_fragtimer_executing = 1;
17159 	mutex_exit(&ill->ill_lock);
17160 
17161 	if (ill->ill_isv6)
17162 		timeout = ipst->ips_ipv6_frag_timeout;
17163 	else
17164 		timeout = ipst->ips_ip_g_frag_timeout;
17165 
17166 	frag_pending = ill_frag_timeout(ill, timeout);
17167 
17168 	/*
17169 	 * Restart the timer, if we have fragments pending or if someone
17170 	 * wanted us to be scheduled again.
17171 	 */
17172 	mutex_enter(&ill->ill_lock);
17173 	ill->ill_fragtimer_executing = 0;
17174 	ill->ill_frag_timer_id = 0;
17175 	if (frag_pending || ill->ill_fragtimer_needrestart)
17176 		ill_frag_timer_start(ill);
17177 	mutex_exit(&ill->ill_lock);
17178 }
17179 
17180 void
17181 ill_frag_timer_start(ill_t *ill)
17182 {
17183 	ip_stack_t	*ipst = ill->ill_ipst;
17184 	clock_t	timeo_ms;
17185 
17186 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17187 
17188 	/* If the ill is closing or opening don't proceed */
17189 	if (ill->ill_state_flags & ILL_CONDEMNED)
17190 		return;
17191 
17192 	if (ill->ill_fragtimer_executing) {
17193 		/*
17194 		 * ill_frag_timer is currently executing. Just record the
17195 		 * the fact that we want the timer to be restarted.
17196 		 * ill_frag_timer will post a timeout before it returns,
17197 		 * ensuring it will be called again.
17198 		 */
17199 		ill->ill_fragtimer_needrestart = 1;
17200 		return;
17201 	}
17202 
17203 	if (ill->ill_frag_timer_id == 0) {
17204 		if (ill->ill_isv6)
17205 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17206 		else
17207 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17208 		/*
17209 		 * The timer is neither running nor is the timeout handler
17210 		 * executing. Post a timeout so that ill_frag_timer will be
17211 		 * called
17212 		 */
17213 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17214 		    MSEC_TO_TICK(timeo_ms >> 1));
17215 		ill->ill_fragtimer_needrestart = 0;
17216 	}
17217 }
17218 
17219 /*
17220  * This routine is needed for loopback when forwarding multicasts.
17221  *
17222  * IPQoS Notes:
17223  * IPPF processing is done in fanout routines.
17224  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17225  * processing for IPsec packets is done when it comes back in clear.
17226  * NOTE : The callers of this function need to do the ire_refrele for the
17227  *	  ire that is being passed in.
17228  */
17229 void
17230 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17231     ill_t *recv_ill, uint32_t esp_udp_ports)
17232 {
17233 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17234 	ill_t	*ill = (ill_t *)q->q_ptr;
17235 	uint32_t	sum;
17236 	uint32_t	u1;
17237 	uint32_t	u2;
17238 	int		hdr_length;
17239 	boolean_t	mctl_present;
17240 	mblk_t		*first_mp = mp;
17241 	mblk_t		*hada_mp = NULL;
17242 	ipha_t		*inner_ipha;
17243 	ip_stack_t	*ipst;
17244 
17245 	ASSERT(recv_ill != NULL);
17246 	ipst = recv_ill->ill_ipst;
17247 
17248 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17249 	    "ip_rput_locl_start: q %p", q);
17250 
17251 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17252 	ASSERT(ill != NULL);
17253 
17254 #define	rptr	((uchar_t *)ipha)
17255 #define	iphs	((uint16_t *)ipha)
17256 
17257 	/*
17258 	 * no UDP or TCP packet should come here anymore.
17259 	 */
17260 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17261 	    ipha->ipha_protocol != IPPROTO_UDP);
17262 
17263 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17264 	if (mctl_present &&
17265 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17266 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17267 
17268 		/*
17269 		 * It's an IPsec accelerated packet.
17270 		 * Keep a pointer to the data attributes around until
17271 		 * we allocate the ipsec_info_t.
17272 		 */
17273 		IPSECHW_DEBUG(IPSECHW_PKT,
17274 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17275 		hada_mp = first_mp;
17276 		hada_mp->b_cont = NULL;
17277 		/*
17278 		 * Since it is accelerated, it comes directly from
17279 		 * the ill and the data attributes is followed by
17280 		 * the packet data.
17281 		 */
17282 		ASSERT(mp->b_datap->db_type != M_CTL);
17283 		first_mp = mp;
17284 		mctl_present = B_FALSE;
17285 	}
17286 
17287 	/*
17288 	 * IF M_CTL is not present, then ipsec_in_is_secure
17289 	 * should return B_TRUE. There is a case where loopback
17290 	 * packets has an M_CTL in the front with all the
17291 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17292 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17293 	 * packets never comes here, it is safe to ASSERT the
17294 	 * following.
17295 	 */
17296 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17297 
17298 	/*
17299 	 * Also, we should never have an mctl_present if this is an
17300 	 * ESP-in-UDP packet.
17301 	 */
17302 	ASSERT(!mctl_present || !esp_in_udp_packet);
17303 
17304 	/* u1 is # words of IP options */
17305 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17306 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17307 
17308 	/*
17309 	 * Don't verify header checksum if we just removed UDP header or
17310 	 * packet is coming back from AH/ESP.
17311 	 */
17312 	if (!esp_in_udp_packet && !mctl_present) {
17313 		if (u1) {
17314 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17315 				if (hada_mp != NULL)
17316 					freemsg(hada_mp);
17317 				return;
17318 			}
17319 		} else {
17320 			/* Check the IP header checksum.  */
17321 #define	uph	((uint16_t *)ipha)
17322 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17323 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17324 #undef  uph
17325 			/* finish doing IP checksum */
17326 			sum = (sum & 0xFFFF) + (sum >> 16);
17327 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17328 			if (sum && sum != 0xFFFF) {
17329 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17330 				goto drop_pkt;
17331 			}
17332 		}
17333 	}
17334 
17335 	/*
17336 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17337 	 * might be called more than once for secure packets, count only
17338 	 * the first time.
17339 	 */
17340 	if (!mctl_present) {
17341 		UPDATE_IB_PKT_COUNT(ire);
17342 		ire->ire_last_used_time = lbolt;
17343 	}
17344 
17345 	/* Check for fragmentation offset. */
17346 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17347 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17348 	if (u1) {
17349 		/*
17350 		 * We re-assemble fragments before we do the AH/ESP
17351 		 * processing. Thus, M_CTL should not be present
17352 		 * while we are re-assembling.
17353 		 */
17354 		ASSERT(!mctl_present);
17355 		ASSERT(first_mp == mp);
17356 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17357 			return;
17358 
17359 		/*
17360 		 * Make sure that first_mp points back to mp as
17361 		 * the mp we came in with could have changed in
17362 		 * ip_rput_fragment().
17363 		 */
17364 		ipha = (ipha_t *)mp->b_rptr;
17365 		first_mp = mp;
17366 	}
17367 
17368 	/*
17369 	 * Clear hardware checksumming flag as it is currently only
17370 	 * used by TCP and UDP.
17371 	 */
17372 	DB_CKSUMFLAGS(mp) = 0;
17373 
17374 	/* Now we have a complete datagram, destined for this machine. */
17375 	u1 = IPH_HDR_LENGTH(ipha);
17376 	switch (ipha->ipha_protocol) {
17377 	case IPPROTO_ICMP: {
17378 		ire_t		*ire_zone;
17379 		ilm_t		*ilm;
17380 		mblk_t		*mp1;
17381 		zoneid_t	last_zoneid;
17382 		ilm_walker_t	ilw;
17383 
17384 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17385 			ASSERT(ire->ire_type == IRE_BROADCAST);
17386 
17387 			/*
17388 			 * In the multicast case, applications may have joined
17389 			 * the group from different zones, so we need to deliver
17390 			 * the packet to each of them. Loop through the
17391 			 * multicast memberships structures (ilm) on the receive
17392 			 * ill and send a copy of the packet up each matching
17393 			 * one. However, we don't do this for multicasts sent on
17394 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17395 			 * they must stay in the sender's zone.
17396 			 *
17397 			 * ilm_add_v6() ensures that ilms in the same zone are
17398 			 * contiguous in the ill_ilm list. We use this property
17399 			 * to avoid sending duplicates needed when two
17400 			 * applications in the same zone join the same group on
17401 			 * different logical interfaces: we ignore the ilm if
17402 			 * its zoneid is the same as the last matching one.
17403 			 * In addition, the sending of the packet for
17404 			 * ire_zoneid is delayed until all of the other ilms
17405 			 * have been exhausted.
17406 			 */
17407 			last_zoneid = -1;
17408 			ilm = ilm_walker_start(&ilw, recv_ill);
17409 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17410 				if (ipha->ipha_dst != ilm->ilm_addr ||
17411 				    ilm->ilm_zoneid == last_zoneid ||
17412 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17413 				    ilm->ilm_zoneid == ALL_ZONES ||
17414 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17415 					continue;
17416 				mp1 = ip_copymsg(first_mp);
17417 				if (mp1 == NULL)
17418 					continue;
17419 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17420 				    0, sum, mctl_present, B_TRUE,
17421 				    recv_ill, ilm->ilm_zoneid);
17422 				last_zoneid = ilm->ilm_zoneid;
17423 			}
17424 			ilm_walker_finish(&ilw);
17425 		} else if (ire->ire_type == IRE_BROADCAST) {
17426 			/*
17427 			 * In the broadcast case, there may be many zones
17428 			 * which need a copy of the packet delivered to them.
17429 			 * There is one IRE_BROADCAST per broadcast address
17430 			 * and per zone; we walk those using a helper function.
17431 			 * In addition, the sending of the packet for ire is
17432 			 * delayed until all of the other ires have been
17433 			 * processed.
17434 			 */
17435 			IRB_REFHOLD(ire->ire_bucket);
17436 			ire_zone = NULL;
17437 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17438 			    ire)) != NULL) {
17439 				mp1 = ip_copymsg(first_mp);
17440 				if (mp1 == NULL)
17441 					continue;
17442 
17443 				UPDATE_IB_PKT_COUNT(ire_zone);
17444 				ire_zone->ire_last_used_time = lbolt;
17445 				icmp_inbound(q, mp1, B_TRUE, ill,
17446 				    0, sum, mctl_present, B_TRUE,
17447 				    recv_ill, ire_zone->ire_zoneid);
17448 			}
17449 			IRB_REFRELE(ire->ire_bucket);
17450 		}
17451 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17452 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17453 		    ire->ire_zoneid);
17454 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17455 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17456 		return;
17457 	}
17458 	case IPPROTO_IGMP:
17459 		/*
17460 		 * If we are not willing to accept IGMP packets in clear,
17461 		 * then check with global policy.
17462 		 */
17463 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17464 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17465 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17466 			if (first_mp == NULL)
17467 				return;
17468 		}
17469 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17470 			freemsg(first_mp);
17471 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17472 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17473 			return;
17474 		}
17475 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17476 			/* Bad packet - discarded by igmp_input */
17477 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17478 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17479 			if (mctl_present)
17480 				freeb(first_mp);
17481 			return;
17482 		}
17483 		/*
17484 		 * igmp_input() may have returned the pulled up message.
17485 		 * So first_mp and ipha need to be reinitialized.
17486 		 */
17487 		ipha = (ipha_t *)mp->b_rptr;
17488 		if (mctl_present)
17489 			first_mp->b_cont = mp;
17490 		else
17491 			first_mp = mp;
17492 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17493 		    connf_head != NULL) {
17494 			/* No user-level listener for IGMP packets */
17495 			goto drop_pkt;
17496 		}
17497 		/* deliver to local raw users */
17498 		break;
17499 	case IPPROTO_PIM:
17500 		/*
17501 		 * If we are not willing to accept PIM packets in clear,
17502 		 * then check with global policy.
17503 		 */
17504 		if (ipst->ips_pim_accept_clear_messages == 0) {
17505 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17506 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17507 			if (first_mp == NULL)
17508 				return;
17509 		}
17510 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17511 			freemsg(first_mp);
17512 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17513 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17514 			return;
17515 		}
17516 		if (pim_input(q, mp, ill) != 0) {
17517 			/* Bad packet - discarded by pim_input */
17518 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17519 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17520 			if (mctl_present)
17521 				freeb(first_mp);
17522 			return;
17523 		}
17524 
17525 		/*
17526 		 * pim_input() may have pulled up the message so ipha needs to
17527 		 * be reinitialized.
17528 		 */
17529 		ipha = (ipha_t *)mp->b_rptr;
17530 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17531 		    connf_head != NULL) {
17532 			/* No user-level listener for PIM packets */
17533 			goto drop_pkt;
17534 		}
17535 		/* deliver to local raw users */
17536 		break;
17537 	case IPPROTO_ENCAP:
17538 		/*
17539 		 * Handle self-encapsulated packets (IP-in-IP where
17540 		 * the inner addresses == the outer addresses).
17541 		 */
17542 		hdr_length = IPH_HDR_LENGTH(ipha);
17543 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17544 		    mp->b_wptr) {
17545 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17546 			    sizeof (ipha_t) - mp->b_rptr)) {
17547 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17548 				freemsg(first_mp);
17549 				return;
17550 			}
17551 			ipha = (ipha_t *)mp->b_rptr;
17552 		}
17553 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17554 		/*
17555 		 * Check the sanity of the inner IP header.
17556 		 */
17557 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17558 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17559 			freemsg(first_mp);
17560 			return;
17561 		}
17562 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17563 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17564 			freemsg(first_mp);
17565 			return;
17566 		}
17567 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17568 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17569 			ipsec_in_t *ii;
17570 
17571 			/*
17572 			 * Self-encapsulated tunnel packet. Remove
17573 			 * the outer IP header and fanout again.
17574 			 * We also need to make sure that the inner
17575 			 * header is pulled up until options.
17576 			 */
17577 			mp->b_rptr = (uchar_t *)inner_ipha;
17578 			ipha = inner_ipha;
17579 			hdr_length = IPH_HDR_LENGTH(ipha);
17580 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17581 				if (!pullupmsg(mp, (uchar_t *)ipha +
17582 				    + hdr_length - mp->b_rptr)) {
17583 					freemsg(first_mp);
17584 					return;
17585 				}
17586 				ipha = (ipha_t *)mp->b_rptr;
17587 			}
17588 			if (hdr_length > sizeof (ipha_t)) {
17589 				/* We got options on the inner packet. */
17590 				ipaddr_t dst = ipha->ipha_dst;
17591 
17592 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17593 				    -1) {
17594 					/* Bad options! */
17595 					return;
17596 				}
17597 				if (dst != ipha->ipha_dst) {
17598 					/*
17599 					 * Someone put a source-route in
17600 					 * the inside header of a self-
17601 					 * encapsulated packet.  Drop it
17602 					 * with extreme prejudice and let
17603 					 * the sender know.
17604 					 */
17605 					icmp_unreachable(q, first_mp,
17606 					    ICMP_SOURCE_ROUTE_FAILED,
17607 					    recv_ill->ill_zoneid, ipst);
17608 					return;
17609 				}
17610 			}
17611 			if (!mctl_present) {
17612 				ASSERT(first_mp == mp);
17613 				/*
17614 				 * This means that somebody is sending
17615 				 * Self-encapsualted packets without AH/ESP.
17616 				 * If AH/ESP was present, we would have already
17617 				 * allocated the first_mp.
17618 				 *
17619 				 * Send this packet to find a tunnel endpoint.
17620 				 * if I can't find one, an ICMP
17621 				 * PROTOCOL_UNREACHABLE will get sent.
17622 				 */
17623 				goto fanout;
17624 			}
17625 			/*
17626 			 * We generally store the ill_index if we need to
17627 			 * do IPsec processing as we lose the ill queue when
17628 			 * we come back. But in this case, we never should
17629 			 * have to store the ill_index here as it should have
17630 			 * been stored previously when we processed the
17631 			 * AH/ESP header in this routine or for non-ipsec
17632 			 * cases, we still have the queue. But for some bad
17633 			 * packets from the wire, we can get to IPsec after
17634 			 * this and we better store the index for that case.
17635 			 */
17636 			ill = (ill_t *)q->q_ptr;
17637 			ii = (ipsec_in_t *)first_mp->b_rptr;
17638 			ii->ipsec_in_ill_index =
17639 			    ill->ill_phyint->phyint_ifindex;
17640 			ii->ipsec_in_rill_index =
17641 			    recv_ill->ill_phyint->phyint_ifindex;
17642 			if (ii->ipsec_in_decaps) {
17643 				/*
17644 				 * This packet is self-encapsulated multiple
17645 				 * times. We don't want to recurse infinitely.
17646 				 * To keep it simple, drop the packet.
17647 				 */
17648 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17649 				freemsg(first_mp);
17650 				return;
17651 			}
17652 			ii->ipsec_in_decaps = B_TRUE;
17653 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17654 			    ire);
17655 			return;
17656 		}
17657 		break;
17658 	case IPPROTO_AH:
17659 	case IPPROTO_ESP: {
17660 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17661 
17662 		/*
17663 		 * Fast path for AH/ESP. If this is the first time
17664 		 * we are sending a datagram to AH/ESP, allocate
17665 		 * a IPSEC_IN message and prepend it. Otherwise,
17666 		 * just fanout.
17667 		 */
17668 
17669 		int ipsec_rc;
17670 		ipsec_in_t *ii;
17671 		netstack_t *ns = ipst->ips_netstack;
17672 
17673 		IP_STAT(ipst, ipsec_proto_ahesp);
17674 		if (!mctl_present) {
17675 			ASSERT(first_mp == mp);
17676 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17677 			if (first_mp == NULL) {
17678 				ip1dbg(("ip_proto_input: IPSEC_IN "
17679 				    "allocation failure.\n"));
17680 				freemsg(hada_mp); /* okay ifnull */
17681 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17682 				freemsg(mp);
17683 				return;
17684 			}
17685 			/*
17686 			 * Store the ill_index so that when we come back
17687 			 * from IPsec we ride on the same queue.
17688 			 */
17689 			ill = (ill_t *)q->q_ptr;
17690 			ii = (ipsec_in_t *)first_mp->b_rptr;
17691 			ii->ipsec_in_ill_index =
17692 			    ill->ill_phyint->phyint_ifindex;
17693 			ii->ipsec_in_rill_index =
17694 			    recv_ill->ill_phyint->phyint_ifindex;
17695 			first_mp->b_cont = mp;
17696 			/*
17697 			 * Cache hardware acceleration info.
17698 			 */
17699 			if (hada_mp != NULL) {
17700 				IPSECHW_DEBUG(IPSECHW_PKT,
17701 				    ("ip_rput_local: caching data attr.\n"));
17702 				ii->ipsec_in_accelerated = B_TRUE;
17703 				ii->ipsec_in_da = hada_mp;
17704 				hada_mp = NULL;
17705 			}
17706 		} else {
17707 			ii = (ipsec_in_t *)first_mp->b_rptr;
17708 		}
17709 
17710 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17711 
17712 		if (!ipsec_loaded(ipss)) {
17713 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17714 			    ire->ire_zoneid, ipst);
17715 			return;
17716 		}
17717 
17718 		ns = ipst->ips_netstack;
17719 		/* select inbound SA and have IPsec process the pkt */
17720 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17721 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17722 			boolean_t esp_in_udp_sa;
17723 			if (esph == NULL)
17724 				return;
17725 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17726 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17727 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17728 			    IPSA_F_NATT) != 0);
17729 			/*
17730 			 * The following is a fancy, but quick, way of saying:
17731 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17732 			 *    OR
17733 			 * ESP SA and ESP-in-UDP packet --> drop
17734 			 */
17735 			if (esp_in_udp_sa != esp_in_udp_packet) {
17736 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17737 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17738 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17739 				    &ns->netstack_ipsec->ipsec_dropper);
17740 				return;
17741 			}
17742 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17743 			    first_mp, esph);
17744 		} else {
17745 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17746 			if (ah == NULL)
17747 				return;
17748 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17749 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17750 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17751 			    first_mp, ah);
17752 		}
17753 
17754 		switch (ipsec_rc) {
17755 		case IPSEC_STATUS_SUCCESS:
17756 			break;
17757 		case IPSEC_STATUS_FAILED:
17758 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17759 			/* FALLTHRU */
17760 		case IPSEC_STATUS_PENDING:
17761 			return;
17762 		}
17763 		/* we're done with IPsec processing, send it up */
17764 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17765 		return;
17766 	}
17767 	default:
17768 		break;
17769 	}
17770 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17771 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17772 		    ire->ire_zoneid));
17773 		goto drop_pkt;
17774 	}
17775 	/*
17776 	 * Handle protocols with which IP is less intimate.  There
17777 	 * can be more than one stream bound to a particular
17778 	 * protocol.  When this is the case, each one gets a copy
17779 	 * of any incoming packets.
17780 	 */
17781 fanout:
17782 	ip_fanout_proto(q, first_mp, ill, ipha,
17783 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17784 	    B_TRUE, recv_ill, ire->ire_zoneid);
17785 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17786 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17787 	return;
17788 
17789 drop_pkt:
17790 	freemsg(first_mp);
17791 	if (hada_mp != NULL)
17792 		freeb(hada_mp);
17793 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17794 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17795 #undef	rptr
17796 #undef  iphs
17797 
17798 }
17799 
17800 /*
17801  * Update any source route, record route or timestamp options.
17802  * Check that we are at end of strict source route.
17803  * The options have already been checked for sanity in ip_rput_options().
17804  */
17805 static boolean_t
17806 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17807     ip_stack_t *ipst)
17808 {
17809 	ipoptp_t	opts;
17810 	uchar_t		*opt;
17811 	uint8_t		optval;
17812 	uint8_t		optlen;
17813 	ipaddr_t	dst;
17814 	uint32_t	ts;
17815 	ire_t		*dst_ire;
17816 	timestruc_t	now;
17817 	zoneid_t	zoneid;
17818 	ill_t		*ill;
17819 
17820 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17821 
17822 	ip2dbg(("ip_rput_local_options\n"));
17823 
17824 	for (optval = ipoptp_first(&opts, ipha);
17825 	    optval != IPOPT_EOL;
17826 	    optval = ipoptp_next(&opts)) {
17827 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17828 		opt = opts.ipoptp_cur;
17829 		optlen = opts.ipoptp_len;
17830 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17831 		    optval, optlen));
17832 		switch (optval) {
17833 			uint32_t off;
17834 		case IPOPT_SSRR:
17835 		case IPOPT_LSRR:
17836 			off = opt[IPOPT_OFFSET];
17837 			off--;
17838 			if (optlen < IP_ADDR_LEN ||
17839 			    off > optlen - IP_ADDR_LEN) {
17840 				/* End of source route */
17841 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17842 				break;
17843 			}
17844 			/*
17845 			 * This will only happen if two consecutive entries
17846 			 * in the source route contains our address or if
17847 			 * it is a packet with a loose source route which
17848 			 * reaches us before consuming the whole source route
17849 			 */
17850 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17851 			if (optval == IPOPT_SSRR) {
17852 				goto bad_src_route;
17853 			}
17854 			/*
17855 			 * Hack: instead of dropping the packet truncate the
17856 			 * source route to what has been used by filling the
17857 			 * rest with IPOPT_NOP.
17858 			 */
17859 			opt[IPOPT_OLEN] = (uint8_t)off;
17860 			while (off < optlen) {
17861 				opt[off++] = IPOPT_NOP;
17862 			}
17863 			break;
17864 		case IPOPT_RR:
17865 			off = opt[IPOPT_OFFSET];
17866 			off--;
17867 			if (optlen < IP_ADDR_LEN ||
17868 			    off > optlen - IP_ADDR_LEN) {
17869 				/* No more room - ignore */
17870 				ip1dbg((
17871 				    "ip_rput_local_options: end of RR\n"));
17872 				break;
17873 			}
17874 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17875 			    IP_ADDR_LEN);
17876 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17877 			break;
17878 		case IPOPT_TS:
17879 			/* Insert timestamp if there is romm */
17880 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17881 			case IPOPT_TS_TSONLY:
17882 				off = IPOPT_TS_TIMELEN;
17883 				break;
17884 			case IPOPT_TS_PRESPEC:
17885 			case IPOPT_TS_PRESPEC_RFC791:
17886 				/* Verify that the address matched */
17887 				off = opt[IPOPT_OFFSET] - 1;
17888 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17889 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17890 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17891 				    ipst);
17892 				if (dst_ire == NULL) {
17893 					/* Not for us */
17894 					break;
17895 				}
17896 				ire_refrele(dst_ire);
17897 				/* FALLTHRU */
17898 			case IPOPT_TS_TSANDADDR:
17899 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17900 				break;
17901 			default:
17902 				/*
17903 				 * ip_*put_options should have already
17904 				 * dropped this packet.
17905 				 */
17906 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17907 				    "unknown IT - bug in ip_rput_options?\n");
17908 				return (B_TRUE);	/* Keep "lint" happy */
17909 			}
17910 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17911 				/* Increase overflow counter */
17912 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17913 				opt[IPOPT_POS_OV_FLG] =
17914 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17915 				    (off << 4));
17916 				break;
17917 			}
17918 			off = opt[IPOPT_OFFSET] - 1;
17919 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17920 			case IPOPT_TS_PRESPEC:
17921 			case IPOPT_TS_PRESPEC_RFC791:
17922 			case IPOPT_TS_TSANDADDR:
17923 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17924 				    IP_ADDR_LEN);
17925 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17926 				/* FALLTHRU */
17927 			case IPOPT_TS_TSONLY:
17928 				off = opt[IPOPT_OFFSET] - 1;
17929 				/* Compute # of milliseconds since midnight */
17930 				gethrestime(&now);
17931 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17932 				    now.tv_nsec / (NANOSEC / MILLISEC);
17933 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17934 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17935 				break;
17936 			}
17937 			break;
17938 		}
17939 	}
17940 	return (B_TRUE);
17941 
17942 bad_src_route:
17943 	q = WR(q);
17944 	if (q->q_next != NULL)
17945 		ill = q->q_ptr;
17946 	else
17947 		ill = NULL;
17948 
17949 	/* make sure we clear any indication of a hardware checksum */
17950 	DB_CKSUMFLAGS(mp) = 0;
17951 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17952 	if (zoneid == ALL_ZONES)
17953 		freemsg(mp);
17954 	else
17955 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17956 	return (B_FALSE);
17957 
17958 }
17959 
17960 /*
17961  * Process IP options in an inbound packet.  If an option affects the
17962  * effective destination address, return the next hop address via dstp.
17963  * Returns -1 if something fails in which case an ICMP error has been sent
17964  * and mp freed.
17965  */
17966 static int
17967 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17968     ip_stack_t *ipst)
17969 {
17970 	ipoptp_t	opts;
17971 	uchar_t		*opt;
17972 	uint8_t		optval;
17973 	uint8_t		optlen;
17974 	ipaddr_t	dst;
17975 	intptr_t	code = 0;
17976 	ire_t		*ire = NULL;
17977 	zoneid_t	zoneid;
17978 	ill_t		*ill;
17979 
17980 	ip2dbg(("ip_rput_options\n"));
17981 	dst = ipha->ipha_dst;
17982 	for (optval = ipoptp_first(&opts, ipha);
17983 	    optval != IPOPT_EOL;
17984 	    optval = ipoptp_next(&opts)) {
17985 		opt = opts.ipoptp_cur;
17986 		optlen = opts.ipoptp_len;
17987 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17988 		    optval, optlen));
17989 		/*
17990 		 * Note: we need to verify the checksum before we
17991 		 * modify anything thus this routine only extracts the next
17992 		 * hop dst from any source route.
17993 		 */
17994 		switch (optval) {
17995 			uint32_t off;
17996 		case IPOPT_SSRR:
17997 		case IPOPT_LSRR:
17998 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17999 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18000 			if (ire == NULL) {
18001 				if (optval == IPOPT_SSRR) {
18002 					ip1dbg(("ip_rput_options: not next"
18003 					    " strict source route 0x%x\n",
18004 					    ntohl(dst)));
18005 					code = (char *)&ipha->ipha_dst -
18006 					    (char *)ipha;
18007 					goto param_prob; /* RouterReq's */
18008 				}
18009 				ip2dbg(("ip_rput_options: "
18010 				    "not next source route 0x%x\n",
18011 				    ntohl(dst)));
18012 				break;
18013 			}
18014 			ire_refrele(ire);
18015 
18016 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18017 				ip1dbg((
18018 				    "ip_rput_options: bad option offset\n"));
18019 				code = (char *)&opt[IPOPT_OLEN] -
18020 				    (char *)ipha;
18021 				goto param_prob;
18022 			}
18023 			off = opt[IPOPT_OFFSET];
18024 			off--;
18025 		redo_srr:
18026 			if (optlen < IP_ADDR_LEN ||
18027 			    off > optlen - IP_ADDR_LEN) {
18028 				/* End of source route */
18029 				ip1dbg(("ip_rput_options: end of SR\n"));
18030 				break;
18031 			}
18032 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18033 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18034 			    ntohl(dst)));
18035 
18036 			/*
18037 			 * Check if our address is present more than
18038 			 * once as consecutive hops in source route.
18039 			 * XXX verify per-interface ip_forwarding
18040 			 * for source route?
18041 			 */
18042 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18043 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18044 
18045 			if (ire != NULL) {
18046 				ire_refrele(ire);
18047 				off += IP_ADDR_LEN;
18048 				goto redo_srr;
18049 			}
18050 
18051 			if (dst == htonl(INADDR_LOOPBACK)) {
18052 				ip1dbg(("ip_rput_options: loopback addr in "
18053 				    "source route!\n"));
18054 				goto bad_src_route;
18055 			}
18056 			/*
18057 			 * For strict: verify that dst is directly
18058 			 * reachable.
18059 			 */
18060 			if (optval == IPOPT_SSRR) {
18061 				ire = ire_ftable_lookup(dst, 0, 0,
18062 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18063 				    msg_getlabel(mp),
18064 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18065 				if (ire == NULL) {
18066 					ip1dbg(("ip_rput_options: SSRR not "
18067 					    "directly reachable: 0x%x\n",
18068 					    ntohl(dst)));
18069 					goto bad_src_route;
18070 				}
18071 				ire_refrele(ire);
18072 			}
18073 			/*
18074 			 * Defer update of the offset and the record route
18075 			 * until the packet is forwarded.
18076 			 */
18077 			break;
18078 		case IPOPT_RR:
18079 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18080 				ip1dbg((
18081 				    "ip_rput_options: bad option offset\n"));
18082 				code = (char *)&opt[IPOPT_OLEN] -
18083 				    (char *)ipha;
18084 				goto param_prob;
18085 			}
18086 			break;
18087 		case IPOPT_TS:
18088 			/*
18089 			 * Verify that length >= 5 and that there is either
18090 			 * room for another timestamp or that the overflow
18091 			 * counter is not maxed out.
18092 			 */
18093 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18094 			if (optlen < IPOPT_MINLEN_IT) {
18095 				goto param_prob;
18096 			}
18097 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18098 				ip1dbg((
18099 				    "ip_rput_options: bad option offset\n"));
18100 				code = (char *)&opt[IPOPT_OFFSET] -
18101 				    (char *)ipha;
18102 				goto param_prob;
18103 			}
18104 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18105 			case IPOPT_TS_TSONLY:
18106 				off = IPOPT_TS_TIMELEN;
18107 				break;
18108 			case IPOPT_TS_TSANDADDR:
18109 			case IPOPT_TS_PRESPEC:
18110 			case IPOPT_TS_PRESPEC_RFC791:
18111 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18112 				break;
18113 			default:
18114 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18115 				    (char *)ipha;
18116 				goto param_prob;
18117 			}
18118 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18119 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18120 				/*
18121 				 * No room and the overflow counter is 15
18122 				 * already.
18123 				 */
18124 				goto param_prob;
18125 			}
18126 			break;
18127 		}
18128 	}
18129 
18130 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18131 		*dstp = dst;
18132 		return (0);
18133 	}
18134 
18135 	ip1dbg(("ip_rput_options: error processing IP options."));
18136 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18137 
18138 param_prob:
18139 	q = WR(q);
18140 	if (q->q_next != NULL)
18141 		ill = q->q_ptr;
18142 	else
18143 		ill = NULL;
18144 
18145 	/* make sure we clear any indication of a hardware checksum */
18146 	DB_CKSUMFLAGS(mp) = 0;
18147 	/* Don't know whether this is for non-global or global/forwarding */
18148 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18149 	if (zoneid == ALL_ZONES)
18150 		freemsg(mp);
18151 	else
18152 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18153 	return (-1);
18154 
18155 bad_src_route:
18156 	q = WR(q);
18157 	if (q->q_next != NULL)
18158 		ill = q->q_ptr;
18159 	else
18160 		ill = NULL;
18161 
18162 	/* make sure we clear any indication of a hardware checksum */
18163 	DB_CKSUMFLAGS(mp) = 0;
18164 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18165 	if (zoneid == ALL_ZONES)
18166 		freemsg(mp);
18167 	else
18168 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18169 	return (-1);
18170 }
18171 
18172 /*
18173  * IP & ICMP info in >=14 msg's ...
18174  *  - ip fixed part (mib2_ip_t)
18175  *  - icmp fixed part (mib2_icmp_t)
18176  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18177  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18178  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18179  *  - ipRouteAttributeTable (ip 102)	labeled routes
18180  *  - ip multicast membership (ip_member_t)
18181  *  - ip multicast source filtering (ip_grpsrc_t)
18182  *  - igmp fixed part (struct igmpstat)
18183  *  - multicast routing stats (struct mrtstat)
18184  *  - multicast routing vifs (array of struct vifctl)
18185  *  - multicast routing routes (array of struct mfcctl)
18186  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18187  *					One per ill plus one generic
18188  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18189  *					One per ill plus one generic
18190  *  - ipv6RouteEntry			all IPv6 IREs
18191  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18192  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18193  *  - ipv6AddrEntry			all IPv6 ipifs
18194  *  - ipv6 multicast membership (ipv6_member_t)
18195  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18196  *
18197  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18198  *
18199  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18200  * already filled in by the caller.
18201  * Return value of 0 indicates that no messages were sent and caller
18202  * should free mpctl.
18203  */
18204 int
18205 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18206 {
18207 	ip_stack_t *ipst;
18208 	sctp_stack_t *sctps;
18209 
18210 	if (q->q_next != NULL) {
18211 		ipst = ILLQ_TO_IPST(q);
18212 	} else {
18213 		ipst = CONNQ_TO_IPST(q);
18214 	}
18215 	ASSERT(ipst != NULL);
18216 	sctps = ipst->ips_netstack->netstack_sctp;
18217 
18218 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18219 		return (0);
18220 	}
18221 
18222 	/*
18223 	 * For the purposes of the (broken) packet shell use
18224 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18225 	 * to make TCP and UDP appear first in the list of mib items.
18226 	 * TBD: We could expand this and use it in netstat so that
18227 	 * the kernel doesn't have to produce large tables (connections,
18228 	 * routes, etc) when netstat only wants the statistics or a particular
18229 	 * table.
18230 	 */
18231 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18232 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18233 			return (1);
18234 		}
18235 	}
18236 
18237 	if (level != MIB2_TCP) {
18238 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18239 			return (1);
18240 		}
18241 	}
18242 
18243 	if (level != MIB2_UDP) {
18244 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18245 			return (1);
18246 		}
18247 	}
18248 
18249 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18250 	    ipst)) == NULL) {
18251 		return (1);
18252 	}
18253 
18254 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18255 		return (1);
18256 	}
18257 
18258 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18259 		return (1);
18260 	}
18261 
18262 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18263 		return (1);
18264 	}
18265 
18266 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18267 		return (1);
18268 	}
18269 
18270 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18271 		return (1);
18272 	}
18273 
18274 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18275 		return (1);
18276 	}
18277 
18278 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18279 		return (1);
18280 	}
18281 
18282 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18283 		return (1);
18284 	}
18285 
18286 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18287 		return (1);
18288 	}
18289 
18290 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18291 		return (1);
18292 	}
18293 
18294 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18295 		return (1);
18296 	}
18297 
18298 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18299 		return (1);
18300 	}
18301 
18302 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18303 		return (1);
18304 	}
18305 
18306 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18307 	if (mpctl == NULL)
18308 		return (1);
18309 
18310 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18311 	if (mpctl == NULL)
18312 		return (1);
18313 
18314 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18315 		return (1);
18316 	}
18317 	freemsg(mpctl);
18318 	return (1);
18319 }
18320 
18321 /* Get global (legacy) IPv4 statistics */
18322 static mblk_t *
18323 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18324     ip_stack_t *ipst)
18325 {
18326 	mib2_ip_t		old_ip_mib;
18327 	struct opthdr		*optp;
18328 	mblk_t			*mp2ctl;
18329 
18330 	/*
18331 	 * make a copy of the original message
18332 	 */
18333 	mp2ctl = copymsg(mpctl);
18334 
18335 	/* fixed length IP structure... */
18336 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18337 	optp->level = MIB2_IP;
18338 	optp->name = 0;
18339 	SET_MIB(old_ip_mib.ipForwarding,
18340 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18341 	SET_MIB(old_ip_mib.ipDefaultTTL,
18342 	    (uint32_t)ipst->ips_ip_def_ttl);
18343 	SET_MIB(old_ip_mib.ipReasmTimeout,
18344 	    ipst->ips_ip_g_frag_timeout);
18345 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18346 	    sizeof (mib2_ipAddrEntry_t));
18347 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18348 	    sizeof (mib2_ipRouteEntry_t));
18349 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18350 	    sizeof (mib2_ipNetToMediaEntry_t));
18351 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18352 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18353 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18354 	    sizeof (mib2_ipAttributeEntry_t));
18355 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18356 
18357 	/*
18358 	 * Grab the statistics from the new IP MIB
18359 	 */
18360 	SET_MIB(old_ip_mib.ipInReceives,
18361 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18362 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18363 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18364 	SET_MIB(old_ip_mib.ipForwDatagrams,
18365 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18366 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18367 	    ipmib->ipIfStatsInUnknownProtos);
18368 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18369 	SET_MIB(old_ip_mib.ipInDelivers,
18370 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18371 	SET_MIB(old_ip_mib.ipOutRequests,
18372 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18373 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18374 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18375 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18376 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18377 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18378 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18379 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18380 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18381 
18382 	/* ipRoutingDiscards is not being used */
18383 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18384 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18385 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18386 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18387 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18388 	    ipmib->ipIfStatsReasmDuplicates);
18389 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18390 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18391 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18392 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18393 	SET_MIB(old_ip_mib.rawipInOverflows,
18394 	    ipmib->rawipIfStatsInOverflows);
18395 
18396 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18397 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18398 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18399 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18400 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18401 	    ipmib->ipIfStatsOutSwitchIPVersion);
18402 
18403 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18404 	    (int)sizeof (old_ip_mib))) {
18405 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18406 		    (uint_t)sizeof (old_ip_mib)));
18407 	}
18408 
18409 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18410 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18411 	    (int)optp->level, (int)optp->name, (int)optp->len));
18412 	qreply(q, mpctl);
18413 	return (mp2ctl);
18414 }
18415 
18416 /* Per interface IPv4 statistics */
18417 static mblk_t *
18418 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18419 {
18420 	struct opthdr		*optp;
18421 	mblk_t			*mp2ctl;
18422 	ill_t			*ill;
18423 	ill_walk_context_t	ctx;
18424 	mblk_t			*mp_tail = NULL;
18425 	mib2_ipIfStatsEntry_t	global_ip_mib;
18426 
18427 	/*
18428 	 * Make a copy of the original message
18429 	 */
18430 	mp2ctl = copymsg(mpctl);
18431 
18432 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18433 	optp->level = MIB2_IP;
18434 	optp->name = MIB2_IP_TRAFFIC_STATS;
18435 	/* Include "unknown interface" ip_mib */
18436 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18437 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18438 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18439 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18440 	    (ipst->ips_ip_g_forward ? 1 : 2));
18441 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18442 	    (uint32_t)ipst->ips_ip_def_ttl);
18443 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18444 	    sizeof (mib2_ipIfStatsEntry_t));
18445 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18446 	    sizeof (mib2_ipAddrEntry_t));
18447 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18448 	    sizeof (mib2_ipRouteEntry_t));
18449 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18450 	    sizeof (mib2_ipNetToMediaEntry_t));
18451 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18452 	    sizeof (ip_member_t));
18453 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18454 	    sizeof (ip_grpsrc_t));
18455 
18456 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18457 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18458 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18459 		    "failed to allocate %u bytes\n",
18460 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18461 	}
18462 
18463 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18464 
18465 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18466 	ill = ILL_START_WALK_V4(&ctx, ipst);
18467 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18468 		ill->ill_ip_mib->ipIfStatsIfIndex =
18469 		    ill->ill_phyint->phyint_ifindex;
18470 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18471 		    (ipst->ips_ip_g_forward ? 1 : 2));
18472 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18473 		    (uint32_t)ipst->ips_ip_def_ttl);
18474 
18475 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18476 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18477 		    (char *)ill->ill_ip_mib,
18478 		    (int)sizeof (*ill->ill_ip_mib))) {
18479 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18480 			    "failed to allocate %u bytes\n",
18481 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18482 		}
18483 	}
18484 	rw_exit(&ipst->ips_ill_g_lock);
18485 
18486 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18487 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18488 	    "level %d, name %d, len %d\n",
18489 	    (int)optp->level, (int)optp->name, (int)optp->len));
18490 	qreply(q, mpctl);
18491 
18492 	if (mp2ctl == NULL)
18493 		return (NULL);
18494 
18495 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18496 }
18497 
18498 /* Global IPv4 ICMP statistics */
18499 static mblk_t *
18500 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18501 {
18502 	struct opthdr		*optp;
18503 	mblk_t			*mp2ctl;
18504 
18505 	/*
18506 	 * Make a copy of the original message
18507 	 */
18508 	mp2ctl = copymsg(mpctl);
18509 
18510 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18511 	optp->level = MIB2_ICMP;
18512 	optp->name = 0;
18513 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18514 	    (int)sizeof (ipst->ips_icmp_mib))) {
18515 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18516 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18517 	}
18518 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18519 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18520 	    (int)optp->level, (int)optp->name, (int)optp->len));
18521 	qreply(q, mpctl);
18522 	return (mp2ctl);
18523 }
18524 
18525 /* Global IPv4 IGMP statistics */
18526 static mblk_t *
18527 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18528 {
18529 	struct opthdr		*optp;
18530 	mblk_t			*mp2ctl;
18531 
18532 	/*
18533 	 * make a copy of the original message
18534 	 */
18535 	mp2ctl = copymsg(mpctl);
18536 
18537 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18538 	optp->level = EXPER_IGMP;
18539 	optp->name = 0;
18540 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18541 	    (int)sizeof (ipst->ips_igmpstat))) {
18542 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18543 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18544 	}
18545 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18546 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18547 	    (int)optp->level, (int)optp->name, (int)optp->len));
18548 	qreply(q, mpctl);
18549 	return (mp2ctl);
18550 }
18551 
18552 /* Global IPv4 Multicast Routing statistics */
18553 static mblk_t *
18554 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18555 {
18556 	struct opthdr		*optp;
18557 	mblk_t			*mp2ctl;
18558 
18559 	/*
18560 	 * make a copy of the original message
18561 	 */
18562 	mp2ctl = copymsg(mpctl);
18563 
18564 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18565 	optp->level = EXPER_DVMRP;
18566 	optp->name = 0;
18567 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18568 		ip0dbg(("ip_mroute_stats: failed\n"));
18569 	}
18570 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18571 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18572 	    (int)optp->level, (int)optp->name, (int)optp->len));
18573 	qreply(q, mpctl);
18574 	return (mp2ctl);
18575 }
18576 
18577 /* IPv4 address information */
18578 static mblk_t *
18579 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18580 {
18581 	struct opthdr		*optp;
18582 	mblk_t			*mp2ctl;
18583 	mblk_t			*mp_tail = NULL;
18584 	ill_t			*ill;
18585 	ipif_t			*ipif;
18586 	uint_t			bitval;
18587 	mib2_ipAddrEntry_t	mae;
18588 	zoneid_t		zoneid;
18589 	ill_walk_context_t ctx;
18590 
18591 	/*
18592 	 * make a copy of the original message
18593 	 */
18594 	mp2ctl = copymsg(mpctl);
18595 
18596 	/* ipAddrEntryTable */
18597 
18598 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18599 	optp->level = MIB2_IP;
18600 	optp->name = MIB2_IP_ADDR;
18601 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18602 
18603 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18604 	ill = ILL_START_WALK_V4(&ctx, ipst);
18605 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18606 		for (ipif = ill->ill_ipif; ipif != NULL;
18607 		    ipif = ipif->ipif_next) {
18608 			if (ipif->ipif_zoneid != zoneid &&
18609 			    ipif->ipif_zoneid != ALL_ZONES)
18610 				continue;
18611 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18612 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18613 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18614 
18615 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18616 			    OCTET_LENGTH);
18617 			mae.ipAdEntIfIndex.o_length =
18618 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18619 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18620 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18621 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18622 			mae.ipAdEntInfo.ae_subnet_len =
18623 			    ip_mask_to_plen(ipif->ipif_net_mask);
18624 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18625 			for (bitval = 1;
18626 			    bitval &&
18627 			    !(bitval & ipif->ipif_brd_addr);
18628 			    bitval <<= 1)
18629 				noop;
18630 			mae.ipAdEntBcastAddr = bitval;
18631 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18632 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18633 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18634 			mae.ipAdEntInfo.ae_broadcast_addr =
18635 			    ipif->ipif_brd_addr;
18636 			mae.ipAdEntInfo.ae_pp_dst_addr =
18637 			    ipif->ipif_pp_dst_addr;
18638 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18639 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18640 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18641 
18642 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18643 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18644 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18645 				    "allocate %u bytes\n",
18646 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18647 			}
18648 		}
18649 	}
18650 	rw_exit(&ipst->ips_ill_g_lock);
18651 
18652 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18653 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18654 	    (int)optp->level, (int)optp->name, (int)optp->len));
18655 	qreply(q, mpctl);
18656 	return (mp2ctl);
18657 }
18658 
18659 /* IPv6 address information */
18660 static mblk_t *
18661 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18662 {
18663 	struct opthdr		*optp;
18664 	mblk_t			*mp2ctl;
18665 	mblk_t			*mp_tail = NULL;
18666 	ill_t			*ill;
18667 	ipif_t			*ipif;
18668 	mib2_ipv6AddrEntry_t	mae6;
18669 	zoneid_t		zoneid;
18670 	ill_walk_context_t	ctx;
18671 
18672 	/*
18673 	 * make a copy of the original message
18674 	 */
18675 	mp2ctl = copymsg(mpctl);
18676 
18677 	/* ipv6AddrEntryTable */
18678 
18679 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18680 	optp->level = MIB2_IP6;
18681 	optp->name = MIB2_IP6_ADDR;
18682 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18683 
18684 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18685 	ill = ILL_START_WALK_V6(&ctx, ipst);
18686 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18687 		for (ipif = ill->ill_ipif; ipif != NULL;
18688 		    ipif = ipif->ipif_next) {
18689 			if (ipif->ipif_zoneid != zoneid &&
18690 			    ipif->ipif_zoneid != ALL_ZONES)
18691 				continue;
18692 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18693 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18694 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18695 
18696 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18697 			    OCTET_LENGTH);
18698 			mae6.ipv6AddrIfIndex.o_length =
18699 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18700 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18701 			mae6.ipv6AddrPfxLength =
18702 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18703 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18704 			mae6.ipv6AddrInfo.ae_subnet_len =
18705 			    mae6.ipv6AddrPfxLength;
18706 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18707 
18708 			/* Type: stateless(1), stateful(2), unknown(3) */
18709 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18710 				mae6.ipv6AddrType = 1;
18711 			else
18712 				mae6.ipv6AddrType = 2;
18713 			/* Anycast: true(1), false(2) */
18714 			if (ipif->ipif_flags & IPIF_ANYCAST)
18715 				mae6.ipv6AddrAnycastFlag = 1;
18716 			else
18717 				mae6.ipv6AddrAnycastFlag = 2;
18718 
18719 			/*
18720 			 * Address status: preferred(1), deprecated(2),
18721 			 * invalid(3), inaccessible(4), unknown(5)
18722 			 */
18723 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18724 				mae6.ipv6AddrStatus = 3;
18725 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18726 				mae6.ipv6AddrStatus = 2;
18727 			else
18728 				mae6.ipv6AddrStatus = 1;
18729 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18730 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18731 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18732 			    ipif->ipif_v6pp_dst_addr;
18733 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18734 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18735 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18736 			mae6.ipv6AddrIdentifier = ill->ill_token;
18737 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18738 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18739 			mae6.ipv6AddrRetransmitTime =
18740 			    ill->ill_reachable_retrans_time;
18741 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18742 			    (char *)&mae6,
18743 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18744 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18745 				    "allocate %u bytes\n",
18746 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18747 			}
18748 		}
18749 	}
18750 	rw_exit(&ipst->ips_ill_g_lock);
18751 
18752 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18753 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18754 	    (int)optp->level, (int)optp->name, (int)optp->len));
18755 	qreply(q, mpctl);
18756 	return (mp2ctl);
18757 }
18758 
18759 /* IPv4 multicast group membership. */
18760 static mblk_t *
18761 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18762 {
18763 	struct opthdr		*optp;
18764 	mblk_t			*mp2ctl;
18765 	ill_t			*ill;
18766 	ipif_t			*ipif;
18767 	ilm_t			*ilm;
18768 	ip_member_t		ipm;
18769 	mblk_t			*mp_tail = NULL;
18770 	ill_walk_context_t	ctx;
18771 	zoneid_t		zoneid;
18772 	ilm_walker_t		ilw;
18773 
18774 	/*
18775 	 * make a copy of the original message
18776 	 */
18777 	mp2ctl = copymsg(mpctl);
18778 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18779 
18780 	/* ipGroupMember table */
18781 	optp = (struct opthdr *)&mpctl->b_rptr[
18782 	    sizeof (struct T_optmgmt_ack)];
18783 	optp->level = MIB2_IP;
18784 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18785 
18786 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18787 	ill = ILL_START_WALK_V4(&ctx, ipst);
18788 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18789 		if (IS_UNDER_IPMP(ill))
18790 			continue;
18791 
18792 		ilm = ilm_walker_start(&ilw, ill);
18793 		for (ipif = ill->ill_ipif; ipif != NULL;
18794 		    ipif = ipif->ipif_next) {
18795 			if (ipif->ipif_zoneid != zoneid &&
18796 			    ipif->ipif_zoneid != ALL_ZONES)
18797 				continue;	/* not this zone */
18798 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18799 			    OCTET_LENGTH);
18800 			ipm.ipGroupMemberIfIndex.o_length =
18801 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18802 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18803 				ASSERT(ilm->ilm_ipif != NULL);
18804 				ASSERT(ilm->ilm_ill == NULL);
18805 				if (ilm->ilm_ipif != ipif)
18806 					continue;
18807 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18808 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18809 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18810 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18811 				    (char *)&ipm, (int)sizeof (ipm))) {
18812 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18813 					    "failed to allocate %u bytes\n",
18814 					    (uint_t)sizeof (ipm)));
18815 				}
18816 			}
18817 		}
18818 		ilm_walker_finish(&ilw);
18819 	}
18820 	rw_exit(&ipst->ips_ill_g_lock);
18821 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18822 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18823 	    (int)optp->level, (int)optp->name, (int)optp->len));
18824 	qreply(q, mpctl);
18825 	return (mp2ctl);
18826 }
18827 
18828 /* IPv6 multicast group membership. */
18829 static mblk_t *
18830 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18831 {
18832 	struct opthdr		*optp;
18833 	mblk_t			*mp2ctl;
18834 	ill_t			*ill;
18835 	ilm_t			*ilm;
18836 	ipv6_member_t		ipm6;
18837 	mblk_t			*mp_tail = NULL;
18838 	ill_walk_context_t	ctx;
18839 	zoneid_t		zoneid;
18840 	ilm_walker_t		ilw;
18841 
18842 	/*
18843 	 * make a copy of the original message
18844 	 */
18845 	mp2ctl = copymsg(mpctl);
18846 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18847 
18848 	/* ip6GroupMember table */
18849 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18850 	optp->level = MIB2_IP6;
18851 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18852 
18853 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18854 	ill = ILL_START_WALK_V6(&ctx, ipst);
18855 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18856 		if (IS_UNDER_IPMP(ill))
18857 			continue;
18858 
18859 		ilm = ilm_walker_start(&ilw, ill);
18860 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18861 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18862 			ASSERT(ilm->ilm_ipif == NULL);
18863 			ASSERT(ilm->ilm_ill != NULL);
18864 			if (ilm->ilm_zoneid != zoneid)
18865 				continue;	/* not this zone */
18866 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18867 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18868 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18869 			if (!snmp_append_data2(mpctl->b_cont,
18870 			    &mp_tail,
18871 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18872 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18873 				    "failed to allocate %u bytes\n",
18874 				    (uint_t)sizeof (ipm6)));
18875 			}
18876 		}
18877 		ilm_walker_finish(&ilw);
18878 	}
18879 	rw_exit(&ipst->ips_ill_g_lock);
18880 
18881 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18882 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18883 	    (int)optp->level, (int)optp->name, (int)optp->len));
18884 	qreply(q, mpctl);
18885 	return (mp2ctl);
18886 }
18887 
18888 /* IP multicast filtered sources */
18889 static mblk_t *
18890 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18891 {
18892 	struct opthdr		*optp;
18893 	mblk_t			*mp2ctl;
18894 	ill_t			*ill;
18895 	ipif_t			*ipif;
18896 	ilm_t			*ilm;
18897 	ip_grpsrc_t		ips;
18898 	mblk_t			*mp_tail = NULL;
18899 	ill_walk_context_t	ctx;
18900 	zoneid_t		zoneid;
18901 	int			i;
18902 	slist_t			*sl;
18903 	ilm_walker_t		ilw;
18904 
18905 	/*
18906 	 * make a copy of the original message
18907 	 */
18908 	mp2ctl = copymsg(mpctl);
18909 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18910 
18911 	/* ipGroupSource table */
18912 	optp = (struct opthdr *)&mpctl->b_rptr[
18913 	    sizeof (struct T_optmgmt_ack)];
18914 	optp->level = MIB2_IP;
18915 	optp->name = EXPER_IP_GROUP_SOURCES;
18916 
18917 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18918 	ill = ILL_START_WALK_V4(&ctx, ipst);
18919 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18920 		if (IS_UNDER_IPMP(ill))
18921 			continue;
18922 
18923 		ilm = ilm_walker_start(&ilw, ill);
18924 		for (ipif = ill->ill_ipif; ipif != NULL;
18925 		    ipif = ipif->ipif_next) {
18926 			if (ipif->ipif_zoneid != zoneid)
18927 				continue;	/* not this zone */
18928 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18929 			    OCTET_LENGTH);
18930 			ips.ipGroupSourceIfIndex.o_length =
18931 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18932 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18933 				ASSERT(ilm->ilm_ipif != NULL);
18934 				ASSERT(ilm->ilm_ill == NULL);
18935 				sl = ilm->ilm_filter;
18936 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18937 					continue;
18938 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18939 				for (i = 0; i < sl->sl_numsrc; i++) {
18940 					if (!IN6_IS_ADDR_V4MAPPED(
18941 					    &sl->sl_addr[i]))
18942 						continue;
18943 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18944 					    ips.ipGroupSourceAddress);
18945 					if (snmp_append_data2(mpctl->b_cont,
18946 					    &mp_tail, (char *)&ips,
18947 					    (int)sizeof (ips)) == 0) {
18948 						ip1dbg(("ip_snmp_get_mib2_"
18949 						    "ip_group_src: failed to "
18950 						    "allocate %u bytes\n",
18951 						    (uint_t)sizeof (ips)));
18952 					}
18953 				}
18954 			}
18955 		}
18956 		ilm_walker_finish(&ilw);
18957 	}
18958 	rw_exit(&ipst->ips_ill_g_lock);
18959 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18960 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18961 	    (int)optp->level, (int)optp->name, (int)optp->len));
18962 	qreply(q, mpctl);
18963 	return (mp2ctl);
18964 }
18965 
18966 /* IPv6 multicast filtered sources. */
18967 static mblk_t *
18968 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18969 {
18970 	struct opthdr		*optp;
18971 	mblk_t			*mp2ctl;
18972 	ill_t			*ill;
18973 	ilm_t			*ilm;
18974 	ipv6_grpsrc_t		ips6;
18975 	mblk_t			*mp_tail = NULL;
18976 	ill_walk_context_t	ctx;
18977 	zoneid_t		zoneid;
18978 	int			i;
18979 	slist_t			*sl;
18980 	ilm_walker_t		ilw;
18981 
18982 	/*
18983 	 * make a copy of the original message
18984 	 */
18985 	mp2ctl = copymsg(mpctl);
18986 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18987 
18988 	/* ip6GroupMember table */
18989 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18990 	optp->level = MIB2_IP6;
18991 	optp->name = EXPER_IP6_GROUP_SOURCES;
18992 
18993 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18994 	ill = ILL_START_WALK_V6(&ctx, ipst);
18995 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18996 		if (IS_UNDER_IPMP(ill))
18997 			continue;
18998 
18999 		ilm = ilm_walker_start(&ilw, ill);
19000 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19001 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19002 			ASSERT(ilm->ilm_ipif == NULL);
19003 			ASSERT(ilm->ilm_ill != NULL);
19004 			sl = ilm->ilm_filter;
19005 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19006 				continue;
19007 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19008 			for (i = 0; i < sl->sl_numsrc; i++) {
19009 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19010 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19011 				    (char *)&ips6, (int)sizeof (ips6))) {
19012 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19013 					    "group_src: failed to allocate "
19014 					    "%u bytes\n",
19015 					    (uint_t)sizeof (ips6)));
19016 				}
19017 			}
19018 		}
19019 		ilm_walker_finish(&ilw);
19020 	}
19021 	rw_exit(&ipst->ips_ill_g_lock);
19022 
19023 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19024 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19025 	    (int)optp->level, (int)optp->name, (int)optp->len));
19026 	qreply(q, mpctl);
19027 	return (mp2ctl);
19028 }
19029 
19030 /* Multicast routing virtual interface table. */
19031 static mblk_t *
19032 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19033 {
19034 	struct opthdr		*optp;
19035 	mblk_t			*mp2ctl;
19036 
19037 	/*
19038 	 * make a copy of the original message
19039 	 */
19040 	mp2ctl = copymsg(mpctl);
19041 
19042 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19043 	optp->level = EXPER_DVMRP;
19044 	optp->name = EXPER_DVMRP_VIF;
19045 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19046 		ip0dbg(("ip_mroute_vif: failed\n"));
19047 	}
19048 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19049 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19050 	    (int)optp->level, (int)optp->name, (int)optp->len));
19051 	qreply(q, mpctl);
19052 	return (mp2ctl);
19053 }
19054 
19055 /* Multicast routing table. */
19056 static mblk_t *
19057 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19058 {
19059 	struct opthdr		*optp;
19060 	mblk_t			*mp2ctl;
19061 
19062 	/*
19063 	 * make a copy of the original message
19064 	 */
19065 	mp2ctl = copymsg(mpctl);
19066 
19067 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19068 	optp->level = EXPER_DVMRP;
19069 	optp->name = EXPER_DVMRP_MRT;
19070 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19071 		ip0dbg(("ip_mroute_mrt: failed\n"));
19072 	}
19073 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19074 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19075 	    (int)optp->level, (int)optp->name, (int)optp->len));
19076 	qreply(q, mpctl);
19077 	return (mp2ctl);
19078 }
19079 
19080 /*
19081  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19082  * in one IRE walk.
19083  */
19084 static mblk_t *
19085 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19086     ip_stack_t *ipst)
19087 {
19088 	struct opthdr	*optp;
19089 	mblk_t		*mp2ctl;	/* Returned */
19090 	mblk_t		*mp3ctl;	/* nettomedia */
19091 	mblk_t		*mp4ctl;	/* routeattrs */
19092 	iproutedata_t	ird;
19093 	zoneid_t	zoneid;
19094 
19095 	/*
19096 	 * make copies of the original message
19097 	 *	- mp2ctl is returned unchanged to the caller for his use
19098 	 *	- mpctl is sent upstream as ipRouteEntryTable
19099 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19100 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19101 	 */
19102 	mp2ctl = copymsg(mpctl);
19103 	mp3ctl = copymsg(mpctl);
19104 	mp4ctl = copymsg(mpctl);
19105 	if (mp3ctl == NULL || mp4ctl == NULL) {
19106 		freemsg(mp4ctl);
19107 		freemsg(mp3ctl);
19108 		freemsg(mp2ctl);
19109 		freemsg(mpctl);
19110 		return (NULL);
19111 	}
19112 
19113 	bzero(&ird, sizeof (ird));
19114 
19115 	ird.ird_route.lp_head = mpctl->b_cont;
19116 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19117 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19118 	/*
19119 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19120 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19121 	 * intended a temporary solution until a proper MIB API is provided
19122 	 * that provides complete filtering/caller-opt-in.
19123 	 */
19124 	if (level == EXPER_IP_AND_TESTHIDDEN)
19125 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19126 
19127 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19128 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19129 
19130 	/* ipRouteEntryTable in mpctl */
19131 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19132 	optp->level = MIB2_IP;
19133 	optp->name = MIB2_IP_ROUTE;
19134 	optp->len = msgdsize(ird.ird_route.lp_head);
19135 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19136 	    (int)optp->level, (int)optp->name, (int)optp->len));
19137 	qreply(q, mpctl);
19138 
19139 	/* ipNetToMediaEntryTable in mp3ctl */
19140 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19141 	optp->level = MIB2_IP;
19142 	optp->name = MIB2_IP_MEDIA;
19143 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19144 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19145 	    (int)optp->level, (int)optp->name, (int)optp->len));
19146 	qreply(q, mp3ctl);
19147 
19148 	/* ipRouteAttributeTable in mp4ctl */
19149 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19150 	optp->level = MIB2_IP;
19151 	optp->name = EXPER_IP_RTATTR;
19152 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19153 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19154 	    (int)optp->level, (int)optp->name, (int)optp->len));
19155 	if (optp->len == 0)
19156 		freemsg(mp4ctl);
19157 	else
19158 		qreply(q, mp4ctl);
19159 
19160 	return (mp2ctl);
19161 }
19162 
19163 /*
19164  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19165  * ipv6NetToMediaEntryTable in an NDP walk.
19166  */
19167 static mblk_t *
19168 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19169     ip_stack_t *ipst)
19170 {
19171 	struct opthdr	*optp;
19172 	mblk_t		*mp2ctl;	/* Returned */
19173 	mblk_t		*mp3ctl;	/* nettomedia */
19174 	mblk_t		*mp4ctl;	/* routeattrs */
19175 	iproutedata_t	ird;
19176 	zoneid_t	zoneid;
19177 
19178 	/*
19179 	 * make copies of the original message
19180 	 *	- mp2ctl is returned unchanged to the caller for his use
19181 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19182 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19183 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19184 	 */
19185 	mp2ctl = copymsg(mpctl);
19186 	mp3ctl = copymsg(mpctl);
19187 	mp4ctl = copymsg(mpctl);
19188 	if (mp3ctl == NULL || mp4ctl == NULL) {
19189 		freemsg(mp4ctl);
19190 		freemsg(mp3ctl);
19191 		freemsg(mp2ctl);
19192 		freemsg(mpctl);
19193 		return (NULL);
19194 	}
19195 
19196 	bzero(&ird, sizeof (ird));
19197 
19198 	ird.ird_route.lp_head = mpctl->b_cont;
19199 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19200 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19201 	/*
19202 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19203 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19204 	 * intended a temporary solution until a proper MIB API is provided
19205 	 * that provides complete filtering/caller-opt-in.
19206 	 */
19207 	if (level == EXPER_IP_AND_TESTHIDDEN)
19208 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19209 
19210 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19211 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19212 
19213 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19214 	optp->level = MIB2_IP6;
19215 	optp->name = MIB2_IP6_ROUTE;
19216 	optp->len = msgdsize(ird.ird_route.lp_head);
19217 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19218 	    (int)optp->level, (int)optp->name, (int)optp->len));
19219 	qreply(q, mpctl);
19220 
19221 	/* ipv6NetToMediaEntryTable in mp3ctl */
19222 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19223 
19224 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19225 	optp->level = MIB2_IP6;
19226 	optp->name = MIB2_IP6_MEDIA;
19227 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19228 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19229 	    (int)optp->level, (int)optp->name, (int)optp->len));
19230 	qreply(q, mp3ctl);
19231 
19232 	/* ipv6RouteAttributeTable in mp4ctl */
19233 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19234 	optp->level = MIB2_IP6;
19235 	optp->name = EXPER_IP_RTATTR;
19236 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19237 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19238 	    (int)optp->level, (int)optp->name, (int)optp->len));
19239 	if (optp->len == 0)
19240 		freemsg(mp4ctl);
19241 	else
19242 		qreply(q, mp4ctl);
19243 
19244 	return (mp2ctl);
19245 }
19246 
19247 /*
19248  * IPv6 mib: One per ill
19249  */
19250 static mblk_t *
19251 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19252 {
19253 	struct opthdr		*optp;
19254 	mblk_t			*mp2ctl;
19255 	ill_t			*ill;
19256 	ill_walk_context_t	ctx;
19257 	mblk_t			*mp_tail = NULL;
19258 
19259 	/*
19260 	 * Make a copy of the original message
19261 	 */
19262 	mp2ctl = copymsg(mpctl);
19263 
19264 	/* fixed length IPv6 structure ... */
19265 
19266 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19267 	optp->level = MIB2_IP6;
19268 	optp->name = 0;
19269 	/* Include "unknown interface" ip6_mib */
19270 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19271 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19272 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19273 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19274 	    ipst->ips_ipv6_forward ? 1 : 2);
19275 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19276 	    ipst->ips_ipv6_def_hops);
19277 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19278 	    sizeof (mib2_ipIfStatsEntry_t));
19279 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19280 	    sizeof (mib2_ipv6AddrEntry_t));
19281 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19282 	    sizeof (mib2_ipv6RouteEntry_t));
19283 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19284 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19285 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19286 	    sizeof (ipv6_member_t));
19287 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19288 	    sizeof (ipv6_grpsrc_t));
19289 
19290 	/*
19291 	 * Synchronize 64- and 32-bit counters
19292 	 */
19293 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19294 	    ipIfStatsHCInReceives);
19295 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19296 	    ipIfStatsHCInDelivers);
19297 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19298 	    ipIfStatsHCOutRequests);
19299 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19300 	    ipIfStatsHCOutForwDatagrams);
19301 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19302 	    ipIfStatsHCOutMcastPkts);
19303 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19304 	    ipIfStatsHCInMcastPkts);
19305 
19306 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19307 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19308 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19309 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19310 	}
19311 
19312 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19313 	ill = ILL_START_WALK_V6(&ctx, ipst);
19314 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19315 		ill->ill_ip_mib->ipIfStatsIfIndex =
19316 		    ill->ill_phyint->phyint_ifindex;
19317 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19318 		    ipst->ips_ipv6_forward ? 1 : 2);
19319 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19320 		    ill->ill_max_hops);
19321 
19322 		/*
19323 		 * Synchronize 64- and 32-bit counters
19324 		 */
19325 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19326 		    ipIfStatsHCInReceives);
19327 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19328 		    ipIfStatsHCInDelivers);
19329 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19330 		    ipIfStatsHCOutRequests);
19331 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19332 		    ipIfStatsHCOutForwDatagrams);
19333 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19334 		    ipIfStatsHCOutMcastPkts);
19335 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19336 		    ipIfStatsHCInMcastPkts);
19337 
19338 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19339 		    (char *)ill->ill_ip_mib,
19340 		    (int)sizeof (*ill->ill_ip_mib))) {
19341 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19342 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19343 		}
19344 	}
19345 	rw_exit(&ipst->ips_ill_g_lock);
19346 
19347 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19348 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19349 	    (int)optp->level, (int)optp->name, (int)optp->len));
19350 	qreply(q, mpctl);
19351 	return (mp2ctl);
19352 }
19353 
19354 /*
19355  * ICMPv6 mib: One per ill
19356  */
19357 static mblk_t *
19358 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19359 {
19360 	struct opthdr		*optp;
19361 	mblk_t			*mp2ctl;
19362 	ill_t			*ill;
19363 	ill_walk_context_t	ctx;
19364 	mblk_t			*mp_tail = NULL;
19365 	/*
19366 	 * Make a copy of the original message
19367 	 */
19368 	mp2ctl = copymsg(mpctl);
19369 
19370 	/* fixed length ICMPv6 structure ... */
19371 
19372 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19373 	optp->level = MIB2_ICMP6;
19374 	optp->name = 0;
19375 	/* Include "unknown interface" icmp6_mib */
19376 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19377 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19378 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19379 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19380 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19381 	    (char *)&ipst->ips_icmp6_mib,
19382 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19383 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19384 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19385 	}
19386 
19387 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19388 	ill = ILL_START_WALK_V6(&ctx, ipst);
19389 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19390 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19391 		    ill->ill_phyint->phyint_ifindex;
19392 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19393 		    (char *)ill->ill_icmp6_mib,
19394 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19395 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19396 			    "%u bytes\n",
19397 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19398 		}
19399 	}
19400 	rw_exit(&ipst->ips_ill_g_lock);
19401 
19402 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19403 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19404 	    (int)optp->level, (int)optp->name, (int)optp->len));
19405 	qreply(q, mpctl);
19406 	return (mp2ctl);
19407 }
19408 
19409 /*
19410  * ire_walk routine to create both ipRouteEntryTable and
19411  * ipRouteAttributeTable in one IRE walk
19412  */
19413 static void
19414 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19415 {
19416 	ill_t				*ill;
19417 	ipif_t				*ipif;
19418 	mib2_ipRouteEntry_t		*re;
19419 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19420 	ipaddr_t			gw_addr;
19421 	tsol_ire_gw_secattr_t		*attrp;
19422 	tsol_gc_t			*gc = NULL;
19423 	tsol_gcgrp_t			*gcgrp = NULL;
19424 	uint_t				sacnt = 0;
19425 	int				i;
19426 
19427 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19428 
19429 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19430 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19431 		return;
19432 	}
19433 
19434 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19435 		return;
19436 
19437 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19438 		mutex_enter(&attrp->igsa_lock);
19439 		if ((gc = attrp->igsa_gc) != NULL) {
19440 			gcgrp = gc->gc_grp;
19441 			ASSERT(gcgrp != NULL);
19442 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19443 			sacnt = 1;
19444 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19445 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19446 			gc = gcgrp->gcgrp_head;
19447 			sacnt = gcgrp->gcgrp_count;
19448 		}
19449 		mutex_exit(&attrp->igsa_lock);
19450 
19451 		/* do nothing if there's no gc to report */
19452 		if (gc == NULL) {
19453 			ASSERT(sacnt == 0);
19454 			if (gcgrp != NULL) {
19455 				/* we might as well drop the lock now */
19456 				rw_exit(&gcgrp->gcgrp_rwlock);
19457 				gcgrp = NULL;
19458 			}
19459 			attrp = NULL;
19460 		}
19461 
19462 		ASSERT(gc == NULL || (gcgrp != NULL &&
19463 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19464 	}
19465 	ASSERT(sacnt == 0 || gc != NULL);
19466 
19467 	if (sacnt != 0 &&
19468 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19469 		kmem_free(re, sizeof (*re));
19470 		rw_exit(&gcgrp->gcgrp_rwlock);
19471 		return;
19472 	}
19473 
19474 	/*
19475 	 * Return all IRE types for route table... let caller pick and choose
19476 	 */
19477 	re->ipRouteDest = ire->ire_addr;
19478 	ipif = ire->ire_ipif;
19479 	re->ipRouteIfIndex.o_length = 0;
19480 	if (ire->ire_type == IRE_CACHE) {
19481 		ill = (ill_t *)ire->ire_stq->q_ptr;
19482 		re->ipRouteIfIndex.o_length =
19483 		    ill->ill_name_length == 0 ? 0 :
19484 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19485 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19486 		    re->ipRouteIfIndex.o_length);
19487 	} else if (ipif != NULL) {
19488 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19489 		re->ipRouteIfIndex.o_length =
19490 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19491 	}
19492 	re->ipRouteMetric1 = -1;
19493 	re->ipRouteMetric2 = -1;
19494 	re->ipRouteMetric3 = -1;
19495 	re->ipRouteMetric4 = -1;
19496 
19497 	gw_addr = ire->ire_gateway_addr;
19498 
19499 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19500 		re->ipRouteNextHop = ire->ire_src_addr;
19501 	else
19502 		re->ipRouteNextHop = gw_addr;
19503 	/* indirect(4), direct(3), or invalid(2) */
19504 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19505 		re->ipRouteType = 2;
19506 	else
19507 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19508 	re->ipRouteProto = -1;
19509 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19510 	re->ipRouteMask = ire->ire_mask;
19511 	re->ipRouteMetric5 = -1;
19512 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19513 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19514 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19515 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19516 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19517 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19518 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19519 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19520 
19521 	if (ire->ire_flags & RTF_DYNAMIC) {
19522 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19523 	} else {
19524 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19525 	}
19526 
19527 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19528 	    (char *)re, (int)sizeof (*re))) {
19529 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19530 		    (uint_t)sizeof (*re)));
19531 	}
19532 
19533 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19534 		iaeptr->iae_routeidx = ird->ird_idx;
19535 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19536 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19537 	}
19538 
19539 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19540 	    (char *)iae, sacnt * sizeof (*iae))) {
19541 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19542 		    (unsigned)(sacnt * sizeof (*iae))));
19543 	}
19544 
19545 	/* bump route index for next pass */
19546 	ird->ird_idx++;
19547 
19548 	kmem_free(re, sizeof (*re));
19549 	if (sacnt != 0)
19550 		kmem_free(iae, sacnt * sizeof (*iae));
19551 
19552 	if (gcgrp != NULL)
19553 		rw_exit(&gcgrp->gcgrp_rwlock);
19554 }
19555 
19556 /*
19557  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19558  */
19559 static void
19560 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19561 {
19562 	ill_t				*ill;
19563 	ipif_t				*ipif;
19564 	mib2_ipv6RouteEntry_t		*re;
19565 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19566 	in6_addr_t			gw_addr_v6;
19567 	tsol_ire_gw_secattr_t		*attrp;
19568 	tsol_gc_t			*gc = NULL;
19569 	tsol_gcgrp_t			*gcgrp = NULL;
19570 	uint_t				sacnt = 0;
19571 	int				i;
19572 
19573 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19574 
19575 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19576 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19577 		return;
19578 	}
19579 
19580 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19581 		return;
19582 
19583 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19584 		mutex_enter(&attrp->igsa_lock);
19585 		if ((gc = attrp->igsa_gc) != NULL) {
19586 			gcgrp = gc->gc_grp;
19587 			ASSERT(gcgrp != NULL);
19588 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19589 			sacnt = 1;
19590 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19591 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19592 			gc = gcgrp->gcgrp_head;
19593 			sacnt = gcgrp->gcgrp_count;
19594 		}
19595 		mutex_exit(&attrp->igsa_lock);
19596 
19597 		/* do nothing if there's no gc to report */
19598 		if (gc == NULL) {
19599 			ASSERT(sacnt == 0);
19600 			if (gcgrp != NULL) {
19601 				/* we might as well drop the lock now */
19602 				rw_exit(&gcgrp->gcgrp_rwlock);
19603 				gcgrp = NULL;
19604 			}
19605 			attrp = NULL;
19606 		}
19607 
19608 		ASSERT(gc == NULL || (gcgrp != NULL &&
19609 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19610 	}
19611 	ASSERT(sacnt == 0 || gc != NULL);
19612 
19613 	if (sacnt != 0 &&
19614 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19615 		kmem_free(re, sizeof (*re));
19616 		rw_exit(&gcgrp->gcgrp_rwlock);
19617 		return;
19618 	}
19619 
19620 	/*
19621 	 * Return all IRE types for route table... let caller pick and choose
19622 	 */
19623 	re->ipv6RouteDest = ire->ire_addr_v6;
19624 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19625 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19626 	re->ipv6RouteIfIndex.o_length = 0;
19627 	ipif = ire->ire_ipif;
19628 	if (ire->ire_type == IRE_CACHE) {
19629 		ill = (ill_t *)ire->ire_stq->q_ptr;
19630 		re->ipv6RouteIfIndex.o_length =
19631 		    ill->ill_name_length == 0 ? 0 :
19632 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19633 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19634 		    re->ipv6RouteIfIndex.o_length);
19635 	} else if (ipif != NULL) {
19636 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19637 		re->ipv6RouteIfIndex.o_length =
19638 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19639 	}
19640 
19641 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19642 
19643 	mutex_enter(&ire->ire_lock);
19644 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19645 	mutex_exit(&ire->ire_lock);
19646 
19647 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19648 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19649 	else
19650 		re->ipv6RouteNextHop = gw_addr_v6;
19651 
19652 	/* remote(4), local(3), or discard(2) */
19653 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19654 		re->ipv6RouteType = 2;
19655 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19656 		re->ipv6RouteType = 3;
19657 	else
19658 		re->ipv6RouteType = 4;
19659 
19660 	re->ipv6RouteProtocol	= -1;
19661 	re->ipv6RoutePolicy	= 0;
19662 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19663 	re->ipv6RouteNextHopRDI	= 0;
19664 	re->ipv6RouteWeight	= 0;
19665 	re->ipv6RouteMetric	= 0;
19666 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19667 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19668 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19669 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19670 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19671 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19672 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19673 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19674 
19675 	if (ire->ire_flags & RTF_DYNAMIC) {
19676 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19677 	} else {
19678 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19679 	}
19680 
19681 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19682 	    (char *)re, (int)sizeof (*re))) {
19683 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19684 		    (uint_t)sizeof (*re)));
19685 	}
19686 
19687 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19688 		iaeptr->iae_routeidx = ird->ird_idx;
19689 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19690 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19691 	}
19692 
19693 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19694 	    (char *)iae, sacnt * sizeof (*iae))) {
19695 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19696 		    (unsigned)(sacnt * sizeof (*iae))));
19697 	}
19698 
19699 	/* bump route index for next pass */
19700 	ird->ird_idx++;
19701 
19702 	kmem_free(re, sizeof (*re));
19703 	if (sacnt != 0)
19704 		kmem_free(iae, sacnt * sizeof (*iae));
19705 
19706 	if (gcgrp != NULL)
19707 		rw_exit(&gcgrp->gcgrp_rwlock);
19708 }
19709 
19710 /*
19711  * ndp_walk routine to create ipv6NetToMediaEntryTable
19712  */
19713 static int
19714 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19715 {
19716 	ill_t				*ill;
19717 	mib2_ipv6NetToMediaEntry_t	ntme;
19718 	dl_unitdata_req_t		*dl;
19719 
19720 	ill = nce->nce_ill;
19721 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19722 		return (0);
19723 
19724 	/*
19725 	 * Neighbor cache entry attached to IRE with on-link
19726 	 * destination.
19727 	 */
19728 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19729 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19730 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19731 	    (nce->nce_res_mp != NULL)) {
19732 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19733 		ntme.ipv6NetToMediaPhysAddress.o_length =
19734 		    dl->dl_dest_addr_length;
19735 	} else {
19736 		ntme.ipv6NetToMediaPhysAddress.o_length =
19737 		    ill->ill_phys_addr_length;
19738 	}
19739 	if (nce->nce_res_mp != NULL) {
19740 		bcopy((char *)nce->nce_res_mp->b_rptr +
19741 		    NCE_LL_ADDR_OFFSET(ill),
19742 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19743 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19744 	} else {
19745 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19746 		    ill->ill_phys_addr_length);
19747 	}
19748 	/*
19749 	 * Note: Returns ND_* states. Should be:
19750 	 * reachable(1), stale(2), delay(3), probe(4),
19751 	 * invalid(5), unknown(6)
19752 	 */
19753 	ntme.ipv6NetToMediaState = nce->nce_state;
19754 	ntme.ipv6NetToMediaLastUpdated = 0;
19755 
19756 	/* other(1), dynamic(2), static(3), local(4) */
19757 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19758 		ntme.ipv6NetToMediaType = 4;
19759 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19760 		ntme.ipv6NetToMediaType = 1;
19761 	} else {
19762 		ntme.ipv6NetToMediaType = 2;
19763 	}
19764 
19765 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19766 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19767 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19768 		    (uint_t)sizeof (ntme)));
19769 	}
19770 	return (0);
19771 }
19772 
19773 /*
19774  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19775  */
19776 /* ARGSUSED */
19777 int
19778 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19779 {
19780 	switch (level) {
19781 	case MIB2_IP:
19782 	case MIB2_ICMP:
19783 		switch (name) {
19784 		default:
19785 			break;
19786 		}
19787 		return (1);
19788 	default:
19789 		return (1);
19790 	}
19791 }
19792 
19793 /*
19794  * When there exists both a 64- and 32-bit counter of a particular type
19795  * (i.e., InReceives), only the 64-bit counters are added.
19796  */
19797 void
19798 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19799 {
19800 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19801 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19802 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19803 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19804 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19805 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19806 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19807 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19808 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19809 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19810 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19811 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19812 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19813 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19814 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19815 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19816 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19817 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19818 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19819 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19820 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19821 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19822 	    o2->ipIfStatsInWrongIPVersion);
19823 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19824 	    o2->ipIfStatsInWrongIPVersion);
19825 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19826 	    o2->ipIfStatsOutSwitchIPVersion);
19827 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19828 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19829 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19830 	    o2->ipIfStatsHCInForwDatagrams);
19831 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19832 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19833 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19834 	    o2->ipIfStatsHCOutForwDatagrams);
19835 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19836 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19837 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19838 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19839 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19840 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19841 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19842 	    o2->ipIfStatsHCOutMcastOctets);
19843 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19844 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19845 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19846 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19847 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19848 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19849 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19850 }
19851 
19852 void
19853 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19854 {
19855 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19856 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19857 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19859 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19861 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19862 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19863 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19864 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19865 	    o2->ipv6IfIcmpInRouterSolicits);
19866 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19867 	    o2->ipv6IfIcmpInRouterAdvertisements);
19868 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19869 	    o2->ipv6IfIcmpInNeighborSolicits);
19870 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19871 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19872 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19873 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19874 	    o2->ipv6IfIcmpInGroupMembQueries);
19875 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19876 	    o2->ipv6IfIcmpInGroupMembResponses);
19877 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19878 	    o2->ipv6IfIcmpInGroupMembReductions);
19879 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19880 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19881 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19882 	    o2->ipv6IfIcmpOutDestUnreachs);
19883 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19884 	    o2->ipv6IfIcmpOutAdminProhibs);
19885 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19886 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19887 	    o2->ipv6IfIcmpOutParmProblems);
19888 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19889 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19890 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19891 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19892 	    o2->ipv6IfIcmpOutRouterSolicits);
19893 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19894 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19895 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19896 	    o2->ipv6IfIcmpOutNeighborSolicits);
19897 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19898 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19899 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19900 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19901 	    o2->ipv6IfIcmpOutGroupMembQueries);
19902 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19903 	    o2->ipv6IfIcmpOutGroupMembResponses);
19904 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19905 	    o2->ipv6IfIcmpOutGroupMembReductions);
19906 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19907 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19908 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19909 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19910 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19911 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19912 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19913 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19914 	    o2->ipv6IfIcmpInGroupMembTotal);
19915 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19916 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19917 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19918 	    o2->ipv6IfIcmpInGroupMembBadReports);
19919 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19920 	    o2->ipv6IfIcmpInGroupMembOurReports);
19921 }
19922 
19923 /*
19924  * Called before the options are updated to check if this packet will
19925  * be source routed from here.
19926  * This routine assumes that the options are well formed i.e. that they
19927  * have already been checked.
19928  */
19929 static boolean_t
19930 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19931 {
19932 	ipoptp_t	opts;
19933 	uchar_t		*opt;
19934 	uint8_t		optval;
19935 	uint8_t		optlen;
19936 	ipaddr_t	dst;
19937 	ire_t		*ire;
19938 
19939 	if (IS_SIMPLE_IPH(ipha)) {
19940 		ip2dbg(("not source routed\n"));
19941 		return (B_FALSE);
19942 	}
19943 	dst = ipha->ipha_dst;
19944 	for (optval = ipoptp_first(&opts, ipha);
19945 	    optval != IPOPT_EOL;
19946 	    optval = ipoptp_next(&opts)) {
19947 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19948 		opt = opts.ipoptp_cur;
19949 		optlen = opts.ipoptp_len;
19950 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19951 		    optval, optlen));
19952 		switch (optval) {
19953 			uint32_t off;
19954 		case IPOPT_SSRR:
19955 		case IPOPT_LSRR:
19956 			/*
19957 			 * If dst is one of our addresses and there are some
19958 			 * entries left in the source route return (true).
19959 			 */
19960 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19961 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19962 			if (ire == NULL) {
19963 				ip2dbg(("ip_source_routed: not next"
19964 				    " source route 0x%x\n",
19965 				    ntohl(dst)));
19966 				return (B_FALSE);
19967 			}
19968 			ire_refrele(ire);
19969 			off = opt[IPOPT_OFFSET];
19970 			off--;
19971 			if (optlen < IP_ADDR_LEN ||
19972 			    off > optlen - IP_ADDR_LEN) {
19973 				/* End of source route */
19974 				ip1dbg(("ip_source_routed: end of SR\n"));
19975 				return (B_FALSE);
19976 			}
19977 			return (B_TRUE);
19978 		}
19979 	}
19980 	ip2dbg(("not source routed\n"));
19981 	return (B_FALSE);
19982 }
19983 
19984 /*
19985  * Check if the packet contains any source route.
19986  */
19987 static boolean_t
19988 ip_source_route_included(ipha_t *ipha)
19989 {
19990 	ipoptp_t	opts;
19991 	uint8_t		optval;
19992 
19993 	if (IS_SIMPLE_IPH(ipha))
19994 		return (B_FALSE);
19995 	for (optval = ipoptp_first(&opts, ipha);
19996 	    optval != IPOPT_EOL;
19997 	    optval = ipoptp_next(&opts)) {
19998 		switch (optval) {
19999 		case IPOPT_SSRR:
20000 		case IPOPT_LSRR:
20001 			return (B_TRUE);
20002 		}
20003 	}
20004 	return (B_FALSE);
20005 }
20006 
20007 /*
20008  * Called when the IRE expiration timer fires.
20009  */
20010 void
20011 ip_trash_timer_expire(void *args)
20012 {
20013 	int			flush_flag = 0;
20014 	ire_expire_arg_t	iea;
20015 	ip_stack_t		*ipst = (ip_stack_t *)args;
20016 
20017 	iea.iea_ipst = ipst;	/* No netstack_hold */
20018 
20019 	/*
20020 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20021 	 * This lock makes sure that a new invocation of this function
20022 	 * that occurs due to an almost immediate timer firing will not
20023 	 * progress beyond this point until the current invocation is done
20024 	 */
20025 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20026 	ipst->ips_ip_ire_expire_id = 0;
20027 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20028 
20029 	/* Periodic timer */
20030 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20031 	    ipst->ips_ip_ire_arp_interval) {
20032 		/*
20033 		 * Remove all IRE_CACHE entries since they might
20034 		 * contain arp information.
20035 		 */
20036 		flush_flag |= FLUSH_ARP_TIME;
20037 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20038 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20039 	}
20040 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20041 	    ipst->ips_ip_ire_redir_interval) {
20042 		/* Remove all redirects */
20043 		flush_flag |= FLUSH_REDIRECT_TIME;
20044 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20045 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20046 	}
20047 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20048 	    ipst->ips_ip_ire_pathmtu_interval) {
20049 		/* Increase path mtu */
20050 		flush_flag |= FLUSH_MTU_TIME;
20051 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20052 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20053 	}
20054 
20055 	/*
20056 	 * Optimize for the case when there are no redirects in the
20057 	 * ftable, that is, no need to walk the ftable in that case.
20058 	 */
20059 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20060 		iea.iea_flush_flag = flush_flag;
20061 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20062 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20063 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20064 		    NULL, ALL_ZONES, ipst);
20065 	}
20066 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20067 	    ipst->ips_ip_redirect_cnt > 0) {
20068 		iea.iea_flush_flag = flush_flag;
20069 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20070 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20071 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20072 	}
20073 	if (flush_flag & FLUSH_MTU_TIME) {
20074 		/*
20075 		 * Walk all IPv6 IRE's and update them
20076 		 * Note that ARP and redirect timers are not
20077 		 * needed since NUD handles stale entries.
20078 		 */
20079 		flush_flag = FLUSH_MTU_TIME;
20080 		iea.iea_flush_flag = flush_flag;
20081 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20082 		    ALL_ZONES, ipst);
20083 	}
20084 
20085 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20086 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20087 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20088 
20089 	/*
20090 	 * Hold the lock to serialize timeout calls and prevent
20091 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20092 	 * for the timer to fire and a new invocation of this function
20093 	 * to start before the return value of timeout has been stored
20094 	 * in ip_ire_expire_id by the current invocation.
20095 	 */
20096 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20097 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20098 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20099 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20100 }
20101 
20102 /*
20103  * Called by the memory allocator subsystem directly, when the system
20104  * is running low on memory.
20105  */
20106 /* ARGSUSED */
20107 void
20108 ip_trash_ire_reclaim(void *args)
20109 {
20110 	netstack_handle_t nh;
20111 	netstack_t *ns;
20112 
20113 	netstack_next_init(&nh);
20114 	while ((ns = netstack_next(&nh)) != NULL) {
20115 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20116 		netstack_rele(ns);
20117 	}
20118 	netstack_next_fini(&nh);
20119 }
20120 
20121 static void
20122 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20123 {
20124 	ire_cache_count_t icc;
20125 	ire_cache_reclaim_t icr;
20126 	ncc_cache_count_t ncc;
20127 	nce_cache_reclaim_t ncr;
20128 	uint_t delete_cnt;
20129 	/*
20130 	 * Memory reclaim call back.
20131 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20132 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20133 	 * entries, determine what fraction to free for
20134 	 * each category of IRE_CACHE entries giving absolute priority
20135 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20136 	 * entry will be freed unless all offlink entries are freed).
20137 	 */
20138 	icc.icc_total = 0;
20139 	icc.icc_unused = 0;
20140 	icc.icc_offlink = 0;
20141 	icc.icc_pmtu = 0;
20142 	icc.icc_onlink = 0;
20143 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20144 
20145 	/*
20146 	 * Free NCEs for IPv6 like the onlink ires.
20147 	 */
20148 	ncc.ncc_total = 0;
20149 	ncc.ncc_host = 0;
20150 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20151 
20152 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20153 	    icc.icc_pmtu + icc.icc_onlink);
20154 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20155 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20156 	if (delete_cnt == 0)
20157 		return;
20158 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20159 	/* Always delete all unused offlink entries */
20160 	icr.icr_ipst = ipst;
20161 	icr.icr_unused = 1;
20162 	if (delete_cnt <= icc.icc_unused) {
20163 		/*
20164 		 * Only need to free unused entries.  In other words,
20165 		 * there are enough unused entries to free to meet our
20166 		 * target number of freed ire cache entries.
20167 		 */
20168 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20169 		ncr.ncr_host = 0;
20170 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20171 		/*
20172 		 * Only need to free unused entries, plus a fraction of offlink
20173 		 * entries.  It follows from the first if statement that
20174 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20175 		 */
20176 		delete_cnt -= icc.icc_unused;
20177 		/* Round up # deleted by truncating fraction */
20178 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20179 		icr.icr_pmtu = icr.icr_onlink = 0;
20180 		ncr.ncr_host = 0;
20181 	} else if (delete_cnt <=
20182 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20183 		/*
20184 		 * Free all unused and offlink entries, plus a fraction of
20185 		 * pmtu entries.  It follows from the previous if statement
20186 		 * that icc_pmtu is non-zero, and that
20187 		 * delete_cnt != icc_unused + icc_offlink.
20188 		 */
20189 		icr.icr_offlink = 1;
20190 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20191 		/* Round up # deleted by truncating fraction */
20192 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20193 		icr.icr_onlink = 0;
20194 		ncr.ncr_host = 0;
20195 	} else {
20196 		/*
20197 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20198 		 * of onlink entries.  If we're here, then we know that
20199 		 * icc_onlink is non-zero, and that
20200 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20201 		 */
20202 		icr.icr_offlink = icr.icr_pmtu = 1;
20203 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20204 		    icc.icc_pmtu;
20205 		/* Round up # deleted by truncating fraction */
20206 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20207 		/* Using the same delete fraction as for onlink IREs */
20208 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20209 	}
20210 #ifdef DEBUG
20211 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20212 	    "fractions %d/%d/%d/%d\n",
20213 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20214 	    icc.icc_unused, icc.icc_offlink,
20215 	    icc.icc_pmtu, icc.icc_onlink,
20216 	    icr.icr_unused, icr.icr_offlink,
20217 	    icr.icr_pmtu, icr.icr_onlink));
20218 #endif
20219 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20220 	if (ncr.ncr_host != 0)
20221 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20222 		    (uchar_t *)&ncr, ipst);
20223 #ifdef DEBUG
20224 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20225 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20226 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20227 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20228 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20229 	    icc.icc_pmtu, icc.icc_onlink));
20230 #endif
20231 }
20232 
20233 /*
20234  * ip_unbind is called when a copy of an unbind request is received from the
20235  * upper level protocol.  We remove this conn from any fanout hash list it is
20236  * on, and zero out the bind information.  No reply is expected up above.
20237  */
20238 void
20239 ip_unbind(conn_t *connp)
20240 {
20241 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20242 
20243 	if (is_system_labeled() && connp->conn_anon_port) {
20244 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20245 		    connp->conn_mlp_type, connp->conn_ulp,
20246 		    ntohs(connp->conn_lport), B_FALSE);
20247 		connp->conn_anon_port = 0;
20248 	}
20249 	connp->conn_mlp_type = mlptSingle;
20250 
20251 	ipcl_hash_remove(connp);
20252 }
20253 
20254 /*
20255  * Write side put procedure.  Outbound data, IOCTLs, responses from
20256  * resolvers, etc, come down through here.
20257  *
20258  * arg2 is always a queue_t *.
20259  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20260  * the zoneid.
20261  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20262  */
20263 void
20264 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20265 {
20266 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20267 }
20268 
20269 void
20270 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20271     ip_opt_info_t *infop)
20272 {
20273 	conn_t		*connp = NULL;
20274 	queue_t		*q = (queue_t *)arg2;
20275 	ipha_t		*ipha;
20276 #define	rptr	((uchar_t *)ipha)
20277 	ire_t		*ire = NULL;
20278 	ire_t		*sctp_ire = NULL;
20279 	uint32_t	v_hlen_tos_len;
20280 	ipaddr_t	dst;
20281 	mblk_t		*first_mp = NULL;
20282 	boolean_t	mctl_present;
20283 	ipsec_out_t	*io;
20284 	int		match_flags;
20285 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20286 	ipif_t		*dst_ipif;
20287 	boolean_t	multirt_need_resolve = B_FALSE;
20288 	mblk_t		*copy_mp = NULL;
20289 	int		err = 0;
20290 	zoneid_t	zoneid;
20291 	boolean_t	need_decref = B_FALSE;
20292 	boolean_t	ignore_dontroute = B_FALSE;
20293 	boolean_t	ignore_nexthop = B_FALSE;
20294 	boolean_t	ip_nexthop = B_FALSE;
20295 	ipaddr_t	nexthop_addr;
20296 	ip_stack_t	*ipst;
20297 
20298 #ifdef	_BIG_ENDIAN
20299 #define	V_HLEN	(v_hlen_tos_len >> 24)
20300 #else
20301 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20302 #endif
20303 
20304 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20305 	    "ip_wput_start: q %p", q);
20306 
20307 	/*
20308 	 * ip_wput fast path
20309 	 */
20310 
20311 	/* is packet from ARP ? */
20312 	if (q->q_next != NULL) {
20313 		zoneid = (zoneid_t)(uintptr_t)arg;
20314 		goto qnext;
20315 	}
20316 
20317 	connp = (conn_t *)arg;
20318 	ASSERT(connp != NULL);
20319 	zoneid = connp->conn_zoneid;
20320 	ipst = connp->conn_netstack->netstack_ip;
20321 	ASSERT(ipst != NULL);
20322 
20323 	/* is queue flow controlled? */
20324 	if ((q->q_first != NULL || connp->conn_draining) &&
20325 	    (caller == IP_WPUT)) {
20326 		ASSERT(!need_decref);
20327 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20328 		(void) putq(q, mp);
20329 		return;
20330 	}
20331 
20332 	/* Multidata transmit? */
20333 	if (DB_TYPE(mp) == M_MULTIDATA) {
20334 		/*
20335 		 * We should never get here, since all Multidata messages
20336 		 * originating from tcp should have been directed over to
20337 		 * tcp_multisend() in the first place.
20338 		 */
20339 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20340 		freemsg(mp);
20341 		return;
20342 	} else if (DB_TYPE(mp) != M_DATA)
20343 		goto notdata;
20344 
20345 	if (mp->b_flag & MSGHASREF) {
20346 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20347 		mp->b_flag &= ~MSGHASREF;
20348 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20349 		need_decref = B_TRUE;
20350 	}
20351 	ipha = (ipha_t *)mp->b_rptr;
20352 
20353 	/* is IP header non-aligned or mblk smaller than basic IP header */
20354 #ifndef SAFETY_BEFORE_SPEED
20355 	if (!OK_32PTR(rptr) ||
20356 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20357 		goto hdrtoosmall;
20358 #endif
20359 
20360 	ASSERT(OK_32PTR(ipha));
20361 
20362 	/*
20363 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20364 	 * wrong version, we'll catch it again in ip_output_v6.
20365 	 *
20366 	 * Note that this is *only* locally-generated output here, and never
20367 	 * forwarded data, and that we need to deal only with transports that
20368 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20369 	 * label.)
20370 	 */
20371 	if (is_system_labeled() &&
20372 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20373 	    !connp->conn_ulp_labeled) {
20374 		cred_t	*credp;
20375 		pid_t	pid;
20376 
20377 		credp = BEST_CRED(mp, connp, &pid);
20378 		err = tsol_check_label(credp, &mp,
20379 		    connp->conn_mac_exempt, ipst, pid);
20380 		ipha = (ipha_t *)mp->b_rptr;
20381 		if (err != 0) {
20382 			first_mp = mp;
20383 			if (err == EINVAL)
20384 				goto icmp_parameter_problem;
20385 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20386 			goto discard_pkt;
20387 		}
20388 	}
20389 
20390 	ASSERT(infop != NULL);
20391 
20392 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20393 		/*
20394 		 * IP_PKTINFO ancillary option is present.
20395 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20396 		 * allows using address of any zone as the source address.
20397 		 */
20398 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20399 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20400 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20401 		if (ire == NULL)
20402 			goto drop_pkt;
20403 		ire_refrele(ire);
20404 		ire = NULL;
20405 	}
20406 
20407 	/*
20408 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20409 	 */
20410 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20411 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20412 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20413 
20414 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20415 			goto drop_pkt;
20416 		/*
20417 		 * check that there is an ipif belonging
20418 		 * to our zone. IPCL_ZONEID is not used because
20419 		 * IP_ALLZONES option is valid only when the ill is
20420 		 * accessible from all zones i.e has a valid ipif in
20421 		 * all zones.
20422 		 */
20423 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20424 			goto drop_pkt;
20425 		}
20426 	}
20427 
20428 	/*
20429 	 * If there is a policy, try to attach an ipsec_out in
20430 	 * the front. At the end, first_mp either points to a
20431 	 * M_DATA message or IPSEC_OUT message linked to a
20432 	 * M_DATA message. We have to do it now as we might
20433 	 * lose the "conn" if we go through ip_newroute.
20434 	 */
20435 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20436 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20437 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20438 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20439 			if (need_decref)
20440 				CONN_DEC_REF(connp);
20441 			return;
20442 		} else {
20443 			ASSERT(mp->b_datap->db_type == M_CTL);
20444 			first_mp = mp;
20445 			mp = mp->b_cont;
20446 			mctl_present = B_TRUE;
20447 		}
20448 	} else {
20449 		first_mp = mp;
20450 		mctl_present = B_FALSE;
20451 	}
20452 
20453 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20454 
20455 	/* is wrong version or IP options present */
20456 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20457 		goto version_hdrlen_check;
20458 	dst = ipha->ipha_dst;
20459 
20460 	/* If IP_BOUND_IF has been set, use that ill. */
20461 	if (connp->conn_outgoing_ill != NULL) {
20462 		xmit_ill = conn_get_held_ill(connp,
20463 		    &connp->conn_outgoing_ill, &err);
20464 		if (err == ILL_LOOKUP_FAILED)
20465 			goto drop_pkt;
20466 
20467 		goto send_from_ill;
20468 	}
20469 
20470 	/* is packet multicast? */
20471 	if (CLASSD(dst))
20472 		goto multicast;
20473 
20474 	/*
20475 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20476 	 * takes precedence over conn_dontroute and conn_nexthop_set
20477 	 */
20478 	if (xmit_ill != NULL)
20479 		goto send_from_ill;
20480 
20481 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20482 		/*
20483 		 * If the destination is a broadcast, local, or loopback
20484 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20485 		 * standard path.
20486 		 */
20487 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20488 		if ((ire == NULL) || (ire->ire_type &
20489 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20490 			if (ire != NULL) {
20491 				ire_refrele(ire);
20492 				/* No more access to ire */
20493 				ire = NULL;
20494 			}
20495 			/*
20496 			 * bypass routing checks and go directly to interface.
20497 			 */
20498 			if (connp->conn_dontroute)
20499 				goto dontroute;
20500 
20501 			ASSERT(connp->conn_nexthop_set);
20502 			ip_nexthop = B_TRUE;
20503 			nexthop_addr = connp->conn_nexthop_v4;
20504 			goto send_from_ill;
20505 		}
20506 
20507 		/* Must be a broadcast, a loopback or a local ire */
20508 		ire_refrele(ire);
20509 		/* No more access to ire */
20510 		ire = NULL;
20511 	}
20512 
20513 	/*
20514 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20515 	 * this for the tcp global queue and listen end point
20516 	 * as it does not really have a real destination to
20517 	 * talk to.  This is also true for SCTP.
20518 	 */
20519 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20520 	    !connp->conn_fully_bound) {
20521 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20522 		if (ire == NULL)
20523 			goto noirefound;
20524 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20525 		    "ip_wput_end: q %p (%S)", q, "end");
20526 
20527 		/*
20528 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20529 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20530 		 */
20531 		if (ire->ire_flags & RTF_MULTIRT) {
20532 
20533 			/*
20534 			 * Force the TTL of multirouted packets if required.
20535 			 * The TTL of such packets is bounded by the
20536 			 * ip_multirt_ttl ndd variable.
20537 			 */
20538 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20539 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20540 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20541 				    "(was %d), dst 0x%08x\n",
20542 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20543 				    ntohl(ire->ire_addr)));
20544 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20545 			}
20546 			/*
20547 			 * We look at this point if there are pending
20548 			 * unresolved routes. ire_multirt_resolvable()
20549 			 * checks in O(n) that all IRE_OFFSUBNET ire
20550 			 * entries for the packet's destination and
20551 			 * flagged RTF_MULTIRT are currently resolved.
20552 			 * If some remain unresolved, we make a copy
20553 			 * of the current message. It will be used
20554 			 * to initiate additional route resolutions.
20555 			 */
20556 			multirt_need_resolve =
20557 			    ire_multirt_need_resolve(ire->ire_addr,
20558 			    msg_getlabel(first_mp), ipst);
20559 			ip2dbg(("ip_wput[TCP]: ire %p, "
20560 			    "multirt_need_resolve %d, first_mp %p\n",
20561 			    (void *)ire, multirt_need_resolve,
20562 			    (void *)first_mp));
20563 			if (multirt_need_resolve) {
20564 				copy_mp = copymsg(first_mp);
20565 				if (copy_mp != NULL) {
20566 					MULTIRT_DEBUG_TAG(copy_mp);
20567 				}
20568 			}
20569 		}
20570 
20571 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20572 
20573 		/*
20574 		 * Try to resolve another multiroute if
20575 		 * ire_multirt_need_resolve() deemed it necessary.
20576 		 */
20577 		if (copy_mp != NULL)
20578 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20579 		if (need_decref)
20580 			CONN_DEC_REF(connp);
20581 		return;
20582 	}
20583 
20584 	/*
20585 	 * Access to conn_ire_cache. (protected by conn_lock)
20586 	 *
20587 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20588 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20589 	 * send a packet or two with the IRE_CACHE that is going away.
20590 	 * Access to the ire requires an ire refhold on the ire prior to
20591 	 * its use since an interface unplumb thread may delete the cached
20592 	 * ire and release the refhold at any time.
20593 	 *
20594 	 * Caching an ire in the conn_ire_cache
20595 	 *
20596 	 * o Caching an ire pointer in the conn requires a strict check for
20597 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20598 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20599 	 * in the conn is done after making sure under the bucket lock that the
20600 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20601 	 * caching an ire after the unplumb thread has cleaned up the conn.
20602 	 * If the conn does not send a packet subsequently the unplumb thread
20603 	 * will be hanging waiting for the ire count to drop to zero.
20604 	 *
20605 	 * o We also need to atomically test for a null conn_ire_cache and
20606 	 * set the conn_ire_cache under the the protection of the conn_lock
20607 	 * to avoid races among concurrent threads trying to simultaneously
20608 	 * cache an ire in the conn_ire_cache.
20609 	 */
20610 	mutex_enter(&connp->conn_lock);
20611 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20612 
20613 	if (ire != NULL && ire->ire_addr == dst &&
20614 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20615 
20616 		IRE_REFHOLD(ire);
20617 		mutex_exit(&connp->conn_lock);
20618 
20619 	} else {
20620 		boolean_t cached = B_FALSE;
20621 		connp->conn_ire_cache = NULL;
20622 		mutex_exit(&connp->conn_lock);
20623 		/* Release the old ire */
20624 		if (ire != NULL && sctp_ire == NULL)
20625 			IRE_REFRELE_NOTR(ire);
20626 
20627 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20628 		if (ire == NULL)
20629 			goto noirefound;
20630 		IRE_REFHOLD_NOTR(ire);
20631 
20632 		mutex_enter(&connp->conn_lock);
20633 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20634 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20635 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20636 				if (connp->conn_ulp == IPPROTO_TCP)
20637 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20638 				connp->conn_ire_cache = ire;
20639 				cached = B_TRUE;
20640 			}
20641 			rw_exit(&ire->ire_bucket->irb_lock);
20642 		}
20643 		mutex_exit(&connp->conn_lock);
20644 
20645 		/*
20646 		 * We can continue to use the ire but since it was
20647 		 * not cached, we should drop the extra reference.
20648 		 */
20649 		if (!cached)
20650 			IRE_REFRELE_NOTR(ire);
20651 	}
20652 
20653 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20654 	    "ip_wput_end: q %p (%S)", q, "end");
20655 
20656 	/*
20657 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20658 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20659 	 */
20660 	if (ire->ire_flags & RTF_MULTIRT) {
20661 		/*
20662 		 * Force the TTL of multirouted packets if required.
20663 		 * The TTL of such packets is bounded by the
20664 		 * ip_multirt_ttl ndd variable.
20665 		 */
20666 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20667 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20668 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20669 			    "(was %d), dst 0x%08x\n",
20670 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20671 			    ntohl(ire->ire_addr)));
20672 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20673 		}
20674 
20675 		/*
20676 		 * At this point, we check to see if there are any pending
20677 		 * unresolved routes. ire_multirt_resolvable()
20678 		 * checks in O(n) that all IRE_OFFSUBNET ire
20679 		 * entries for the packet's destination and
20680 		 * flagged RTF_MULTIRT are currently resolved.
20681 		 * If some remain unresolved, we make a copy
20682 		 * of the current message. It will be used
20683 		 * to initiate additional route resolutions.
20684 		 */
20685 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20686 		    msg_getlabel(first_mp), ipst);
20687 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20688 		    "multirt_need_resolve %d, first_mp %p\n",
20689 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20690 		if (multirt_need_resolve) {
20691 			copy_mp = copymsg(first_mp);
20692 			if (copy_mp != NULL) {
20693 				MULTIRT_DEBUG_TAG(copy_mp);
20694 			}
20695 		}
20696 	}
20697 
20698 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20699 
20700 	/*
20701 	 * Try to resolve another multiroute if
20702 	 * ire_multirt_resolvable() deemed it necessary
20703 	 */
20704 	if (copy_mp != NULL)
20705 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20706 	if (need_decref)
20707 		CONN_DEC_REF(connp);
20708 	return;
20709 
20710 qnext:
20711 	/*
20712 	 * Upper Level Protocols pass down complete IP datagrams
20713 	 * as M_DATA messages.	Everything else is a sideshow.
20714 	 *
20715 	 * 1) We could be re-entering ip_wput because of ip_neworute
20716 	 *    in which case we could have a IPSEC_OUT message. We
20717 	 *    need to pass through ip_wput like other datagrams and
20718 	 *    hence cannot branch to ip_wput_nondata.
20719 	 *
20720 	 * 2) ARP, AH, ESP, and other clients who are on the module
20721 	 *    instance of IP stream, give us something to deal with.
20722 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20723 	 *
20724 	 * 3) ICMP replies also could come here.
20725 	 */
20726 	ipst = ILLQ_TO_IPST(q);
20727 
20728 	if (DB_TYPE(mp) != M_DATA) {
20729 notdata:
20730 		if (DB_TYPE(mp) == M_CTL) {
20731 			/*
20732 			 * M_CTL messages are used by ARP, AH and ESP to
20733 			 * communicate with IP. We deal with IPSEC_IN and
20734 			 * IPSEC_OUT here. ip_wput_nondata handles other
20735 			 * cases.
20736 			 */
20737 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20738 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20739 				first_mp = mp->b_cont;
20740 				first_mp->b_flag &= ~MSGHASREF;
20741 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20742 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20743 				CONN_DEC_REF(connp);
20744 				connp = NULL;
20745 			}
20746 			if (ii->ipsec_info_type == IPSEC_IN) {
20747 				/*
20748 				 * Either this message goes back to
20749 				 * IPsec for further processing or to
20750 				 * ULP after policy checks.
20751 				 */
20752 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20753 				return;
20754 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20755 				io = (ipsec_out_t *)ii;
20756 				if (io->ipsec_out_proc_begin) {
20757 					/*
20758 					 * IPsec processing has already started.
20759 					 * Complete it.
20760 					 * IPQoS notes: We don't care what is
20761 					 * in ipsec_out_ill_index since this
20762 					 * won't be processed for IPQoS policies
20763 					 * in ipsec_out_process.
20764 					 */
20765 					ipsec_out_process(q, mp, NULL,
20766 					    io->ipsec_out_ill_index);
20767 					return;
20768 				} else {
20769 					connp = (q->q_next != NULL) ?
20770 					    NULL : Q_TO_CONN(q);
20771 					first_mp = mp;
20772 					mp = mp->b_cont;
20773 					mctl_present = B_TRUE;
20774 				}
20775 				zoneid = io->ipsec_out_zoneid;
20776 				ASSERT(zoneid != ALL_ZONES);
20777 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20778 				/*
20779 				 * It's an IPsec control message requesting
20780 				 * an SADB update to be sent to the IPsec
20781 				 * hardware acceleration capable ills.
20782 				 */
20783 				ipsec_ctl_t *ipsec_ctl =
20784 				    (ipsec_ctl_t *)mp->b_rptr;
20785 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20786 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20787 				mblk_t *cmp = mp->b_cont;
20788 
20789 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20790 				ASSERT(cmp != NULL);
20791 
20792 				freeb(mp);
20793 				ill_ipsec_capab_send_all(satype, cmp, sa,
20794 				    ipst->ips_netstack);
20795 				return;
20796 			} else {
20797 				/*
20798 				 * This must be ARP or special TSOL signaling.
20799 				 */
20800 				ip_wput_nondata(NULL, q, mp, NULL);
20801 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20802 				    "ip_wput_end: q %p (%S)", q, "nondata");
20803 				return;
20804 			}
20805 		} else {
20806 			/*
20807 			 * This must be non-(ARP/AH/ESP) messages.
20808 			 */
20809 			ASSERT(!need_decref);
20810 			ip_wput_nondata(NULL, q, mp, NULL);
20811 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20812 			    "ip_wput_end: q %p (%S)", q, "nondata");
20813 			return;
20814 		}
20815 	} else {
20816 		first_mp = mp;
20817 		mctl_present = B_FALSE;
20818 	}
20819 
20820 	ASSERT(first_mp != NULL);
20821 
20822 	if (mctl_present) {
20823 		io = (ipsec_out_t *)first_mp->b_rptr;
20824 		if (io->ipsec_out_ip_nexthop) {
20825 			/*
20826 			 * We may have lost the conn context if we are
20827 			 * coming here from ip_newroute(). Copy the
20828 			 * nexthop information.
20829 			 */
20830 			ip_nexthop = B_TRUE;
20831 			nexthop_addr = io->ipsec_out_nexthop_addr;
20832 
20833 			ipha = (ipha_t *)mp->b_rptr;
20834 			dst = ipha->ipha_dst;
20835 			goto send_from_ill;
20836 		}
20837 	}
20838 
20839 	ASSERT(xmit_ill == NULL);
20840 
20841 	/* We have a complete IP datagram heading outbound. */
20842 	ipha = (ipha_t *)mp->b_rptr;
20843 
20844 #ifndef SPEED_BEFORE_SAFETY
20845 	/*
20846 	 * Make sure we have a full-word aligned message and that at least
20847 	 * a simple IP header is accessible in the first message.  If not,
20848 	 * try a pullup.  For labeled systems we need to always take this
20849 	 * path as M_CTLs are "notdata" but have trailing data to process.
20850 	 */
20851 	if (!OK_32PTR(rptr) ||
20852 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20853 hdrtoosmall:
20854 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20855 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20856 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20857 			if (first_mp == NULL)
20858 				first_mp = mp;
20859 			goto discard_pkt;
20860 		}
20861 
20862 		/* This function assumes that mp points to an IPv4 packet. */
20863 		if (is_system_labeled() &&
20864 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20865 		    (connp == NULL || !connp->conn_ulp_labeled)) {
20866 			cred_t	*credp;
20867 			pid_t	pid;
20868 
20869 			if (connp != NULL) {
20870 				credp = BEST_CRED(mp, connp, &pid);
20871 				err = tsol_check_label(credp, &mp,
20872 				    connp->conn_mac_exempt, ipst, pid);
20873 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
20874 				err = tsol_check_label(credp, &mp,
20875 				    B_FALSE, ipst, pid);
20876 			}
20877 			ipha = (ipha_t *)mp->b_rptr;
20878 			if (mctl_present)
20879 				first_mp->b_cont = mp;
20880 			else
20881 				first_mp = mp;
20882 			if (err != 0) {
20883 				if (err == EINVAL)
20884 					goto icmp_parameter_problem;
20885 				ip2dbg(("ip_wput: label check failed (%d)\n",
20886 				    err));
20887 				goto discard_pkt;
20888 			}
20889 		}
20890 
20891 		ipha = (ipha_t *)mp->b_rptr;
20892 		if (first_mp == NULL) {
20893 			ASSERT(xmit_ill == NULL);
20894 			/*
20895 			 * If we got here because of "goto hdrtoosmall"
20896 			 * We need to attach a IPSEC_OUT.
20897 			 */
20898 			if (connp->conn_out_enforce_policy) {
20899 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20900 				    NULL, ipha->ipha_protocol,
20901 				    ipst->ips_netstack)) == NULL)) {
20902 					BUMP_MIB(&ipst->ips_ip_mib,
20903 					    ipIfStatsOutDiscards);
20904 					if (need_decref)
20905 						CONN_DEC_REF(connp);
20906 					return;
20907 				} else {
20908 					ASSERT(mp->b_datap->db_type == M_CTL);
20909 					first_mp = mp;
20910 					mp = mp->b_cont;
20911 					mctl_present = B_TRUE;
20912 				}
20913 			} else {
20914 				first_mp = mp;
20915 				mctl_present = B_FALSE;
20916 			}
20917 		}
20918 	}
20919 #endif
20920 
20921 	/* Most of the code below is written for speed, not readability */
20922 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20923 
20924 	/*
20925 	 * If ip_newroute() fails, we're going to need a full
20926 	 * header for the icmp wraparound.
20927 	 */
20928 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20929 		uint_t	v_hlen;
20930 version_hdrlen_check:
20931 		ASSERT(first_mp != NULL);
20932 		v_hlen = V_HLEN;
20933 		/*
20934 		 * siphon off IPv6 packets coming down from transport
20935 		 * layer modules here.
20936 		 * Note: high-order bit carries NUD reachability confirmation
20937 		 */
20938 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20939 			/*
20940 			 * FIXME: assume that callers of ip_output* call
20941 			 * the right version?
20942 			 */
20943 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20944 			ASSERT(xmit_ill == NULL);
20945 			if (need_decref)
20946 				mp->b_flag |= MSGHASREF;
20947 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20948 			return;
20949 		}
20950 
20951 		if ((v_hlen >> 4) != IP_VERSION) {
20952 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20953 			    "ip_wput_end: q %p (%S)", q, "badvers");
20954 			goto discard_pkt;
20955 		}
20956 		/*
20957 		 * Is the header length at least 20 bytes?
20958 		 *
20959 		 * Are there enough bytes accessible in the header?  If
20960 		 * not, try a pullup.
20961 		 */
20962 		v_hlen &= 0xF;
20963 		v_hlen <<= 2;
20964 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20965 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20966 			    "ip_wput_end: q %p (%S)", q, "badlen");
20967 			goto discard_pkt;
20968 		}
20969 		if (v_hlen > (mp->b_wptr - rptr)) {
20970 			if (!pullupmsg(mp, v_hlen)) {
20971 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20972 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20973 				goto discard_pkt;
20974 			}
20975 			ipha = (ipha_t *)mp->b_rptr;
20976 		}
20977 		/*
20978 		 * Move first entry from any source route into ipha_dst and
20979 		 * verify the options
20980 		 */
20981 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20982 		    zoneid, ipst)) {
20983 			ASSERT(xmit_ill == NULL);
20984 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20985 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20986 			    "ip_wput_end: q %p (%S)", q, "badopts");
20987 			if (need_decref)
20988 				CONN_DEC_REF(connp);
20989 			return;
20990 		}
20991 	}
20992 	dst = ipha->ipha_dst;
20993 
20994 	/*
20995 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20996 	 * we have to run the packet through ip_newroute which will take
20997 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20998 	 * a resolver, or assigning a default gateway, etc.
20999 	 */
21000 	if (CLASSD(dst)) {
21001 		ipif_t	*ipif;
21002 		uint32_t setsrc = 0;
21003 
21004 multicast:
21005 		ASSERT(first_mp != NULL);
21006 		ip2dbg(("ip_wput: CLASSD\n"));
21007 		if (connp == NULL) {
21008 			/*
21009 			 * Use the first good ipif on the ill.
21010 			 * XXX Should this ever happen? (Appears
21011 			 * to show up with just ppp and no ethernet due
21012 			 * to in.rdisc.)
21013 			 * However, ire_send should be able to
21014 			 * call ip_wput_ire directly.
21015 			 *
21016 			 * XXX Also, this can happen for ICMP and other packets
21017 			 * with multicast source addresses.  Perhaps we should
21018 			 * fix things so that we drop the packet in question,
21019 			 * but for now, just run with it.
21020 			 */
21021 			ill_t *ill = (ill_t *)q->q_ptr;
21022 
21023 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21024 			if (ipif == NULL) {
21025 				if (need_decref)
21026 					CONN_DEC_REF(connp);
21027 				freemsg(first_mp);
21028 				return;
21029 			}
21030 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21031 			    ntohl(dst), ill->ill_name));
21032 		} else {
21033 			/*
21034 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21035 			 * and IP_MULTICAST_IF.  The block comment above this
21036 			 * function explains the locking mechanism used here.
21037 			 */
21038 			if (xmit_ill == NULL) {
21039 				xmit_ill = conn_get_held_ill(connp,
21040 				    &connp->conn_outgoing_ill, &err);
21041 				if (err == ILL_LOOKUP_FAILED) {
21042 					ip1dbg(("ip_wput: No ill for "
21043 					    "IP_BOUND_IF\n"));
21044 					BUMP_MIB(&ipst->ips_ip_mib,
21045 					    ipIfStatsOutNoRoutes);
21046 					goto drop_pkt;
21047 				}
21048 			}
21049 
21050 			if (xmit_ill == NULL) {
21051 				ipif = conn_get_held_ipif(connp,
21052 				    &connp->conn_multicast_ipif, &err);
21053 				if (err == IPIF_LOOKUP_FAILED) {
21054 					ip1dbg(("ip_wput: No ipif for "
21055 					    "multicast\n"));
21056 					BUMP_MIB(&ipst->ips_ip_mib,
21057 					    ipIfStatsOutNoRoutes);
21058 					goto drop_pkt;
21059 				}
21060 			}
21061 			if (xmit_ill != NULL) {
21062 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21063 				if (ipif == NULL) {
21064 					ip1dbg(("ip_wput: No ipif for "
21065 					    "xmit_ill\n"));
21066 					BUMP_MIB(&ipst->ips_ip_mib,
21067 					    ipIfStatsOutNoRoutes);
21068 					goto drop_pkt;
21069 				}
21070 			} else if (ipif == NULL || ipif->ipif_isv6) {
21071 				/*
21072 				 * We must do this ipif determination here
21073 				 * else we could pass through ip_newroute
21074 				 * and come back here without the conn context.
21075 				 *
21076 				 * Note: we do late binding i.e. we bind to
21077 				 * the interface when the first packet is sent.
21078 				 * For performance reasons we do not rebind on
21079 				 * each packet but keep the binding until the
21080 				 * next IP_MULTICAST_IF option.
21081 				 *
21082 				 * conn_multicast_{ipif,ill} are shared between
21083 				 * IPv4 and IPv6 and AF_INET6 sockets can
21084 				 * send both IPv4 and IPv6 packets. Hence
21085 				 * we have to check that "isv6" matches above.
21086 				 */
21087 				if (ipif != NULL)
21088 					ipif_refrele(ipif);
21089 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21090 				if (ipif == NULL) {
21091 					ip1dbg(("ip_wput: No ipif for "
21092 					    "multicast\n"));
21093 					BUMP_MIB(&ipst->ips_ip_mib,
21094 					    ipIfStatsOutNoRoutes);
21095 					goto drop_pkt;
21096 				}
21097 				err = conn_set_held_ipif(connp,
21098 				    &connp->conn_multicast_ipif, ipif);
21099 				if (err == IPIF_LOOKUP_FAILED) {
21100 					ipif_refrele(ipif);
21101 					ip1dbg(("ip_wput: No ipif for "
21102 					    "multicast\n"));
21103 					BUMP_MIB(&ipst->ips_ip_mib,
21104 					    ipIfStatsOutNoRoutes);
21105 					goto drop_pkt;
21106 				}
21107 			}
21108 		}
21109 		ASSERT(!ipif->ipif_isv6);
21110 		/*
21111 		 * As we may lose the conn by the time we reach ip_wput_ire,
21112 		 * we copy conn_multicast_loop and conn_dontroute on to an
21113 		 * ipsec_out. In case if this datagram goes out secure,
21114 		 * we need the ill_index also. Copy that also into the
21115 		 * ipsec_out.
21116 		 */
21117 		if (mctl_present) {
21118 			io = (ipsec_out_t *)first_mp->b_rptr;
21119 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21120 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21121 		} else {
21122 			ASSERT(mp == first_mp);
21123 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21124 			    BPRI_HI)) == NULL) {
21125 				ipif_refrele(ipif);
21126 				first_mp = mp;
21127 				goto discard_pkt;
21128 			}
21129 			first_mp->b_datap->db_type = M_CTL;
21130 			first_mp->b_wptr += sizeof (ipsec_info_t);
21131 			/* ipsec_out_secure is B_FALSE now */
21132 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21133 			io = (ipsec_out_t *)first_mp->b_rptr;
21134 			io->ipsec_out_type = IPSEC_OUT;
21135 			io->ipsec_out_len = sizeof (ipsec_out_t);
21136 			io->ipsec_out_use_global_policy = B_TRUE;
21137 			io->ipsec_out_ns = ipst->ips_netstack;
21138 			first_mp->b_cont = mp;
21139 			mctl_present = B_TRUE;
21140 		}
21141 
21142 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21143 		io->ipsec_out_ill_index =
21144 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21145 
21146 		if (connp != NULL) {
21147 			io->ipsec_out_multicast_loop =
21148 			    connp->conn_multicast_loop;
21149 			io->ipsec_out_dontroute = connp->conn_dontroute;
21150 			io->ipsec_out_zoneid = connp->conn_zoneid;
21151 		}
21152 		/*
21153 		 * If the application uses IP_MULTICAST_IF with
21154 		 * different logical addresses of the same ILL, we
21155 		 * need to make sure that the soruce address of
21156 		 * the packet matches the logical IP address used
21157 		 * in the option. We do it by initializing ipha_src
21158 		 * here. This should keep IPsec also happy as
21159 		 * when we return from IPsec processing, we don't
21160 		 * have to worry about getting the right address on
21161 		 * the packet. Thus it is sufficient to look for
21162 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21163 		 * MATCH_IRE_IPIF.
21164 		 *
21165 		 * NOTE : We need to do it for non-secure case also as
21166 		 * this might go out secure if there is a global policy
21167 		 * match in ip_wput_ire.
21168 		 *
21169 		 * As we do not have the ire yet, it is possible that
21170 		 * we set the source address here and then later discover
21171 		 * that the ire implies the source address to be assigned
21172 		 * through the RTF_SETSRC flag.
21173 		 * In that case, the setsrc variable will remind us
21174 		 * that overwritting the source address by the one
21175 		 * of the RTF_SETSRC-flagged ire is allowed.
21176 		 */
21177 		if (ipha->ipha_src == INADDR_ANY &&
21178 		    (connp == NULL || !connp->conn_unspec_src)) {
21179 			ipha->ipha_src = ipif->ipif_src_addr;
21180 			setsrc = RTF_SETSRC;
21181 		}
21182 		/*
21183 		 * Find an IRE which matches the destination and the outgoing
21184 		 * queue (i.e. the outgoing interface.)
21185 		 * For loopback use a unicast IP address for
21186 		 * the ire lookup.
21187 		 */
21188 		if (IS_LOOPBACK(ipif->ipif_ill))
21189 			dst = ipif->ipif_lcl_addr;
21190 
21191 		/*
21192 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21193 		 * We don't need to lookup ire in ctable as the packet
21194 		 * needs to be sent to the destination through the specified
21195 		 * ill irrespective of ires in the cache table.
21196 		 */
21197 		ire = NULL;
21198 		if (xmit_ill == NULL) {
21199 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21200 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21201 		}
21202 
21203 		if (ire == NULL) {
21204 			/*
21205 			 * Multicast loopback and multicast forwarding is
21206 			 * done in ip_wput_ire.
21207 			 *
21208 			 * Mark this packet to make it be delivered to
21209 			 * ip_wput_ire after the new ire has been
21210 			 * created.
21211 			 *
21212 			 * The call to ip_newroute_ipif takes into account
21213 			 * the setsrc reminder. In any case, we take care
21214 			 * of the RTF_MULTIRT flag.
21215 			 */
21216 			mp->b_prev = mp->b_next = NULL;
21217 			if (xmit_ill == NULL ||
21218 			    xmit_ill->ill_ipif_up_count > 0) {
21219 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21220 				    setsrc | RTF_MULTIRT, zoneid, infop);
21221 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21222 				    "ip_wput_end: q %p (%S)", q, "noire");
21223 			} else {
21224 				freemsg(first_mp);
21225 			}
21226 			ipif_refrele(ipif);
21227 			if (xmit_ill != NULL)
21228 				ill_refrele(xmit_ill);
21229 			if (need_decref)
21230 				CONN_DEC_REF(connp);
21231 			return;
21232 		}
21233 
21234 		ipif_refrele(ipif);
21235 		ipif = NULL;
21236 		ASSERT(xmit_ill == NULL);
21237 
21238 		/*
21239 		 * Honor the RTF_SETSRC flag for multicast packets,
21240 		 * if allowed by the setsrc reminder.
21241 		 */
21242 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21243 			ipha->ipha_src = ire->ire_src_addr;
21244 		}
21245 
21246 		/*
21247 		 * Unconditionally force the TTL to 1 for
21248 		 * multirouted multicast packets:
21249 		 * multirouted multicast should not cross
21250 		 * multicast routers.
21251 		 */
21252 		if (ire->ire_flags & RTF_MULTIRT) {
21253 			if (ipha->ipha_ttl > 1) {
21254 				ip2dbg(("ip_wput: forcing multicast "
21255 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21256 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21257 				ipha->ipha_ttl = 1;
21258 			}
21259 		}
21260 	} else {
21261 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21262 		if ((ire != NULL) && (ire->ire_type &
21263 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21264 			ignore_dontroute = B_TRUE;
21265 			ignore_nexthop = B_TRUE;
21266 		}
21267 		if (ire != NULL) {
21268 			ire_refrele(ire);
21269 			ire = NULL;
21270 		}
21271 		/*
21272 		 * Guard against coming in from arp in which case conn is NULL.
21273 		 * Also guard against non M_DATA with dontroute set but
21274 		 * destined to local, loopback or broadcast addresses.
21275 		 */
21276 		if (connp != NULL && connp->conn_dontroute &&
21277 		    !ignore_dontroute) {
21278 dontroute:
21279 			/*
21280 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21281 			 * routing protocols from seeing false direct
21282 			 * connectivity.
21283 			 */
21284 			ipha->ipha_ttl = 1;
21285 			/* If suitable ipif not found, drop packet */
21286 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21287 			if (dst_ipif == NULL) {
21288 noroute:
21289 				ip1dbg(("ip_wput: no route for dst using"
21290 				    " SO_DONTROUTE\n"));
21291 				BUMP_MIB(&ipst->ips_ip_mib,
21292 				    ipIfStatsOutNoRoutes);
21293 				mp->b_prev = mp->b_next = NULL;
21294 				if (first_mp == NULL)
21295 					first_mp = mp;
21296 				goto drop_pkt;
21297 			} else {
21298 				/*
21299 				 * If suitable ipif has been found, set
21300 				 * xmit_ill to the corresponding
21301 				 * ipif_ill because we'll be using the
21302 				 * send_from_ill logic below.
21303 				 */
21304 				ASSERT(xmit_ill == NULL);
21305 				xmit_ill = dst_ipif->ipif_ill;
21306 				mutex_enter(&xmit_ill->ill_lock);
21307 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21308 					mutex_exit(&xmit_ill->ill_lock);
21309 					xmit_ill = NULL;
21310 					ipif_refrele(dst_ipif);
21311 					goto noroute;
21312 				}
21313 				ill_refhold_locked(xmit_ill);
21314 				mutex_exit(&xmit_ill->ill_lock);
21315 				ipif_refrele(dst_ipif);
21316 			}
21317 		}
21318 
21319 send_from_ill:
21320 		if (xmit_ill != NULL) {
21321 			ipif_t *ipif;
21322 
21323 			/*
21324 			 * Mark this packet as originated locally
21325 			 */
21326 			mp->b_prev = mp->b_next = NULL;
21327 
21328 			/*
21329 			 * Could be SO_DONTROUTE case also.
21330 			 * Verify that at least one ipif is up on the ill.
21331 			 */
21332 			if (xmit_ill->ill_ipif_up_count == 0) {
21333 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21334 				    xmit_ill->ill_name));
21335 				goto drop_pkt;
21336 			}
21337 
21338 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21339 			if (ipif == NULL) {
21340 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21341 				    xmit_ill->ill_name));
21342 				goto drop_pkt;
21343 			}
21344 
21345 			match_flags = 0;
21346 			if (IS_UNDER_IPMP(xmit_ill))
21347 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21348 
21349 			/*
21350 			 * Look for a ire that is part of the group,
21351 			 * if found use it else call ip_newroute_ipif.
21352 			 * IPCL_ZONEID is not used for matching because
21353 			 * IP_ALLZONES option is valid only when the
21354 			 * ill is accessible from all zones i.e has a
21355 			 * valid ipif in all zones.
21356 			 */
21357 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21358 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21359 			    msg_getlabel(mp), match_flags, ipst);
21360 			/*
21361 			 * If an ire exists use it or else create
21362 			 * an ire but don't add it to the cache.
21363 			 * Adding an ire may cause issues with
21364 			 * asymmetric routing.
21365 			 * In case of multiroute always act as if
21366 			 * ire does not exist.
21367 			 */
21368 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21369 				if (ire != NULL)
21370 					ire_refrele(ire);
21371 				ip_newroute_ipif(q, first_mp, ipif,
21372 				    dst, connp, 0, zoneid, infop);
21373 				ipif_refrele(ipif);
21374 				ip1dbg(("ip_output: xmit_ill via %s\n",
21375 				    xmit_ill->ill_name));
21376 				ill_refrele(xmit_ill);
21377 				if (need_decref)
21378 					CONN_DEC_REF(connp);
21379 				return;
21380 			}
21381 			ipif_refrele(ipif);
21382 		} else if (ip_nexthop || (connp != NULL &&
21383 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21384 			if (!ip_nexthop) {
21385 				ip_nexthop = B_TRUE;
21386 				nexthop_addr = connp->conn_nexthop_v4;
21387 			}
21388 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21389 			    MATCH_IRE_GW;
21390 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21391 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21392 		} else {
21393 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21394 			    ipst);
21395 		}
21396 		if (!ire) {
21397 			if (ip_nexthop && !ignore_nexthop) {
21398 				if (mctl_present) {
21399 					io = (ipsec_out_t *)first_mp->b_rptr;
21400 					ASSERT(first_mp->b_datap->db_type ==
21401 					    M_CTL);
21402 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21403 				} else {
21404 					ASSERT(mp == first_mp);
21405 					first_mp = allocb(
21406 					    sizeof (ipsec_info_t), BPRI_HI);
21407 					if (first_mp == NULL) {
21408 						first_mp = mp;
21409 						goto discard_pkt;
21410 					}
21411 					first_mp->b_datap->db_type = M_CTL;
21412 					first_mp->b_wptr +=
21413 					    sizeof (ipsec_info_t);
21414 					/* ipsec_out_secure is B_FALSE now */
21415 					bzero(first_mp->b_rptr,
21416 					    sizeof (ipsec_info_t));
21417 					io = (ipsec_out_t *)first_mp->b_rptr;
21418 					io->ipsec_out_type = IPSEC_OUT;
21419 					io->ipsec_out_len =
21420 					    sizeof (ipsec_out_t);
21421 					io->ipsec_out_use_global_policy =
21422 					    B_TRUE;
21423 					io->ipsec_out_ns = ipst->ips_netstack;
21424 					first_mp->b_cont = mp;
21425 					mctl_present = B_TRUE;
21426 				}
21427 				io->ipsec_out_ip_nexthop = ip_nexthop;
21428 				io->ipsec_out_nexthop_addr = nexthop_addr;
21429 			}
21430 noirefound:
21431 			/*
21432 			 * Mark this packet as having originated on
21433 			 * this machine.  This will be noted in
21434 			 * ire_add_then_send, which needs to know
21435 			 * whether to run it back through ip_wput or
21436 			 * ip_rput following successful resolution.
21437 			 */
21438 			mp->b_prev = NULL;
21439 			mp->b_next = NULL;
21440 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21441 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21442 			    "ip_wput_end: q %p (%S)", q, "newroute");
21443 			if (xmit_ill != NULL)
21444 				ill_refrele(xmit_ill);
21445 			if (need_decref)
21446 				CONN_DEC_REF(connp);
21447 			return;
21448 		}
21449 	}
21450 
21451 	/* We now know where we are going with it. */
21452 
21453 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21454 	    "ip_wput_end: q %p (%S)", q, "end");
21455 
21456 	/*
21457 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21458 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21459 	 */
21460 	if (ire->ire_flags & RTF_MULTIRT) {
21461 		/*
21462 		 * Force the TTL of multirouted packets if required.
21463 		 * The TTL of such packets is bounded by the
21464 		 * ip_multirt_ttl ndd variable.
21465 		 */
21466 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21467 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21468 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21469 			    "(was %d), dst 0x%08x\n",
21470 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21471 			    ntohl(ire->ire_addr)));
21472 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21473 		}
21474 		/*
21475 		 * At this point, we check to see if there are any pending
21476 		 * unresolved routes. ire_multirt_resolvable()
21477 		 * checks in O(n) that all IRE_OFFSUBNET ire
21478 		 * entries for the packet's destination and
21479 		 * flagged RTF_MULTIRT are currently resolved.
21480 		 * If some remain unresolved, we make a copy
21481 		 * of the current message. It will be used
21482 		 * to initiate additional route resolutions.
21483 		 */
21484 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21485 		    msg_getlabel(first_mp), ipst);
21486 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21487 		    "multirt_need_resolve %d, first_mp %p\n",
21488 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21489 		if (multirt_need_resolve) {
21490 			copy_mp = copymsg(first_mp);
21491 			if (copy_mp != NULL) {
21492 				MULTIRT_DEBUG_TAG(copy_mp);
21493 			}
21494 		}
21495 	}
21496 
21497 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21498 	/*
21499 	 * Try to resolve another multiroute if
21500 	 * ire_multirt_resolvable() deemed it necessary.
21501 	 * At this point, we need to distinguish
21502 	 * multicasts from other packets. For multicasts,
21503 	 * we call ip_newroute_ipif() and request that both
21504 	 * multirouting and setsrc flags are checked.
21505 	 */
21506 	if (copy_mp != NULL) {
21507 		if (CLASSD(dst)) {
21508 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21509 			if (ipif) {
21510 				ASSERT(infop->ip_opt_ill_index == 0);
21511 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21512 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21513 				ipif_refrele(ipif);
21514 			} else {
21515 				MULTIRT_DEBUG_UNTAG(copy_mp);
21516 				freemsg(copy_mp);
21517 				copy_mp = NULL;
21518 			}
21519 		} else {
21520 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21521 		}
21522 	}
21523 	if (xmit_ill != NULL)
21524 		ill_refrele(xmit_ill);
21525 	if (need_decref)
21526 		CONN_DEC_REF(connp);
21527 	return;
21528 
21529 icmp_parameter_problem:
21530 	/* could not have originated externally */
21531 	ASSERT(mp->b_prev == NULL);
21532 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21533 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21534 		/* it's the IP header length that's in trouble */
21535 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21536 		first_mp = NULL;
21537 	}
21538 
21539 discard_pkt:
21540 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21541 drop_pkt:
21542 	ip1dbg(("ip_wput: dropped packet\n"));
21543 	if (ire != NULL)
21544 		ire_refrele(ire);
21545 	if (need_decref)
21546 		CONN_DEC_REF(connp);
21547 	freemsg(first_mp);
21548 	if (xmit_ill != NULL)
21549 		ill_refrele(xmit_ill);
21550 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21551 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21552 }
21553 
21554 /*
21555  * If this is a conn_t queue, then we pass in the conn. This includes the
21556  * zoneid.
21557  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21558  * in which case we use the global zoneid since those are all part of
21559  * the global zone.
21560  */
21561 void
21562 ip_wput(queue_t *q, mblk_t *mp)
21563 {
21564 	if (CONN_Q(q))
21565 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21566 	else
21567 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21568 }
21569 
21570 /*
21571  *
21572  * The following rules must be observed when accessing any ipif or ill
21573  * that has been cached in the conn. Typically conn_outgoing_ill,
21574  * conn_multicast_ipif and conn_multicast_ill.
21575  *
21576  * Access: The ipif or ill pointed to from the conn can be accessed under
21577  * the protection of the conn_lock or after it has been refheld under the
21578  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21579  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21580  * The reason for this is that a concurrent unplumb could actually be
21581  * cleaning up these cached pointers by walking the conns and might have
21582  * finished cleaning up the conn in question. The macros check that an
21583  * unplumb has not yet started on the ipif or ill.
21584  *
21585  * Caching: An ipif or ill pointer may be cached in the conn only after
21586  * making sure that an unplumb has not started. So the caching is done
21587  * while holding both the conn_lock and the ill_lock and after using the
21588  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21589  * flag before starting the cleanup of conns.
21590  *
21591  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21592  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21593  * or a reference to the ipif or a reference to an ire that references the
21594  * ipif. An ipif only changes its ill when migrating from an underlying ill
21595  * to an IPMP ill in ipif_up().
21596  */
21597 ipif_t *
21598 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21599 {
21600 	ipif_t	*ipif;
21601 	ill_t	*ill;
21602 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21603 
21604 	*err = 0;
21605 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21606 	mutex_enter(&connp->conn_lock);
21607 	ipif = *ipifp;
21608 	if (ipif != NULL) {
21609 		ill = ipif->ipif_ill;
21610 		mutex_enter(&ill->ill_lock);
21611 		if (IPIF_CAN_LOOKUP(ipif)) {
21612 			ipif_refhold_locked(ipif);
21613 			mutex_exit(&ill->ill_lock);
21614 			mutex_exit(&connp->conn_lock);
21615 			rw_exit(&ipst->ips_ill_g_lock);
21616 			return (ipif);
21617 		} else {
21618 			*err = IPIF_LOOKUP_FAILED;
21619 		}
21620 		mutex_exit(&ill->ill_lock);
21621 	}
21622 	mutex_exit(&connp->conn_lock);
21623 	rw_exit(&ipst->ips_ill_g_lock);
21624 	return (NULL);
21625 }
21626 
21627 ill_t *
21628 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21629 {
21630 	ill_t	*ill;
21631 
21632 	*err = 0;
21633 	mutex_enter(&connp->conn_lock);
21634 	ill = *illp;
21635 	if (ill != NULL) {
21636 		mutex_enter(&ill->ill_lock);
21637 		if (ILL_CAN_LOOKUP(ill)) {
21638 			ill_refhold_locked(ill);
21639 			mutex_exit(&ill->ill_lock);
21640 			mutex_exit(&connp->conn_lock);
21641 			return (ill);
21642 		} else {
21643 			*err = ILL_LOOKUP_FAILED;
21644 		}
21645 		mutex_exit(&ill->ill_lock);
21646 	}
21647 	mutex_exit(&connp->conn_lock);
21648 	return (NULL);
21649 }
21650 
21651 static int
21652 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21653 {
21654 	ill_t	*ill;
21655 
21656 	ill = ipif->ipif_ill;
21657 	mutex_enter(&connp->conn_lock);
21658 	mutex_enter(&ill->ill_lock);
21659 	if (IPIF_CAN_LOOKUP(ipif)) {
21660 		*ipifp = ipif;
21661 		mutex_exit(&ill->ill_lock);
21662 		mutex_exit(&connp->conn_lock);
21663 		return (0);
21664 	}
21665 	mutex_exit(&ill->ill_lock);
21666 	mutex_exit(&connp->conn_lock);
21667 	return (IPIF_LOOKUP_FAILED);
21668 }
21669 
21670 /*
21671  * This is called if the outbound datagram needs fragmentation.
21672  *
21673  * NOTE : This function does not ire_refrele the ire argument passed in.
21674  */
21675 static void
21676 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21677     ip_stack_t *ipst, conn_t *connp)
21678 {
21679 	ipha_t		*ipha;
21680 	mblk_t		*mp;
21681 	uint32_t	v_hlen_tos_len;
21682 	uint32_t	max_frag;
21683 	uint32_t	frag_flag;
21684 	boolean_t	dont_use;
21685 
21686 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21687 		mp = ipsec_mp->b_cont;
21688 	} else {
21689 		mp = ipsec_mp;
21690 	}
21691 
21692 	ipha = (ipha_t *)mp->b_rptr;
21693 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21694 
21695 #ifdef	_BIG_ENDIAN
21696 #define	V_HLEN	(v_hlen_tos_len >> 24)
21697 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21698 #else
21699 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21700 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21701 #endif
21702 
21703 #ifndef SPEED_BEFORE_SAFETY
21704 	/*
21705 	 * Check that ipha_length is consistent with
21706 	 * the mblk length
21707 	 */
21708 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21709 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21710 		    LENGTH, msgdsize(mp)));
21711 		freemsg(ipsec_mp);
21712 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21713 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21714 		    "packet length mismatch");
21715 		return;
21716 	}
21717 #endif
21718 	/*
21719 	 * Don't use frag_flag if pre-built packet or source
21720 	 * routed or if multicast (since multicast packets do not solicit
21721 	 * ICMP "packet too big" messages). Get the values of
21722 	 * max_frag and frag_flag atomically by acquiring the
21723 	 * ire_lock.
21724 	 */
21725 	mutex_enter(&ire->ire_lock);
21726 	max_frag = ire->ire_max_frag;
21727 	frag_flag = ire->ire_frag_flag;
21728 	mutex_exit(&ire->ire_lock);
21729 
21730 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21731 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21732 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21733 
21734 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21735 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21736 }
21737 
21738 /*
21739  * Used for deciding the MSS size for the upper layer. Thus
21740  * we need to check the outbound policy values in the conn.
21741  */
21742 int
21743 conn_ipsec_length(conn_t *connp)
21744 {
21745 	ipsec_latch_t *ipl;
21746 
21747 	ipl = connp->conn_latch;
21748 	if (ipl == NULL)
21749 		return (0);
21750 
21751 	if (ipl->ipl_out_policy == NULL)
21752 		return (0);
21753 
21754 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21755 }
21756 
21757 /*
21758  * Returns an estimate of the IPsec headers size. This is used if
21759  * we don't want to call into IPsec to get the exact size.
21760  */
21761 int
21762 ipsec_out_extra_length(mblk_t *ipsec_mp)
21763 {
21764 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21765 	ipsec_action_t *a;
21766 
21767 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21768 	if (!io->ipsec_out_secure)
21769 		return (0);
21770 
21771 	a = io->ipsec_out_act;
21772 
21773 	if (a == NULL) {
21774 		ASSERT(io->ipsec_out_policy != NULL);
21775 		a = io->ipsec_out_policy->ipsp_act;
21776 	}
21777 	ASSERT(a != NULL);
21778 
21779 	return (a->ipa_ovhd);
21780 }
21781 
21782 /*
21783  * Returns an estimate of the IPsec headers size. This is used if
21784  * we don't want to call into IPsec to get the exact size.
21785  */
21786 int
21787 ipsec_in_extra_length(mblk_t *ipsec_mp)
21788 {
21789 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21790 	ipsec_action_t *a;
21791 
21792 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21793 
21794 	a = ii->ipsec_in_action;
21795 	return (a == NULL ? 0 : a->ipa_ovhd);
21796 }
21797 
21798 /*
21799  * If there are any source route options, return the true final
21800  * destination. Otherwise, return the destination.
21801  */
21802 ipaddr_t
21803 ip_get_dst(ipha_t *ipha)
21804 {
21805 	ipoptp_t	opts;
21806 	uchar_t		*opt;
21807 	uint8_t		optval;
21808 	uint8_t		optlen;
21809 	ipaddr_t	dst;
21810 	uint32_t off;
21811 
21812 	dst = ipha->ipha_dst;
21813 
21814 	if (IS_SIMPLE_IPH(ipha))
21815 		return (dst);
21816 
21817 	for (optval = ipoptp_first(&opts, ipha);
21818 	    optval != IPOPT_EOL;
21819 	    optval = ipoptp_next(&opts)) {
21820 		opt = opts.ipoptp_cur;
21821 		optlen = opts.ipoptp_len;
21822 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21823 		switch (optval) {
21824 		case IPOPT_SSRR:
21825 		case IPOPT_LSRR:
21826 			off = opt[IPOPT_OFFSET];
21827 			/*
21828 			 * If one of the conditions is true, it means
21829 			 * end of options and dst already has the right
21830 			 * value.
21831 			 */
21832 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21833 				off = optlen - IP_ADDR_LEN;
21834 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21835 			}
21836 			return (dst);
21837 		default:
21838 			break;
21839 		}
21840 	}
21841 
21842 	return (dst);
21843 }
21844 
21845 mblk_t *
21846 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21847     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21848 {
21849 	ipsec_out_t	*io;
21850 	mblk_t		*first_mp;
21851 	boolean_t policy_present;
21852 	ip_stack_t	*ipst;
21853 	ipsec_stack_t	*ipss;
21854 
21855 	ASSERT(ire != NULL);
21856 	ipst = ire->ire_ipst;
21857 	ipss = ipst->ips_netstack->netstack_ipsec;
21858 
21859 	first_mp = mp;
21860 	if (mp->b_datap->db_type == M_CTL) {
21861 		io = (ipsec_out_t *)first_mp->b_rptr;
21862 		/*
21863 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21864 		 *
21865 		 * 1) There is per-socket policy (including cached global
21866 		 *    policy) or a policy on the IP-in-IP tunnel.
21867 		 * 2) There is no per-socket policy, but it is
21868 		 *    a multicast packet that needs to go out
21869 		 *    on a specific interface. This is the case
21870 		 *    where (ip_wput and ip_wput_multicast) attaches
21871 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21872 		 *
21873 		 * In case (2) we check with global policy to
21874 		 * see if there is a match and set the ill_index
21875 		 * appropriately so that we can lookup the ire
21876 		 * properly in ip_wput_ipsec_out.
21877 		 */
21878 
21879 		/*
21880 		 * ipsec_out_use_global_policy is set to B_FALSE
21881 		 * in ipsec_in_to_out(). Refer to that function for
21882 		 * details.
21883 		 */
21884 		if ((io->ipsec_out_latch == NULL) &&
21885 		    (io->ipsec_out_use_global_policy)) {
21886 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21887 			    ire, connp, unspec_src, zoneid));
21888 		}
21889 		if (!io->ipsec_out_secure) {
21890 			/*
21891 			 * If this is not a secure packet, drop
21892 			 * the IPSEC_OUT mp and treat it as a clear
21893 			 * packet. This happens when we are sending
21894 			 * a ICMP reply back to a clear packet. See
21895 			 * ipsec_in_to_out() for details.
21896 			 */
21897 			mp = first_mp->b_cont;
21898 			freeb(first_mp);
21899 		}
21900 		return (mp);
21901 	}
21902 	/*
21903 	 * See whether we need to attach a global policy here. We
21904 	 * don't depend on the conn (as it could be null) for deciding
21905 	 * what policy this datagram should go through because it
21906 	 * should have happened in ip_wput if there was some
21907 	 * policy. This normally happens for connections which are not
21908 	 * fully bound preventing us from caching policies in
21909 	 * ip_bind. Packets coming from the TCP listener/global queue
21910 	 * - which are non-hard_bound - could also be affected by
21911 	 * applying policy here.
21912 	 *
21913 	 * If this packet is coming from tcp global queue or listener,
21914 	 * we will be applying policy here.  This may not be *right*
21915 	 * if these packets are coming from the detached connection as
21916 	 * it could have gone in clear before. This happens only if a
21917 	 * TCP connection started when there is no policy and somebody
21918 	 * added policy before it became detached. Thus packets of the
21919 	 * detached connection could go out secure and the other end
21920 	 * would drop it because it will be expecting in clear. The
21921 	 * converse is not true i.e if somebody starts a TCP
21922 	 * connection and deletes the policy, all the packets will
21923 	 * still go out with the policy that existed before deleting
21924 	 * because ip_unbind sends up policy information which is used
21925 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21926 	 * TCP to attach a dummy IPSEC_OUT and set
21927 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21928 	 * affect performance for normal cases, we are not doing it.
21929 	 * Thus, set policy before starting any TCP connections.
21930 	 *
21931 	 * NOTE - We might apply policy even for a hard bound connection
21932 	 * - for which we cached policy in ip_bind - if somebody added
21933 	 * global policy after we inherited the policy in ip_bind.
21934 	 * This means that the packets that were going out in clear
21935 	 * previously would start going secure and hence get dropped
21936 	 * on the other side. To fix this, TCP attaches a dummy
21937 	 * ipsec_out and make sure that we don't apply global policy.
21938 	 */
21939 	if (ipha != NULL)
21940 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21941 	else
21942 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21943 	if (!policy_present)
21944 		return (mp);
21945 
21946 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21947 	    zoneid));
21948 }
21949 
21950 /*
21951  * This function does the ire_refrele of the ire passed in as the
21952  * argument. As this function looks up more ires i.e broadcast ires,
21953  * it needs to REFRELE them. Currently, for simplicity we don't
21954  * differentiate the one passed in and looked up here. We always
21955  * REFRELE.
21956  * IPQoS Notes:
21957  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21958  * IPsec packets are done in ipsec_out_process.
21959  */
21960 void
21961 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21962     zoneid_t zoneid)
21963 {
21964 	ipha_t		*ipha;
21965 #define	rptr	((uchar_t *)ipha)
21966 	queue_t		*stq;
21967 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21968 	uint32_t	v_hlen_tos_len;
21969 	uint32_t	ttl_protocol;
21970 	ipaddr_t	src;
21971 	ipaddr_t	dst;
21972 	uint32_t	cksum;
21973 	ipaddr_t	orig_src;
21974 	ire_t		*ire1;
21975 	mblk_t		*next_mp;
21976 	uint_t		hlen;
21977 	uint16_t	*up;
21978 	uint32_t	max_frag = ire->ire_max_frag;
21979 	ill_t		*ill = ire_to_ill(ire);
21980 	int		clusterwide;
21981 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21982 	int		ipsec_len;
21983 	mblk_t		*first_mp;
21984 	ipsec_out_t	*io;
21985 	boolean_t	conn_dontroute;		/* conn value for multicast */
21986 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21987 	boolean_t	multicast_forward;	/* Should we forward ? */
21988 	boolean_t	unspec_src;
21989 	ill_t		*conn_outgoing_ill = NULL;
21990 	ill_t		*ire_ill;
21991 	ill_t		*ire1_ill;
21992 	ill_t		*out_ill;
21993 	uint32_t 	ill_index = 0;
21994 	boolean_t	multirt_send = B_FALSE;
21995 	int		err;
21996 	ipxmit_state_t	pktxmit_state;
21997 	ip_stack_t	*ipst = ire->ire_ipst;
21998 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21999 
22000 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22001 	    "ip_wput_ire_start: q %p", q);
22002 
22003 	multicast_forward = B_FALSE;
22004 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22005 
22006 	if (ire->ire_flags & RTF_MULTIRT) {
22007 		/*
22008 		 * Multirouting case. The bucket where ire is stored
22009 		 * probably holds other RTF_MULTIRT flagged ire
22010 		 * to the destination. In this call to ip_wput_ire,
22011 		 * we attempt to send the packet through all
22012 		 * those ires. Thus, we first ensure that ire is the
22013 		 * first RTF_MULTIRT ire in the bucket,
22014 		 * before walking the ire list.
22015 		 */
22016 		ire_t *first_ire;
22017 		irb_t *irb = ire->ire_bucket;
22018 		ASSERT(irb != NULL);
22019 
22020 		/* Make sure we do not omit any multiroute ire. */
22021 		IRB_REFHOLD(irb);
22022 		for (first_ire = irb->irb_ire;
22023 		    first_ire != NULL;
22024 		    first_ire = first_ire->ire_next) {
22025 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22026 			    (first_ire->ire_addr == ire->ire_addr) &&
22027 			    !(first_ire->ire_marks &
22028 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22029 				break;
22030 		}
22031 
22032 		if ((first_ire != NULL) && (first_ire != ire)) {
22033 			IRE_REFHOLD(first_ire);
22034 			ire_refrele(ire);
22035 			ire = first_ire;
22036 			ill = ire_to_ill(ire);
22037 		}
22038 		IRB_REFRELE(irb);
22039 	}
22040 
22041 	/*
22042 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22043 	 * for performance we don't grab the mutexs in the fastpath
22044 	 */
22045 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22046 	    connp->conn_outgoing_ill != NULL) {
22047 		conn_outgoing_ill = conn_get_held_ill(connp,
22048 		    &connp->conn_outgoing_ill, &err);
22049 		if (err == ILL_LOOKUP_FAILED) {
22050 			ire_refrele(ire);
22051 			freemsg(mp);
22052 			return;
22053 		}
22054 	}
22055 
22056 	if (mp->b_datap->db_type != M_CTL) {
22057 		ipha = (ipha_t *)mp->b_rptr;
22058 	} else {
22059 		io = (ipsec_out_t *)mp->b_rptr;
22060 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22061 		ASSERT(zoneid == io->ipsec_out_zoneid);
22062 		ASSERT(zoneid != ALL_ZONES);
22063 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22064 		dst = ipha->ipha_dst;
22065 		/*
22066 		 * For the multicast case, ipsec_out carries conn_dontroute and
22067 		 * conn_multicast_loop as conn may not be available here. We
22068 		 * need this for multicast loopback and forwarding which is done
22069 		 * later in the code.
22070 		 */
22071 		if (CLASSD(dst)) {
22072 			conn_dontroute = io->ipsec_out_dontroute;
22073 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22074 			/*
22075 			 * If conn_dontroute is not set or conn_multicast_loop
22076 			 * is set, we need to do forwarding/loopback. For
22077 			 * datagrams from ip_wput_multicast, conn_dontroute is
22078 			 * set to B_TRUE and conn_multicast_loop is set to
22079 			 * B_FALSE so that we neither do forwarding nor
22080 			 * loopback.
22081 			 */
22082 			if (!conn_dontroute || conn_multicast_loop)
22083 				multicast_forward = B_TRUE;
22084 		}
22085 	}
22086 
22087 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22088 	    ire->ire_zoneid != ALL_ZONES) {
22089 		/*
22090 		 * When a zone sends a packet to another zone, we try to deliver
22091 		 * the packet under the same conditions as if the destination
22092 		 * was a real node on the network. To do so, we look for a
22093 		 * matching route in the forwarding table.
22094 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22095 		 * ip_newroute() does.
22096 		 * Note that IRE_LOCAL are special, since they are used
22097 		 * when the zoneid doesn't match in some cases. This means that
22098 		 * we need to handle ipha_src differently since ire_src_addr
22099 		 * belongs to the receiving zone instead of the sending zone.
22100 		 * When ip_restrict_interzone_loopback is set, then
22101 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22102 		 * for loopback between zones when the logical "Ethernet" would
22103 		 * have looped them back.
22104 		 */
22105 		ire_t *src_ire;
22106 
22107 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22108 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22109 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22110 		if (src_ire != NULL &&
22111 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22112 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22113 		    ire_local_same_lan(ire, src_ire))) {
22114 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22115 				ipha->ipha_src = src_ire->ire_src_addr;
22116 			ire_refrele(src_ire);
22117 		} else {
22118 			ire_refrele(ire);
22119 			if (conn_outgoing_ill != NULL)
22120 				ill_refrele(conn_outgoing_ill);
22121 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22122 			if (src_ire != NULL) {
22123 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22124 					ire_refrele(src_ire);
22125 					freemsg(mp);
22126 					return;
22127 				}
22128 				ire_refrele(src_ire);
22129 			}
22130 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22131 				/* Failed */
22132 				freemsg(mp);
22133 				return;
22134 			}
22135 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22136 			    ipst);
22137 			return;
22138 		}
22139 	}
22140 
22141 	if (mp->b_datap->db_type == M_CTL ||
22142 	    ipss->ipsec_outbound_v4_policy_present) {
22143 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22144 		    unspec_src, zoneid);
22145 		if (mp == NULL) {
22146 			ire_refrele(ire);
22147 			if (conn_outgoing_ill != NULL)
22148 				ill_refrele(conn_outgoing_ill);
22149 			return;
22150 		}
22151 		/*
22152 		 * Trusted Extensions supports all-zones interfaces, so
22153 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22154 		 * the global zone.
22155 		 */
22156 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22157 			io = (ipsec_out_t *)mp->b_rptr;
22158 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22159 			zoneid = io->ipsec_out_zoneid;
22160 		}
22161 	}
22162 
22163 	first_mp = mp;
22164 	ipsec_len = 0;
22165 
22166 	if (first_mp->b_datap->db_type == M_CTL) {
22167 		io = (ipsec_out_t *)first_mp->b_rptr;
22168 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22169 		mp = first_mp->b_cont;
22170 		ipsec_len = ipsec_out_extra_length(first_mp);
22171 		ASSERT(ipsec_len >= 0);
22172 		/* We already picked up the zoneid from the M_CTL above */
22173 		ASSERT(zoneid == io->ipsec_out_zoneid);
22174 		ASSERT(zoneid != ALL_ZONES);
22175 
22176 		/*
22177 		 * Drop M_CTL here if IPsec processing is not needed.
22178 		 * (Non-IPsec use of M_CTL extracted any information it
22179 		 * needed above).
22180 		 */
22181 		if (ipsec_len == 0) {
22182 			freeb(first_mp);
22183 			first_mp = mp;
22184 		}
22185 	}
22186 
22187 	/*
22188 	 * Fast path for ip_wput_ire
22189 	 */
22190 
22191 	ipha = (ipha_t *)mp->b_rptr;
22192 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22193 	dst = ipha->ipha_dst;
22194 
22195 	/*
22196 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22197 	 * if the socket is a SOCK_RAW type. The transport checksum should
22198 	 * be provided in the pre-built packet, so we don't need to compute it.
22199 	 * Also, other application set flags, like DF, should not be altered.
22200 	 * Other transport MUST pass down zero.
22201 	 */
22202 	ip_hdr_included = ipha->ipha_ident;
22203 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22204 
22205 	if (CLASSD(dst)) {
22206 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22207 		    ntohl(dst),
22208 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22209 		    ntohl(ire->ire_addr)));
22210 	}
22211 
22212 /* Macros to extract header fields from data already in registers */
22213 #ifdef	_BIG_ENDIAN
22214 #define	V_HLEN	(v_hlen_tos_len >> 24)
22215 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22216 #define	PROTO	(ttl_protocol & 0xFF)
22217 #else
22218 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22219 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22220 #define	PROTO	(ttl_protocol >> 8)
22221 #endif
22222 
22223 	orig_src = src = ipha->ipha_src;
22224 	/* (The loop back to "another" is explained down below.) */
22225 another:;
22226 	/*
22227 	 * Assign an ident value for this packet.  We assign idents on
22228 	 * a per destination basis out of the IRE.  There could be
22229 	 * other threads targeting the same destination, so we have to
22230 	 * arrange for a atomic increment.  Note that we use a 32-bit
22231 	 * atomic add because it has better performance than its
22232 	 * 16-bit sibling.
22233 	 *
22234 	 * If running in cluster mode and if the source address
22235 	 * belongs to a replicated service then vector through
22236 	 * cl_inet_ipident vector to allocate ip identifier
22237 	 * NOTE: This is a contract private interface with the
22238 	 * clustering group.
22239 	 */
22240 	clusterwide = 0;
22241 	if (cl_inet_ipident) {
22242 		ASSERT(cl_inet_isclusterwide);
22243 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22244 
22245 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22246 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22247 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22248 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22249 			    (uint8_t *)(uintptr_t)dst, NULL);
22250 			clusterwide = 1;
22251 		}
22252 	}
22253 	if (!clusterwide) {
22254 		ipha->ipha_ident =
22255 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22256 	}
22257 
22258 #ifndef _BIG_ENDIAN
22259 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22260 #endif
22261 
22262 	/*
22263 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22264 	 * This is needed to obey conn_unspec_src when packets go through
22265 	 * ip_newroute + arp.
22266 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22267 	 */
22268 	if (src == INADDR_ANY && !unspec_src) {
22269 		/*
22270 		 * Assign the appropriate source address from the IRE if none
22271 		 * was specified.
22272 		 */
22273 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22274 
22275 		src = ire->ire_src_addr;
22276 		if (connp == NULL) {
22277 			ip1dbg(("ip_wput_ire: no connp and no src "
22278 			    "address for dst 0x%x, using src 0x%x\n",
22279 			    ntohl(dst),
22280 			    ntohl(src)));
22281 		}
22282 		ipha->ipha_src = src;
22283 	}
22284 	stq = ire->ire_stq;
22285 
22286 	/*
22287 	 * We only allow ire chains for broadcasts since there will
22288 	 * be multiple IRE_CACHE entries for the same multicast
22289 	 * address (one per ipif).
22290 	 */
22291 	next_mp = NULL;
22292 
22293 	/* broadcast packet */
22294 	if (ire->ire_type == IRE_BROADCAST)
22295 		goto broadcast;
22296 
22297 	/* loopback ? */
22298 	if (stq == NULL)
22299 		goto nullstq;
22300 
22301 	/* The ill_index for outbound ILL */
22302 	ill_index = Q_TO_INDEX(stq);
22303 
22304 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22305 	ttl_protocol = ((uint16_t *)ipha)[4];
22306 
22307 	/* pseudo checksum (do it in parts for IP header checksum) */
22308 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22309 
22310 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22311 		queue_t *dev_q = stq->q_next;
22312 
22313 		/*
22314 		 * For DIRECT_CAPABLE, we do flow control at
22315 		 * the time of sending the packet. See
22316 		 * ILL_SEND_TX().
22317 		 */
22318 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22319 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22320 			goto blocked;
22321 
22322 		if ((PROTO == IPPROTO_UDP) &&
22323 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22324 			hlen = (V_HLEN & 0xF) << 2;
22325 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22326 			if (*up != 0) {
22327 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22328 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22329 				/* Software checksum? */
22330 				if (DB_CKSUMFLAGS(mp) == 0) {
22331 					IP_STAT(ipst, ip_out_sw_cksum);
22332 					IP_STAT_UPDATE(ipst,
22333 					    ip_udp_out_sw_cksum_bytes,
22334 					    LENGTH - hlen);
22335 				}
22336 			}
22337 		}
22338 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22339 		hlen = (V_HLEN & 0xF) << 2;
22340 		if (PROTO == IPPROTO_TCP) {
22341 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22342 			/*
22343 			 * The packet header is processed once and for all, even
22344 			 * in the multirouting case. We disable hardware
22345 			 * checksum if the packet is multirouted, as it will be
22346 			 * replicated via several interfaces, and not all of
22347 			 * them may have this capability.
22348 			 */
22349 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22350 			    LENGTH, max_frag, ipsec_len, cksum);
22351 			/* Software checksum? */
22352 			if (DB_CKSUMFLAGS(mp) == 0) {
22353 				IP_STAT(ipst, ip_out_sw_cksum);
22354 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22355 				    LENGTH - hlen);
22356 			}
22357 		} else {
22358 			sctp_hdr_t	*sctph;
22359 
22360 			ASSERT(PROTO == IPPROTO_SCTP);
22361 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22362 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22363 			/*
22364 			 * Zero out the checksum field to ensure proper
22365 			 * checksum calculation.
22366 			 */
22367 			sctph->sh_chksum = 0;
22368 #ifdef	DEBUG
22369 			if (!skip_sctp_cksum)
22370 #endif
22371 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22372 		}
22373 	}
22374 
22375 	/*
22376 	 * If this is a multicast packet and originated from ip_wput
22377 	 * we need to do loopback and forwarding checks. If it comes
22378 	 * from ip_wput_multicast, we SHOULD not do this.
22379 	 */
22380 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22381 
22382 	/* checksum */
22383 	cksum += ttl_protocol;
22384 
22385 	/* fragment the packet */
22386 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22387 		goto fragmentit;
22388 	/*
22389 	 * Don't use frag_flag if packet is pre-built or source
22390 	 * routed or if multicast (since multicast packets do
22391 	 * not solicit ICMP "packet too big" messages).
22392 	 */
22393 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22394 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22395 	    !ip_source_route_included(ipha)) &&
22396 	    !CLASSD(ipha->ipha_dst))
22397 		ipha->ipha_fragment_offset_and_flags |=
22398 		    htons(ire->ire_frag_flag);
22399 
22400 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22401 		/* calculate IP header checksum */
22402 		cksum += ipha->ipha_ident;
22403 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22404 		cksum += ipha->ipha_fragment_offset_and_flags;
22405 
22406 		/* IP options present */
22407 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22408 		if (hlen)
22409 			goto checksumoptions;
22410 
22411 		/* calculate hdr checksum */
22412 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22413 		cksum = ~(cksum + (cksum >> 16));
22414 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22415 	}
22416 	if (ipsec_len != 0) {
22417 		/*
22418 		 * We will do the rest of the processing after
22419 		 * we come back from IPsec in ip_wput_ipsec_out().
22420 		 */
22421 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22422 
22423 		io = (ipsec_out_t *)first_mp->b_rptr;
22424 		io->ipsec_out_ill_index =
22425 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22426 		ipsec_out_process(q, first_mp, ire, 0);
22427 		ire_refrele(ire);
22428 		if (conn_outgoing_ill != NULL)
22429 			ill_refrele(conn_outgoing_ill);
22430 		return;
22431 	}
22432 
22433 	/*
22434 	 * In most cases, the emission loop below is entered only
22435 	 * once. Only in the case where the ire holds the
22436 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22437 	 * flagged ires in the bucket, and send the packet
22438 	 * through all crossed RTF_MULTIRT routes.
22439 	 */
22440 	if (ire->ire_flags & RTF_MULTIRT) {
22441 		multirt_send = B_TRUE;
22442 	}
22443 	do {
22444 		if (multirt_send) {
22445 			irb_t *irb;
22446 			/*
22447 			 * We are in a multiple send case, need to get
22448 			 * the next ire and make a duplicate of the packet.
22449 			 * ire1 holds here the next ire to process in the
22450 			 * bucket. If multirouting is expected,
22451 			 * any non-RTF_MULTIRT ire that has the
22452 			 * right destination address is ignored.
22453 			 */
22454 			irb = ire->ire_bucket;
22455 			ASSERT(irb != NULL);
22456 
22457 			IRB_REFHOLD(irb);
22458 			for (ire1 = ire->ire_next;
22459 			    ire1 != NULL;
22460 			    ire1 = ire1->ire_next) {
22461 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22462 					continue;
22463 				if (ire1->ire_addr != ire->ire_addr)
22464 					continue;
22465 				if (ire1->ire_marks &
22466 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22467 					continue;
22468 
22469 				/* Got one */
22470 				IRE_REFHOLD(ire1);
22471 				break;
22472 			}
22473 			IRB_REFRELE(irb);
22474 
22475 			if (ire1 != NULL) {
22476 				next_mp = copyb(mp);
22477 				if ((next_mp == NULL) ||
22478 				    ((mp->b_cont != NULL) &&
22479 				    ((next_mp->b_cont =
22480 				    dupmsg(mp->b_cont)) == NULL))) {
22481 					freemsg(next_mp);
22482 					next_mp = NULL;
22483 					ire_refrele(ire1);
22484 					ire1 = NULL;
22485 				}
22486 			}
22487 
22488 			/* Last multiroute ire; don't loop anymore. */
22489 			if (ire1 == NULL) {
22490 				multirt_send = B_FALSE;
22491 			}
22492 		}
22493 
22494 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22495 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22496 		    mblk_t *, mp);
22497 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22498 		    ipst->ips_ipv4firewall_physical_out,
22499 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22500 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22501 
22502 		if (mp == NULL)
22503 			goto release_ire_and_ill;
22504 
22505 		if (ipst->ips_ip4_observe.he_interested) {
22506 			zoneid_t szone;
22507 
22508 			/*
22509 			 * On the outbound path the destination zone will be
22510 			 * unknown as we're sending this packet out on the
22511 			 * wire.
22512 			 */
22513 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22514 			    ALL_ZONES);
22515 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22516 			    ire->ire_ipif->ipif_ill, ipst);
22517 		}
22518 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22519 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22520 
22521 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22522 
22523 		if ((pktxmit_state == SEND_FAILED) ||
22524 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22525 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22526 			    "- packet dropped\n"));
22527 release_ire_and_ill:
22528 			ire_refrele(ire);
22529 			if (next_mp != NULL) {
22530 				freemsg(next_mp);
22531 				ire_refrele(ire1);
22532 			}
22533 			if (conn_outgoing_ill != NULL)
22534 				ill_refrele(conn_outgoing_ill);
22535 			return;
22536 		}
22537 
22538 		if (CLASSD(dst)) {
22539 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22540 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22541 			    LENGTH);
22542 		}
22543 
22544 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22545 		    "ip_wput_ire_end: q %p (%S)",
22546 		    q, "last copy out");
22547 		IRE_REFRELE(ire);
22548 
22549 		if (multirt_send) {
22550 			ASSERT(ire1);
22551 			/*
22552 			 * Proceed with the next RTF_MULTIRT ire,
22553 			 * Also set up the send-to queue accordingly.
22554 			 */
22555 			ire = ire1;
22556 			ire1 = NULL;
22557 			stq = ire->ire_stq;
22558 			mp = next_mp;
22559 			next_mp = NULL;
22560 			ipha = (ipha_t *)mp->b_rptr;
22561 			ill_index = Q_TO_INDEX(stq);
22562 			ill = (ill_t *)stq->q_ptr;
22563 		}
22564 	} while (multirt_send);
22565 	if (conn_outgoing_ill != NULL)
22566 		ill_refrele(conn_outgoing_ill);
22567 	return;
22568 
22569 	/*
22570 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22571 	 */
22572 broadcast:
22573 	{
22574 		/*
22575 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22576 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22577 		 * can be overridden stack-wide through the ip_broadcast_ttl
22578 		 * ndd tunable, or on a per-connection basis through the
22579 		 * IP_BROADCAST_TTL socket option.
22580 		 *
22581 		 * In the event that we are replying to incoming ICMP packets,
22582 		 * connp could be NULL.
22583 		 */
22584 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22585 		if (connp != NULL) {
22586 			if (connp->conn_dontroute)
22587 				ipha->ipha_ttl = 1;
22588 			else if (connp->conn_broadcast_ttl != 0)
22589 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22590 		}
22591 
22592 		/*
22593 		 * Note that we are not doing a IRB_REFHOLD here.
22594 		 * Actually we don't care if the list changes i.e
22595 		 * if somebody deletes an IRE from the list while
22596 		 * we drop the lock, the next time we come around
22597 		 * ire_next will be NULL and hence we won't send
22598 		 * out multiple copies which is fine.
22599 		 */
22600 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22601 		ire1 = ire->ire_next;
22602 		if (conn_outgoing_ill != NULL) {
22603 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22604 				ASSERT(ire1 == ire->ire_next);
22605 				if (ire1 != NULL && ire1->ire_addr == dst) {
22606 					ire_refrele(ire);
22607 					ire = ire1;
22608 					IRE_REFHOLD(ire);
22609 					ire1 = ire->ire_next;
22610 					continue;
22611 				}
22612 				rw_exit(&ire->ire_bucket->irb_lock);
22613 				/* Did not find a matching ill */
22614 				ip1dbg(("ip_wput_ire: broadcast with no "
22615 				    "matching IP_BOUND_IF ill %s dst %x\n",
22616 				    conn_outgoing_ill->ill_name, dst));
22617 				freemsg(first_mp);
22618 				if (ire != NULL)
22619 					ire_refrele(ire);
22620 				ill_refrele(conn_outgoing_ill);
22621 				return;
22622 			}
22623 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22624 			/*
22625 			 * If the next IRE has the same address and is not one
22626 			 * of the two copies that we need to send, try to see
22627 			 * whether this copy should be sent at all. This
22628 			 * assumes that we insert loopbacks first and then
22629 			 * non-loopbacks. This is acheived by inserting the
22630 			 * loopback always before non-loopback.
22631 			 * This is used to send a single copy of a broadcast
22632 			 * packet out all physical interfaces that have an
22633 			 * matching IRE_BROADCAST while also looping
22634 			 * back one copy (to ip_wput_local) for each
22635 			 * matching physical interface. However, we avoid
22636 			 * sending packets out different logical that match by
22637 			 * having ipif_up/ipif_down supress duplicate
22638 			 * IRE_BROADCASTS.
22639 			 *
22640 			 * This feature is currently used to get broadcasts
22641 			 * sent to multiple interfaces, when the broadcast
22642 			 * address being used applies to multiple interfaces.
22643 			 * For example, a whole net broadcast will be
22644 			 * replicated on every connected subnet of
22645 			 * the target net.
22646 			 *
22647 			 * Each zone has its own set of IRE_BROADCASTs, so that
22648 			 * we're able to distribute inbound packets to multiple
22649 			 * zones who share a broadcast address. We avoid looping
22650 			 * back outbound packets in different zones but on the
22651 			 * same ill, as the application would see duplicates.
22652 			 *
22653 			 * This logic assumes that ire_add_v4() groups the
22654 			 * IRE_BROADCAST entries so that those with the same
22655 			 * ire_addr are kept together.
22656 			 */
22657 			ire_ill = ire->ire_ipif->ipif_ill;
22658 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22659 				while (ire1 != NULL && ire1->ire_addr == dst) {
22660 					ire1_ill = ire1->ire_ipif->ipif_ill;
22661 					if (ire1_ill != ire_ill)
22662 						break;
22663 					ire1 = ire1->ire_next;
22664 				}
22665 			}
22666 		}
22667 		ASSERT(multirt_send == B_FALSE);
22668 		if (ire1 != NULL && ire1->ire_addr == dst) {
22669 			if ((ire->ire_flags & RTF_MULTIRT) &&
22670 			    (ire1->ire_flags & RTF_MULTIRT)) {
22671 				/*
22672 				 * We are in the multirouting case.
22673 				 * The message must be sent at least
22674 				 * on both ires. These ires have been
22675 				 * inserted AFTER the standard ones
22676 				 * in ip_rt_add(). There are thus no
22677 				 * other ire entries for the destination
22678 				 * address in the rest of the bucket
22679 				 * that do not have the RTF_MULTIRT
22680 				 * flag. We don't process a copy
22681 				 * of the message here. This will be
22682 				 * done in the final sending loop.
22683 				 */
22684 				multirt_send = B_TRUE;
22685 			} else {
22686 				next_mp = ip_copymsg(first_mp);
22687 				if (next_mp != NULL)
22688 					IRE_REFHOLD(ire1);
22689 			}
22690 		}
22691 		rw_exit(&ire->ire_bucket->irb_lock);
22692 	}
22693 
22694 	if (stq) {
22695 		/*
22696 		 * A non-NULL send-to queue means this packet is going
22697 		 * out of this machine.
22698 		 */
22699 		out_ill = (ill_t *)stq->q_ptr;
22700 
22701 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22702 		ttl_protocol = ((uint16_t *)ipha)[4];
22703 		/*
22704 		 * We accumulate the pseudo header checksum in cksum.
22705 		 * This is pretty hairy code, so watch close.  One
22706 		 * thing to keep in mind is that UDP and TCP have
22707 		 * stored their respective datagram lengths in their
22708 		 * checksum fields.  This lines things up real nice.
22709 		 */
22710 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22711 		    (src >> 16) + (src & 0xFFFF);
22712 		/*
22713 		 * We assume the udp checksum field contains the
22714 		 * length, so to compute the pseudo header checksum,
22715 		 * all we need is the protocol number and src/dst.
22716 		 */
22717 		/* Provide the checksums for UDP and TCP. */
22718 		if ((PROTO == IPPROTO_TCP) &&
22719 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22720 			/* hlen gets the number of uchar_ts in the IP header */
22721 			hlen = (V_HLEN & 0xF) << 2;
22722 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22723 			IP_STAT(ipst, ip_out_sw_cksum);
22724 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22725 			    LENGTH - hlen);
22726 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22727 		} else if (PROTO == IPPROTO_SCTP &&
22728 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22729 			sctp_hdr_t	*sctph;
22730 
22731 			hlen = (V_HLEN & 0xF) << 2;
22732 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22733 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22734 			sctph->sh_chksum = 0;
22735 #ifdef	DEBUG
22736 			if (!skip_sctp_cksum)
22737 #endif
22738 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22739 		} else {
22740 			queue_t	*dev_q = stq->q_next;
22741 
22742 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22743 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22744 blocked:
22745 				ipha->ipha_ident = ip_hdr_included;
22746 				/*
22747 				 * If we don't have a conn to apply
22748 				 * backpressure, free the message.
22749 				 * In the ire_send path, we don't know
22750 				 * the position to requeue the packet. Rather
22751 				 * than reorder packets, we just drop this
22752 				 * packet.
22753 				 */
22754 				if (ipst->ips_ip_output_queue &&
22755 				    connp != NULL &&
22756 				    caller != IRE_SEND) {
22757 					if (caller == IP_WSRV) {
22758 						idl_tx_list_t *idl_txl;
22759 
22760 						idl_txl =
22761 						    &ipst->ips_idl_tx_list[0];
22762 						connp->conn_did_putbq = 1;
22763 						(void) putbq(connp->conn_wq,
22764 						    first_mp);
22765 						conn_drain_insert(connp,
22766 						    idl_txl);
22767 						/*
22768 						 * This is the service thread,
22769 						 * and the queue is already
22770 						 * noenabled. The check for
22771 						 * canput and the putbq is not
22772 						 * atomic. So we need to check
22773 						 * again.
22774 						 */
22775 						if (canput(stq->q_next))
22776 							connp->conn_did_putbq
22777 							    = 0;
22778 						IP_STAT(ipst, ip_conn_flputbq);
22779 					} else {
22780 						/*
22781 						 * We are not the service proc.
22782 						 * ip_wsrv will be scheduled or
22783 						 * is already running.
22784 						 */
22785 
22786 						(void) putq(connp->conn_wq,
22787 						    first_mp);
22788 					}
22789 				} else {
22790 					out_ill = (ill_t *)stq->q_ptr;
22791 					BUMP_MIB(out_ill->ill_ip_mib,
22792 					    ipIfStatsOutDiscards);
22793 					freemsg(first_mp);
22794 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22795 					    "ip_wput_ire_end: q %p (%S)",
22796 					    q, "discard");
22797 				}
22798 				ire_refrele(ire);
22799 				if (next_mp) {
22800 					ire_refrele(ire1);
22801 					freemsg(next_mp);
22802 				}
22803 				if (conn_outgoing_ill != NULL)
22804 					ill_refrele(conn_outgoing_ill);
22805 				return;
22806 			}
22807 			if ((PROTO == IPPROTO_UDP) &&
22808 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22809 				/*
22810 				 * hlen gets the number of uchar_ts in the
22811 				 * IP header
22812 				 */
22813 				hlen = (V_HLEN & 0xF) << 2;
22814 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22815 				max_frag = ire->ire_max_frag;
22816 				if (*up != 0) {
22817 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22818 					    up, PROTO, hlen, LENGTH, max_frag,
22819 					    ipsec_len, cksum);
22820 					/* Software checksum? */
22821 					if (DB_CKSUMFLAGS(mp) == 0) {
22822 						IP_STAT(ipst, ip_out_sw_cksum);
22823 						IP_STAT_UPDATE(ipst,
22824 						    ip_udp_out_sw_cksum_bytes,
22825 						    LENGTH - hlen);
22826 					}
22827 				}
22828 			}
22829 		}
22830 		/*
22831 		 * Need to do this even when fragmenting. The local
22832 		 * loopback can be done without computing checksums
22833 		 * but forwarding out other interface must be done
22834 		 * after the IP checksum (and ULP checksums) have been
22835 		 * computed.
22836 		 *
22837 		 * NOTE : multicast_forward is set only if this packet
22838 		 * originated from ip_wput. For packets originating from
22839 		 * ip_wput_multicast, it is not set.
22840 		 */
22841 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22842 multi_loopback:
22843 			ip2dbg(("ip_wput: multicast, loop %d\n",
22844 			    conn_multicast_loop));
22845 
22846 			/*  Forget header checksum offload */
22847 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22848 
22849 			/*
22850 			 * Local loopback of multicasts?  Check the
22851 			 * ill.
22852 			 *
22853 			 * Note that the loopback function will not come
22854 			 * in through ip_rput - it will only do the
22855 			 * client fanout thus we need to do an mforward
22856 			 * as well.  The is different from the BSD
22857 			 * logic.
22858 			 */
22859 			if (ill != NULL) {
22860 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22861 				    ALL_ZONES) != NULL) {
22862 					/*
22863 					 * Pass along the virtual output q.
22864 					 * ip_wput_local() will distribute the
22865 					 * packet to all the matching zones,
22866 					 * except the sending zone when
22867 					 * IP_MULTICAST_LOOP is false.
22868 					 */
22869 					ip_multicast_loopback(q, ill, first_mp,
22870 					    conn_multicast_loop ? 0 :
22871 					    IP_FF_NO_MCAST_LOOP, zoneid);
22872 				}
22873 			}
22874 			if (ipha->ipha_ttl == 0) {
22875 				/*
22876 				 * 0 => only to this host i.e. we are
22877 				 * done. We are also done if this was the
22878 				 * loopback interface since it is sufficient
22879 				 * to loopback one copy of a multicast packet.
22880 				 */
22881 				freemsg(first_mp);
22882 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22883 				    "ip_wput_ire_end: q %p (%S)",
22884 				    q, "loopback");
22885 				ire_refrele(ire);
22886 				if (conn_outgoing_ill != NULL)
22887 					ill_refrele(conn_outgoing_ill);
22888 				return;
22889 			}
22890 			/*
22891 			 * ILLF_MULTICAST is checked in ip_newroute
22892 			 * i.e. we don't need to check it here since
22893 			 * all IRE_CACHEs come from ip_newroute.
22894 			 * For multicast traffic, SO_DONTROUTE is interpreted
22895 			 * to mean only send the packet out the interface
22896 			 * (optionally specified with IP_MULTICAST_IF)
22897 			 * and do not forward it out additional interfaces.
22898 			 * RSVP and the rsvp daemon is an example of a
22899 			 * protocol and user level process that
22900 			 * handles it's own routing. Hence, it uses the
22901 			 * SO_DONTROUTE option to accomplish this.
22902 			 */
22903 
22904 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22905 			    ill != NULL) {
22906 				/* Unconditionally redo the checksum */
22907 				ipha->ipha_hdr_checksum = 0;
22908 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22909 
22910 				/*
22911 				 * If this needs to go out secure, we need
22912 				 * to wait till we finish the IPsec
22913 				 * processing.
22914 				 */
22915 				if (ipsec_len == 0 &&
22916 				    ip_mforward(ill, ipha, mp)) {
22917 					freemsg(first_mp);
22918 					ip1dbg(("ip_wput: mforward failed\n"));
22919 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22920 					    "ip_wput_ire_end: q %p (%S)",
22921 					    q, "mforward failed");
22922 					ire_refrele(ire);
22923 					if (conn_outgoing_ill != NULL)
22924 						ill_refrele(conn_outgoing_ill);
22925 					return;
22926 				}
22927 			}
22928 		}
22929 		max_frag = ire->ire_max_frag;
22930 		cksum += ttl_protocol;
22931 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22932 			/* No fragmentation required for this one. */
22933 			/*
22934 			 * Don't use frag_flag if packet is pre-built or source
22935 			 * routed or if multicast (since multicast packets do
22936 			 * not solicit ICMP "packet too big" messages).
22937 			 */
22938 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22939 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22940 			    !ip_source_route_included(ipha)) &&
22941 			    !CLASSD(ipha->ipha_dst))
22942 				ipha->ipha_fragment_offset_and_flags |=
22943 				    htons(ire->ire_frag_flag);
22944 
22945 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22946 				/* Complete the IP header checksum. */
22947 				cksum += ipha->ipha_ident;
22948 				cksum += (v_hlen_tos_len >> 16)+
22949 				    (v_hlen_tos_len & 0xFFFF);
22950 				cksum += ipha->ipha_fragment_offset_and_flags;
22951 				hlen = (V_HLEN & 0xF) -
22952 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22953 				if (hlen) {
22954 checksumoptions:
22955 					/*
22956 					 * Account for the IP Options in the IP
22957 					 * header checksum.
22958 					 */
22959 					up = (uint16_t *)(rptr+
22960 					    IP_SIMPLE_HDR_LENGTH);
22961 					do {
22962 						cksum += up[0];
22963 						cksum += up[1];
22964 						up += 2;
22965 					} while (--hlen);
22966 				}
22967 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22968 				cksum = ~(cksum + (cksum >> 16));
22969 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22970 			}
22971 			if (ipsec_len != 0) {
22972 				ipsec_out_process(q, first_mp, ire, ill_index);
22973 				if (!next_mp) {
22974 					ire_refrele(ire);
22975 					if (conn_outgoing_ill != NULL)
22976 						ill_refrele(conn_outgoing_ill);
22977 					return;
22978 				}
22979 				goto next;
22980 			}
22981 
22982 			/*
22983 			 * multirt_send has already been handled
22984 			 * for broadcast, but not yet for multicast
22985 			 * or IP options.
22986 			 */
22987 			if (next_mp == NULL) {
22988 				if (ire->ire_flags & RTF_MULTIRT) {
22989 					multirt_send = B_TRUE;
22990 				}
22991 			}
22992 
22993 			/*
22994 			 * In most cases, the emission loop below is
22995 			 * entered only once. Only in the case where
22996 			 * the ire holds the RTF_MULTIRT flag, do we loop
22997 			 * to process all RTF_MULTIRT ires in the bucket,
22998 			 * and send the packet through all crossed
22999 			 * RTF_MULTIRT routes.
23000 			 */
23001 			do {
23002 				if (multirt_send) {
23003 					irb_t *irb;
23004 
23005 					irb = ire->ire_bucket;
23006 					ASSERT(irb != NULL);
23007 					/*
23008 					 * We are in a multiple send case,
23009 					 * need to get the next IRE and make
23010 					 * a duplicate of the packet.
23011 					 */
23012 					IRB_REFHOLD(irb);
23013 					for (ire1 = ire->ire_next;
23014 					    ire1 != NULL;
23015 					    ire1 = ire1->ire_next) {
23016 						if (!(ire1->ire_flags &
23017 						    RTF_MULTIRT))
23018 							continue;
23019 
23020 						if (ire1->ire_addr !=
23021 						    ire->ire_addr)
23022 							continue;
23023 
23024 						if (ire1->ire_marks &
23025 						    (IRE_MARK_CONDEMNED |
23026 						    IRE_MARK_TESTHIDDEN))
23027 							continue;
23028 
23029 						/* Got one */
23030 						IRE_REFHOLD(ire1);
23031 						break;
23032 					}
23033 					IRB_REFRELE(irb);
23034 
23035 					if (ire1 != NULL) {
23036 						next_mp = copyb(mp);
23037 						if ((next_mp == NULL) ||
23038 						    ((mp->b_cont != NULL) &&
23039 						    ((next_mp->b_cont =
23040 						    dupmsg(mp->b_cont))
23041 						    == NULL))) {
23042 							freemsg(next_mp);
23043 							next_mp = NULL;
23044 							ire_refrele(ire1);
23045 							ire1 = NULL;
23046 						}
23047 					}
23048 
23049 					/*
23050 					 * Last multiroute ire; don't loop
23051 					 * anymore. The emission is over
23052 					 * and next_mp is NULL.
23053 					 */
23054 					if (ire1 == NULL) {
23055 						multirt_send = B_FALSE;
23056 					}
23057 				}
23058 
23059 				out_ill = ire_to_ill(ire);
23060 				DTRACE_PROBE4(ip4__physical__out__start,
23061 				    ill_t *, NULL,
23062 				    ill_t *, out_ill,
23063 				    ipha_t *, ipha, mblk_t *, mp);
23064 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23065 				    ipst->ips_ipv4firewall_physical_out,
23066 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23067 				DTRACE_PROBE1(ip4__physical__out__end,
23068 				    mblk_t *, mp);
23069 				if (mp == NULL)
23070 					goto release_ire_and_ill_2;
23071 
23072 				ASSERT(ipsec_len == 0);
23073 				mp->b_prev =
23074 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23075 				DTRACE_PROBE2(ip__xmit__2,
23076 				    mblk_t *, mp, ire_t *, ire);
23077 				pktxmit_state = ip_xmit_v4(mp, ire,
23078 				    NULL, B_TRUE, connp);
23079 				if ((pktxmit_state == SEND_FAILED) ||
23080 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23081 release_ire_and_ill_2:
23082 					if (next_mp) {
23083 						freemsg(next_mp);
23084 						ire_refrele(ire1);
23085 					}
23086 					ire_refrele(ire);
23087 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23088 					    "ip_wput_ire_end: q %p (%S)",
23089 					    q, "discard MDATA");
23090 					if (conn_outgoing_ill != NULL)
23091 						ill_refrele(conn_outgoing_ill);
23092 					return;
23093 				}
23094 
23095 				if (CLASSD(dst)) {
23096 					BUMP_MIB(out_ill->ill_ip_mib,
23097 					    ipIfStatsHCOutMcastPkts);
23098 					UPDATE_MIB(out_ill->ill_ip_mib,
23099 					    ipIfStatsHCOutMcastOctets,
23100 					    LENGTH);
23101 				} else if (ire->ire_type == IRE_BROADCAST) {
23102 					BUMP_MIB(out_ill->ill_ip_mib,
23103 					    ipIfStatsHCOutBcastPkts);
23104 				}
23105 
23106 				if (multirt_send) {
23107 					/*
23108 					 * We are in a multiple send case,
23109 					 * need to re-enter the sending loop
23110 					 * using the next ire.
23111 					 */
23112 					ire_refrele(ire);
23113 					ire = ire1;
23114 					stq = ire->ire_stq;
23115 					mp = next_mp;
23116 					next_mp = NULL;
23117 					ipha = (ipha_t *)mp->b_rptr;
23118 					ill_index = Q_TO_INDEX(stq);
23119 				}
23120 			} while (multirt_send);
23121 
23122 			if (!next_mp) {
23123 				/*
23124 				 * Last copy going out (the ultra-common
23125 				 * case).  Note that we intentionally replicate
23126 				 * the putnext rather than calling it before
23127 				 * the next_mp check in hopes of a little
23128 				 * tail-call action out of the compiler.
23129 				 */
23130 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23131 				    "ip_wput_ire_end: q %p (%S)",
23132 				    q, "last copy out(1)");
23133 				ire_refrele(ire);
23134 				if (conn_outgoing_ill != NULL)
23135 					ill_refrele(conn_outgoing_ill);
23136 				return;
23137 			}
23138 			/* More copies going out below. */
23139 		} else {
23140 			int offset;
23141 fragmentit:
23142 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23143 			/*
23144 			 * If this would generate a icmp_frag_needed message,
23145 			 * we need to handle it before we do the IPsec
23146 			 * processing. Otherwise, we need to strip the IPsec
23147 			 * headers before we send up the message to the ULPs
23148 			 * which becomes messy and difficult.
23149 			 */
23150 			if (ipsec_len != 0) {
23151 				if ((max_frag < (unsigned int)(LENGTH +
23152 				    ipsec_len)) && (offset & IPH_DF)) {
23153 					out_ill = (ill_t *)stq->q_ptr;
23154 					BUMP_MIB(out_ill->ill_ip_mib,
23155 					    ipIfStatsOutFragFails);
23156 					BUMP_MIB(out_ill->ill_ip_mib,
23157 					    ipIfStatsOutFragReqds);
23158 					ipha->ipha_hdr_checksum = 0;
23159 					ipha->ipha_hdr_checksum =
23160 					    (uint16_t)ip_csum_hdr(ipha);
23161 					icmp_frag_needed(ire->ire_stq, first_mp,
23162 					    max_frag, zoneid, ipst);
23163 					if (!next_mp) {
23164 						ire_refrele(ire);
23165 						if (conn_outgoing_ill != NULL) {
23166 							ill_refrele(
23167 							    conn_outgoing_ill);
23168 						}
23169 						return;
23170 					}
23171 				} else {
23172 					/*
23173 					 * This won't cause a icmp_frag_needed
23174 					 * message. to be generated. Send it on
23175 					 * the wire. Note that this could still
23176 					 * cause fragmentation and all we
23177 					 * do is the generation of the message
23178 					 * to the ULP if needed before IPsec.
23179 					 */
23180 					if (!next_mp) {
23181 						ipsec_out_process(q, first_mp,
23182 						    ire, ill_index);
23183 						TRACE_2(TR_FAC_IP,
23184 						    TR_IP_WPUT_IRE_END,
23185 						    "ip_wput_ire_end: q %p "
23186 						    "(%S)", q,
23187 						    "last ipsec_out_process");
23188 						ire_refrele(ire);
23189 						if (conn_outgoing_ill != NULL) {
23190 							ill_refrele(
23191 							    conn_outgoing_ill);
23192 						}
23193 						return;
23194 					}
23195 					ipsec_out_process(q, first_mp,
23196 					    ire, ill_index);
23197 				}
23198 			} else {
23199 				/*
23200 				 * Initiate IPPF processing. For
23201 				 * fragmentable packets we finish
23202 				 * all QOS packet processing before
23203 				 * calling:
23204 				 * ip_wput_ire_fragmentit->ip_wput_frag
23205 				 */
23206 
23207 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23208 					ip_process(IPP_LOCAL_OUT, &mp,
23209 					    ill_index);
23210 					if (mp == NULL) {
23211 						out_ill = (ill_t *)stq->q_ptr;
23212 						BUMP_MIB(out_ill->ill_ip_mib,
23213 						    ipIfStatsOutDiscards);
23214 						if (next_mp != NULL) {
23215 							freemsg(next_mp);
23216 							ire_refrele(ire1);
23217 						}
23218 						ire_refrele(ire);
23219 						TRACE_2(TR_FAC_IP,
23220 						    TR_IP_WPUT_IRE_END,
23221 						    "ip_wput_ire: q %p (%S)",
23222 						    q, "discard MDATA");
23223 						if (conn_outgoing_ill != NULL) {
23224 							ill_refrele(
23225 							    conn_outgoing_ill);
23226 						}
23227 						return;
23228 					}
23229 				}
23230 				if (!next_mp) {
23231 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23232 					    "ip_wput_ire_end: q %p (%S)",
23233 					    q, "last fragmentation");
23234 					ip_wput_ire_fragmentit(mp, ire,
23235 					    zoneid, ipst, connp);
23236 					ire_refrele(ire);
23237 					if (conn_outgoing_ill != NULL)
23238 						ill_refrele(conn_outgoing_ill);
23239 					return;
23240 				}
23241 				ip_wput_ire_fragmentit(mp, ire,
23242 				    zoneid, ipst, connp);
23243 			}
23244 		}
23245 	} else {
23246 nullstq:
23247 		/* A NULL stq means the destination address is local. */
23248 		UPDATE_OB_PKT_COUNT(ire);
23249 		ire->ire_last_used_time = lbolt;
23250 		ASSERT(ire->ire_ipif != NULL);
23251 		if (!next_mp) {
23252 			/*
23253 			 * Is there an "in" and "out" for traffic local
23254 			 * to a host (loopback)?  The code in Solaris doesn't
23255 			 * explicitly draw a line in its code for in vs out,
23256 			 * so we've had to draw a line in the sand: ip_wput_ire
23257 			 * is considered to be the "output" side and
23258 			 * ip_wput_local to be the "input" side.
23259 			 */
23260 			out_ill = ire_to_ill(ire);
23261 
23262 			/*
23263 			 * DTrace this as ip:::send.  A blocked packet will
23264 			 * fire the send probe, but not the receive probe.
23265 			 */
23266 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23267 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23268 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23269 
23270 			DTRACE_PROBE4(ip4__loopback__out__start,
23271 			    ill_t *, NULL, ill_t *, out_ill,
23272 			    ipha_t *, ipha, mblk_t *, first_mp);
23273 
23274 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23275 			    ipst->ips_ipv4firewall_loopback_out,
23276 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23277 
23278 			DTRACE_PROBE1(ip4__loopback__out_end,
23279 			    mblk_t *, first_mp);
23280 
23281 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23282 			    "ip_wput_ire_end: q %p (%S)",
23283 			    q, "local address");
23284 
23285 			if (first_mp != NULL)
23286 				ip_wput_local(q, out_ill, ipha,
23287 				    first_mp, ire, 0, ire->ire_zoneid);
23288 			ire_refrele(ire);
23289 			if (conn_outgoing_ill != NULL)
23290 				ill_refrele(conn_outgoing_ill);
23291 			return;
23292 		}
23293 
23294 		out_ill = ire_to_ill(ire);
23295 
23296 		/*
23297 		 * DTrace this as ip:::send.  A blocked packet will fire the
23298 		 * send probe, but not the receive probe.
23299 		 */
23300 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23301 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23302 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23303 
23304 		DTRACE_PROBE4(ip4__loopback__out__start,
23305 		    ill_t *, NULL, ill_t *, out_ill,
23306 		    ipha_t *, ipha, mblk_t *, first_mp);
23307 
23308 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23309 		    ipst->ips_ipv4firewall_loopback_out,
23310 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23311 
23312 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23313 
23314 		if (first_mp != NULL)
23315 			ip_wput_local(q, out_ill, ipha,
23316 			    first_mp, ire, 0, ire->ire_zoneid);
23317 	}
23318 next:
23319 	/*
23320 	 * More copies going out to additional interfaces.
23321 	 * ire1 has already been held. We don't need the
23322 	 * "ire" anymore.
23323 	 */
23324 	ire_refrele(ire);
23325 	ire = ire1;
23326 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23327 	mp = next_mp;
23328 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23329 	ill = ire_to_ill(ire);
23330 	first_mp = mp;
23331 	if (ipsec_len != 0) {
23332 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23333 		mp = mp->b_cont;
23334 	}
23335 	dst = ire->ire_addr;
23336 	ipha = (ipha_t *)mp->b_rptr;
23337 	/*
23338 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23339 	 * Restore ipha_ident "no checksum" flag.
23340 	 */
23341 	src = orig_src;
23342 	ipha->ipha_ident = ip_hdr_included;
23343 	goto another;
23344 
23345 #undef	rptr
23346 #undef	Q_TO_INDEX
23347 }
23348 
23349 /*
23350  * Routine to allocate a message that is used to notify the ULP about MDT.
23351  * The caller may provide a pointer to the link-layer MDT capabilities,
23352  * or NULL if MDT is to be disabled on the stream.
23353  */
23354 mblk_t *
23355 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23356 {
23357 	mblk_t *mp;
23358 	ip_mdt_info_t *mdti;
23359 	ill_mdt_capab_t *idst;
23360 
23361 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23362 		DB_TYPE(mp) = M_CTL;
23363 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23364 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23365 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23366 		idst = &(mdti->mdt_capab);
23367 
23368 		/*
23369 		 * If the caller provides us with the capability, copy
23370 		 * it over into our notification message; otherwise
23371 		 * we zero out the capability portion.
23372 		 */
23373 		if (isrc != NULL)
23374 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23375 		else
23376 			bzero((caddr_t)idst, sizeof (*idst));
23377 	}
23378 	return (mp);
23379 }
23380 
23381 /*
23382  * Routine which determines whether MDT can be enabled on the destination
23383  * IRE and IPC combination, and if so, allocates and returns the MDT
23384  * notification mblk that may be used by ULP.  We also check if we need to
23385  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23386  * MDT usage in the past have been lifted.  This gets called during IP
23387  * and ULP binding.
23388  */
23389 mblk_t *
23390 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23391     ill_mdt_capab_t *mdt_cap)
23392 {
23393 	mblk_t *mp;
23394 	boolean_t rc = B_FALSE;
23395 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23396 
23397 	ASSERT(dst_ire != NULL);
23398 	ASSERT(connp != NULL);
23399 	ASSERT(mdt_cap != NULL);
23400 
23401 	/*
23402 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23403 	 * Multidata, which is handled in tcp_multisend().  This
23404 	 * is the reason why we do all these checks here, to ensure
23405 	 * that we don't enable Multidata for the cases which we
23406 	 * can't handle at the moment.
23407 	 */
23408 	do {
23409 		/* Only do TCP at the moment */
23410 		if (connp->conn_ulp != IPPROTO_TCP)
23411 			break;
23412 
23413 		/*
23414 		 * IPsec outbound policy present?  Note that we get here
23415 		 * after calling ipsec_conn_cache_policy() where the global
23416 		 * policy checking is performed.  conn_latch will be
23417 		 * non-NULL as long as there's a policy defined,
23418 		 * i.e. conn_out_enforce_policy may be NULL in such case
23419 		 * when the connection is non-secure, and hence we check
23420 		 * further if the latch refers to an outbound policy.
23421 		 */
23422 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23423 			break;
23424 
23425 		/* CGTP (multiroute) is enabled? */
23426 		if (dst_ire->ire_flags & RTF_MULTIRT)
23427 			break;
23428 
23429 		/* Outbound IPQoS enabled? */
23430 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23431 			/*
23432 			 * In this case, we disable MDT for this and all
23433 			 * future connections going over the interface.
23434 			 */
23435 			mdt_cap->ill_mdt_on = 0;
23436 			break;
23437 		}
23438 
23439 		/* socket option(s) present? */
23440 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23441 			break;
23442 
23443 		rc = B_TRUE;
23444 	/* CONSTCOND */
23445 	} while (0);
23446 
23447 	/* Remember the result */
23448 	connp->conn_mdt_ok = rc;
23449 
23450 	if (!rc)
23451 		return (NULL);
23452 	else if (!mdt_cap->ill_mdt_on) {
23453 		/*
23454 		 * If MDT has been previously turned off in the past, and we
23455 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23456 		 * then enable it for this interface.
23457 		 */
23458 		mdt_cap->ill_mdt_on = 1;
23459 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23460 		    "interface %s\n", ill_name));
23461 	}
23462 
23463 	/* Allocate the MDT info mblk */
23464 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23465 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23466 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23467 		return (NULL);
23468 	}
23469 	return (mp);
23470 }
23471 
23472 /*
23473  * Routine to allocate a message that is used to notify the ULP about LSO.
23474  * The caller may provide a pointer to the link-layer LSO capabilities,
23475  * or NULL if LSO is to be disabled on the stream.
23476  */
23477 mblk_t *
23478 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23479 {
23480 	mblk_t *mp;
23481 	ip_lso_info_t *lsoi;
23482 	ill_lso_capab_t *idst;
23483 
23484 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23485 		DB_TYPE(mp) = M_CTL;
23486 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23487 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23488 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23489 		idst = &(lsoi->lso_capab);
23490 
23491 		/*
23492 		 * If the caller provides us with the capability, copy
23493 		 * it over into our notification message; otherwise
23494 		 * we zero out the capability portion.
23495 		 */
23496 		if (isrc != NULL)
23497 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23498 		else
23499 			bzero((caddr_t)idst, sizeof (*idst));
23500 	}
23501 	return (mp);
23502 }
23503 
23504 /*
23505  * Routine which determines whether LSO can be enabled on the destination
23506  * IRE and IPC combination, and if so, allocates and returns the LSO
23507  * notification mblk that may be used by ULP.  We also check if we need to
23508  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23509  * LSO usage in the past have been lifted.  This gets called during IP
23510  * and ULP binding.
23511  */
23512 mblk_t *
23513 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23514     ill_lso_capab_t *lso_cap)
23515 {
23516 	mblk_t *mp;
23517 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23518 
23519 	ASSERT(dst_ire != NULL);
23520 	ASSERT(connp != NULL);
23521 	ASSERT(lso_cap != NULL);
23522 
23523 	connp->conn_lso_ok = B_TRUE;
23524 
23525 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23526 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23527 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23528 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23529 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23530 		connp->conn_lso_ok = B_FALSE;
23531 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23532 			/*
23533 			 * Disable LSO for this and all future connections going
23534 			 * over the interface.
23535 			 */
23536 			lso_cap->ill_lso_on = 0;
23537 		}
23538 	}
23539 
23540 	if (!connp->conn_lso_ok)
23541 		return (NULL);
23542 	else if (!lso_cap->ill_lso_on) {
23543 		/*
23544 		 * If LSO has been previously turned off in the past, and we
23545 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23546 		 * then enable it for this interface.
23547 		 */
23548 		lso_cap->ill_lso_on = 1;
23549 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23550 		    ill_name));
23551 	}
23552 
23553 	/* Allocate the LSO info mblk */
23554 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23555 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23556 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23557 
23558 	return (mp);
23559 }
23560 
23561 /*
23562  * Create destination address attribute, and fill it with the physical
23563  * destination address and SAP taken from the template DL_UNITDATA_REQ
23564  * message block.
23565  */
23566 boolean_t
23567 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23568 {
23569 	dl_unitdata_req_t *dlurp;
23570 	pattr_t *pa;
23571 	pattrinfo_t pa_info;
23572 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23573 	uint_t das_len, das_off;
23574 
23575 	ASSERT(dlmp != NULL);
23576 
23577 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23578 	das_len = dlurp->dl_dest_addr_length;
23579 	das_off = dlurp->dl_dest_addr_offset;
23580 
23581 	pa_info.type = PATTR_DSTADDRSAP;
23582 	pa_info.len = sizeof (**das) + das_len - 1;
23583 
23584 	/* create and associate the attribute */
23585 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23586 	if (pa != NULL) {
23587 		ASSERT(*das != NULL);
23588 		(*das)->addr_is_group = 0;
23589 		(*das)->addr_len = (uint8_t)das_len;
23590 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23591 	}
23592 
23593 	return (pa != NULL);
23594 }
23595 
23596 /*
23597  * Create hardware checksum attribute and fill it with the values passed.
23598  */
23599 boolean_t
23600 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23601     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23602 {
23603 	pattr_t *pa;
23604 	pattrinfo_t pa_info;
23605 
23606 	ASSERT(mmd != NULL);
23607 
23608 	pa_info.type = PATTR_HCKSUM;
23609 	pa_info.len = sizeof (pattr_hcksum_t);
23610 
23611 	/* create and associate the attribute */
23612 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23613 	if (pa != NULL) {
23614 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23615 
23616 		hck->hcksum_start_offset = start_offset;
23617 		hck->hcksum_stuff_offset = stuff_offset;
23618 		hck->hcksum_end_offset = end_offset;
23619 		hck->hcksum_flags = flags;
23620 	}
23621 	return (pa != NULL);
23622 }
23623 
23624 /*
23625  * Create zerocopy attribute and fill it with the specified flags
23626  */
23627 boolean_t
23628 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23629 {
23630 	pattr_t *pa;
23631 	pattrinfo_t pa_info;
23632 
23633 	ASSERT(mmd != NULL);
23634 	pa_info.type = PATTR_ZCOPY;
23635 	pa_info.len = sizeof (pattr_zcopy_t);
23636 
23637 	/* create and associate the attribute */
23638 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23639 	if (pa != NULL) {
23640 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23641 
23642 		zcopy->zcopy_flags = flags;
23643 	}
23644 	return (pa != NULL);
23645 }
23646 
23647 /*
23648  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23649  * block chain. We could rewrite to handle arbitrary message block chains but
23650  * that would make the code complicated and slow. Right now there three
23651  * restrictions:
23652  *
23653  *   1. The first message block must contain the complete IP header and
23654  *	at least 1 byte of payload data.
23655  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23656  *	so that we can use a single Multidata message.
23657  *   3. No frag must be distributed over two or more message blocks so
23658  *	that we don't need more than two packet descriptors per frag.
23659  *
23660  * The above restrictions allow us to support userland applications (which
23661  * will send down a single message block) and NFS over UDP (which will
23662  * send down a chain of at most three message blocks).
23663  *
23664  * We also don't use MDT for payloads with less than or equal to
23665  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23666  */
23667 boolean_t
23668 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23669 {
23670 	int	blocks;
23671 	ssize_t	total, missing, size;
23672 
23673 	ASSERT(mp != NULL);
23674 	ASSERT(hdr_len > 0);
23675 
23676 	size = MBLKL(mp) - hdr_len;
23677 	if (size <= 0)
23678 		return (B_FALSE);
23679 
23680 	/* The first mblk contains the header and some payload. */
23681 	blocks = 1;
23682 	total = size;
23683 	size %= len;
23684 	missing = (size == 0) ? 0 : (len - size);
23685 	mp = mp->b_cont;
23686 
23687 	while (mp != NULL) {
23688 		/*
23689 		 * Give up if we encounter a zero length message block.
23690 		 * In practice, this should rarely happen and therefore
23691 		 * not worth the trouble of freeing and re-linking the
23692 		 * mblk from the chain to handle such case.
23693 		 */
23694 		if ((size = MBLKL(mp)) == 0)
23695 			return (B_FALSE);
23696 
23697 		/* Too many payload buffers for a single Multidata message? */
23698 		if (++blocks > MULTIDATA_MAX_PBUFS)
23699 			return (B_FALSE);
23700 
23701 		total += size;
23702 		/* Is a frag distributed over two or more message blocks? */
23703 		if (missing > size)
23704 			return (B_FALSE);
23705 		size -= missing;
23706 
23707 		size %= len;
23708 		missing = (size == 0) ? 0 : (len - size);
23709 
23710 		mp = mp->b_cont;
23711 	}
23712 
23713 	return (total > ip_wput_frag_mdt_min);
23714 }
23715 
23716 /*
23717  * Outbound IPv4 fragmentation routine using MDT.
23718  */
23719 static void
23720 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23721     uint32_t frag_flag, int offset)
23722 {
23723 	ipha_t		*ipha_orig;
23724 	int		i1, ip_data_end;
23725 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23726 	mblk_t		*hdr_mp, *md_mp = NULL;
23727 	unsigned char	*hdr_ptr, *pld_ptr;
23728 	multidata_t	*mmd;
23729 	ip_pdescinfo_t	pdi;
23730 	ill_t		*ill;
23731 	ip_stack_t	*ipst = ire->ire_ipst;
23732 
23733 	ASSERT(DB_TYPE(mp) == M_DATA);
23734 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23735 
23736 	ill = ire_to_ill(ire);
23737 	ASSERT(ill != NULL);
23738 
23739 	ipha_orig = (ipha_t *)mp->b_rptr;
23740 	mp->b_rptr += sizeof (ipha_t);
23741 
23742 	/* Calculate how many packets we will send out */
23743 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23744 	pkts = (i1 + len - 1) / len;
23745 	ASSERT(pkts > 1);
23746 
23747 	/* Allocate a message block which will hold all the IP Headers. */
23748 	wroff = ipst->ips_ip_wroff_extra;
23749 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23750 
23751 	i1 = pkts * hdr_chunk_len;
23752 	/*
23753 	 * Create the header buffer, Multidata and destination address
23754 	 * and SAP attribute that should be associated with it.
23755 	 */
23756 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23757 	    ((hdr_mp->b_wptr += i1),
23758 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23759 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23760 		freemsg(mp);
23761 		if (md_mp == NULL) {
23762 			freemsg(hdr_mp);
23763 		} else {
23764 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23765 			freemsg(md_mp);
23766 		}
23767 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23768 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23769 		return;
23770 	}
23771 	IP_STAT(ipst, ip_frag_mdt_allocd);
23772 
23773 	/*
23774 	 * Add a payload buffer to the Multidata; this operation must not
23775 	 * fail, or otherwise our logic in this routine is broken.  There
23776 	 * is no memory allocation done by the routine, so any returned
23777 	 * failure simply tells us that we've done something wrong.
23778 	 *
23779 	 * A failure tells us that either we're adding the same payload
23780 	 * buffer more than once, or we're trying to add more buffers than
23781 	 * allowed.  None of the above cases should happen, and we panic
23782 	 * because either there's horrible heap corruption, and/or
23783 	 * programming mistake.
23784 	 */
23785 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23786 		goto pbuf_panic;
23787 
23788 	hdr_ptr = hdr_mp->b_rptr;
23789 	pld_ptr = mp->b_rptr;
23790 
23791 	/* Establish the ending byte offset, based on the starting offset. */
23792 	offset <<= 3;
23793 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23794 	    IP_SIMPLE_HDR_LENGTH;
23795 
23796 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23797 
23798 	while (pld_ptr < mp->b_wptr) {
23799 		ipha_t		*ipha;
23800 		uint16_t	offset_and_flags;
23801 		uint16_t	ip_len;
23802 		int		error;
23803 
23804 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23805 		ipha = (ipha_t *)(hdr_ptr + wroff);
23806 		ASSERT(OK_32PTR(ipha));
23807 		*ipha = *ipha_orig;
23808 
23809 		if (ip_data_end - offset > len) {
23810 			offset_and_flags = IPH_MF;
23811 		} else {
23812 			/*
23813 			 * Last frag. Set len to the length of this last piece.
23814 			 */
23815 			len = ip_data_end - offset;
23816 			/* A frag of a frag might have IPH_MF non-zero */
23817 			offset_and_flags =
23818 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23819 			    IPH_MF;
23820 		}
23821 		offset_and_flags |= (uint16_t)(offset >> 3);
23822 		offset_and_flags |= (uint16_t)frag_flag;
23823 		/* Store the offset and flags in the IP header. */
23824 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23825 
23826 		/* Store the length in the IP header. */
23827 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23828 		ipha->ipha_length = htons(ip_len);
23829 
23830 		/*
23831 		 * Set the IP header checksum.  Note that mp is just
23832 		 * the header, so this is easy to pass to ip_csum.
23833 		 */
23834 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23835 
23836 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23837 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23838 		    NULL, int, 0);
23839 
23840 		/*
23841 		 * Record offset and size of header and data of the next packet
23842 		 * in the multidata message.
23843 		 */
23844 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23845 		PDESC_PLD_INIT(&pdi);
23846 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23847 		ASSERT(i1 > 0);
23848 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23849 		if (i1 == len) {
23850 			pld_ptr += len;
23851 		} else {
23852 			i1 = len - i1;
23853 			mp = mp->b_cont;
23854 			ASSERT(mp != NULL);
23855 			ASSERT(MBLKL(mp) >= i1);
23856 			/*
23857 			 * Attach the next payload message block to the
23858 			 * multidata message.
23859 			 */
23860 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23861 				goto pbuf_panic;
23862 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23863 			pld_ptr = mp->b_rptr + i1;
23864 		}
23865 
23866 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23867 		    KM_NOSLEEP)) == NULL) {
23868 			/*
23869 			 * Any failure other than ENOMEM indicates that we
23870 			 * have passed in invalid pdesc info or parameters
23871 			 * to mmd_addpdesc, which must not happen.
23872 			 *
23873 			 * EINVAL is a result of failure on boundary checks
23874 			 * against the pdesc info contents.  It should not
23875 			 * happen, and we panic because either there's
23876 			 * horrible heap corruption, and/or programming
23877 			 * mistake.
23878 			 */
23879 			if (error != ENOMEM) {
23880 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23881 				    "pdesc logic error detected for "
23882 				    "mmd %p pinfo %p (%d)\n",
23883 				    (void *)mmd, (void *)&pdi, error);
23884 				/* NOTREACHED */
23885 			}
23886 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23887 			/* Free unattached payload message blocks as well */
23888 			md_mp->b_cont = mp->b_cont;
23889 			goto free_mmd;
23890 		}
23891 
23892 		/* Advance fragment offset. */
23893 		offset += len;
23894 
23895 		/* Advance to location for next header in the buffer. */
23896 		hdr_ptr += hdr_chunk_len;
23897 
23898 		/* Did we reach the next payload message block? */
23899 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23900 			mp = mp->b_cont;
23901 			/*
23902 			 * Attach the next message block with payload
23903 			 * data to the multidata message.
23904 			 */
23905 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23906 				goto pbuf_panic;
23907 			pld_ptr = mp->b_rptr;
23908 		}
23909 	}
23910 
23911 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23912 	ASSERT(mp->b_wptr == pld_ptr);
23913 
23914 	/* Update IP statistics */
23915 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23916 
23917 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23918 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23919 
23920 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23921 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23922 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23923 
23924 	if (pkt_type == OB_PKT) {
23925 		ire->ire_ob_pkt_count += pkts;
23926 		if (ire->ire_ipif != NULL)
23927 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23928 	} else {
23929 		/* The type is IB_PKT in the forwarding path. */
23930 		ire->ire_ib_pkt_count += pkts;
23931 		ASSERT(!IRE_IS_LOCAL(ire));
23932 		if (ire->ire_type & IRE_BROADCAST) {
23933 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23934 		} else {
23935 			UPDATE_MIB(ill->ill_ip_mib,
23936 			    ipIfStatsHCOutForwDatagrams, pkts);
23937 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23938 		}
23939 	}
23940 	ire->ire_last_used_time = lbolt;
23941 	/* Send it down */
23942 	putnext(ire->ire_stq, md_mp);
23943 	return;
23944 
23945 pbuf_panic:
23946 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23947 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23948 	    pbuf_idx);
23949 	/* NOTREACHED */
23950 }
23951 
23952 /*
23953  * Outbound IP fragmentation routine.
23954  *
23955  * NOTE : This routine does not ire_refrele the ire that is passed in
23956  * as the argument.
23957  */
23958 static void
23959 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23960     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
23961 {
23962 	int		i1;
23963 	mblk_t		*ll_hdr_mp;
23964 	int 		ll_hdr_len;
23965 	int		hdr_len;
23966 	mblk_t		*hdr_mp;
23967 	ipha_t		*ipha;
23968 	int		ip_data_end;
23969 	int		len;
23970 	mblk_t		*mp = mp_orig, *mp1;
23971 	int		offset;
23972 	queue_t		*q;
23973 	uint32_t	v_hlen_tos_len;
23974 	mblk_t		*first_mp;
23975 	boolean_t	mctl_present;
23976 	ill_t		*ill;
23977 	ill_t		*out_ill;
23978 	mblk_t		*xmit_mp;
23979 	mblk_t		*carve_mp;
23980 	ire_t		*ire1 = NULL;
23981 	ire_t		*save_ire = NULL;
23982 	mblk_t  	*next_mp = NULL;
23983 	boolean_t	last_frag = B_FALSE;
23984 	boolean_t	multirt_send = B_FALSE;
23985 	ire_t		*first_ire = NULL;
23986 	irb_t		*irb = NULL;
23987 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23988 
23989 	ill = ire_to_ill(ire);
23990 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23991 
23992 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23993 
23994 	if (max_frag == 0) {
23995 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23996 		    " -  dropping packet\n"));
23997 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23998 		freemsg(mp);
23999 		return;
24000 	}
24001 
24002 	/*
24003 	 * IPsec does not allow hw accelerated packets to be fragmented
24004 	 * This check is made in ip_wput_ipsec_out prior to coming here
24005 	 * via ip_wput_ire_fragmentit.
24006 	 *
24007 	 * If at this point we have an ire whose ARP request has not
24008 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24009 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24010 	 * This packet and all fragmentable packets for this ire will
24011 	 * continue to get dropped while ire_nce->nce_state remains in
24012 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24013 	 * ND_REACHABLE, all subsquent large packets for this ire will
24014 	 * get fragemented and sent out by this function.
24015 	 */
24016 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24017 		/* If nce_state is ND_INITIAL, trigger ARP query */
24018 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24019 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24020 		    " -  dropping packet\n"));
24021 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24022 		freemsg(mp);
24023 		return;
24024 	}
24025 
24026 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24027 	    "ip_wput_frag_start:");
24028 
24029 	if (mp->b_datap->db_type == M_CTL) {
24030 		first_mp = mp;
24031 		mp_orig = mp = mp->b_cont;
24032 		mctl_present = B_TRUE;
24033 	} else {
24034 		first_mp = mp;
24035 		mctl_present = B_FALSE;
24036 	}
24037 
24038 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24039 	ipha = (ipha_t *)mp->b_rptr;
24040 
24041 	/*
24042 	 * If the Don't Fragment flag is on, generate an ICMP destination
24043 	 * unreachable, fragmentation needed.
24044 	 */
24045 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24046 	if (offset & IPH_DF) {
24047 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24048 		if (is_system_labeled()) {
24049 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24050 			    ire->ire_max_frag - max_frag, AF_INET);
24051 		}
24052 		/*
24053 		 * Need to compute hdr checksum if called from ip_wput_ire.
24054 		 * Note that ip_rput_forward verifies the checksum before
24055 		 * calling this routine so in that case this is a noop.
24056 		 */
24057 		ipha->ipha_hdr_checksum = 0;
24058 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24059 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24060 		    ipst);
24061 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24062 		    "ip_wput_frag_end:(%S)",
24063 		    "don't fragment");
24064 		return;
24065 	}
24066 	/*
24067 	 * Labeled systems adjust max_frag if they add a label
24068 	 * to send the correct path mtu.  We need the real mtu since we
24069 	 * are fragmenting the packet after label adjustment.
24070 	 */
24071 	if (is_system_labeled())
24072 		max_frag = ire->ire_max_frag;
24073 	if (mctl_present)
24074 		freeb(first_mp);
24075 	/*
24076 	 * Establish the starting offset.  May not be zero if we are fragging
24077 	 * a fragment that is being forwarded.
24078 	 */
24079 	offset = offset & IPH_OFFSET;
24080 
24081 	/* TODO why is this test needed? */
24082 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24083 	if (((max_frag - LENGTH) & ~7) < 8) {
24084 		/* TODO: notify ulp somehow */
24085 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24086 		freemsg(mp);
24087 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24088 		    "ip_wput_frag_end:(%S)",
24089 		    "len < 8");
24090 		return;
24091 	}
24092 
24093 	hdr_len = (V_HLEN & 0xF) << 2;
24094 
24095 	ipha->ipha_hdr_checksum = 0;
24096 
24097 	/*
24098 	 * Establish the number of bytes maximum per frag, after putting
24099 	 * in the header.
24100 	 */
24101 	len = (max_frag - hdr_len) & ~7;
24102 
24103 	/* Check if we can use MDT to send out the frags. */
24104 	ASSERT(!IRE_IS_LOCAL(ire));
24105 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24106 	    ipst->ips_ip_multidata_outbound &&
24107 	    !(ire->ire_flags & RTF_MULTIRT) &&
24108 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24109 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24110 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24111 		ASSERT(ill->ill_mdt_capab != NULL);
24112 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24113 			/*
24114 			 * If MDT has been previously turned off in the past,
24115 			 * and we currently can do MDT (due to IPQoS policy
24116 			 * removal, etc.) then enable it for this interface.
24117 			 */
24118 			ill->ill_mdt_capab->ill_mdt_on = 1;
24119 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24120 			    ill->ill_name));
24121 		}
24122 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24123 		    offset);
24124 		return;
24125 	}
24126 
24127 	/* Get a copy of the header for the trailing frags */
24128 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24129 	    mp);
24130 	if (!hdr_mp) {
24131 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24132 		freemsg(mp);
24133 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24134 		    "ip_wput_frag_end:(%S)",
24135 		    "couldn't copy hdr");
24136 		return;
24137 	}
24138 
24139 	/* Store the starting offset, with the MoreFrags flag. */
24140 	i1 = offset | IPH_MF | frag_flag;
24141 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24142 
24143 	/* Establish the ending byte offset, based on the starting offset. */
24144 	offset <<= 3;
24145 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24146 
24147 	/* Store the length of the first fragment in the IP header. */
24148 	i1 = len + hdr_len;
24149 	ASSERT(i1 <= IP_MAXPACKET);
24150 	ipha->ipha_length = htons((uint16_t)i1);
24151 
24152 	/*
24153 	 * Compute the IP header checksum for the first frag.  We have to
24154 	 * watch out that we stop at the end of the header.
24155 	 */
24156 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24157 
24158 	/*
24159 	 * Now carve off the first frag.  Note that this will include the
24160 	 * original IP header.
24161 	 */
24162 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24163 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24164 		freeb(hdr_mp);
24165 		freemsg(mp_orig);
24166 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24167 		    "ip_wput_frag_end:(%S)",
24168 		    "couldn't carve first");
24169 		return;
24170 	}
24171 
24172 	/*
24173 	 * Multirouting case. Each fragment is replicated
24174 	 * via all non-condemned RTF_MULTIRT routes
24175 	 * currently resolved.
24176 	 * We ensure that first_ire is the first RTF_MULTIRT
24177 	 * ire in the bucket.
24178 	 */
24179 	if (ire->ire_flags & RTF_MULTIRT) {
24180 		irb = ire->ire_bucket;
24181 		ASSERT(irb != NULL);
24182 
24183 		multirt_send = B_TRUE;
24184 
24185 		/* Make sure we do not omit any multiroute ire. */
24186 		IRB_REFHOLD(irb);
24187 		for (first_ire = irb->irb_ire;
24188 		    first_ire != NULL;
24189 		    first_ire = first_ire->ire_next) {
24190 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24191 			    (first_ire->ire_addr == ire->ire_addr) &&
24192 			    !(first_ire->ire_marks &
24193 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24194 				break;
24195 		}
24196 
24197 		if (first_ire != NULL) {
24198 			if (first_ire != ire) {
24199 				IRE_REFHOLD(first_ire);
24200 				/*
24201 				 * Do not release the ire passed in
24202 				 * as the argument.
24203 				 */
24204 				ire = first_ire;
24205 			} else {
24206 				first_ire = NULL;
24207 			}
24208 		}
24209 		IRB_REFRELE(irb);
24210 
24211 		/*
24212 		 * Save the first ire; we will need to restore it
24213 		 * for the trailing frags.
24214 		 * We REFHOLD save_ire, as each iterated ire will be
24215 		 * REFRELEd.
24216 		 */
24217 		save_ire = ire;
24218 		IRE_REFHOLD(save_ire);
24219 	}
24220 
24221 	/*
24222 	 * First fragment emission loop.
24223 	 * In most cases, the emission loop below is entered only
24224 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24225 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24226 	 * bucket, and send the fragment through all crossed
24227 	 * RTF_MULTIRT routes.
24228 	 */
24229 	do {
24230 		if (ire->ire_flags & RTF_MULTIRT) {
24231 			/*
24232 			 * We are in a multiple send case, need to get
24233 			 * the next ire and make a copy of the packet.
24234 			 * ire1 holds here the next ire to process in the
24235 			 * bucket. If multirouting is expected,
24236 			 * any non-RTF_MULTIRT ire that has the
24237 			 * right destination address is ignored.
24238 			 *
24239 			 * We have to take into account the MTU of
24240 			 * each walked ire. max_frag is set by the
24241 			 * the caller and generally refers to
24242 			 * the primary ire entry. Here we ensure that
24243 			 * no route with a lower MTU will be used, as
24244 			 * fragments are carved once for all ires,
24245 			 * then replicated.
24246 			 */
24247 			ASSERT(irb != NULL);
24248 			IRB_REFHOLD(irb);
24249 			for (ire1 = ire->ire_next;
24250 			    ire1 != NULL;
24251 			    ire1 = ire1->ire_next) {
24252 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24253 					continue;
24254 				if (ire1->ire_addr != ire->ire_addr)
24255 					continue;
24256 				if (ire1->ire_marks &
24257 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24258 					continue;
24259 				/*
24260 				 * Ensure we do not exceed the MTU
24261 				 * of the next route.
24262 				 */
24263 				if (ire1->ire_max_frag < max_frag) {
24264 					ip_multirt_bad_mtu(ire1, max_frag);
24265 					continue;
24266 				}
24267 
24268 				/* Got one. */
24269 				IRE_REFHOLD(ire1);
24270 				break;
24271 			}
24272 			IRB_REFRELE(irb);
24273 
24274 			if (ire1 != NULL) {
24275 				next_mp = copyb(mp);
24276 				if ((next_mp == NULL) ||
24277 				    ((mp->b_cont != NULL) &&
24278 				    ((next_mp->b_cont =
24279 				    dupmsg(mp->b_cont)) == NULL))) {
24280 					freemsg(next_mp);
24281 					next_mp = NULL;
24282 					ire_refrele(ire1);
24283 					ire1 = NULL;
24284 				}
24285 			}
24286 
24287 			/* Last multiroute ire; don't loop anymore. */
24288 			if (ire1 == NULL) {
24289 				multirt_send = B_FALSE;
24290 			}
24291 		}
24292 
24293 		ll_hdr_len = 0;
24294 		LOCK_IRE_FP_MP(ire);
24295 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24296 		if (ll_hdr_mp != NULL) {
24297 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24298 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24299 		} else {
24300 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24301 		}
24302 
24303 		/* If there is a transmit header, get a copy for this frag. */
24304 		/*
24305 		 * TODO: should check db_ref before calling ip_carve_mp since
24306 		 * it might give us a dup.
24307 		 */
24308 		if (!ll_hdr_mp) {
24309 			/* No xmit header. */
24310 			xmit_mp = mp;
24311 
24312 		/* We have a link-layer header that can fit in our mblk. */
24313 		} else if (mp->b_datap->db_ref == 1 &&
24314 		    ll_hdr_len != 0 &&
24315 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24316 			/* M_DATA fastpath */
24317 			mp->b_rptr -= ll_hdr_len;
24318 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24319 			xmit_mp = mp;
24320 
24321 		/* Corner case if copyb has failed */
24322 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24323 			UNLOCK_IRE_FP_MP(ire);
24324 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24325 			freeb(hdr_mp);
24326 			freemsg(mp);
24327 			freemsg(mp_orig);
24328 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24329 			    "ip_wput_frag_end:(%S)",
24330 			    "discard");
24331 
24332 			if (multirt_send) {
24333 				ASSERT(ire1);
24334 				ASSERT(next_mp);
24335 
24336 				freemsg(next_mp);
24337 				ire_refrele(ire1);
24338 			}
24339 			if (save_ire != NULL)
24340 				IRE_REFRELE(save_ire);
24341 
24342 			if (first_ire != NULL)
24343 				ire_refrele(first_ire);
24344 			return;
24345 
24346 		/*
24347 		 * Case of res_mp OR the fastpath mp can't fit
24348 		 * in the mblk
24349 		 */
24350 		} else {
24351 			xmit_mp->b_cont = mp;
24352 
24353 			/*
24354 			 * Get priority marking, if any.
24355 			 * We propagate the CoS marking from the
24356 			 * original packet that went to QoS processing
24357 			 * in ip_wput_ire to the newly carved mp.
24358 			 */
24359 			if (DB_TYPE(xmit_mp) == M_DATA)
24360 				xmit_mp->b_band = mp->b_band;
24361 		}
24362 		UNLOCK_IRE_FP_MP(ire);
24363 
24364 		q = ire->ire_stq;
24365 		out_ill = (ill_t *)q->q_ptr;
24366 
24367 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24368 
24369 		DTRACE_PROBE4(ip4__physical__out__start,
24370 		    ill_t *, NULL, ill_t *, out_ill,
24371 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24372 
24373 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24374 		    ipst->ips_ipv4firewall_physical_out,
24375 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24376 
24377 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24378 
24379 		if (xmit_mp != NULL) {
24380 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24381 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24382 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24383 
24384 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24385 
24386 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24387 			UPDATE_MIB(out_ill->ill_ip_mib,
24388 			    ipIfStatsHCOutOctets, i1);
24389 
24390 			if (pkt_type != OB_PKT) {
24391 				/*
24392 				 * Update the packet count and MIB stats
24393 				 * of trailing RTF_MULTIRT ires.
24394 				 */
24395 				UPDATE_OB_PKT_COUNT(ire);
24396 				BUMP_MIB(out_ill->ill_ip_mib,
24397 				    ipIfStatsOutFragReqds);
24398 			}
24399 		}
24400 
24401 		if (multirt_send) {
24402 			/*
24403 			 * We are in a multiple send case; look for
24404 			 * the next ire and re-enter the loop.
24405 			 */
24406 			ASSERT(ire1);
24407 			ASSERT(next_mp);
24408 			/* REFRELE the current ire before looping */
24409 			ire_refrele(ire);
24410 			ire = ire1;
24411 			ire1 = NULL;
24412 			mp = next_mp;
24413 			next_mp = NULL;
24414 		}
24415 	} while (multirt_send);
24416 
24417 	ASSERT(ire1 == NULL);
24418 
24419 	/* Restore the original ire; we need it for the trailing frags */
24420 	if (save_ire != NULL) {
24421 		/* REFRELE the last iterated ire */
24422 		ire_refrele(ire);
24423 		/* save_ire has been REFHOLDed */
24424 		ire = save_ire;
24425 		save_ire = NULL;
24426 		q = ire->ire_stq;
24427 	}
24428 
24429 	if (pkt_type == OB_PKT) {
24430 		UPDATE_OB_PKT_COUNT(ire);
24431 	} else {
24432 		out_ill = (ill_t *)q->q_ptr;
24433 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24434 		UPDATE_IB_PKT_COUNT(ire);
24435 	}
24436 
24437 	/* Advance the offset to the second frag starting point. */
24438 	offset += len;
24439 	/*
24440 	 * Update hdr_len from the copied header - there might be less options
24441 	 * in the later fragments.
24442 	 */
24443 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24444 	/* Loop until done. */
24445 	for (;;) {
24446 		uint16_t	offset_and_flags;
24447 		uint16_t	ip_len;
24448 
24449 		if (ip_data_end - offset > len) {
24450 			/*
24451 			 * Carve off the appropriate amount from the original
24452 			 * datagram.
24453 			 */
24454 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24455 				mp = NULL;
24456 				break;
24457 			}
24458 			/*
24459 			 * More frags after this one.  Get another copy
24460 			 * of the header.
24461 			 */
24462 			if (carve_mp->b_datap->db_ref == 1 &&
24463 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24464 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24465 				/* Inline IP header */
24466 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24467 				    hdr_mp->b_rptr;
24468 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24469 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24470 				mp = carve_mp;
24471 			} else {
24472 				if (!(mp = copyb(hdr_mp))) {
24473 					freemsg(carve_mp);
24474 					break;
24475 				}
24476 				/* Get priority marking, if any. */
24477 				mp->b_band = carve_mp->b_band;
24478 				mp->b_cont = carve_mp;
24479 			}
24480 			ipha = (ipha_t *)mp->b_rptr;
24481 			offset_and_flags = IPH_MF;
24482 		} else {
24483 			/*
24484 			 * Last frag.  Consume the header. Set len to
24485 			 * the length of this last piece.
24486 			 */
24487 			len = ip_data_end - offset;
24488 
24489 			/*
24490 			 * Carve off the appropriate amount from the original
24491 			 * datagram.
24492 			 */
24493 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24494 				mp = NULL;
24495 				break;
24496 			}
24497 			if (carve_mp->b_datap->db_ref == 1 &&
24498 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24499 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24500 				/* Inline IP header */
24501 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24502 				    hdr_mp->b_rptr;
24503 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24504 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24505 				mp = carve_mp;
24506 				freeb(hdr_mp);
24507 				hdr_mp = mp;
24508 			} else {
24509 				mp = hdr_mp;
24510 				/* Get priority marking, if any. */
24511 				mp->b_band = carve_mp->b_band;
24512 				mp->b_cont = carve_mp;
24513 			}
24514 			ipha = (ipha_t *)mp->b_rptr;
24515 			/* A frag of a frag might have IPH_MF non-zero */
24516 			offset_and_flags =
24517 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24518 			    IPH_MF;
24519 		}
24520 		offset_and_flags |= (uint16_t)(offset >> 3);
24521 		offset_and_flags |= (uint16_t)frag_flag;
24522 		/* Store the offset and flags in the IP header. */
24523 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24524 
24525 		/* Store the length in the IP header. */
24526 		ip_len = (uint16_t)(len + hdr_len);
24527 		ipha->ipha_length = htons(ip_len);
24528 
24529 		/*
24530 		 * Set the IP header checksum.	Note that mp is just
24531 		 * the header, so this is easy to pass to ip_csum.
24532 		 */
24533 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24534 
24535 		/* Attach a transmit header, if any, and ship it. */
24536 		if (pkt_type == OB_PKT) {
24537 			UPDATE_OB_PKT_COUNT(ire);
24538 		} else {
24539 			out_ill = (ill_t *)q->q_ptr;
24540 			BUMP_MIB(out_ill->ill_ip_mib,
24541 			    ipIfStatsHCOutForwDatagrams);
24542 			UPDATE_IB_PKT_COUNT(ire);
24543 		}
24544 
24545 		if (ire->ire_flags & RTF_MULTIRT) {
24546 			irb = ire->ire_bucket;
24547 			ASSERT(irb != NULL);
24548 
24549 			multirt_send = B_TRUE;
24550 
24551 			/*
24552 			 * Save the original ire; we will need to restore it
24553 			 * for the tailing frags.
24554 			 */
24555 			save_ire = ire;
24556 			IRE_REFHOLD(save_ire);
24557 		}
24558 		/*
24559 		 * Emission loop for this fragment, similar
24560 		 * to what is done for the first fragment.
24561 		 */
24562 		do {
24563 			if (multirt_send) {
24564 				/*
24565 				 * We are in a multiple send case, need to get
24566 				 * the next ire and make a copy of the packet.
24567 				 */
24568 				ASSERT(irb != NULL);
24569 				IRB_REFHOLD(irb);
24570 				for (ire1 = ire->ire_next;
24571 				    ire1 != NULL;
24572 				    ire1 = ire1->ire_next) {
24573 					if (!(ire1->ire_flags & RTF_MULTIRT))
24574 						continue;
24575 					if (ire1->ire_addr != ire->ire_addr)
24576 						continue;
24577 					if (ire1->ire_marks &
24578 					    (IRE_MARK_CONDEMNED |
24579 					    IRE_MARK_TESTHIDDEN))
24580 						continue;
24581 					/*
24582 					 * Ensure we do not exceed the MTU
24583 					 * of the next route.
24584 					 */
24585 					if (ire1->ire_max_frag < max_frag) {
24586 						ip_multirt_bad_mtu(ire1,
24587 						    max_frag);
24588 						continue;
24589 					}
24590 
24591 					/* Got one. */
24592 					IRE_REFHOLD(ire1);
24593 					break;
24594 				}
24595 				IRB_REFRELE(irb);
24596 
24597 				if (ire1 != NULL) {
24598 					next_mp = copyb(mp);
24599 					if ((next_mp == NULL) ||
24600 					    ((mp->b_cont != NULL) &&
24601 					    ((next_mp->b_cont =
24602 					    dupmsg(mp->b_cont)) == NULL))) {
24603 						freemsg(next_mp);
24604 						next_mp = NULL;
24605 						ire_refrele(ire1);
24606 						ire1 = NULL;
24607 					}
24608 				}
24609 
24610 				/* Last multiroute ire; don't loop anymore. */
24611 				if (ire1 == NULL) {
24612 					multirt_send = B_FALSE;
24613 				}
24614 			}
24615 
24616 			/* Update transmit header */
24617 			ll_hdr_len = 0;
24618 			LOCK_IRE_FP_MP(ire);
24619 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24620 			if (ll_hdr_mp != NULL) {
24621 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24622 				ll_hdr_len = MBLKL(ll_hdr_mp);
24623 			} else {
24624 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24625 			}
24626 
24627 			if (!ll_hdr_mp) {
24628 				xmit_mp = mp;
24629 
24630 			/*
24631 			 * We have link-layer header that can fit in
24632 			 * our mblk.
24633 			 */
24634 			} else if (mp->b_datap->db_ref == 1 &&
24635 			    ll_hdr_len != 0 &&
24636 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24637 				/* M_DATA fastpath */
24638 				mp->b_rptr -= ll_hdr_len;
24639 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24640 				    ll_hdr_len);
24641 				xmit_mp = mp;
24642 
24643 			/*
24644 			 * Case of res_mp OR the fastpath mp can't fit
24645 			 * in the mblk
24646 			 */
24647 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24648 				xmit_mp->b_cont = mp;
24649 				/* Get priority marking, if any. */
24650 				if (DB_TYPE(xmit_mp) == M_DATA)
24651 					xmit_mp->b_band = mp->b_band;
24652 
24653 			/* Corner case if copyb failed */
24654 			} else {
24655 				/*
24656 				 * Exit both the replication and
24657 				 * fragmentation loops.
24658 				 */
24659 				UNLOCK_IRE_FP_MP(ire);
24660 				goto drop_pkt;
24661 			}
24662 			UNLOCK_IRE_FP_MP(ire);
24663 
24664 			mp1 = mp;
24665 			out_ill = (ill_t *)q->q_ptr;
24666 
24667 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24668 
24669 			DTRACE_PROBE4(ip4__physical__out__start,
24670 			    ill_t *, NULL, ill_t *, out_ill,
24671 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24672 
24673 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24674 			    ipst->ips_ipv4firewall_physical_out,
24675 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24676 
24677 			DTRACE_PROBE1(ip4__physical__out__end,
24678 			    mblk_t *, xmit_mp);
24679 
24680 			if (mp != mp1 && hdr_mp == mp1)
24681 				hdr_mp = mp;
24682 			if (mp != mp1 && mp_orig == mp1)
24683 				mp_orig = mp;
24684 
24685 			if (xmit_mp != NULL) {
24686 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24687 				    NULL, void_ip_t *, ipha,
24688 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24689 				    ipha, ip6_t *, NULL, int, 0);
24690 
24691 				ILL_SEND_TX(out_ill, ire, connp,
24692 				    xmit_mp, 0, connp);
24693 
24694 				BUMP_MIB(out_ill->ill_ip_mib,
24695 				    ipIfStatsHCOutTransmits);
24696 				UPDATE_MIB(out_ill->ill_ip_mib,
24697 				    ipIfStatsHCOutOctets, ip_len);
24698 
24699 				if (pkt_type != OB_PKT) {
24700 					/*
24701 					 * Update the packet count of trailing
24702 					 * RTF_MULTIRT ires.
24703 					 */
24704 					UPDATE_OB_PKT_COUNT(ire);
24705 				}
24706 			}
24707 
24708 			/* All done if we just consumed the hdr_mp. */
24709 			if (mp == hdr_mp) {
24710 				last_frag = B_TRUE;
24711 				BUMP_MIB(out_ill->ill_ip_mib,
24712 				    ipIfStatsOutFragOKs);
24713 			}
24714 
24715 			if (multirt_send) {
24716 				/*
24717 				 * We are in a multiple send case; look for
24718 				 * the next ire and re-enter the loop.
24719 				 */
24720 				ASSERT(ire1);
24721 				ASSERT(next_mp);
24722 				/* REFRELE the current ire before looping */
24723 				ire_refrele(ire);
24724 				ire = ire1;
24725 				ire1 = NULL;
24726 				q = ire->ire_stq;
24727 				mp = next_mp;
24728 				next_mp = NULL;
24729 			}
24730 		} while (multirt_send);
24731 		/*
24732 		 * Restore the original ire; we need it for the
24733 		 * trailing frags
24734 		 */
24735 		if (save_ire != NULL) {
24736 			ASSERT(ire1 == NULL);
24737 			/* REFRELE the last iterated ire */
24738 			ire_refrele(ire);
24739 			/* save_ire has been REFHOLDed */
24740 			ire = save_ire;
24741 			q = ire->ire_stq;
24742 			save_ire = NULL;
24743 		}
24744 
24745 		if (last_frag) {
24746 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24747 			    "ip_wput_frag_end:(%S)",
24748 			    "consumed hdr_mp");
24749 
24750 			if (first_ire != NULL)
24751 				ire_refrele(first_ire);
24752 			return;
24753 		}
24754 		/* Otherwise, advance and loop. */
24755 		offset += len;
24756 	}
24757 
24758 drop_pkt:
24759 	/* Clean up following allocation failure. */
24760 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24761 	freemsg(mp);
24762 	if (mp != hdr_mp)
24763 		freeb(hdr_mp);
24764 	if (mp != mp_orig)
24765 		freemsg(mp_orig);
24766 
24767 	if (save_ire != NULL)
24768 		IRE_REFRELE(save_ire);
24769 	if (first_ire != NULL)
24770 		ire_refrele(first_ire);
24771 
24772 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24773 	    "ip_wput_frag_end:(%S)",
24774 	    "end--alloc failure");
24775 }
24776 
24777 /*
24778  * Copy the header plus those options which have the copy bit set
24779  * src is the template to make sure we preserve the cred for TX purposes.
24780  */
24781 static mblk_t *
24782 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24783     mblk_t *src)
24784 {
24785 	mblk_t	*mp;
24786 	uchar_t	*up;
24787 
24788 	/*
24789 	 * Quick check if we need to look for options without the copy bit
24790 	 * set
24791 	 */
24792 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24793 	if (!mp)
24794 		return (mp);
24795 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24796 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24797 		bcopy(rptr, mp->b_rptr, hdr_len);
24798 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24799 		return (mp);
24800 	}
24801 	up  = mp->b_rptr;
24802 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24803 	up += IP_SIMPLE_HDR_LENGTH;
24804 	rptr += IP_SIMPLE_HDR_LENGTH;
24805 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24806 	while (hdr_len > 0) {
24807 		uint32_t optval;
24808 		uint32_t optlen;
24809 
24810 		optval = *rptr;
24811 		if (optval == IPOPT_EOL)
24812 			break;
24813 		if (optval == IPOPT_NOP)
24814 			optlen = 1;
24815 		else
24816 			optlen = rptr[1];
24817 		if (optval & IPOPT_COPY) {
24818 			bcopy(rptr, up, optlen);
24819 			up += optlen;
24820 		}
24821 		rptr += optlen;
24822 		hdr_len -= optlen;
24823 	}
24824 	/*
24825 	 * Make sure that we drop an even number of words by filling
24826 	 * with EOL to the next word boundary.
24827 	 */
24828 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24829 	    hdr_len & 0x3; hdr_len++)
24830 		*up++ = IPOPT_EOL;
24831 	mp->b_wptr = up;
24832 	/* Update header length */
24833 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24834 	return (mp);
24835 }
24836 
24837 /*
24838  * Delivery to local recipients including fanout to multiple recipients.
24839  * Does not do checksumming of UDP/TCP.
24840  * Note: q should be the read side queue for either the ill or conn.
24841  * Note: rq should be the read side q for the lower (ill) stream.
24842  * We don't send packets to IPPF processing, thus the last argument
24843  * to all the fanout calls are B_FALSE.
24844  */
24845 void
24846 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24847     int fanout_flags, zoneid_t zoneid)
24848 {
24849 	uint32_t	protocol;
24850 	mblk_t		*first_mp;
24851 	boolean_t	mctl_present;
24852 	int		ire_type;
24853 #define	rptr	((uchar_t *)ipha)
24854 	ip_stack_t	*ipst = ill->ill_ipst;
24855 
24856 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24857 	    "ip_wput_local_start: q %p", q);
24858 
24859 	if (ire != NULL) {
24860 		ire_type = ire->ire_type;
24861 	} else {
24862 		/*
24863 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24864 		 * packet is not multicast, we can't tell the ire type.
24865 		 */
24866 		ASSERT(CLASSD(ipha->ipha_dst));
24867 		ire_type = IRE_BROADCAST;
24868 	}
24869 
24870 	first_mp = mp;
24871 	if (first_mp->b_datap->db_type == M_CTL) {
24872 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24873 		if (!io->ipsec_out_secure) {
24874 			/*
24875 			 * This ipsec_out_t was allocated in ip_wput
24876 			 * for multicast packets to store the ill_index.
24877 			 * As this is being delivered locally, we don't
24878 			 * need this anymore.
24879 			 */
24880 			mp = first_mp->b_cont;
24881 			freeb(first_mp);
24882 			first_mp = mp;
24883 			mctl_present = B_FALSE;
24884 		} else {
24885 			/*
24886 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24887 			 * security properties for the looped-back packet.
24888 			 */
24889 			mctl_present = B_TRUE;
24890 			mp = first_mp->b_cont;
24891 			ASSERT(mp != NULL);
24892 			ipsec_out_to_in(first_mp);
24893 		}
24894 	} else {
24895 		mctl_present = B_FALSE;
24896 	}
24897 
24898 	DTRACE_PROBE4(ip4__loopback__in__start,
24899 	    ill_t *, ill, ill_t *, NULL,
24900 	    ipha_t *, ipha, mblk_t *, first_mp);
24901 
24902 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24903 	    ipst->ips_ipv4firewall_loopback_in,
24904 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24905 
24906 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24907 
24908 	if (first_mp == NULL)
24909 		return;
24910 
24911 	if (ipst->ips_ip4_observe.he_interested) {
24912 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24913 		zoneid_t stackzoneid = netstackid_to_zoneid(
24914 		    ipst->ips_netstack->netstack_stackid);
24915 
24916 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24917 		/*
24918 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24919 		 * address.  Restrict the lookup below to the destination zone.
24920 		 */
24921 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24922 			lookup_zoneid = zoneid;
24923 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24924 		    lookup_zoneid);
24925 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill, ipst);
24926 	}
24927 
24928 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
24929 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
24930 	    int, 1);
24931 
24932 	ipst->ips_loopback_packets++;
24933 
24934 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24935 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24936 	if (!IS_SIMPLE_IPH(ipha)) {
24937 		ip_wput_local_options(ipha, ipst);
24938 	}
24939 
24940 	protocol = ipha->ipha_protocol;
24941 	switch (protocol) {
24942 	case IPPROTO_ICMP: {
24943 		ire_t		*ire_zone;
24944 		ilm_t		*ilm;
24945 		mblk_t		*mp1;
24946 		zoneid_t	last_zoneid;
24947 		ilm_walker_t	ilw;
24948 
24949 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24950 			ASSERT(ire_type == IRE_BROADCAST);
24951 			/*
24952 			 * In the multicast case, applications may have joined
24953 			 * the group from different zones, so we need to deliver
24954 			 * the packet to each of them. Loop through the
24955 			 * multicast memberships structures (ilm) on the receive
24956 			 * ill and send a copy of the packet up each matching
24957 			 * one. However, we don't do this for multicasts sent on
24958 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24959 			 * they must stay in the sender's zone.
24960 			 *
24961 			 * ilm_add_v6() ensures that ilms in the same zone are
24962 			 * contiguous in the ill_ilm list. We use this property
24963 			 * to avoid sending duplicates needed when two
24964 			 * applications in the same zone join the same group on
24965 			 * different logical interfaces: we ignore the ilm if
24966 			 * it's zoneid is the same as the last matching one.
24967 			 * In addition, the sending of the packet for
24968 			 * ire_zoneid is delayed until all of the other ilms
24969 			 * have been exhausted.
24970 			 */
24971 			last_zoneid = -1;
24972 			ilm = ilm_walker_start(&ilw, ill);
24973 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
24974 				if (ipha->ipha_dst != ilm->ilm_addr ||
24975 				    ilm->ilm_zoneid == last_zoneid ||
24976 				    ilm->ilm_zoneid == zoneid ||
24977 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24978 					continue;
24979 				mp1 = ip_copymsg(first_mp);
24980 				if (mp1 == NULL)
24981 					continue;
24982 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
24983 				    0, 0, mctl_present, B_FALSE, ill,
24984 				    ilm->ilm_zoneid);
24985 				last_zoneid = ilm->ilm_zoneid;
24986 			}
24987 			ilm_walker_finish(&ilw);
24988 			/*
24989 			 * Loopback case: the sending endpoint has
24990 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24991 			 * dispatch the multicast packet to the sending zone.
24992 			 */
24993 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24994 				freemsg(first_mp);
24995 				return;
24996 			}
24997 		} else if (ire_type == IRE_BROADCAST) {
24998 			/*
24999 			 * In the broadcast case, there may be many zones
25000 			 * which need a copy of the packet delivered to them.
25001 			 * There is one IRE_BROADCAST per broadcast address
25002 			 * and per zone; we walk those using a helper function.
25003 			 * In addition, the sending of the packet for zoneid is
25004 			 * delayed until all of the other ires have been
25005 			 * processed.
25006 			 */
25007 			IRB_REFHOLD(ire->ire_bucket);
25008 			ire_zone = NULL;
25009 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25010 			    ire)) != NULL) {
25011 				mp1 = ip_copymsg(first_mp);
25012 				if (mp1 == NULL)
25013 					continue;
25014 
25015 				UPDATE_IB_PKT_COUNT(ire_zone);
25016 				ire_zone->ire_last_used_time = lbolt;
25017 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25018 				    mctl_present, B_FALSE, ill,
25019 				    ire_zone->ire_zoneid);
25020 			}
25021 			IRB_REFRELE(ire->ire_bucket);
25022 		}
25023 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25024 		    0, mctl_present, B_FALSE, ill, zoneid);
25025 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25026 		    "ip_wput_local_end: q %p (%S)",
25027 		    q, "icmp");
25028 		return;
25029 	}
25030 	case IPPROTO_IGMP:
25031 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25032 			/* Bad packet - discarded by igmp_input */
25033 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25034 			    "ip_wput_local_end: q %p (%S)",
25035 			    q, "igmp_input--bad packet");
25036 			if (mctl_present)
25037 				freeb(first_mp);
25038 			return;
25039 		}
25040 		/*
25041 		 * igmp_input() may have returned the pulled up message.
25042 		 * So first_mp and ipha need to be reinitialized.
25043 		 */
25044 		ipha = (ipha_t *)mp->b_rptr;
25045 		if (mctl_present)
25046 			first_mp->b_cont = mp;
25047 		else
25048 			first_mp = mp;
25049 		/* deliver to local raw users */
25050 		break;
25051 	case IPPROTO_ENCAP:
25052 		/*
25053 		 * This case is covered by either ip_fanout_proto, or by
25054 		 * the above security processing for self-tunneled packets.
25055 		 */
25056 		break;
25057 	case IPPROTO_UDP: {
25058 		uint16_t	*up;
25059 		uint32_t	ports;
25060 
25061 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25062 		    UDP_PORTS_OFFSET);
25063 		/* Force a 'valid' checksum. */
25064 		up[3] = 0;
25065 
25066 		ports = *(uint32_t *)up;
25067 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25068 		    (ire_type == IRE_BROADCAST),
25069 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25070 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25071 		    ill, zoneid);
25072 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25073 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25074 		return;
25075 	}
25076 	case IPPROTO_TCP: {
25077 
25078 		/*
25079 		 * For TCP, discard broadcast packets.
25080 		 */
25081 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25082 			freemsg(first_mp);
25083 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25084 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25085 			return;
25086 		}
25087 
25088 		if (mp->b_datap->db_type == M_DATA) {
25089 			/*
25090 			 * M_DATA mblk, so init mblk (chain) for no struio().
25091 			 */
25092 			mblk_t	*mp1 = mp;
25093 
25094 			do {
25095 				mp1->b_datap->db_struioflag = 0;
25096 			} while ((mp1 = mp1->b_cont) != NULL);
25097 		}
25098 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25099 		    <= mp->b_wptr);
25100 		ip_fanout_tcp(q, first_mp, ill, ipha,
25101 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25102 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25103 		    mctl_present, B_FALSE, zoneid);
25104 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25105 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25106 		return;
25107 	}
25108 	case IPPROTO_SCTP:
25109 	{
25110 		uint32_t	ports;
25111 
25112 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25113 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25114 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25115 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25116 		return;
25117 	}
25118 
25119 	default:
25120 		break;
25121 	}
25122 	/*
25123 	 * Find a client for some other protocol.  We give
25124 	 * copies to multiple clients, if more than one is
25125 	 * bound.
25126 	 */
25127 	ip_fanout_proto(q, first_mp, ill, ipha,
25128 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25129 	    mctl_present, B_FALSE, ill, zoneid);
25130 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25131 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25132 #undef	rptr
25133 }
25134 
25135 /*
25136  * Update any source route, record route, or timestamp options.
25137  * Check that we are at end of strict source route.
25138  * The options have been sanity checked by ip_wput_options().
25139  */
25140 static void
25141 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25142 {
25143 	ipoptp_t	opts;
25144 	uchar_t		*opt;
25145 	uint8_t		optval;
25146 	uint8_t		optlen;
25147 	ipaddr_t	dst;
25148 	uint32_t	ts;
25149 	ire_t		*ire;
25150 	timestruc_t	now;
25151 
25152 	ip2dbg(("ip_wput_local_options\n"));
25153 	for (optval = ipoptp_first(&opts, ipha);
25154 	    optval != IPOPT_EOL;
25155 	    optval = ipoptp_next(&opts)) {
25156 		opt = opts.ipoptp_cur;
25157 		optlen = opts.ipoptp_len;
25158 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25159 		switch (optval) {
25160 			uint32_t off;
25161 		case IPOPT_SSRR:
25162 		case IPOPT_LSRR:
25163 			off = opt[IPOPT_OFFSET];
25164 			off--;
25165 			if (optlen < IP_ADDR_LEN ||
25166 			    off > optlen - IP_ADDR_LEN) {
25167 				/* End of source route */
25168 				break;
25169 			}
25170 			/*
25171 			 * This will only happen if two consecutive entries
25172 			 * in the source route contains our address or if
25173 			 * it is a packet with a loose source route which
25174 			 * reaches us before consuming the whole source route
25175 			 */
25176 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25177 			if (optval == IPOPT_SSRR) {
25178 				return;
25179 			}
25180 			/*
25181 			 * Hack: instead of dropping the packet truncate the
25182 			 * source route to what has been used by filling the
25183 			 * rest with IPOPT_NOP.
25184 			 */
25185 			opt[IPOPT_OLEN] = (uint8_t)off;
25186 			while (off < optlen) {
25187 				opt[off++] = IPOPT_NOP;
25188 			}
25189 			break;
25190 		case IPOPT_RR:
25191 			off = opt[IPOPT_OFFSET];
25192 			off--;
25193 			if (optlen < IP_ADDR_LEN ||
25194 			    off > optlen - IP_ADDR_LEN) {
25195 				/* No more room - ignore */
25196 				ip1dbg((
25197 				    "ip_wput_forward_options: end of RR\n"));
25198 				break;
25199 			}
25200 			dst = htonl(INADDR_LOOPBACK);
25201 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25202 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25203 			break;
25204 		case IPOPT_TS:
25205 			/* Insert timestamp if there is romm */
25206 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25207 			case IPOPT_TS_TSONLY:
25208 				off = IPOPT_TS_TIMELEN;
25209 				break;
25210 			case IPOPT_TS_PRESPEC:
25211 			case IPOPT_TS_PRESPEC_RFC791:
25212 				/* Verify that the address matched */
25213 				off = opt[IPOPT_OFFSET] - 1;
25214 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25215 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25216 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25217 				    ipst);
25218 				if (ire == NULL) {
25219 					/* Not for us */
25220 					break;
25221 				}
25222 				ire_refrele(ire);
25223 				/* FALLTHRU */
25224 			case IPOPT_TS_TSANDADDR:
25225 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25226 				break;
25227 			default:
25228 				/*
25229 				 * ip_*put_options should have already
25230 				 * dropped this packet.
25231 				 */
25232 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25233 				    "unknown IT - bug in ip_wput_options?\n");
25234 				return;	/* Keep "lint" happy */
25235 			}
25236 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25237 				/* Increase overflow counter */
25238 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25239 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25240 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25241 				    (off << 4);
25242 				break;
25243 			}
25244 			off = opt[IPOPT_OFFSET] - 1;
25245 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25246 			case IPOPT_TS_PRESPEC:
25247 			case IPOPT_TS_PRESPEC_RFC791:
25248 			case IPOPT_TS_TSANDADDR:
25249 				dst = htonl(INADDR_LOOPBACK);
25250 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25251 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25252 				/* FALLTHRU */
25253 			case IPOPT_TS_TSONLY:
25254 				off = opt[IPOPT_OFFSET] - 1;
25255 				/* Compute # of milliseconds since midnight */
25256 				gethrestime(&now);
25257 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25258 				    now.tv_nsec / (NANOSEC / MILLISEC);
25259 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25260 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25261 				break;
25262 			}
25263 			break;
25264 		}
25265 	}
25266 }
25267 
25268 /*
25269  * Send out a multicast packet on interface ipif.
25270  * The sender does not have an conn.
25271  * Caller verifies that this isn't a PHYI_LOOPBACK.
25272  */
25273 void
25274 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25275 {
25276 	ipha_t	*ipha;
25277 	ire_t	*ire;
25278 	ipaddr_t	dst;
25279 	mblk_t		*first_mp;
25280 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25281 
25282 	/* igmp_sendpkt always allocates a ipsec_out_t */
25283 	ASSERT(mp->b_datap->db_type == M_CTL);
25284 	ASSERT(!ipif->ipif_isv6);
25285 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25286 
25287 	first_mp = mp;
25288 	mp = first_mp->b_cont;
25289 	ASSERT(mp->b_datap->db_type == M_DATA);
25290 	ipha = (ipha_t *)mp->b_rptr;
25291 
25292 	/*
25293 	 * Find an IRE which matches the destination and the outgoing
25294 	 * queue (i.e. the outgoing interface.)
25295 	 */
25296 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25297 		dst = ipif->ipif_pp_dst_addr;
25298 	else
25299 		dst = ipha->ipha_dst;
25300 	/*
25301 	 * The source address has already been initialized by the
25302 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25303 	 * be sufficient rather than MATCH_IRE_IPIF.
25304 	 *
25305 	 * This function is used for sending IGMP packets.  For IPMP,
25306 	 * we sidestep IGMP snooping issues by sending all multicast
25307 	 * traffic on a single interface in the IPMP group.
25308 	 */
25309 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25310 	    MATCH_IRE_ILL, ipst);
25311 	if (!ire) {
25312 		/*
25313 		 * Mark this packet to make it be delivered to
25314 		 * ip_wput_ire after the new ire has been
25315 		 * created.
25316 		 */
25317 		mp->b_prev = NULL;
25318 		mp->b_next = NULL;
25319 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25320 		    zoneid, &zero_info);
25321 		return;
25322 	}
25323 
25324 	/*
25325 	 * Honor the RTF_SETSRC flag; this is the only case
25326 	 * where we force this addr whatever the current src addr is,
25327 	 * because this address is set by igmp_sendpkt(), and
25328 	 * cannot be specified by any user.
25329 	 */
25330 	if (ire->ire_flags & RTF_SETSRC) {
25331 		ipha->ipha_src = ire->ire_src_addr;
25332 	}
25333 
25334 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25335 }
25336 
25337 /*
25338  * NOTE : This function does not ire_refrele the ire argument passed in.
25339  *
25340  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25341  * failure. The nce_fp_mp can vanish any time in the case of
25342  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25343  * the ire_lock to access the nce_fp_mp in this case.
25344  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25345  * prepending a fastpath message IPQoS processing must precede it, we also set
25346  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25347  * (IPQoS might have set the b_band for CoS marking).
25348  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25349  * must follow it so that IPQoS can mark the dl_priority field for CoS
25350  * marking, if needed.
25351  */
25352 static mblk_t *
25353 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25354     uint32_t ill_index, ipha_t **iphap)
25355 {
25356 	uint_t	hlen;
25357 	ipha_t *ipha;
25358 	mblk_t *mp1;
25359 	boolean_t qos_done = B_FALSE;
25360 	uchar_t	*ll_hdr;
25361 	ip_stack_t	*ipst = ire->ire_ipst;
25362 
25363 #define	rptr	((uchar_t *)ipha)
25364 
25365 	ipha = (ipha_t *)mp->b_rptr;
25366 	hlen = 0;
25367 	LOCK_IRE_FP_MP(ire);
25368 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25369 		ASSERT(DB_TYPE(mp1) == M_DATA);
25370 		/* Initiate IPPF processing */
25371 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25372 			UNLOCK_IRE_FP_MP(ire);
25373 			ip_process(proc, &mp, ill_index);
25374 			if (mp == NULL)
25375 				return (NULL);
25376 
25377 			ipha = (ipha_t *)mp->b_rptr;
25378 			LOCK_IRE_FP_MP(ire);
25379 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25380 				qos_done = B_TRUE;
25381 				goto no_fp_mp;
25382 			}
25383 			ASSERT(DB_TYPE(mp1) == M_DATA);
25384 		}
25385 		hlen = MBLKL(mp1);
25386 		/*
25387 		 * Check if we have enough room to prepend fastpath
25388 		 * header
25389 		 */
25390 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25391 			ll_hdr = rptr - hlen;
25392 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25393 			/*
25394 			 * Set the b_rptr to the start of the link layer
25395 			 * header
25396 			 */
25397 			mp->b_rptr = ll_hdr;
25398 			mp1 = mp;
25399 		} else {
25400 			mp1 = copyb(mp1);
25401 			if (mp1 == NULL)
25402 				goto unlock_err;
25403 			mp1->b_band = mp->b_band;
25404 			mp1->b_cont = mp;
25405 			/*
25406 			 * XXX disable ICK_VALID and compute checksum
25407 			 * here; can happen if nce_fp_mp changes and
25408 			 * it can't be copied now due to insufficient
25409 			 * space. (unlikely, fp mp can change, but it
25410 			 * does not increase in length)
25411 			 */
25412 		}
25413 		UNLOCK_IRE_FP_MP(ire);
25414 	} else {
25415 no_fp_mp:
25416 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25417 		if (mp1 == NULL) {
25418 unlock_err:
25419 			UNLOCK_IRE_FP_MP(ire);
25420 			freemsg(mp);
25421 			return (NULL);
25422 		}
25423 		UNLOCK_IRE_FP_MP(ire);
25424 		mp1->b_cont = mp;
25425 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25426 			ip_process(proc, &mp1, ill_index);
25427 			if (mp1 == NULL)
25428 				return (NULL);
25429 
25430 			if (mp1->b_cont == NULL)
25431 				ipha = NULL;
25432 			else
25433 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25434 		}
25435 	}
25436 
25437 	*iphap = ipha;
25438 	return (mp1);
25439 #undef rptr
25440 }
25441 
25442 /*
25443  * Finish the outbound IPsec processing for an IPv6 packet. This function
25444  * is called from ipsec_out_process() if the IPsec packet was processed
25445  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25446  * asynchronously.
25447  */
25448 void
25449 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25450     ire_t *ire_arg)
25451 {
25452 	in6_addr_t *v6dstp;
25453 	ire_t *ire;
25454 	mblk_t *mp;
25455 	ip6_t *ip6h1;
25456 	uint_t	ill_index;
25457 	ipsec_out_t *io;
25458 	boolean_t hwaccel;
25459 	uint32_t flags = IP6_NO_IPPOLICY;
25460 	int match_flags;
25461 	zoneid_t zoneid;
25462 	boolean_t ill_need_rele = B_FALSE;
25463 	boolean_t ire_need_rele = B_FALSE;
25464 	ip_stack_t	*ipst;
25465 
25466 	mp = ipsec_mp->b_cont;
25467 	ip6h1 = (ip6_t *)mp->b_rptr;
25468 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25469 	ASSERT(io->ipsec_out_ns != NULL);
25470 	ipst = io->ipsec_out_ns->netstack_ip;
25471 	ill_index = io->ipsec_out_ill_index;
25472 	if (io->ipsec_out_reachable) {
25473 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25474 	}
25475 	hwaccel = io->ipsec_out_accelerated;
25476 	zoneid = io->ipsec_out_zoneid;
25477 	ASSERT(zoneid != ALL_ZONES);
25478 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25479 	/* Multicast addresses should have non-zero ill_index. */
25480 	v6dstp = &ip6h->ip6_dst;
25481 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25482 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25483 
25484 	if (ill == NULL && ill_index != 0) {
25485 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25486 		/* Failure case frees things for us. */
25487 		if (ill == NULL)
25488 			return;
25489 
25490 		ill_need_rele = B_TRUE;
25491 	}
25492 	ASSERT(mp != NULL);
25493 
25494 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25495 		boolean_t unspec_src;
25496 		ipif_t	*ipif;
25497 
25498 		/*
25499 		 * Use the ill_index to get the right ill.
25500 		 */
25501 		unspec_src = io->ipsec_out_unspec_src;
25502 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25503 		if (ipif == NULL) {
25504 			if (ill_need_rele)
25505 				ill_refrele(ill);
25506 			freemsg(ipsec_mp);
25507 			return;
25508 		}
25509 
25510 		if (ire_arg != NULL) {
25511 			ire = ire_arg;
25512 		} else {
25513 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25514 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25515 			ire_need_rele = B_TRUE;
25516 		}
25517 		if (ire != NULL) {
25518 			ipif_refrele(ipif);
25519 			/*
25520 			 * XXX Do the multicast forwarding now, as the IPsec
25521 			 * processing has been done.
25522 			 */
25523 			goto send;
25524 		}
25525 
25526 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25527 		mp->b_prev = NULL;
25528 		mp->b_next = NULL;
25529 
25530 		/*
25531 		 * If the IPsec packet was processed asynchronously,
25532 		 * drop it now.
25533 		 */
25534 		if (q == NULL) {
25535 			if (ill_need_rele)
25536 				ill_refrele(ill);
25537 			freemsg(ipsec_mp);
25538 			return;
25539 		}
25540 
25541 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25542 		    unspec_src, zoneid);
25543 		ipif_refrele(ipif);
25544 	} else {
25545 		if (ire_arg != NULL) {
25546 			ire = ire_arg;
25547 		} else {
25548 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25549 			ire_need_rele = B_TRUE;
25550 		}
25551 		if (ire != NULL)
25552 			goto send;
25553 		/*
25554 		 * ire disappeared underneath.
25555 		 *
25556 		 * What we need to do here is the ip_newroute
25557 		 * logic to get the ire without doing the IPsec
25558 		 * processing. Follow the same old path. But this
25559 		 * time, ip_wput or ire_add_then_send will call us
25560 		 * directly as all the IPsec operations are done.
25561 		 */
25562 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25563 		mp->b_prev = NULL;
25564 		mp->b_next = NULL;
25565 
25566 		/*
25567 		 * If the IPsec packet was processed asynchronously,
25568 		 * drop it now.
25569 		 */
25570 		if (q == NULL) {
25571 			if (ill_need_rele)
25572 				ill_refrele(ill);
25573 			freemsg(ipsec_mp);
25574 			return;
25575 		}
25576 
25577 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25578 		    zoneid, ipst);
25579 	}
25580 	if (ill != NULL && ill_need_rele)
25581 		ill_refrele(ill);
25582 	return;
25583 send:
25584 	if (ill != NULL && ill_need_rele)
25585 		ill_refrele(ill);
25586 
25587 	/* Local delivery */
25588 	if (ire->ire_stq == NULL) {
25589 		ill_t	*out_ill;
25590 		ASSERT(q != NULL);
25591 
25592 		/* PFHooks: LOOPBACK_OUT */
25593 		out_ill = ire_to_ill(ire);
25594 
25595 		/*
25596 		 * DTrace this as ip:::send.  A blocked packet will fire the
25597 		 * send probe, but not the receive probe.
25598 		 */
25599 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25600 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25601 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25602 
25603 		DTRACE_PROBE4(ip6__loopback__out__start,
25604 		    ill_t *, NULL, ill_t *, out_ill,
25605 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25606 
25607 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25608 		    ipst->ips_ipv6firewall_loopback_out,
25609 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25610 
25611 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25612 
25613 		if (ipsec_mp != NULL) {
25614 			ip_wput_local_v6(RD(q), out_ill,
25615 			    ip6h, ipsec_mp, ire, 0, zoneid);
25616 		}
25617 		if (ire_need_rele)
25618 			ire_refrele(ire);
25619 		return;
25620 	}
25621 	/*
25622 	 * Everything is done. Send it out on the wire.
25623 	 * We force the insertion of a fragment header using the
25624 	 * IPH_FRAG_HDR flag in two cases:
25625 	 * - after reception of an ICMPv6 "packet too big" message
25626 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25627 	 * - for multirouted IPv6 packets, so that the receiver can
25628 	 *   discard duplicates according to their fragment identifier
25629 	 */
25630 	/* XXX fix flow control problems. */
25631 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25632 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25633 		if (hwaccel) {
25634 			/*
25635 			 * hardware acceleration does not handle these
25636 			 * "slow path" cases.
25637 			 */
25638 			/* IPsec KSTATS: should bump bean counter here. */
25639 			if (ire_need_rele)
25640 				ire_refrele(ire);
25641 			freemsg(ipsec_mp);
25642 			return;
25643 		}
25644 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25645 		    (mp->b_cont ? msgdsize(mp) :
25646 		    mp->b_wptr - (uchar_t *)ip6h)) {
25647 			/* IPsec KSTATS: should bump bean counter here. */
25648 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25649 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25650 			    msgdsize(mp)));
25651 			if (ire_need_rele)
25652 				ire_refrele(ire);
25653 			freemsg(ipsec_mp);
25654 			return;
25655 		}
25656 		ASSERT(mp->b_prev == NULL);
25657 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25658 		    ntohs(ip6h->ip6_plen) +
25659 		    IPV6_HDR_LEN, ire->ire_max_frag));
25660 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25661 		    ire->ire_max_frag);
25662 	} else {
25663 		UPDATE_OB_PKT_COUNT(ire);
25664 		ire->ire_last_used_time = lbolt;
25665 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25666 	}
25667 	if (ire_need_rele)
25668 		ire_refrele(ire);
25669 	freeb(ipsec_mp);
25670 }
25671 
25672 void
25673 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25674 {
25675 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25676 	da_ipsec_t *hada;	/* data attributes */
25677 	ill_t *ill = (ill_t *)q->q_ptr;
25678 
25679 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25680 
25681 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25682 		/* IPsec KSTATS: Bump lose counter here! */
25683 		freemsg(mp);
25684 		return;
25685 	}
25686 
25687 	/*
25688 	 * It's an IPsec packet that must be
25689 	 * accelerated by the Provider, and the
25690 	 * outbound ill is IPsec acceleration capable.
25691 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25692 	 * to the ill.
25693 	 * IPsec KSTATS: should bump packet counter here.
25694 	 */
25695 
25696 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25697 	if (hada_mp == NULL) {
25698 		/* IPsec KSTATS: should bump packet counter here. */
25699 		freemsg(mp);
25700 		return;
25701 	}
25702 
25703 	hada_mp->b_datap->db_type = M_CTL;
25704 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25705 	hada_mp->b_cont = mp;
25706 
25707 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25708 	bzero(hada, sizeof (da_ipsec_t));
25709 	hada->da_type = IPHADA_M_CTL;
25710 
25711 	putnext(q, hada_mp);
25712 }
25713 
25714 /*
25715  * Finish the outbound IPsec processing. This function is called from
25716  * ipsec_out_process() if the IPsec packet was processed
25717  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25718  * asynchronously.
25719  */
25720 void
25721 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25722     ire_t *ire_arg)
25723 {
25724 	uint32_t v_hlen_tos_len;
25725 	ipaddr_t	dst;
25726 	ipif_t	*ipif = NULL;
25727 	ire_t *ire;
25728 	ire_t *ire1 = NULL;
25729 	mblk_t *next_mp = NULL;
25730 	uint32_t max_frag;
25731 	boolean_t multirt_send = B_FALSE;
25732 	mblk_t *mp;
25733 	ipha_t *ipha1;
25734 	uint_t	ill_index;
25735 	ipsec_out_t *io;
25736 	int match_flags;
25737 	irb_t *irb = NULL;
25738 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25739 	zoneid_t zoneid;
25740 	ipxmit_state_t	pktxmit_state;
25741 	ip_stack_t	*ipst;
25742 
25743 #ifdef	_BIG_ENDIAN
25744 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25745 #else
25746 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25747 #endif
25748 
25749 	mp = ipsec_mp->b_cont;
25750 	ipha1 = (ipha_t *)mp->b_rptr;
25751 	ASSERT(mp != NULL);
25752 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25753 	dst = ipha->ipha_dst;
25754 
25755 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25756 	ill_index = io->ipsec_out_ill_index;
25757 	zoneid = io->ipsec_out_zoneid;
25758 	ASSERT(zoneid != ALL_ZONES);
25759 	ipst = io->ipsec_out_ns->netstack_ip;
25760 	ASSERT(io->ipsec_out_ns != NULL);
25761 
25762 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25763 	if (ill == NULL && ill_index != 0) {
25764 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25765 		/* Failure case frees things for us. */
25766 		if (ill == NULL)
25767 			return;
25768 
25769 		ill_need_rele = B_TRUE;
25770 	}
25771 
25772 	if (CLASSD(dst)) {
25773 		boolean_t conn_dontroute;
25774 		/*
25775 		 * Use the ill_index to get the right ipif.
25776 		 */
25777 		conn_dontroute = io->ipsec_out_dontroute;
25778 		if (ill_index == 0)
25779 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25780 		else
25781 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25782 		if (ipif == NULL) {
25783 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25784 			    " multicast\n"));
25785 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25786 			freemsg(ipsec_mp);
25787 			goto done;
25788 		}
25789 		/*
25790 		 * ipha_src has already been intialized with the
25791 		 * value of the ipif in ip_wput. All we need now is
25792 		 * an ire to send this downstream.
25793 		 */
25794 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25795 		    msg_getlabel(mp), match_flags, ipst);
25796 		if (ire != NULL) {
25797 			ill_t *ill1;
25798 			/*
25799 			 * Do the multicast forwarding now, as the IPsec
25800 			 * processing has been done.
25801 			 */
25802 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25803 			    (ill1 = ire_to_ill(ire))) {
25804 				if (ip_mforward(ill1, ipha, mp)) {
25805 					freemsg(ipsec_mp);
25806 					ip1dbg(("ip_wput_ipsec_out: mforward "
25807 					    "failed\n"));
25808 					ire_refrele(ire);
25809 					goto done;
25810 				}
25811 			}
25812 			goto send;
25813 		}
25814 
25815 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25816 		mp->b_prev = NULL;
25817 		mp->b_next = NULL;
25818 
25819 		/*
25820 		 * If the IPsec packet was processed asynchronously,
25821 		 * drop it now.
25822 		 */
25823 		if (q == NULL) {
25824 			freemsg(ipsec_mp);
25825 			goto done;
25826 		}
25827 
25828 		/*
25829 		 * We may be using a wrong ipif to create the ire.
25830 		 * But it is okay as the source address is assigned
25831 		 * for the packet already. Next outbound packet would
25832 		 * create the IRE with the right IPIF in ip_wput.
25833 		 *
25834 		 * Also handle RTF_MULTIRT routes.
25835 		 */
25836 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25837 		    zoneid, &zero_info);
25838 	} else {
25839 		if (ire_arg != NULL) {
25840 			ire = ire_arg;
25841 			ire_need_rele = B_FALSE;
25842 		} else {
25843 			ire = ire_cache_lookup(dst, zoneid,
25844 			    msg_getlabel(mp), ipst);
25845 		}
25846 		if (ire != NULL) {
25847 			goto send;
25848 		}
25849 
25850 		/*
25851 		 * ire disappeared underneath.
25852 		 *
25853 		 * What we need to do here is the ip_newroute
25854 		 * logic to get the ire without doing the IPsec
25855 		 * processing. Follow the same old path. But this
25856 		 * time, ip_wput or ire_add_then_put will call us
25857 		 * directly as all the IPsec operations are done.
25858 		 */
25859 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25860 		mp->b_prev = NULL;
25861 		mp->b_next = NULL;
25862 
25863 		/*
25864 		 * If the IPsec packet was processed asynchronously,
25865 		 * drop it now.
25866 		 */
25867 		if (q == NULL) {
25868 			freemsg(ipsec_mp);
25869 			goto done;
25870 		}
25871 
25872 		/*
25873 		 * Since we're going through ip_newroute() again, we
25874 		 * need to make sure we don't:
25875 		 *
25876 		 *	1.) Trigger the ASSERT() with the ipha_ident
25877 		 *	    overloading.
25878 		 *	2.) Redo transport-layer checksumming, since we've
25879 		 *	    already done all that to get this far.
25880 		 *
25881 		 * The easiest way not do either of the above is to set
25882 		 * the ipha_ident field to IP_HDR_INCLUDED.
25883 		 */
25884 		ipha->ipha_ident = IP_HDR_INCLUDED;
25885 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25886 		    zoneid, ipst);
25887 	}
25888 	goto done;
25889 send:
25890 	if (ire->ire_stq == NULL) {
25891 		ill_t	*out_ill;
25892 		/*
25893 		 * Loopbacks go through ip_wput_local except for one case.
25894 		 * We come here if we generate a icmp_frag_needed message
25895 		 * after IPsec processing is over. When this function calls
25896 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25897 		 * icmp_frag_needed. The message generated comes back here
25898 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25899 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25900 		 * source address as it is usually set in ip_wput_ire. As
25901 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25902 		 * and we end up here. We can't enter ip_wput_ire once the
25903 		 * IPsec processing is over and hence we need to do it here.
25904 		 */
25905 		ASSERT(q != NULL);
25906 		UPDATE_OB_PKT_COUNT(ire);
25907 		ire->ire_last_used_time = lbolt;
25908 		if (ipha->ipha_src == 0)
25909 			ipha->ipha_src = ire->ire_src_addr;
25910 
25911 		/* PFHooks: LOOPBACK_OUT */
25912 		out_ill = ire_to_ill(ire);
25913 
25914 		/*
25915 		 * DTrace this as ip:::send.  A blocked packet will fire the
25916 		 * send probe, but not the receive probe.
25917 		 */
25918 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25919 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25920 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25921 
25922 		DTRACE_PROBE4(ip4__loopback__out__start,
25923 		    ill_t *, NULL, ill_t *, out_ill,
25924 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25925 
25926 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25927 		    ipst->ips_ipv4firewall_loopback_out,
25928 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
25929 
25930 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25931 
25932 		if (ipsec_mp != NULL)
25933 			ip_wput_local(RD(q), out_ill,
25934 			    ipha, ipsec_mp, ire, 0, zoneid);
25935 		if (ire_need_rele)
25936 			ire_refrele(ire);
25937 		goto done;
25938 	}
25939 
25940 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25941 		/*
25942 		 * We are through with IPsec processing.
25943 		 * Fragment this and send it on the wire.
25944 		 */
25945 		if (io->ipsec_out_accelerated) {
25946 			/*
25947 			 * The packet has been accelerated but must
25948 			 * be fragmented. This should not happen
25949 			 * since AH and ESP must not accelerate
25950 			 * packets that need fragmentation, however
25951 			 * the configuration could have changed
25952 			 * since the AH or ESP processing.
25953 			 * Drop packet.
25954 			 * IPsec KSTATS: bump bean counter here.
25955 			 */
25956 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25957 			    "fragmented accelerated packet!\n"));
25958 			freemsg(ipsec_mp);
25959 		} else {
25960 			ip_wput_ire_fragmentit(ipsec_mp, ire,
25961 			    zoneid, ipst, NULL);
25962 		}
25963 		if (ire_need_rele)
25964 			ire_refrele(ire);
25965 		goto done;
25966 	}
25967 
25968 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25969 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25970 	    (void *)ire->ire_ipif, (void *)ipif));
25971 
25972 	/*
25973 	 * Multiroute the secured packet.
25974 	 */
25975 	if (ire->ire_flags & RTF_MULTIRT) {
25976 		ire_t *first_ire;
25977 		irb = ire->ire_bucket;
25978 		ASSERT(irb != NULL);
25979 		/*
25980 		 * This ire has been looked up as the one that
25981 		 * goes through the given ipif;
25982 		 * make sure we do not omit any other multiroute ire
25983 		 * that may be present in the bucket before this one.
25984 		 */
25985 		IRB_REFHOLD(irb);
25986 		for (first_ire = irb->irb_ire;
25987 		    first_ire != NULL;
25988 		    first_ire = first_ire->ire_next) {
25989 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25990 			    (first_ire->ire_addr == ire->ire_addr) &&
25991 			    !(first_ire->ire_marks &
25992 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
25993 				break;
25994 		}
25995 
25996 		if ((first_ire != NULL) && (first_ire != ire)) {
25997 			/*
25998 			 * Don't change the ire if the packet must
25999 			 * be fragmented if sent via this new one.
26000 			 */
26001 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26002 				IRE_REFHOLD(first_ire);
26003 				if (ire_need_rele)
26004 					ire_refrele(ire);
26005 				else
26006 					ire_need_rele = B_TRUE;
26007 				ire = first_ire;
26008 			}
26009 		}
26010 		IRB_REFRELE(irb);
26011 
26012 		multirt_send = B_TRUE;
26013 		max_frag = ire->ire_max_frag;
26014 	}
26015 
26016 	/*
26017 	 * In most cases, the emission loop below is entered only once.
26018 	 * Only in the case where the ire holds the RTF_MULTIRT
26019 	 * flag, we loop to process all RTF_MULTIRT ires in the
26020 	 * bucket, and send the packet through all crossed
26021 	 * RTF_MULTIRT routes.
26022 	 */
26023 	do {
26024 		if (multirt_send) {
26025 			/*
26026 			 * ire1 holds here the next ire to process in the
26027 			 * bucket. If multirouting is expected,
26028 			 * any non-RTF_MULTIRT ire that has the
26029 			 * right destination address is ignored.
26030 			 */
26031 			ASSERT(irb != NULL);
26032 			IRB_REFHOLD(irb);
26033 			for (ire1 = ire->ire_next;
26034 			    ire1 != NULL;
26035 			    ire1 = ire1->ire_next) {
26036 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26037 					continue;
26038 				if (ire1->ire_addr != ire->ire_addr)
26039 					continue;
26040 				if (ire1->ire_marks &
26041 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26042 					continue;
26043 				/* No loopback here */
26044 				if (ire1->ire_stq == NULL)
26045 					continue;
26046 				/*
26047 				 * Ensure we do not exceed the MTU
26048 				 * of the next route.
26049 				 */
26050 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26051 					ip_multirt_bad_mtu(ire1, max_frag);
26052 					continue;
26053 				}
26054 
26055 				IRE_REFHOLD(ire1);
26056 				break;
26057 			}
26058 			IRB_REFRELE(irb);
26059 			if (ire1 != NULL) {
26060 				/*
26061 				 * We are in a multiple send case, need to
26062 				 * make a copy of the packet.
26063 				 */
26064 				next_mp = copymsg(ipsec_mp);
26065 				if (next_mp == NULL) {
26066 					ire_refrele(ire1);
26067 					ire1 = NULL;
26068 				}
26069 			}
26070 		}
26071 		/*
26072 		 * Everything is done. Send it out on the wire
26073 		 *
26074 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26075 		 * either send it on the wire or, in the case of
26076 		 * HW acceleration, call ipsec_hw_putnext.
26077 		 */
26078 		if (ire->ire_nce &&
26079 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26080 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26081 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26082 			/*
26083 			 * If ire's link-layer is unresolved (this
26084 			 * would only happen if the incomplete ire
26085 			 * was added to cachetable via forwarding path)
26086 			 * don't bother going to ip_xmit_v4. Just drop the
26087 			 * packet.
26088 			 * There is a slight risk here, in that, if we
26089 			 * have the forwarding path create an incomplete
26090 			 * IRE, then until the IRE is completed, any
26091 			 * transmitted IPsec packets will be dropped
26092 			 * instead of being queued waiting for resolution.
26093 			 *
26094 			 * But the likelihood of a forwarding packet and a wput
26095 			 * packet sending to the same dst at the same time
26096 			 * and there not yet be an ARP entry for it is small.
26097 			 * Furthermore, if this actually happens, it might
26098 			 * be likely that wput would generate multiple
26099 			 * packets (and forwarding would also have a train
26100 			 * of packets) for that destination. If this is
26101 			 * the case, some of them would have been dropped
26102 			 * anyway, since ARP only queues a few packets while
26103 			 * waiting for resolution
26104 			 *
26105 			 * NOTE: We should really call ip_xmit_v4,
26106 			 * and let it queue the packet and send the
26107 			 * ARP query and have ARP come back thus:
26108 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26109 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26110 			 * hw accel work. But it's too complex to get
26111 			 * the IPsec hw  acceleration approach to fit
26112 			 * well with ip_xmit_v4 doing ARP without
26113 			 * doing IPsec simplification. For now, we just
26114 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26115 			 * that we can continue with the send on the next
26116 			 * attempt.
26117 			 *
26118 			 * XXX THis should be revisited, when
26119 			 * the IPsec/IP interaction is cleaned up
26120 			 */
26121 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26122 			    " - dropping packet\n"));
26123 			freemsg(ipsec_mp);
26124 			/*
26125 			 * Call ip_xmit_v4() to trigger ARP query
26126 			 * in case the nce_state is ND_INITIAL
26127 			 */
26128 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26129 			goto drop_pkt;
26130 		}
26131 
26132 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26133 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26134 		    mblk_t *, ipsec_mp);
26135 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26136 		    ipst->ips_ipv4firewall_physical_out, NULL,
26137 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26138 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26139 		if (ipsec_mp == NULL)
26140 			goto drop_pkt;
26141 
26142 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26143 		pktxmit_state = ip_xmit_v4(mp, ire,
26144 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26145 
26146 		if ((pktxmit_state ==  SEND_FAILED) ||
26147 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26148 
26149 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26150 drop_pkt:
26151 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26152 			    ipIfStatsOutDiscards);
26153 			if (ire_need_rele)
26154 				ire_refrele(ire);
26155 			if (ire1 != NULL) {
26156 				ire_refrele(ire1);
26157 				freemsg(next_mp);
26158 			}
26159 			goto done;
26160 		}
26161 
26162 		freeb(ipsec_mp);
26163 		if (ire_need_rele)
26164 			ire_refrele(ire);
26165 
26166 		if (ire1 != NULL) {
26167 			ire = ire1;
26168 			ire_need_rele = B_TRUE;
26169 			ASSERT(next_mp);
26170 			ipsec_mp = next_mp;
26171 			mp = ipsec_mp->b_cont;
26172 			ire1 = NULL;
26173 			next_mp = NULL;
26174 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26175 		} else {
26176 			multirt_send = B_FALSE;
26177 		}
26178 	} while (multirt_send);
26179 done:
26180 	if (ill != NULL && ill_need_rele)
26181 		ill_refrele(ill);
26182 	if (ipif != NULL)
26183 		ipif_refrele(ipif);
26184 }
26185 
26186 /*
26187  * Get the ill corresponding to the specified ire, and compare its
26188  * capabilities with the protocol and algorithms specified by the
26189  * the SA obtained from ipsec_out. If they match, annotate the
26190  * ipsec_out structure to indicate that the packet needs acceleration.
26191  *
26192  *
26193  * A packet is eligible for outbound hardware acceleration if the
26194  * following conditions are satisfied:
26195  *
26196  * 1. the packet will not be fragmented
26197  * 2. the provider supports the algorithm
26198  * 3. there is no pending control message being exchanged
26199  * 4. snoop is not attached
26200  * 5. the destination address is not a broadcast or multicast address.
26201  *
26202  * Rationale:
26203  *	- Hardware drivers do not support fragmentation with
26204  *	  the current interface.
26205  *	- snoop, multicast, and broadcast may result in exposure of
26206  *	  a cleartext datagram.
26207  * We check all five of these conditions here.
26208  *
26209  * XXX would like to nuke "ire_t *" parameter here; problem is that
26210  * IRE is only way to figure out if a v4 address is a broadcast and
26211  * thus ineligible for acceleration...
26212  */
26213 static void
26214 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26215 {
26216 	ipsec_out_t *io;
26217 	mblk_t *data_mp;
26218 	uint_t plen, overhead;
26219 	ip_stack_t	*ipst;
26220 	phyint_t	*phyint;
26221 
26222 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26223 		return;
26224 
26225 	if (ill == NULL)
26226 		return;
26227 	ipst = ill->ill_ipst;
26228 	phyint = ill->ill_phyint;
26229 
26230 	/*
26231 	 * Destination address is a broadcast or multicast.  Punt.
26232 	 */
26233 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26234 	    IRE_LOCAL)))
26235 		return;
26236 
26237 	data_mp = ipsec_mp->b_cont;
26238 
26239 	if (ill->ill_isv6) {
26240 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26241 
26242 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26243 			return;
26244 
26245 		plen = ip6h->ip6_plen;
26246 	} else {
26247 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26248 
26249 		if (CLASSD(ipha->ipha_dst))
26250 			return;
26251 
26252 		plen = ipha->ipha_length;
26253 	}
26254 	/*
26255 	 * Is there a pending DLPI control message being exchanged
26256 	 * between IP/IPsec and the DLS Provider? If there is, it
26257 	 * could be a SADB update, and the state of the DLS Provider
26258 	 * SADB might not be in sync with the SADB maintained by
26259 	 * IPsec. To avoid dropping packets or using the wrong keying
26260 	 * material, we do not accelerate this packet.
26261 	 */
26262 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26263 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26264 		    "ill_dlpi_pending! don't accelerate packet\n"));
26265 		return;
26266 	}
26267 
26268 	/*
26269 	 * Is the Provider in promiscous mode? If it does, we don't
26270 	 * accelerate the packet since it will bounce back up to the
26271 	 * listeners in the clear.
26272 	 */
26273 	if (phyint->phyint_flags & PHYI_PROMISC) {
26274 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26275 		    "ill in promiscous mode, don't accelerate packet\n"));
26276 		return;
26277 	}
26278 
26279 	/*
26280 	 * Will the packet require fragmentation?
26281 	 */
26282 
26283 	/*
26284 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26285 	 * as is used elsewhere.
26286 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26287 	 *	+ 2-byte trailer
26288 	 */
26289 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26290 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26291 
26292 	if ((plen + overhead) > ill->ill_max_mtu)
26293 		return;
26294 
26295 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26296 
26297 	/*
26298 	 * Can the ill accelerate this IPsec protocol and algorithm
26299 	 * specified by the SA?
26300 	 */
26301 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26302 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26303 		return;
26304 	}
26305 
26306 	/*
26307 	 * Tell AH or ESP that the outbound ill is capable of
26308 	 * accelerating this packet.
26309 	 */
26310 	io->ipsec_out_is_capab_ill = B_TRUE;
26311 }
26312 
26313 /*
26314  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26315  *
26316  * If this function returns B_TRUE, the requested SA's have been filled
26317  * into the ipsec_out_*_sa pointers.
26318  *
26319  * If the function returns B_FALSE, the packet has been "consumed", most
26320  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26321  *
26322  * The SA references created by the protocol-specific "select"
26323  * function will be released when the ipsec_mp is freed, thanks to the
26324  * ipsec_out_free destructor -- see spd.c.
26325  */
26326 static boolean_t
26327 ipsec_out_select_sa(mblk_t *ipsec_mp)
26328 {
26329 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26330 	ipsec_out_t *io;
26331 	ipsec_policy_t *pp;
26332 	ipsec_action_t *ap;
26333 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26334 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26335 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26336 
26337 	if (!io->ipsec_out_secure) {
26338 		/*
26339 		 * We came here by mistake.
26340 		 * Don't bother with ipsec processing
26341 		 * We should "discourage" this path in the future.
26342 		 */
26343 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26344 		return (B_FALSE);
26345 	}
26346 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26347 	ASSERT((io->ipsec_out_policy != NULL) ||
26348 	    (io->ipsec_out_act != NULL));
26349 
26350 	ASSERT(io->ipsec_out_failed == B_FALSE);
26351 
26352 	/*
26353 	 * IPsec processing has started.
26354 	 */
26355 	io->ipsec_out_proc_begin = B_TRUE;
26356 	ap = io->ipsec_out_act;
26357 	if (ap == NULL) {
26358 		pp = io->ipsec_out_policy;
26359 		ASSERT(pp != NULL);
26360 		ap = pp->ipsp_act;
26361 		ASSERT(ap != NULL);
26362 	}
26363 
26364 	/*
26365 	 * We have an action.  now, let's select SA's.
26366 	 * (In the future, we can cache this in the conn_t..)
26367 	 */
26368 	if (ap->ipa_want_esp) {
26369 		if (io->ipsec_out_esp_sa == NULL) {
26370 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26371 			    IPPROTO_ESP);
26372 		}
26373 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26374 	}
26375 
26376 	if (ap->ipa_want_ah) {
26377 		if (io->ipsec_out_ah_sa == NULL) {
26378 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26379 			    IPPROTO_AH);
26380 		}
26381 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26382 		/*
26383 		 * The ESP and AH processing order needs to be preserved
26384 		 * when both protocols are required (ESP should be applied
26385 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26386 		 * when both ESP and AH are required, and an AH ACQUIRE
26387 		 * is needed.
26388 		 */
26389 		if (ap->ipa_want_esp && need_ah_acquire)
26390 			need_esp_acquire = B_TRUE;
26391 	}
26392 
26393 	/*
26394 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26395 	 * Release SAs that got referenced, but will not be used until we
26396 	 * acquire _all_ of the SAs we need.
26397 	 */
26398 	if (need_ah_acquire || need_esp_acquire) {
26399 		if (io->ipsec_out_ah_sa != NULL) {
26400 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26401 			io->ipsec_out_ah_sa = NULL;
26402 		}
26403 		if (io->ipsec_out_esp_sa != NULL) {
26404 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26405 			io->ipsec_out_esp_sa = NULL;
26406 		}
26407 
26408 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26409 		return (B_FALSE);
26410 	}
26411 
26412 	return (B_TRUE);
26413 }
26414 
26415 /*
26416  * Process an IPSEC_OUT message and see what you can
26417  * do with it.
26418  * IPQoS Notes:
26419  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26420  * IPsec.
26421  * XXX would like to nuke ire_t.
26422  * XXX ill_index better be "real"
26423  */
26424 void
26425 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26426 {
26427 	ipsec_out_t *io;
26428 	ipsec_policy_t *pp;
26429 	ipsec_action_t *ap;
26430 	ipha_t *ipha;
26431 	ip6_t *ip6h;
26432 	mblk_t *mp;
26433 	ill_t *ill;
26434 	zoneid_t zoneid;
26435 	ipsec_status_t ipsec_rc;
26436 	boolean_t ill_need_rele = B_FALSE;
26437 	ip_stack_t	*ipst;
26438 	ipsec_stack_t	*ipss;
26439 
26440 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26441 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26442 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26443 	ipst = io->ipsec_out_ns->netstack_ip;
26444 	mp = ipsec_mp->b_cont;
26445 
26446 	/*
26447 	 * Initiate IPPF processing. We do it here to account for packets
26448 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26449 	 * We can check for ipsec_out_proc_begin even for such packets, as
26450 	 * they will always be false (asserted below).
26451 	 */
26452 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26453 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26454 		    io->ipsec_out_ill_index : ill_index);
26455 		if (mp == NULL) {
26456 			ip2dbg(("ipsec_out_process: packet dropped "\
26457 			    "during IPPF processing\n"));
26458 			freeb(ipsec_mp);
26459 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26460 			return;
26461 		}
26462 	}
26463 
26464 	if (!io->ipsec_out_secure) {
26465 		/*
26466 		 * We came here by mistake.
26467 		 * Don't bother with ipsec processing
26468 		 * Should "discourage" this path in the future.
26469 		 */
26470 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26471 		goto done;
26472 	}
26473 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26474 	ASSERT((io->ipsec_out_policy != NULL) ||
26475 	    (io->ipsec_out_act != NULL));
26476 	ASSERT(io->ipsec_out_failed == B_FALSE);
26477 
26478 	ipss = ipst->ips_netstack->netstack_ipsec;
26479 	if (!ipsec_loaded(ipss)) {
26480 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26481 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26482 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26483 		} else {
26484 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26485 		}
26486 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26487 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26488 		    &ipss->ipsec_dropper);
26489 		return;
26490 	}
26491 
26492 	/*
26493 	 * IPsec processing has started.
26494 	 */
26495 	io->ipsec_out_proc_begin = B_TRUE;
26496 	ap = io->ipsec_out_act;
26497 	if (ap == NULL) {
26498 		pp = io->ipsec_out_policy;
26499 		ASSERT(pp != NULL);
26500 		ap = pp->ipsp_act;
26501 		ASSERT(ap != NULL);
26502 	}
26503 
26504 	/*
26505 	 * Save the outbound ill index. When the packet comes back
26506 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26507 	 * before sending it the accelerated packet.
26508 	 */
26509 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26510 		ill = ire_to_ill(ire);
26511 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26512 	}
26513 
26514 	/*
26515 	 * The order of processing is first insert a IP header if needed.
26516 	 * Then insert the ESP header and then the AH header.
26517 	 */
26518 	if ((io->ipsec_out_se_done == B_FALSE) &&
26519 	    (ap->ipa_want_se)) {
26520 		/*
26521 		 * First get the outer IP header before sending
26522 		 * it to ESP.
26523 		 */
26524 		ipha_t *oipha, *iipha;
26525 		mblk_t *outer_mp, *inner_mp;
26526 
26527 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26528 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26529 			    "ipsec_out_process: "
26530 			    "Self-Encapsulation failed: Out of memory\n");
26531 			freemsg(ipsec_mp);
26532 			if (ill != NULL) {
26533 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26534 			} else {
26535 				BUMP_MIB(&ipst->ips_ip_mib,
26536 				    ipIfStatsOutDiscards);
26537 			}
26538 			return;
26539 		}
26540 		inner_mp = ipsec_mp->b_cont;
26541 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26542 		oipha = (ipha_t *)outer_mp->b_rptr;
26543 		iipha = (ipha_t *)inner_mp->b_rptr;
26544 		*oipha = *iipha;
26545 		outer_mp->b_wptr += sizeof (ipha_t);
26546 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26547 		    sizeof (ipha_t));
26548 		oipha->ipha_protocol = IPPROTO_ENCAP;
26549 		oipha->ipha_version_and_hdr_length =
26550 		    IP_SIMPLE_HDR_VERSION;
26551 		oipha->ipha_hdr_checksum = 0;
26552 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26553 		outer_mp->b_cont = inner_mp;
26554 		ipsec_mp->b_cont = outer_mp;
26555 
26556 		io->ipsec_out_se_done = B_TRUE;
26557 		io->ipsec_out_tunnel = B_TRUE;
26558 	}
26559 
26560 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26561 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26562 	    !ipsec_out_select_sa(ipsec_mp))
26563 		return;
26564 
26565 	/*
26566 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26567 	 * to do the heavy lifting.
26568 	 */
26569 	zoneid = io->ipsec_out_zoneid;
26570 	ASSERT(zoneid != ALL_ZONES);
26571 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26572 		ASSERT(io->ipsec_out_esp_sa != NULL);
26573 		io->ipsec_out_esp_done = B_TRUE;
26574 		/*
26575 		 * Note that since hw accel can only apply one transform,
26576 		 * not two, we skip hw accel for ESP if we also have AH
26577 		 * This is an design limitation of the interface
26578 		 * which should be revisited.
26579 		 */
26580 		ASSERT(ire != NULL);
26581 		if (io->ipsec_out_ah_sa == NULL) {
26582 			ill = (ill_t *)ire->ire_stq->q_ptr;
26583 			ipsec_out_is_accelerated(ipsec_mp,
26584 			    io->ipsec_out_esp_sa, ill, ire);
26585 		}
26586 
26587 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26588 		switch (ipsec_rc) {
26589 		case IPSEC_STATUS_SUCCESS:
26590 			break;
26591 		case IPSEC_STATUS_FAILED:
26592 			if (ill != NULL) {
26593 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26594 			} else {
26595 				BUMP_MIB(&ipst->ips_ip_mib,
26596 				    ipIfStatsOutDiscards);
26597 			}
26598 			/* FALLTHRU */
26599 		case IPSEC_STATUS_PENDING:
26600 			return;
26601 		}
26602 	}
26603 
26604 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26605 		ASSERT(io->ipsec_out_ah_sa != NULL);
26606 		io->ipsec_out_ah_done = B_TRUE;
26607 		if (ire == NULL) {
26608 			int idx = io->ipsec_out_capab_ill_index;
26609 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26610 			    NULL, NULL, NULL, NULL, ipst);
26611 			ill_need_rele = B_TRUE;
26612 		} else {
26613 			ill = (ill_t *)ire->ire_stq->q_ptr;
26614 		}
26615 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26616 		    ire);
26617 
26618 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26619 		switch (ipsec_rc) {
26620 		case IPSEC_STATUS_SUCCESS:
26621 			break;
26622 		case IPSEC_STATUS_FAILED:
26623 			if (ill != NULL) {
26624 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26625 			} else {
26626 				BUMP_MIB(&ipst->ips_ip_mib,
26627 				    ipIfStatsOutDiscards);
26628 			}
26629 			/* FALLTHRU */
26630 		case IPSEC_STATUS_PENDING:
26631 			if (ill != NULL && ill_need_rele)
26632 				ill_refrele(ill);
26633 			return;
26634 		}
26635 	}
26636 	/*
26637 	 * We are done with IPsec processing. Send it over the wire.
26638 	 */
26639 done:
26640 	mp = ipsec_mp->b_cont;
26641 	ipha = (ipha_t *)mp->b_rptr;
26642 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26643 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26644 		    ire);
26645 	} else {
26646 		ip6h = (ip6_t *)ipha;
26647 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26648 		    ire);
26649 	}
26650 	if (ill != NULL && ill_need_rele)
26651 		ill_refrele(ill);
26652 }
26653 
26654 /* ARGSUSED */
26655 void
26656 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26657 {
26658 	opt_restart_t	*or;
26659 	int	err;
26660 	conn_t	*connp;
26661 	cred_t	*cr;
26662 
26663 	ASSERT(CONN_Q(q));
26664 	connp = Q_TO_CONN(q);
26665 
26666 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26667 	or = (opt_restart_t *)first_mp->b_rptr;
26668 	/*
26669 	 * We checked for a db_credp the first time svr4_optcom_req
26670 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26671 	 */
26672 	cr = msg_getcred(first_mp, NULL);
26673 	ASSERT(cr != NULL);
26674 
26675 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26676 		err = svr4_optcom_req(q, first_mp, cr,
26677 		    &ip_opt_obj, B_FALSE);
26678 	} else {
26679 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26680 		err = tpi_optcom_req(q, first_mp, cr,
26681 		    &ip_opt_obj, B_FALSE);
26682 	}
26683 	if (err != EINPROGRESS) {
26684 		/* operation is done */
26685 		CONN_OPER_PENDING_DONE(connp);
26686 	}
26687 }
26688 
26689 /*
26690  * ioctls that go through a down/up sequence may need to wait for the down
26691  * to complete. This involves waiting for the ire and ipif refcnts to go down
26692  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26693  */
26694 /* ARGSUSED */
26695 void
26696 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26697 {
26698 	struct iocblk *iocp;
26699 	mblk_t *mp1;
26700 	ip_ioctl_cmd_t *ipip;
26701 	int err;
26702 	sin_t	*sin;
26703 	struct lifreq *lifr;
26704 	struct ifreq *ifr;
26705 
26706 	iocp = (struct iocblk *)mp->b_rptr;
26707 	ASSERT(ipsq != NULL);
26708 	/* Existence of mp1 verified in ip_wput_nondata */
26709 	mp1 = mp->b_cont->b_cont;
26710 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26711 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26712 		/*
26713 		 * Special case where ipx_current_ipif is not set:
26714 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26715 		 * We are here as were not able to complete the operation in
26716 		 * ipif_set_values because we could not become exclusive on
26717 		 * the new ipsq.
26718 		 */
26719 		ill_t *ill = q->q_ptr;
26720 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26721 	}
26722 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26723 
26724 	if (ipip->ipi_cmd_type == IF_CMD) {
26725 		/* This a old style SIOC[GS]IF* command */
26726 		ifr = (struct ifreq *)mp1->b_rptr;
26727 		sin = (sin_t *)&ifr->ifr_addr;
26728 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26729 		/* This a new style SIOC[GS]LIF* command */
26730 		lifr = (struct lifreq *)mp1->b_rptr;
26731 		sin = (sin_t *)&lifr->lifr_addr;
26732 	} else {
26733 		sin = NULL;
26734 	}
26735 
26736 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26737 	    q, mp, ipip, mp1->b_rptr);
26738 
26739 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26740 }
26741 
26742 /*
26743  * ioctl processing
26744  *
26745  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26746  * the ioctl command in the ioctl tables, determines the copyin data size
26747  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26748  *
26749  * ioctl processing then continues when the M_IOCDATA makes its way down to
26750  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26751  * associated 'conn' is refheld till the end of the ioctl and the general
26752  * ioctl processing function ip_process_ioctl() is called to extract the
26753  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26754  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26755  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26756  * is used to extract the ioctl's arguments.
26757  *
26758  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26759  * so goes thru the serialization primitive ipsq_try_enter. Then the
26760  * appropriate function to handle the ioctl is called based on the entry in
26761  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26762  * which also refreleases the 'conn' that was refheld at the start of the
26763  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26764  *
26765  * Many exclusive ioctls go thru an internal down up sequence as part of
26766  * the operation. For example an attempt to change the IP address of an
26767  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26768  * does all the cleanup such as deleting all ires that use this address.
26769  * Then we need to wait till all references to the interface go away.
26770  */
26771 void
26772 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26773 {
26774 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26775 	ip_ioctl_cmd_t *ipip = arg;
26776 	ip_extract_func_t *extract_funcp;
26777 	cmd_info_t ci;
26778 	int err;
26779 	boolean_t entered_ipsq = B_FALSE;
26780 
26781 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26782 
26783 	if (ipip == NULL)
26784 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26785 
26786 	/*
26787 	 * SIOCLIFADDIF needs to go thru a special path since the
26788 	 * ill may not exist yet. This happens in the case of lo0
26789 	 * which is created using this ioctl.
26790 	 */
26791 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26792 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26793 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26794 		return;
26795 	}
26796 
26797 	ci.ci_ipif = NULL;
26798 	if (ipip->ipi_cmd_type == MISC_CMD) {
26799 		/*
26800 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26801 		 */
26802 		if (ipip->ipi_cmd == IF_UNITSEL) {
26803 			/* ioctl comes down the ill */
26804 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26805 			ipif_refhold(ci.ci_ipif);
26806 		}
26807 		err = 0;
26808 		ci.ci_sin = NULL;
26809 		ci.ci_sin6 = NULL;
26810 		ci.ci_lifr = NULL;
26811 	} else {
26812 		switch (ipip->ipi_cmd_type) {
26813 		case IF_CMD:
26814 		case LIF_CMD:
26815 			extract_funcp = ip_extract_lifreq;
26816 			break;
26817 
26818 		case ARP_CMD:
26819 		case XARP_CMD:
26820 			extract_funcp = ip_extract_arpreq;
26821 			break;
26822 
26823 		case MSFILT_CMD:
26824 			extract_funcp = ip_extract_msfilter;
26825 			break;
26826 
26827 		default:
26828 			ASSERT(0);
26829 		}
26830 
26831 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26832 		if (err != 0) {
26833 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26834 			return;
26835 		}
26836 
26837 		/*
26838 		 * All of the extraction functions return a refheld ipif.
26839 		 */
26840 		ASSERT(ci.ci_ipif != NULL);
26841 	}
26842 
26843 	if (!(ipip->ipi_flags & IPI_WR)) {
26844 		/*
26845 		 * A return value of EINPROGRESS means the ioctl is
26846 		 * either queued and waiting for some reason or has
26847 		 * already completed.
26848 		 */
26849 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26850 		    ci.ci_lifr);
26851 		if (ci.ci_ipif != NULL)
26852 			ipif_refrele(ci.ci_ipif);
26853 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26854 		return;
26855 	}
26856 
26857 	ASSERT(ci.ci_ipif != NULL);
26858 
26859 	/*
26860 	 * If ipsq is non-NULL, we are already being called exclusively.
26861 	 */
26862 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26863 	if (ipsq == NULL) {
26864 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26865 		    NEW_OP, B_TRUE);
26866 		if (ipsq == NULL) {
26867 			ipif_refrele(ci.ci_ipif);
26868 			return;
26869 		}
26870 		entered_ipsq = B_TRUE;
26871 	}
26872 
26873 	/*
26874 	 * Release the ipif so that ipif_down and friends that wait for
26875 	 * references to go away are not misled about the current ipif_refcnt
26876 	 * values. We are writer so we can access the ipif even after releasing
26877 	 * the ipif.
26878 	 */
26879 	ipif_refrele(ci.ci_ipif);
26880 
26881 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26882 
26883 	/*
26884 	 * A return value of EINPROGRESS means the ioctl is
26885 	 * either queued and waiting for some reason or has
26886 	 * already completed.
26887 	 */
26888 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26889 
26890 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26891 
26892 	if (entered_ipsq)
26893 		ipsq_exit(ipsq);
26894 }
26895 
26896 /*
26897  * Complete the ioctl. Typically ioctls use the mi package and need to
26898  * do mi_copyout/mi_copy_done.
26899  */
26900 void
26901 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26902 {
26903 	conn_t	*connp = NULL;
26904 
26905 	if (err == EINPROGRESS)
26906 		return;
26907 
26908 	if (CONN_Q(q)) {
26909 		connp = Q_TO_CONN(q);
26910 		ASSERT(connp->conn_ref >= 2);
26911 	}
26912 
26913 	switch (mode) {
26914 	case COPYOUT:
26915 		if (err == 0)
26916 			mi_copyout(q, mp);
26917 		else
26918 			mi_copy_done(q, mp, err);
26919 		break;
26920 
26921 	case NO_COPYOUT:
26922 		mi_copy_done(q, mp, err);
26923 		break;
26924 
26925 	default:
26926 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26927 		break;
26928 	}
26929 
26930 	/*
26931 	 * The refhold placed at the start of the ioctl is released here.
26932 	 */
26933 	if (connp != NULL)
26934 		CONN_OPER_PENDING_DONE(connp);
26935 
26936 	if (ipsq != NULL)
26937 		ipsq_current_finish(ipsq);
26938 }
26939 
26940 /* Called from ip_wput for all non data messages */
26941 /* ARGSUSED */
26942 void
26943 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26944 {
26945 	mblk_t		*mp1;
26946 	ire_t		*ire, *fake_ire;
26947 	ill_t		*ill;
26948 	struct iocblk	*iocp;
26949 	ip_ioctl_cmd_t	*ipip;
26950 	cred_t		*cr;
26951 	conn_t		*connp;
26952 	int		err;
26953 	nce_t		*nce;
26954 	ipif_t		*ipif;
26955 	ip_stack_t	*ipst;
26956 	char		*proto_str;
26957 
26958 	if (CONN_Q(q)) {
26959 		connp = Q_TO_CONN(q);
26960 		ipst = connp->conn_netstack->netstack_ip;
26961 	} else {
26962 		connp = NULL;
26963 		ipst = ILLQ_TO_IPST(q);
26964 	}
26965 
26966 	switch (DB_TYPE(mp)) {
26967 	case M_IOCTL:
26968 		/*
26969 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26970 		 * will arrange to copy in associated control structures.
26971 		 */
26972 		ip_sioctl_copyin_setup(q, mp);
26973 		return;
26974 	case M_IOCDATA:
26975 		/*
26976 		 * Ensure that this is associated with one of our trans-
26977 		 * parent ioctls.  If it's not ours, discard it if we're
26978 		 * running as a driver, or pass it on if we're a module.
26979 		 */
26980 		iocp = (struct iocblk *)mp->b_rptr;
26981 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26982 		if (ipip == NULL) {
26983 			if (q->q_next == NULL) {
26984 				goto nak;
26985 			} else {
26986 				putnext(q, mp);
26987 			}
26988 			return;
26989 		}
26990 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
26991 			/*
26992 			 * the ioctl is one we recognise, but is not
26993 			 * consumed by IP as a module, pass M_IOCDATA
26994 			 * for processing downstream, but only for
26995 			 * common Streams ioctls.
26996 			 */
26997 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26998 				putnext(q, mp);
26999 				return;
27000 			} else {
27001 				goto nak;
27002 			}
27003 		}
27004 
27005 		/* IOCTL continuation following copyin or copyout. */
27006 		if (mi_copy_state(q, mp, NULL) == -1) {
27007 			/*
27008 			 * The copy operation failed.  mi_copy_state already
27009 			 * cleaned up, so we're out of here.
27010 			 */
27011 			return;
27012 		}
27013 		/*
27014 		 * If we just completed a copy in, we become writer and
27015 		 * continue processing in ip_sioctl_copyin_done.  If it
27016 		 * was a copy out, we call mi_copyout again.  If there is
27017 		 * nothing more to copy out, it will complete the IOCTL.
27018 		 */
27019 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27020 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27021 				mi_copy_done(q, mp, EPROTO);
27022 				return;
27023 			}
27024 			/*
27025 			 * Check for cases that need more copying.  A return
27026 			 * value of 0 means a second copyin has been started,
27027 			 * so we return; a return value of 1 means no more
27028 			 * copying is needed, so we continue.
27029 			 */
27030 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27031 			    MI_COPY_COUNT(mp) == 1) {
27032 				if (ip_copyin_msfilter(q, mp) == 0)
27033 					return;
27034 			}
27035 			/*
27036 			 * Refhold the conn, till the ioctl completes. This is
27037 			 * needed in case the ioctl ends up in the pending mp
27038 			 * list. Every mp in the ill_pending_mp list and
27039 			 * the ipx_pending_mp must have a refhold on the conn
27040 			 * to resume processing. The refhold is released when
27041 			 * the ioctl completes. (normally or abnormally)
27042 			 * In all cases ip_ioctl_finish is called to finish
27043 			 * the ioctl.
27044 			 */
27045 			if (connp != NULL) {
27046 				/* This is not a reentry */
27047 				ASSERT(ipsq == NULL);
27048 				CONN_INC_REF(connp);
27049 			} else {
27050 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27051 					mi_copy_done(q, mp, EINVAL);
27052 					return;
27053 				}
27054 			}
27055 
27056 			ip_process_ioctl(ipsq, q, mp, ipip);
27057 
27058 		} else {
27059 			mi_copyout(q, mp);
27060 		}
27061 		return;
27062 nak:
27063 		iocp->ioc_error = EINVAL;
27064 		mp->b_datap->db_type = M_IOCNAK;
27065 		iocp->ioc_count = 0;
27066 		qreply(q, mp);
27067 		return;
27068 
27069 	case M_IOCNAK:
27070 		/*
27071 		 * The only way we could get here is if a resolver didn't like
27072 		 * an IOCTL we sent it.	 This shouldn't happen.
27073 		 */
27074 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27075 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27076 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27077 		freemsg(mp);
27078 		return;
27079 	case M_IOCACK:
27080 		/* /dev/ip shouldn't see this */
27081 		if (CONN_Q(q))
27082 			goto nak;
27083 
27084 		/*
27085 		 * Finish socket ioctls passed through to ARP.  We use the
27086 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27087 		 * we need to become writer before calling ip_sioctl_iocack().
27088 		 * Note that qwriter_ip() will release the refhold, and that a
27089 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27090 		 * ill stream.
27091 		 */
27092 		iocp = (struct iocblk *)mp->b_rptr;
27093 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27094 			ip_sioctl_iocack(NULL, q, mp, NULL);
27095 			return;
27096 		}
27097 
27098 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27099 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27100 		ill = q->q_ptr;
27101 		ill_refhold(ill);
27102 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27103 		return;
27104 	case M_FLUSH:
27105 		if (*mp->b_rptr & FLUSHW)
27106 			flushq(q, FLUSHALL);
27107 		if (q->q_next) {
27108 			putnext(q, mp);
27109 			return;
27110 		}
27111 		if (*mp->b_rptr & FLUSHR) {
27112 			*mp->b_rptr &= ~FLUSHW;
27113 			qreply(q, mp);
27114 			return;
27115 		}
27116 		freemsg(mp);
27117 		return;
27118 	case IRE_DB_REQ_TYPE:
27119 		if (connp == NULL) {
27120 			proto_str = "IRE_DB_REQ_TYPE";
27121 			goto protonak;
27122 		}
27123 		/* An Upper Level Protocol wants a copy of an IRE. */
27124 		ip_ire_req(q, mp);
27125 		return;
27126 	case M_CTL:
27127 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27128 			break;
27129 
27130 		/* M_CTL messages are used by ARP to tell us things. */
27131 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27132 			break;
27133 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27134 		case AR_ENTRY_SQUERY:
27135 			putnext(q, mp);
27136 			return;
27137 		case AR_CLIENT_NOTIFY:
27138 			ip_arp_news(q, mp);
27139 			return;
27140 		case AR_DLPIOP_DONE:
27141 			ASSERT(q->q_next != NULL);
27142 			ill = (ill_t *)q->q_ptr;
27143 			/* qwriter_ip releases the refhold */
27144 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27145 			ill_refhold(ill);
27146 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27147 			return;
27148 		case AR_ARP_CLOSING:
27149 			/*
27150 			 * ARP (above us) is closing. If no ARP bringup is
27151 			 * currently pending, ack the message so that ARP
27152 			 * can complete its close. Also mark ill_arp_closing
27153 			 * so that new ARP bringups will fail. If any
27154 			 * ARP bringup is currently in progress, we will
27155 			 * ack this when the current ARP bringup completes.
27156 			 */
27157 			ASSERT(q->q_next != NULL);
27158 			ill = (ill_t *)q->q_ptr;
27159 			mutex_enter(&ill->ill_lock);
27160 			ill->ill_arp_closing = 1;
27161 			if (!ill->ill_arp_bringup_pending) {
27162 				mutex_exit(&ill->ill_lock);
27163 				qreply(q, mp);
27164 			} else {
27165 				mutex_exit(&ill->ill_lock);
27166 				freemsg(mp);
27167 			}
27168 			return;
27169 		case AR_ARP_EXTEND:
27170 			/*
27171 			 * The ARP module above us is capable of duplicate
27172 			 * address detection.  Old ATM drivers will not send
27173 			 * this message.
27174 			 */
27175 			ASSERT(q->q_next != NULL);
27176 			ill = (ill_t *)q->q_ptr;
27177 			ill->ill_arp_extend = B_TRUE;
27178 			freemsg(mp);
27179 			return;
27180 		default:
27181 			break;
27182 		}
27183 		break;
27184 	case M_PROTO:
27185 	case M_PCPROTO:
27186 		/*
27187 		 * The only PROTO messages we expect are copies of option
27188 		 * negotiation acknowledgements, AH and ESP bind requests
27189 		 * are also expected.
27190 		 */
27191 		switch (((union T_primitives *)mp->b_rptr)->type) {
27192 		case O_T_BIND_REQ:
27193 		case T_BIND_REQ: {
27194 			/* Request can get queued in bind */
27195 			if (connp == NULL) {
27196 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27197 				goto protonak;
27198 			}
27199 			/*
27200 			 * The transports except SCTP call ip_bind_{v4,v6}()
27201 			 * directly instead of a a putnext. SCTP doesn't
27202 			 * generate any T_BIND_REQ since it has its own
27203 			 * fanout data structures. However, ESP and AH
27204 			 * come in for regular binds; all other cases are
27205 			 * bind retries.
27206 			 */
27207 			ASSERT(!IPCL_IS_SCTP(connp));
27208 
27209 			/* Don't increment refcnt if this is a re-entry */
27210 			if (ipsq == NULL)
27211 				CONN_INC_REF(connp);
27212 
27213 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27214 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27215 			ASSERT(mp != NULL);
27216 
27217 			ASSERT(!IPCL_IS_TCP(connp));
27218 			ASSERT(!IPCL_IS_UDP(connp));
27219 			ASSERT(!IPCL_IS_RAWIP(connp));
27220 			ASSERT(!IPCL_IS_IPTUN(connp));
27221 
27222 			/* The case of AH and ESP */
27223 			qreply(q, mp);
27224 			CONN_OPER_PENDING_DONE(connp);
27225 			return;
27226 		}
27227 		case T_SVR4_OPTMGMT_REQ:
27228 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27229 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27230 
27231 			if (connp == NULL) {
27232 				proto_str = "T_SVR4_OPTMGMT_REQ";
27233 				goto protonak;
27234 			}
27235 
27236 			/*
27237 			 * All Solaris components should pass a db_credp
27238 			 * for this TPI message, hence we ASSERT.
27239 			 * But in case there is some other M_PROTO that looks
27240 			 * like a TPI message sent by some other kernel
27241 			 * component, we check and return an error.
27242 			 */
27243 			cr = msg_getcred(mp, NULL);
27244 			ASSERT(cr != NULL);
27245 			if (cr == NULL) {
27246 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27247 				if (mp != NULL)
27248 					qreply(q, mp);
27249 				return;
27250 			}
27251 
27252 			if (!snmpcom_req(q, mp, ip_snmp_set,
27253 			    ip_snmp_get, cr)) {
27254 				/*
27255 				 * Call svr4_optcom_req so that it can
27256 				 * generate the ack. We don't come here
27257 				 * if this operation is being restarted.
27258 				 * ip_restart_optmgmt will drop the conn ref.
27259 				 * In the case of ipsec option after the ipsec
27260 				 * load is complete conn_restart_ipsec_waiter
27261 				 * drops the conn ref.
27262 				 */
27263 				ASSERT(ipsq == NULL);
27264 				CONN_INC_REF(connp);
27265 				if (ip_check_for_ipsec_opt(q, mp))
27266 					return;
27267 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27268 				    B_FALSE);
27269 				if (err != EINPROGRESS) {
27270 					/* Operation is done */
27271 					CONN_OPER_PENDING_DONE(connp);
27272 				}
27273 			}
27274 			return;
27275 		case T_OPTMGMT_REQ:
27276 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27277 			/*
27278 			 * Note: No snmpcom_req support through new
27279 			 * T_OPTMGMT_REQ.
27280 			 * Call tpi_optcom_req so that it can
27281 			 * generate the ack.
27282 			 */
27283 			if (connp == NULL) {
27284 				proto_str = "T_OPTMGMT_REQ";
27285 				goto protonak;
27286 			}
27287 
27288 			/*
27289 			 * All Solaris components should pass a db_credp
27290 			 * for this TPI message, hence we ASSERT.
27291 			 * But in case there is some other M_PROTO that looks
27292 			 * like a TPI message sent by some other kernel
27293 			 * component, we check and return an error.
27294 			 */
27295 			cr = msg_getcred(mp, NULL);
27296 			ASSERT(cr != NULL);
27297 			if (cr == NULL) {
27298 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27299 				if (mp != NULL)
27300 					qreply(q, mp);
27301 				return;
27302 			}
27303 			ASSERT(ipsq == NULL);
27304 			/*
27305 			 * We don't come here for restart. ip_restart_optmgmt
27306 			 * will drop the conn ref. In the case of ipsec option
27307 			 * after the ipsec load is complete
27308 			 * conn_restart_ipsec_waiter drops the conn ref.
27309 			 */
27310 			CONN_INC_REF(connp);
27311 			if (ip_check_for_ipsec_opt(q, mp))
27312 				return;
27313 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27314 			if (err != EINPROGRESS) {
27315 				/* Operation is done */
27316 				CONN_OPER_PENDING_DONE(connp);
27317 			}
27318 			return;
27319 		case T_UNBIND_REQ:
27320 			if (connp == NULL) {
27321 				proto_str = "T_UNBIND_REQ";
27322 				goto protonak;
27323 			}
27324 			ip_unbind(Q_TO_CONN(q));
27325 			mp = mi_tpi_ok_ack_alloc(mp);
27326 			qreply(q, mp);
27327 			return;
27328 		default:
27329 			/*
27330 			 * Have to drop any DLPI messages coming down from
27331 			 * arp (such as an info_req which would cause ip
27332 			 * to receive an extra info_ack if it was passed
27333 			 * through.
27334 			 */
27335 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27336 			    (int)*(uint_t *)mp->b_rptr));
27337 			freemsg(mp);
27338 			return;
27339 		}
27340 		/* NOTREACHED */
27341 	case IRE_DB_TYPE: {
27342 		nce_t		*nce;
27343 		ill_t		*ill;
27344 		in6_addr_t	gw_addr_v6;
27345 
27346 		/*
27347 		 * This is a response back from a resolver.  It
27348 		 * consists of a message chain containing:
27349 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27350 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27351 		 * The LL_HDR_MBLK is the DLPI header to use to get
27352 		 * the attached packet, and subsequent ones for the
27353 		 * same destination, transmitted.
27354 		 */
27355 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27356 			break;
27357 		/*
27358 		 * First, check to make sure the resolution succeeded.
27359 		 * If it failed, the second mblk will be empty.
27360 		 * If it is, free the chain, dropping the packet.
27361 		 * (We must ire_delete the ire; that frees the ire mblk)
27362 		 * We're doing this now to support PVCs for ATM; it's
27363 		 * a partial xresolv implementation. When we fully implement
27364 		 * xresolv interfaces, instead of freeing everything here
27365 		 * we'll initiate neighbor discovery.
27366 		 *
27367 		 * For v4 (ARP and other external resolvers) the resolver
27368 		 * frees the message, so no check is needed. This check
27369 		 * is required, though, for a full xresolve implementation.
27370 		 * Including this code here now both shows how external
27371 		 * resolvers can NACK a resolution request using an
27372 		 * existing design that has no specific provisions for NACKs,
27373 		 * and also takes into account that the current non-ARP
27374 		 * external resolver has been coded to use this method of
27375 		 * NACKing for all IPv6 (xresolv) cases,
27376 		 * whether our xresolv implementation is complete or not.
27377 		 *
27378 		 */
27379 		ire = (ire_t *)mp->b_rptr;
27380 		ill = ire_to_ill(ire);
27381 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27382 		if (mp1->b_rptr == mp1->b_wptr) {
27383 			if (ire->ire_ipversion == IPV6_VERSION) {
27384 				/*
27385 				 * XRESOLV interface.
27386 				 */
27387 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27388 				mutex_enter(&ire->ire_lock);
27389 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27390 				mutex_exit(&ire->ire_lock);
27391 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27392 					nce = ndp_lookup_v6(ill, B_FALSE,
27393 					    &ire->ire_addr_v6, B_FALSE);
27394 				} else {
27395 					nce = ndp_lookup_v6(ill, B_FALSE,
27396 					    &gw_addr_v6, B_FALSE);
27397 				}
27398 				if (nce != NULL) {
27399 					nce_resolv_failed(nce);
27400 					ndp_delete(nce);
27401 					NCE_REFRELE(nce);
27402 				}
27403 			}
27404 			mp->b_cont = NULL;
27405 			freemsg(mp1);		/* frees the pkt as well */
27406 			ASSERT(ire->ire_nce == NULL);
27407 			ire_delete((ire_t *)mp->b_rptr);
27408 			return;
27409 		}
27410 
27411 		/*
27412 		 * Split them into IRE_MBLK and pkt and feed it into
27413 		 * ire_add_then_send. Then in ire_add_then_send
27414 		 * the IRE will be added, and then the packet will be
27415 		 * run back through ip_wput. This time it will make
27416 		 * it to the wire.
27417 		 */
27418 		mp->b_cont = NULL;
27419 		mp = mp1->b_cont;		/* now, mp points to pkt */
27420 		mp1->b_cont = NULL;
27421 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27422 		if (ire->ire_ipversion == IPV6_VERSION) {
27423 			/*
27424 			 * XRESOLV interface. Find the nce and put a copy
27425 			 * of the dl_unitdata_req in nce_res_mp
27426 			 */
27427 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27428 			mutex_enter(&ire->ire_lock);
27429 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27430 			mutex_exit(&ire->ire_lock);
27431 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27432 				nce = ndp_lookup_v6(ill, B_FALSE,
27433 				    &ire->ire_addr_v6, B_FALSE);
27434 			} else {
27435 				nce = ndp_lookup_v6(ill, B_FALSE,
27436 				    &gw_addr_v6, B_FALSE);
27437 			}
27438 			if (nce != NULL) {
27439 				/*
27440 				 * We have to protect nce_res_mp here
27441 				 * from being accessed by other threads
27442 				 * while we change the mblk pointer.
27443 				 * Other functions will also lock the nce when
27444 				 * accessing nce_res_mp.
27445 				 *
27446 				 * The reason we change the mblk pointer
27447 				 * here rather than copying the resolved address
27448 				 * into the template is that, unlike with
27449 				 * ethernet, we have no guarantee that the
27450 				 * resolved address length will be
27451 				 * smaller than or equal to the lla length
27452 				 * with which the template was allocated,
27453 				 * (for ethernet, they're equal)
27454 				 * so we have to use the actual resolved
27455 				 * address mblk - which holds the real
27456 				 * dl_unitdata_req with the resolved address.
27457 				 *
27458 				 * Doing this is the same behavior as was
27459 				 * previously used in the v4 ARP case.
27460 				 */
27461 				mutex_enter(&nce->nce_lock);
27462 				if (nce->nce_res_mp != NULL)
27463 					freemsg(nce->nce_res_mp);
27464 				nce->nce_res_mp = mp1;
27465 				mutex_exit(&nce->nce_lock);
27466 				/*
27467 				 * We do a fastpath probe here because
27468 				 * we have resolved the address without
27469 				 * using Neighbor Discovery.
27470 				 * In the non-XRESOLV v6 case, the fastpath
27471 				 * probe is done right after neighbor
27472 				 * discovery completes.
27473 				 */
27474 				if (nce->nce_res_mp != NULL) {
27475 					int res;
27476 					nce_fastpath_list_add(nce);
27477 					res = ill_fastpath_probe(ill,
27478 					    nce->nce_res_mp);
27479 					if (res != 0 && res != EAGAIN)
27480 						nce_fastpath_list_delete(nce);
27481 				}
27482 
27483 				ire_add_then_send(q, ire, mp);
27484 				/*
27485 				 * Now we have to clean out any packets
27486 				 * that may have been queued on the nce
27487 				 * while it was waiting for address resolution
27488 				 * to complete.
27489 				 */
27490 				mutex_enter(&nce->nce_lock);
27491 				mp1 = nce->nce_qd_mp;
27492 				nce->nce_qd_mp = NULL;
27493 				mutex_exit(&nce->nce_lock);
27494 				while (mp1 != NULL) {
27495 					mblk_t *nxt_mp;
27496 					queue_t *fwdq = NULL;
27497 					ill_t   *inbound_ill;
27498 					uint_t ifindex;
27499 
27500 					nxt_mp = mp1->b_next;
27501 					mp1->b_next = NULL;
27502 					/*
27503 					 * Retrieve ifindex stored in
27504 					 * ip_rput_data_v6()
27505 					 */
27506 					ifindex =
27507 					    (uint_t)(uintptr_t)mp1->b_prev;
27508 					inbound_ill =
27509 					    ill_lookup_on_ifindex(ifindex,
27510 					    B_TRUE, NULL, NULL, NULL,
27511 					    NULL, ipst);
27512 					mp1->b_prev = NULL;
27513 					if (inbound_ill != NULL)
27514 						fwdq = inbound_ill->ill_rq;
27515 
27516 					if (fwdq != NULL) {
27517 						put(fwdq, mp1);
27518 						ill_refrele(inbound_ill);
27519 					} else
27520 						put(WR(ill->ill_rq), mp1);
27521 					mp1 = nxt_mp;
27522 				}
27523 				NCE_REFRELE(nce);
27524 			} else {	/* nce is NULL; clean up */
27525 				ire_delete(ire);
27526 				freemsg(mp);
27527 				freemsg(mp1);
27528 				return;
27529 			}
27530 		} else {
27531 			nce_t *arpce;
27532 			/*
27533 			 * Link layer resolution succeeded. Recompute the
27534 			 * ire_nce.
27535 			 */
27536 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27537 			if ((arpce = ndp_lookup_v4(ill,
27538 			    (ire->ire_gateway_addr != INADDR_ANY ?
27539 			    &ire->ire_gateway_addr : &ire->ire_addr),
27540 			    B_FALSE)) == NULL) {
27541 				freeb(ire->ire_mp);
27542 				freeb(mp1);
27543 				freemsg(mp);
27544 				return;
27545 			}
27546 			mutex_enter(&arpce->nce_lock);
27547 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27548 			if (arpce->nce_state == ND_REACHABLE) {
27549 				/*
27550 				 * Someone resolved this before us;
27551 				 * cleanup the res_mp. Since ire has
27552 				 * not been added yet, the call to ire_add_v4
27553 				 * from ire_add_then_send (when a dup is
27554 				 * detected) will clean up the ire.
27555 				 */
27556 				freeb(mp1);
27557 			} else {
27558 				ASSERT(arpce->nce_res_mp == NULL);
27559 				arpce->nce_res_mp = mp1;
27560 				arpce->nce_state = ND_REACHABLE;
27561 			}
27562 			mutex_exit(&arpce->nce_lock);
27563 			if (ire->ire_marks & IRE_MARK_NOADD) {
27564 				/*
27565 				 * this ire will not be added to the ire
27566 				 * cache table, so we can set the ire_nce
27567 				 * here, as there are no atomicity constraints.
27568 				 */
27569 				ire->ire_nce = arpce;
27570 				/*
27571 				 * We are associating this nce with the ire
27572 				 * so change the nce ref taken in
27573 				 * ndp_lookup_v4() from
27574 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27575 				 */
27576 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27577 			} else {
27578 				NCE_REFRELE(arpce);
27579 			}
27580 			ire_add_then_send(q, ire, mp);
27581 		}
27582 		return;	/* All is well, the packet has been sent. */
27583 	}
27584 	case IRE_ARPRESOLVE_TYPE: {
27585 
27586 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27587 			break;
27588 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27589 		mp->b_cont = NULL;
27590 		/*
27591 		 * First, check to make sure the resolution succeeded.
27592 		 * If it failed, the second mblk will be empty.
27593 		 */
27594 		if (mp1->b_rptr == mp1->b_wptr) {
27595 			/* cleanup  the incomplete ire, free queued packets */
27596 			freemsg(mp); /* fake ire */
27597 			freeb(mp1);  /* dl_unitdata response */
27598 			return;
27599 		}
27600 
27601 		/*
27602 		 * Update any incomplete nce_t found. We search the ctable
27603 		 * and find the nce from the ire->ire_nce because we need
27604 		 * to pass the ire to ip_xmit_v4 later, and can find both
27605 		 * ire and nce in one lookup.
27606 		 */
27607 		fake_ire = (ire_t *)mp->b_rptr;
27608 
27609 		/*
27610 		 * By the time we come back here from ARP the logical outgoing
27611 		 * interface of the incomplete ire we added in ire_forward()
27612 		 * could have disappeared, causing the incomplete ire to also
27613 		 * disappear.  So we need to retreive the proper ipif for the
27614 		 * ire before looking in ctable.  In the case of IPMP, the
27615 		 * ipif may be on the IPMP ill, so look it up based on the
27616 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27617 		 * Then, we can verify that ire_ipif_seqid still exists.
27618 		 */
27619 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27620 		    NULL, NULL, NULL, NULL, ipst);
27621 		if (ill == NULL) {
27622 			ip1dbg(("ill for incomplete ire vanished\n"));
27623 			freemsg(mp); /* fake ire */
27624 			freeb(mp1);  /* dl_unitdata response */
27625 			return;
27626 		}
27627 
27628 		/* Get the outgoing ipif */
27629 		mutex_enter(&ill->ill_lock);
27630 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27631 		if (ipif == NULL) {
27632 			mutex_exit(&ill->ill_lock);
27633 			ill_refrele(ill);
27634 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27635 			freemsg(mp); /* fake_ire */
27636 			freeb(mp1);  /* dl_unitdata response */
27637 			return;
27638 		}
27639 
27640 		ipif_refhold_locked(ipif);
27641 		mutex_exit(&ill->ill_lock);
27642 		ill_refrele(ill);
27643 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27644 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27645 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27646 		ipif_refrele(ipif);
27647 		if (ire == NULL) {
27648 			/*
27649 			 * no ire was found; check if there is an nce
27650 			 * for this lookup; if it has no ire's pointing at it
27651 			 * cleanup.
27652 			 */
27653 			if ((nce = ndp_lookup_v4(q->q_ptr,
27654 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27655 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27656 			    B_FALSE)) != NULL) {
27657 				/*
27658 				 * cleanup:
27659 				 * We check for refcnt 2 (one for the nce
27660 				 * hash list + 1 for the ref taken by
27661 				 * ndp_lookup_v4) to check that there are
27662 				 * no ire's pointing at the nce.
27663 				 */
27664 				if (nce->nce_refcnt == 2)
27665 					ndp_delete(nce);
27666 				NCE_REFRELE(nce);
27667 			}
27668 			freeb(mp1);  /* dl_unitdata response */
27669 			freemsg(mp); /* fake ire */
27670 			return;
27671 		}
27672 
27673 		nce = ire->ire_nce;
27674 		DTRACE_PROBE2(ire__arpresolve__type,
27675 		    ire_t *, ire, nce_t *, nce);
27676 		mutex_enter(&nce->nce_lock);
27677 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27678 		if (nce->nce_state == ND_REACHABLE) {
27679 			/*
27680 			 * Someone resolved this before us;
27681 			 * our response is not needed any more.
27682 			 */
27683 			mutex_exit(&nce->nce_lock);
27684 			freeb(mp1);  /* dl_unitdata response */
27685 		} else {
27686 			ASSERT(nce->nce_res_mp == NULL);
27687 			nce->nce_res_mp = mp1;
27688 			nce->nce_state = ND_REACHABLE;
27689 			mutex_exit(&nce->nce_lock);
27690 			nce_fastpath(nce);
27691 		}
27692 		/*
27693 		 * The cached nce_t has been updated to be reachable;
27694 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27695 		 */
27696 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27697 		freemsg(mp);
27698 		/*
27699 		 * send out queued packets.
27700 		 */
27701 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27702 
27703 		IRE_REFRELE(ire);
27704 		return;
27705 	}
27706 	default:
27707 		break;
27708 	}
27709 	if (q->q_next) {
27710 		putnext(q, mp);
27711 	} else
27712 		freemsg(mp);
27713 	return;
27714 
27715 protonak:
27716 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27717 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27718 		qreply(q, mp);
27719 }
27720 
27721 /*
27722  * Process IP options in an outbound packet.  Modify the destination if there
27723  * is a source route option.
27724  * Returns non-zero if something fails in which case an ICMP error has been
27725  * sent and mp freed.
27726  */
27727 static int
27728 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27729     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27730 {
27731 	ipoptp_t	opts;
27732 	uchar_t		*opt;
27733 	uint8_t		optval;
27734 	uint8_t		optlen;
27735 	ipaddr_t	dst;
27736 	intptr_t	code = 0;
27737 	mblk_t		*mp;
27738 	ire_t		*ire = NULL;
27739 
27740 	ip2dbg(("ip_wput_options\n"));
27741 	mp = ipsec_mp;
27742 	if (mctl_present) {
27743 		mp = ipsec_mp->b_cont;
27744 	}
27745 
27746 	dst = ipha->ipha_dst;
27747 	for (optval = ipoptp_first(&opts, ipha);
27748 	    optval != IPOPT_EOL;
27749 	    optval = ipoptp_next(&opts)) {
27750 		opt = opts.ipoptp_cur;
27751 		optlen = opts.ipoptp_len;
27752 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27753 		    optval, optlen));
27754 		switch (optval) {
27755 			uint32_t off;
27756 		case IPOPT_SSRR:
27757 		case IPOPT_LSRR:
27758 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27759 				ip1dbg((
27760 				    "ip_wput_options: bad option offset\n"));
27761 				code = (char *)&opt[IPOPT_OLEN] -
27762 				    (char *)ipha;
27763 				goto param_prob;
27764 			}
27765 			off = opt[IPOPT_OFFSET];
27766 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27767 			    ntohl(dst)));
27768 			/*
27769 			 * For strict: verify that dst is directly
27770 			 * reachable.
27771 			 */
27772 			if (optval == IPOPT_SSRR) {
27773 				ire = ire_ftable_lookup(dst, 0, 0,
27774 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27775 				    msg_getlabel(mp),
27776 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27777 				if (ire == NULL) {
27778 					ip1dbg(("ip_wput_options: SSRR not"
27779 					    " directly reachable: 0x%x\n",
27780 					    ntohl(dst)));
27781 					goto bad_src_route;
27782 				}
27783 				ire_refrele(ire);
27784 			}
27785 			break;
27786 		case IPOPT_RR:
27787 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27788 				ip1dbg((
27789 				    "ip_wput_options: bad option offset\n"));
27790 				code = (char *)&opt[IPOPT_OLEN] -
27791 				    (char *)ipha;
27792 				goto param_prob;
27793 			}
27794 			break;
27795 		case IPOPT_TS:
27796 			/*
27797 			 * Verify that length >=5 and that there is either
27798 			 * room for another timestamp or that the overflow
27799 			 * counter is not maxed out.
27800 			 */
27801 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27802 			if (optlen < IPOPT_MINLEN_IT) {
27803 				goto param_prob;
27804 			}
27805 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27806 				ip1dbg((
27807 				    "ip_wput_options: bad option offset\n"));
27808 				code = (char *)&opt[IPOPT_OFFSET] -
27809 				    (char *)ipha;
27810 				goto param_prob;
27811 			}
27812 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27813 			case IPOPT_TS_TSONLY:
27814 				off = IPOPT_TS_TIMELEN;
27815 				break;
27816 			case IPOPT_TS_TSANDADDR:
27817 			case IPOPT_TS_PRESPEC:
27818 			case IPOPT_TS_PRESPEC_RFC791:
27819 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27820 				break;
27821 			default:
27822 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27823 				    (char *)ipha;
27824 				goto param_prob;
27825 			}
27826 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27827 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27828 				/*
27829 				 * No room and the overflow counter is 15
27830 				 * already.
27831 				 */
27832 				goto param_prob;
27833 			}
27834 			break;
27835 		}
27836 	}
27837 
27838 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27839 		return (0);
27840 
27841 	ip1dbg(("ip_wput_options: error processing IP options."));
27842 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27843 
27844 param_prob:
27845 	/*
27846 	 * Since ip_wput() isn't close to finished, we fill
27847 	 * in enough of the header for credible error reporting.
27848 	 */
27849 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27850 		/* Failed */
27851 		freemsg(ipsec_mp);
27852 		return (-1);
27853 	}
27854 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27855 	return (-1);
27856 
27857 bad_src_route:
27858 	/*
27859 	 * Since ip_wput() isn't close to finished, we fill
27860 	 * in enough of the header for credible error reporting.
27861 	 */
27862 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27863 		/* Failed */
27864 		freemsg(ipsec_mp);
27865 		return (-1);
27866 	}
27867 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27868 	return (-1);
27869 }
27870 
27871 /*
27872  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27873  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27874  * thru /etc/system.
27875  */
27876 #define	CONN_MAXDRAINCNT	64
27877 
27878 static void
27879 conn_drain_init(ip_stack_t *ipst)
27880 {
27881 	int i, j;
27882 	idl_tx_list_t *itl_tx;
27883 
27884 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27885 
27886 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27887 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27888 		/*
27889 		 * Default value of the number of drainers is the
27890 		 * number of cpus, subject to maximum of 8 drainers.
27891 		 */
27892 		if (boot_max_ncpus != -1)
27893 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27894 		else
27895 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27896 	}
27897 
27898 	ipst->ips_idl_tx_list =
27899 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
27900 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27901 		itl_tx =  &ipst->ips_idl_tx_list[i];
27902 		itl_tx->txl_drain_list =
27903 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27904 		    sizeof (idl_t), KM_SLEEP);
27905 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
27906 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
27907 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
27908 			    MUTEX_DEFAULT, NULL);
27909 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
27910 		}
27911 	}
27912 }
27913 
27914 static void
27915 conn_drain_fini(ip_stack_t *ipst)
27916 {
27917 	int i;
27918 	idl_tx_list_t *itl_tx;
27919 
27920 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27921 		itl_tx =  &ipst->ips_idl_tx_list[i];
27922 		kmem_free(itl_tx->txl_drain_list,
27923 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27924 	}
27925 	kmem_free(ipst->ips_idl_tx_list,
27926 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
27927 	ipst->ips_idl_tx_list = NULL;
27928 }
27929 
27930 /*
27931  * Note: For an overview of how flowcontrol is handled in IP please see the
27932  * IP Flowcontrol notes at the top of this file.
27933  *
27934  * Flow control has blocked us from proceeding. Insert the given conn in one
27935  * of the conn drain lists. These conn wq's will be qenabled later on when
27936  * STREAMS flow control does a backenable. conn_walk_drain will enable
27937  * the first conn in each of these drain lists. Each of these qenabled conns
27938  * in turn enables the next in the list, after it runs, or when it closes,
27939  * thus sustaining the drain process.
27940  */
27941 void
27942 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
27943 {
27944 	idl_t	*idl = tx_list->txl_drain_list;
27945 	uint_t	index;
27946 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27947 
27948 	mutex_enter(&connp->conn_lock);
27949 	if (connp->conn_state_flags & CONN_CLOSING) {
27950 		/*
27951 		 * The conn is closing as a result of which CONN_CLOSING
27952 		 * is set. Return.
27953 		 */
27954 		mutex_exit(&connp->conn_lock);
27955 		return;
27956 	} else if (connp->conn_idl == NULL) {
27957 		/*
27958 		 * Assign the next drain list round robin. We dont' use
27959 		 * a lock, and thus it may not be strictly round robin.
27960 		 * Atomicity of load/stores is enough to make sure that
27961 		 * conn_drain_list_index is always within bounds.
27962 		 */
27963 		index = tx_list->txl_drain_index;
27964 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27965 		connp->conn_idl = &tx_list->txl_drain_list[index];
27966 		index++;
27967 		if (index == ipst->ips_conn_drain_list_cnt)
27968 			index = 0;
27969 		tx_list->txl_drain_index = index;
27970 	}
27971 	mutex_exit(&connp->conn_lock);
27972 
27973 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27974 	if ((connp->conn_drain_prev != NULL) ||
27975 	    (connp->conn_state_flags & CONN_CLOSING)) {
27976 		/*
27977 		 * The conn is already in the drain list, OR
27978 		 * the conn is closing. We need to check again for
27979 		 * the closing case again since close can happen
27980 		 * after we drop the conn_lock, and before we
27981 		 * acquire the CONN_DRAIN_LIST_LOCK.
27982 		 */
27983 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27984 		return;
27985 	} else {
27986 		idl = connp->conn_idl;
27987 	}
27988 
27989 	/*
27990 	 * The conn is not in the drain list. Insert it at the
27991 	 * tail of the drain list. The drain list is circular
27992 	 * and doubly linked. idl_conn points to the 1st element
27993 	 * in the list.
27994 	 */
27995 	if (idl->idl_conn == NULL) {
27996 		idl->idl_conn = connp;
27997 		connp->conn_drain_next = connp;
27998 		connp->conn_drain_prev = connp;
27999 	} else {
28000 		conn_t *head = idl->idl_conn;
28001 
28002 		connp->conn_drain_next = head;
28003 		connp->conn_drain_prev = head->conn_drain_prev;
28004 		head->conn_drain_prev->conn_drain_next = connp;
28005 		head->conn_drain_prev = connp;
28006 	}
28007 	/*
28008 	 * For non streams based sockets assert flow control.
28009 	 */
28010 	if (IPCL_IS_NONSTR(connp)) {
28011 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28012 		(*connp->conn_upcalls->su_txq_full)
28013 		    (connp->conn_upper_handle, B_TRUE);
28014 	} else {
28015 		conn_setqfull(connp);
28016 		noenable(connp->conn_wq);
28017 	}
28018 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28019 }
28020 
28021 /*
28022  * This conn is closing, and we are called from ip_close. OR
28023  * This conn has been serviced by ip_wsrv, and we need to do the tail
28024  * processing.
28025  * If this conn is part of the drain list, we may need to sustain the drain
28026  * process by qenabling the next conn in the drain list. We may also need to
28027  * remove this conn from the list, if it is done.
28028  */
28029 static void
28030 conn_drain_tail(conn_t *connp, boolean_t closing)
28031 {
28032 	idl_t *idl;
28033 
28034 	/*
28035 	 * connp->conn_idl is stable at this point, and no lock is needed
28036 	 * to check it. If we are called from ip_close, close has already
28037 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28038 	 * called us only because conn_idl is non-null. If we are called thru
28039 	 * service, conn_idl could be null, but it cannot change because
28040 	 * service is single-threaded per queue, and there cannot be another
28041 	 * instance of service trying to call conn_drain_insert on this conn
28042 	 * now.
28043 	 */
28044 	ASSERT(!closing || (connp->conn_idl != NULL));
28045 
28046 	/*
28047 	 * If connp->conn_idl is null, the conn has not been inserted into any
28048 	 * drain list even once since creation of the conn. Just return.
28049 	 */
28050 	if (connp->conn_idl == NULL)
28051 		return;
28052 
28053 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28054 
28055 	if (connp->conn_drain_prev == NULL) {
28056 		/* This conn is currently not in the drain list.  */
28057 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28058 		return;
28059 	}
28060 	idl = connp->conn_idl;
28061 	if (idl->idl_conn_draining == connp) {
28062 		/*
28063 		 * This conn is the current drainer. If this is the last conn
28064 		 * in the drain list, we need to do more checks, in the 'if'
28065 		 * below. Otherwwise we need to just qenable the next conn,
28066 		 * to sustain the draining, and is handled in the 'else'
28067 		 * below.
28068 		 */
28069 		if (connp->conn_drain_next == idl->idl_conn) {
28070 			/*
28071 			 * This conn is the last in this list. This round
28072 			 * of draining is complete. If idl_repeat is set,
28073 			 * it means another flow enabling has happened from
28074 			 * the driver/streams and we need to another round
28075 			 * of draining.
28076 			 * If there are more than 2 conns in the drain list,
28077 			 * do a left rotate by 1, so that all conns except the
28078 			 * conn at the head move towards the head by 1, and the
28079 			 * the conn at the head goes to the tail. This attempts
28080 			 * a more even share for all queues that are being
28081 			 * drained.
28082 			 */
28083 			if ((connp->conn_drain_next != connp) &&
28084 			    (idl->idl_conn->conn_drain_next != connp)) {
28085 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28086 			}
28087 			if (idl->idl_repeat) {
28088 				qenable(idl->idl_conn->conn_wq);
28089 				idl->idl_conn_draining = idl->idl_conn;
28090 				idl->idl_repeat = 0;
28091 			} else {
28092 				idl->idl_conn_draining = NULL;
28093 			}
28094 		} else {
28095 			/*
28096 			 * If the next queue that we are now qenable'ing,
28097 			 * is closing, it will remove itself from this list
28098 			 * and qenable the subsequent queue in ip_close().
28099 			 * Serialization is acheived thru idl_lock.
28100 			 */
28101 			qenable(connp->conn_drain_next->conn_wq);
28102 			idl->idl_conn_draining = connp->conn_drain_next;
28103 		}
28104 	}
28105 	if (!connp->conn_did_putbq || closing) {
28106 		/*
28107 		 * Remove ourself from the drain list, if we did not do
28108 		 * a putbq, or if the conn is closing.
28109 		 * Note: It is possible that q->q_first is non-null. It means
28110 		 * that these messages landed after we did a enableok() in
28111 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28112 		 * service them.
28113 		 */
28114 		if (connp->conn_drain_next == connp) {
28115 			/* Singleton in the list */
28116 			ASSERT(connp->conn_drain_prev == connp);
28117 			idl->idl_conn = NULL;
28118 			idl->idl_conn_draining = NULL;
28119 		} else {
28120 			connp->conn_drain_prev->conn_drain_next =
28121 			    connp->conn_drain_next;
28122 			connp->conn_drain_next->conn_drain_prev =
28123 			    connp->conn_drain_prev;
28124 			if (idl->idl_conn == connp)
28125 				idl->idl_conn = connp->conn_drain_next;
28126 			ASSERT(idl->idl_conn_draining != connp);
28127 
28128 		}
28129 		connp->conn_drain_next = NULL;
28130 		connp->conn_drain_prev = NULL;
28131 
28132 		/*
28133 		 * For non streams based sockets open up flow control.
28134 		 */
28135 		if (IPCL_IS_NONSTR(connp)) {
28136 			(*connp->conn_upcalls->su_txq_full)
28137 			    (connp->conn_upper_handle, B_FALSE);
28138 		} else {
28139 			conn_clrqfull(connp);
28140 			enableok(connp->conn_wq);
28141 		}
28142 	}
28143 
28144 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28145 }
28146 
28147 /*
28148  * Write service routine. Shared perimeter entry point.
28149  * ip_wsrv can be called in any of the following ways.
28150  * 1. The device queue's messages has fallen below the low water mark
28151  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28152  *    the drain lists and backenable the first conn in each list.
28153  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28154  *    qenabled non-tcp upper layers. We start dequeing messages and call
28155  *    ip_wput for each message.
28156  */
28157 
28158 void
28159 ip_wsrv(queue_t *q)
28160 {
28161 	conn_t	*connp;
28162 	ill_t	*ill;
28163 	mblk_t	*mp;
28164 
28165 	if (q->q_next) {
28166 		ill = (ill_t *)q->q_ptr;
28167 		if (ill->ill_state_flags == 0) {
28168 			ip_stack_t *ipst = ill->ill_ipst;
28169 
28170 			/*
28171 			 * The device flow control has opened up.
28172 			 * Walk through conn drain lists and qenable the
28173 			 * first conn in each list. This makes sense only
28174 			 * if the stream is fully plumbed and setup.
28175 			 * Hence the if check above.
28176 			 */
28177 			ip1dbg(("ip_wsrv: walking\n"));
28178 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28179 		}
28180 		return;
28181 	}
28182 
28183 	connp = Q_TO_CONN(q);
28184 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28185 
28186 	/*
28187 	 * 1. Set conn_draining flag to signal that service is active.
28188 	 *
28189 	 * 2. ip_output determines whether it has been called from service,
28190 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28191 	 *    has been called from service.
28192 	 *
28193 	 * 3. Message ordering is preserved by the following logic.
28194 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28195 	 *    the message at the tail, if conn_draining is set (i.e. service
28196 	 *    is running) or if q->q_first is non-null.
28197 	 *
28198 	 *    ii. If ip_output is called from service, and if ip_output cannot
28199 	 *    putnext due to flow control, it does a putbq.
28200 	 *
28201 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28202 	 *    (causing an infinite loop).
28203 	 */
28204 	ASSERT(!connp->conn_did_putbq);
28205 
28206 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28207 		connp->conn_draining = 1;
28208 		noenable(q);
28209 		while ((mp = getq(q)) != NULL) {
28210 			ASSERT(CONN_Q(q));
28211 
28212 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28213 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28214 			if (connp->conn_did_putbq) {
28215 				/* ip_wput did a putbq */
28216 				break;
28217 			}
28218 		}
28219 		/*
28220 		 * At this point, a thread coming down from top, calling
28221 		 * ip_wput, may end up queueing the message. We have not yet
28222 		 * enabled the queue, so ip_wsrv won't be called again.
28223 		 * To avoid this race, check q->q_first again (in the loop)
28224 		 * If the other thread queued the message before we call
28225 		 * enableok(), we will catch it in the q->q_first check.
28226 		 * If the other thread queues the message after we call
28227 		 * enableok(), ip_wsrv will be called again by STREAMS.
28228 		 */
28229 		connp->conn_draining = 0;
28230 		enableok(q);
28231 	}
28232 
28233 	/* Enable the next conn for draining */
28234 	conn_drain_tail(connp, B_FALSE);
28235 
28236 	/*
28237 	 * conn_direct_blocked is used to indicate blocked
28238 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28239 	 * This is the only place where it is set without
28240 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28241 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28242 	 */
28243 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28244 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28245 		connp->conn_direct_blocked = B_FALSE;
28246 	}
28247 
28248 	connp->conn_did_putbq = 0;
28249 }
28250 
28251 /*
28252  * Callback to disable flow control in IP.
28253  *
28254  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28255  * is enabled.
28256  *
28257  * When MAC_TX() is not able to send any more packets, dld sets its queue
28258  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28259  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28260  * function and wakes up corresponding mac worker threads, which in turn
28261  * calls this callback function, and disables flow control.
28262  */
28263 void
28264 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28265 {
28266 	ill_t *ill = (ill_t *)arg;
28267 	ip_stack_t *ipst = ill->ill_ipst;
28268 	idl_tx_list_t *idl_txl;
28269 
28270 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28271 	mutex_enter(&idl_txl->txl_lock);
28272 	/* add code to to set a flag to indicate idl_txl is enabled */
28273 	conn_walk_drain(ipst, idl_txl);
28274 	mutex_exit(&idl_txl->txl_lock);
28275 }
28276 
28277 /*
28278  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28279  * of conns that need to be drained, check if drain is already in progress.
28280  * If so set the idl_repeat bit, indicating that the last conn in the list
28281  * needs to reinitiate the drain once again, for the list. If drain is not
28282  * in progress for the list, initiate the draining, by qenabling the 1st
28283  * conn in the list. The drain is self-sustaining, each qenabled conn will
28284  * in turn qenable the next conn, when it is done/blocked/closing.
28285  */
28286 static void
28287 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28288 {
28289 	int i;
28290 	idl_t *idl;
28291 
28292 	IP_STAT(ipst, ip_conn_walk_drain);
28293 
28294 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28295 		idl = &tx_list->txl_drain_list[i];
28296 		mutex_enter(&idl->idl_lock);
28297 		if (idl->idl_conn == NULL) {
28298 			mutex_exit(&idl->idl_lock);
28299 			continue;
28300 		}
28301 		/*
28302 		 * If this list is not being drained currently by
28303 		 * an ip_wsrv thread, start the process.
28304 		 */
28305 		if (idl->idl_conn_draining == NULL) {
28306 			ASSERT(idl->idl_repeat == 0);
28307 			qenable(idl->idl_conn->conn_wq);
28308 			idl->idl_conn_draining = idl->idl_conn;
28309 		} else {
28310 			idl->idl_repeat = 1;
28311 		}
28312 		mutex_exit(&idl->idl_lock);
28313 	}
28314 }
28315 
28316 /*
28317  * Determine if the ill and multicast aspects of that packets
28318  * "matches" the conn.
28319  */
28320 boolean_t
28321 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28322     zoneid_t zoneid)
28323 {
28324 	ill_t *bound_ill;
28325 	boolean_t found;
28326 	ipif_t *ipif;
28327 	ire_t *ire;
28328 	ipaddr_t dst, src;
28329 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28330 
28331 	dst = ipha->ipha_dst;
28332 	src = ipha->ipha_src;
28333 
28334 	/*
28335 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28336 	 * unicast, broadcast and multicast reception to
28337 	 * conn_incoming_ill. conn_wantpacket itself is called
28338 	 * only for BROADCAST and multicast.
28339 	 */
28340 	bound_ill = connp->conn_incoming_ill;
28341 	if (bound_ill != NULL) {
28342 		if (IS_IPMP(bound_ill)) {
28343 			if (bound_ill->ill_grp != ill->ill_grp)
28344 				return (B_FALSE);
28345 		} else {
28346 			if (bound_ill != ill)
28347 				return (B_FALSE);
28348 		}
28349 	}
28350 
28351 	if (!CLASSD(dst)) {
28352 		if (IPCL_ZONE_MATCH(connp, zoneid))
28353 			return (B_TRUE);
28354 		/*
28355 		 * The conn is in a different zone; we need to check that this
28356 		 * broadcast address is configured in the application's zone.
28357 		 */
28358 		ipif = ipif_get_next_ipif(NULL, ill);
28359 		if (ipif == NULL)
28360 			return (B_FALSE);
28361 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28362 		    connp->conn_zoneid, NULL,
28363 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28364 		ipif_refrele(ipif);
28365 		if (ire != NULL) {
28366 			ire_refrele(ire);
28367 			return (B_TRUE);
28368 		} else {
28369 			return (B_FALSE);
28370 		}
28371 	}
28372 
28373 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28374 	    connp->conn_zoneid == zoneid) {
28375 		/*
28376 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28377 		 * disabled, therefore we don't dispatch the multicast packet to
28378 		 * the sending zone.
28379 		 */
28380 		return (B_FALSE);
28381 	}
28382 
28383 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28384 		/*
28385 		 * Multicast packet on the loopback interface: we only match
28386 		 * conns who joined the group in the specified zone.
28387 		 */
28388 		return (B_FALSE);
28389 	}
28390 
28391 	if (connp->conn_multi_router) {
28392 		/* multicast packet and multicast router socket: send up */
28393 		return (B_TRUE);
28394 	}
28395 
28396 	mutex_enter(&connp->conn_lock);
28397 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28398 	mutex_exit(&connp->conn_lock);
28399 	return (found);
28400 }
28401 
28402 static void
28403 conn_setqfull(conn_t *connp)
28404 {
28405 	queue_t *q = connp->conn_wq;
28406 
28407 	if (!(q->q_flag & QFULL)) {
28408 		mutex_enter(QLOCK(q));
28409 		if (!(q->q_flag & QFULL)) {
28410 			/* still need to set QFULL */
28411 			q->q_flag |= QFULL;
28412 			mutex_exit(QLOCK(q));
28413 		} else {
28414 			mutex_exit(QLOCK(q));
28415 		}
28416 	}
28417 }
28418 
28419 static void
28420 conn_clrqfull(conn_t *connp)
28421 {
28422 	queue_t *q = connp->conn_wq;
28423 
28424 	if (q->q_flag & QFULL) {
28425 		mutex_enter(QLOCK(q));
28426 		if (q->q_flag & QFULL) {
28427 			q->q_flag &= ~QFULL;
28428 			mutex_exit(QLOCK(q));
28429 			if (q->q_flag & QWANTW)
28430 				qbackenable(q, 0);
28431 		} else {
28432 			mutex_exit(QLOCK(q));
28433 		}
28434 	}
28435 }
28436 
28437 /*
28438  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28439  */
28440 /* ARGSUSED */
28441 static void
28442 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28443 {
28444 	ill_t *ill = (ill_t *)q->q_ptr;
28445 	mblk_t	*mp1, *mp2;
28446 	ipif_t  *ipif;
28447 	int err = 0;
28448 	conn_t *connp = NULL;
28449 	ipsq_t	*ipsq;
28450 	arc_t	*arc;
28451 
28452 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28453 
28454 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28455 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28456 
28457 	ASSERT(IAM_WRITER_ILL(ill));
28458 	mp2 = mp->b_cont;
28459 	mp->b_cont = NULL;
28460 
28461 	/*
28462 	 * We have now received the arp bringup completion message
28463 	 * from ARP. Mark the arp bringup as done. Also if the arp
28464 	 * stream has already started closing, send up the AR_ARP_CLOSING
28465 	 * ack now since ARP is waiting in close for this ack.
28466 	 */
28467 	mutex_enter(&ill->ill_lock);
28468 	ill->ill_arp_bringup_pending = 0;
28469 	if (ill->ill_arp_closing) {
28470 		mutex_exit(&ill->ill_lock);
28471 		/* Let's reuse the mp for sending the ack */
28472 		arc = (arc_t *)mp->b_rptr;
28473 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28474 		arc->arc_cmd = AR_ARP_CLOSING;
28475 		qreply(q, mp);
28476 	} else {
28477 		mutex_exit(&ill->ill_lock);
28478 		freeb(mp);
28479 	}
28480 
28481 	ipsq = ill->ill_phyint->phyint_ipsq;
28482 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28483 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28484 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28485 	if (mp1 == NULL) {
28486 		/* bringup was aborted by the user */
28487 		freemsg(mp2);
28488 		return;
28489 	}
28490 
28491 	/*
28492 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28493 	 * must have an associated conn_t.  Otherwise, we're bringing this
28494 	 * interface back up as part of handling an asynchronous event (e.g.,
28495 	 * physical address change).
28496 	 */
28497 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28498 		ASSERT(connp != NULL);
28499 		q = CONNP_TO_WQ(connp);
28500 	} else {
28501 		ASSERT(connp == NULL);
28502 		q = ill->ill_rq;
28503 	}
28504 
28505 	/*
28506 	 * If the DL_BIND_REQ fails, it is noted
28507 	 * in arc_name_offset.
28508 	 */
28509 	err = *((int *)mp2->b_rptr);
28510 	if (err == 0) {
28511 		if (ipif->ipif_isv6) {
28512 			if ((err = ipif_up_done_v6(ipif)) != 0)
28513 				ip0dbg(("ip_arp_done: init failed\n"));
28514 		} else {
28515 			if ((err = ipif_up_done(ipif)) != 0)
28516 				ip0dbg(("ip_arp_done: init failed\n"));
28517 		}
28518 	} else {
28519 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28520 	}
28521 
28522 	freemsg(mp2);
28523 
28524 	if ((err == 0) && (ill->ill_up_ipifs)) {
28525 		err = ill_up_ipifs(ill, q, mp1);
28526 		if (err == EINPROGRESS)
28527 			return;
28528 	}
28529 
28530 	/*
28531 	 * If we have a moved ipif to bring up, and everything has succeeded
28532 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28533 	 * down -- the admin can try to bring it up by hand if need be.
28534 	 */
28535 	if (ill->ill_move_ipif != NULL) {
28536 		ipif = ill->ill_move_ipif;
28537 		ill->ill_move_ipif = NULL;
28538 		if (err == 0) {
28539 			err = ipif_up(ipif, q, mp1);
28540 			if (err == EINPROGRESS)
28541 				return;
28542 		}
28543 	}
28544 
28545 	/*
28546 	 * The operation must complete without EINPROGRESS since
28547 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28548 	 * operation will be stuck forever in the ipsq.
28549 	 */
28550 	ASSERT(err != EINPROGRESS);
28551 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28552 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28553 	else
28554 		ipsq_current_finish(ipsq);
28555 }
28556 
28557 /* Allocate the private structure */
28558 static int
28559 ip_priv_alloc(void **bufp)
28560 {
28561 	void	*buf;
28562 
28563 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28564 		return (ENOMEM);
28565 
28566 	*bufp = buf;
28567 	return (0);
28568 }
28569 
28570 /* Function to delete the private structure */
28571 void
28572 ip_priv_free(void *buf)
28573 {
28574 	ASSERT(buf != NULL);
28575 	kmem_free(buf, sizeof (ip_priv_t));
28576 }
28577 
28578 /*
28579  * The entry point for IPPF processing.
28580  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28581  * routine just returns.
28582  *
28583  * When called, ip_process generates an ipp_packet_t structure
28584  * which holds the state information for this packet and invokes the
28585  * the classifier (via ipp_packet_process). The classification, depending on
28586  * configured filters, results in a list of actions for this packet. Invoking
28587  * an action may cause the packet to be dropped, in which case the resulting
28588  * mblk (*mpp) is NULL. proc indicates the callout position for
28589  * this packet and ill_index is the interface this packet on or will leave
28590  * on (inbound and outbound resp.).
28591  */
28592 void
28593 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28594 {
28595 	mblk_t		*mp;
28596 	ip_priv_t	*priv;
28597 	ipp_action_id_t	aid;
28598 	int		rc = 0;
28599 	ipp_packet_t	*pp;
28600 #define	IP_CLASS	"ip"
28601 
28602 	/* If the classifier is not loaded, return  */
28603 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28604 		return;
28605 	}
28606 
28607 	mp = *mpp;
28608 	ASSERT(mp != NULL);
28609 
28610 	/* Allocate the packet structure */
28611 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28612 	if (rc != 0) {
28613 		*mpp = NULL;
28614 		freemsg(mp);
28615 		return;
28616 	}
28617 
28618 	/* Allocate the private structure */
28619 	rc = ip_priv_alloc((void **)&priv);
28620 	if (rc != 0) {
28621 		*mpp = NULL;
28622 		freemsg(mp);
28623 		ipp_packet_free(pp);
28624 		return;
28625 	}
28626 	priv->proc = proc;
28627 	priv->ill_index = ill_index;
28628 	ipp_packet_set_private(pp, priv, ip_priv_free);
28629 	ipp_packet_set_data(pp, mp);
28630 
28631 	/* Invoke the classifier */
28632 	rc = ipp_packet_process(&pp);
28633 	if (pp != NULL) {
28634 		mp = ipp_packet_get_data(pp);
28635 		ipp_packet_free(pp);
28636 		if (rc != 0) {
28637 			freemsg(mp);
28638 			*mpp = NULL;
28639 		}
28640 	} else {
28641 		*mpp = NULL;
28642 	}
28643 #undef	IP_CLASS
28644 }
28645 
28646 /*
28647  * Propagate a multicast group membership operation (add/drop) on
28648  * all the interfaces crossed by the related multirt routes.
28649  * The call is considered successful if the operation succeeds
28650  * on at least one interface.
28651  */
28652 static int
28653 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28654     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28655     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28656     mblk_t *first_mp)
28657 {
28658 	ire_t		*ire_gw;
28659 	irb_t		*irb;
28660 	int		error = 0;
28661 	opt_restart_t	*or;
28662 	ip_stack_t	*ipst = ire->ire_ipst;
28663 
28664 	irb = ire->ire_bucket;
28665 	ASSERT(irb != NULL);
28666 
28667 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28668 
28669 	or = (opt_restart_t *)first_mp->b_rptr;
28670 	IRB_REFHOLD(irb);
28671 	for (; ire != NULL; ire = ire->ire_next) {
28672 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28673 			continue;
28674 		if (ire->ire_addr != group)
28675 			continue;
28676 
28677 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28678 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28679 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28680 		/* No resolver exists for the gateway; skip this ire. */
28681 		if (ire_gw == NULL)
28682 			continue;
28683 
28684 		/*
28685 		 * This function can return EINPROGRESS. If so the operation
28686 		 * will be restarted from ip_restart_optmgmt which will
28687 		 * call ip_opt_set and option processing will restart for
28688 		 * this option. So we may end up calling 'fn' more than once.
28689 		 * This requires that 'fn' is idempotent except for the
28690 		 * return value. The operation is considered a success if
28691 		 * it succeeds at least once on any one interface.
28692 		 */
28693 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28694 		    NULL, fmode, src, first_mp);
28695 		if (error == 0)
28696 			or->or_private = CGTP_MCAST_SUCCESS;
28697 
28698 		if (ip_debug > 0) {
28699 			ulong_t	off;
28700 			char	*ksym;
28701 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28702 			ip2dbg(("ip_multirt_apply_membership: "
28703 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28704 			    "error %d [success %u]\n",
28705 			    ksym ? ksym : "?",
28706 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28707 			    error, or->or_private));
28708 		}
28709 
28710 		ire_refrele(ire_gw);
28711 		if (error == EINPROGRESS) {
28712 			IRB_REFRELE(irb);
28713 			return (error);
28714 		}
28715 	}
28716 	IRB_REFRELE(irb);
28717 	/*
28718 	 * Consider the call as successful if we succeeded on at least
28719 	 * one interface. Otherwise, return the last encountered error.
28720 	 */
28721 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28722 }
28723 
28724 /*
28725  * Issue a warning regarding a route crossing an interface with an
28726  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28727  * amount of time is logged.
28728  */
28729 static void
28730 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28731 {
28732 	hrtime_t	current = gethrtime();
28733 	char		buf[INET_ADDRSTRLEN];
28734 	ip_stack_t	*ipst = ire->ire_ipst;
28735 
28736 	/* Convert interval in ms to hrtime in ns */
28737 	if (ipst->ips_multirt_bad_mtu_last_time +
28738 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28739 	    current) {
28740 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28741 		    "to %s, incorrect MTU %u (expected %u)\n",
28742 		    ip_dot_addr(ire->ire_addr, buf),
28743 		    ire->ire_max_frag, max_frag);
28744 
28745 		ipst->ips_multirt_bad_mtu_last_time = current;
28746 	}
28747 }
28748 
28749 /*
28750  * Get the CGTP (multirouting) filtering status.
28751  * If 0, the CGTP hooks are transparent.
28752  */
28753 /* ARGSUSED */
28754 static int
28755 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28756 {
28757 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28758 
28759 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28760 	return (0);
28761 }
28762 
28763 /*
28764  * Set the CGTP (multirouting) filtering status.
28765  * If the status is changed from active to transparent
28766  * or from transparent to active, forward the new status
28767  * to the filtering module (if loaded).
28768  */
28769 /* ARGSUSED */
28770 static int
28771 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28772     cred_t *ioc_cr)
28773 {
28774 	long		new_value;
28775 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28776 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28777 
28778 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28779 		return (EPERM);
28780 
28781 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28782 	    new_value < 0 || new_value > 1) {
28783 		return (EINVAL);
28784 	}
28785 
28786 	if ((!*ip_cgtp_filter_value) && new_value) {
28787 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28788 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28789 		    " (module not loaded)" : "");
28790 	}
28791 	if (*ip_cgtp_filter_value && (!new_value)) {
28792 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28793 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28794 		    " (module not loaded)" : "");
28795 	}
28796 
28797 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28798 		int	res;
28799 		netstackid_t stackid;
28800 
28801 		stackid = ipst->ips_netstack->netstack_stackid;
28802 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28803 		    new_value);
28804 		if (res)
28805 			return (res);
28806 	}
28807 
28808 	*ip_cgtp_filter_value = (boolean_t)new_value;
28809 
28810 	return (0);
28811 }
28812 
28813 /*
28814  * Return the expected CGTP hooks version number.
28815  */
28816 int
28817 ip_cgtp_filter_supported(void)
28818 {
28819 	return (ip_cgtp_filter_rev);
28820 }
28821 
28822 /*
28823  * CGTP hooks can be registered by invoking this function.
28824  * Checks that the version number matches.
28825  */
28826 int
28827 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28828 {
28829 	netstack_t *ns;
28830 	ip_stack_t *ipst;
28831 
28832 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28833 		return (ENOTSUP);
28834 
28835 	ns = netstack_find_by_stackid(stackid);
28836 	if (ns == NULL)
28837 		return (EINVAL);
28838 	ipst = ns->netstack_ip;
28839 	ASSERT(ipst != NULL);
28840 
28841 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28842 		netstack_rele(ns);
28843 		return (EALREADY);
28844 	}
28845 
28846 	ipst->ips_ip_cgtp_filter_ops = ops;
28847 	netstack_rele(ns);
28848 	return (0);
28849 }
28850 
28851 /*
28852  * CGTP hooks can be unregistered by invoking this function.
28853  * Returns ENXIO if there was no registration.
28854  * Returns EBUSY if the ndd variable has not been turned off.
28855  */
28856 int
28857 ip_cgtp_filter_unregister(netstackid_t stackid)
28858 {
28859 	netstack_t *ns;
28860 	ip_stack_t *ipst;
28861 
28862 	ns = netstack_find_by_stackid(stackid);
28863 	if (ns == NULL)
28864 		return (EINVAL);
28865 	ipst = ns->netstack_ip;
28866 	ASSERT(ipst != NULL);
28867 
28868 	if (ipst->ips_ip_cgtp_filter) {
28869 		netstack_rele(ns);
28870 		return (EBUSY);
28871 	}
28872 
28873 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28874 		netstack_rele(ns);
28875 		return (ENXIO);
28876 	}
28877 	ipst->ips_ip_cgtp_filter_ops = NULL;
28878 	netstack_rele(ns);
28879 	return (0);
28880 }
28881 
28882 /*
28883  * Check whether there is a CGTP filter registration.
28884  * Returns non-zero if there is a registration, otherwise returns zero.
28885  * Note: returns zero if bad stackid.
28886  */
28887 int
28888 ip_cgtp_filter_is_registered(netstackid_t stackid)
28889 {
28890 	netstack_t *ns;
28891 	ip_stack_t *ipst;
28892 	int ret;
28893 
28894 	ns = netstack_find_by_stackid(stackid);
28895 	if (ns == NULL)
28896 		return (0);
28897 	ipst = ns->netstack_ip;
28898 	ASSERT(ipst != NULL);
28899 
28900 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28901 		ret = 1;
28902 	else
28903 		ret = 0;
28904 
28905 	netstack_rele(ns);
28906 	return (ret);
28907 }
28908 
28909 static int
28910 ip_squeue_switch(int val)
28911 {
28912 	int rval = SQ_FILL;
28913 
28914 	switch (val) {
28915 	case IP_SQUEUE_ENTER_NODRAIN:
28916 		rval = SQ_NODRAIN;
28917 		break;
28918 	case IP_SQUEUE_ENTER:
28919 		rval = SQ_PROCESS;
28920 		break;
28921 	default:
28922 		break;
28923 	}
28924 	return (rval);
28925 }
28926 
28927 /* ARGSUSED */
28928 static int
28929 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28930     caddr_t addr, cred_t *cr)
28931 {
28932 	int *v = (int *)addr;
28933 	long new_value;
28934 
28935 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28936 		return (EPERM);
28937 
28938 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28939 		return (EINVAL);
28940 
28941 	ip_squeue_flag = ip_squeue_switch(new_value);
28942 	*v = new_value;
28943 	return (0);
28944 }
28945 
28946 /*
28947  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
28948  * ip_debug.
28949  */
28950 /* ARGSUSED */
28951 static int
28952 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28953     caddr_t addr, cred_t *cr)
28954 {
28955 	int *v = (int *)addr;
28956 	long new_value;
28957 
28958 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28959 		return (EPERM);
28960 
28961 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28962 		return (EINVAL);
28963 
28964 	*v = new_value;
28965 	return (0);
28966 }
28967 
28968 static void *
28969 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
28970 {
28971 	kstat_t *ksp;
28972 
28973 	ip_stat_t template = {
28974 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
28975 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
28976 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
28977 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
28978 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
28979 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
28980 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
28981 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
28982 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
28983 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
28984 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
28985 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
28986 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
28987 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
28988 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
28989 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
28990 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
28991 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
28992 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
28993 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
28994 		{ "ip_opt",			KSTAT_DATA_UINT64 },
28995 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
28996 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
28997 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
28998 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
28999 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29000 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29001 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29002 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29003 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29004 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29005 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29006 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29007 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29008 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29009 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29010 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29011 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29012 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29013 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29014 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29015 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29016 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29017 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29018 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29019 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29020 	};
29021 
29022 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29023 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29024 	    KSTAT_FLAG_VIRTUAL, stackid);
29025 
29026 	if (ksp == NULL)
29027 		return (NULL);
29028 
29029 	bcopy(&template, ip_statisticsp, sizeof (template));
29030 	ksp->ks_data = (void *)ip_statisticsp;
29031 	ksp->ks_private = (void *)(uintptr_t)stackid;
29032 
29033 	kstat_install(ksp);
29034 	return (ksp);
29035 }
29036 
29037 static void
29038 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29039 {
29040 	if (ksp != NULL) {
29041 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29042 		kstat_delete_netstack(ksp, stackid);
29043 	}
29044 }
29045 
29046 static void *
29047 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29048 {
29049 	kstat_t	*ksp;
29050 
29051 	ip_named_kstat_t template = {
29052 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29053 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29054 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29055 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29056 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29057 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29058 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29059 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29060 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29061 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29062 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29063 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29064 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29065 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29066 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29067 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29068 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29069 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29070 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29071 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29072 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29073 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29074 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29075 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29076 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29077 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29078 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29079 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29080 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29081 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29082 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29083 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29084 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29085 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29086 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29087 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29088 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29089 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29090 	};
29091 
29092 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29093 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29094 	if (ksp == NULL || ksp->ks_data == NULL)
29095 		return (NULL);
29096 
29097 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29098 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29099 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29100 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29101 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29102 
29103 	template.netToMediaEntrySize.value.i32 =
29104 	    sizeof (mib2_ipNetToMediaEntry_t);
29105 
29106 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29107 
29108 	bcopy(&template, ksp->ks_data, sizeof (template));
29109 	ksp->ks_update = ip_kstat_update;
29110 	ksp->ks_private = (void *)(uintptr_t)stackid;
29111 
29112 	kstat_install(ksp);
29113 	return (ksp);
29114 }
29115 
29116 static void
29117 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29118 {
29119 	if (ksp != NULL) {
29120 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29121 		kstat_delete_netstack(ksp, stackid);
29122 	}
29123 }
29124 
29125 static int
29126 ip_kstat_update(kstat_t *kp, int rw)
29127 {
29128 	ip_named_kstat_t *ipkp;
29129 	mib2_ipIfStatsEntry_t ipmib;
29130 	ill_walk_context_t ctx;
29131 	ill_t *ill;
29132 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29133 	netstack_t	*ns;
29134 	ip_stack_t	*ipst;
29135 
29136 	if (kp == NULL || kp->ks_data == NULL)
29137 		return (EIO);
29138 
29139 	if (rw == KSTAT_WRITE)
29140 		return (EACCES);
29141 
29142 	ns = netstack_find_by_stackid(stackid);
29143 	if (ns == NULL)
29144 		return (-1);
29145 	ipst = ns->netstack_ip;
29146 	if (ipst == NULL) {
29147 		netstack_rele(ns);
29148 		return (-1);
29149 	}
29150 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29151 
29152 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29153 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29154 	ill = ILL_START_WALK_V4(&ctx, ipst);
29155 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29156 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29157 	rw_exit(&ipst->ips_ill_g_lock);
29158 
29159 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29160 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29161 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29162 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29163 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29164 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29165 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29166 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29167 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29168 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29169 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29170 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29171 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29172 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29173 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29174 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29175 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29176 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29177 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29178 
29179 	ipkp->routingDiscards.value.ui32 =	0;
29180 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29181 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29182 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29183 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29184 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29185 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29186 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29187 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29188 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29189 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29190 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29191 
29192 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29193 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29194 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29195 
29196 	netstack_rele(ns);
29197 
29198 	return (0);
29199 }
29200 
29201 static void *
29202 icmp_kstat_init(netstackid_t stackid)
29203 {
29204 	kstat_t	*ksp;
29205 
29206 	icmp_named_kstat_t template = {
29207 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29208 		{ "inErrors",		KSTAT_DATA_UINT32 },
29209 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29210 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29211 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29212 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29213 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29214 		{ "inEchos",		KSTAT_DATA_UINT32 },
29215 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29216 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29217 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29218 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29219 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29220 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29221 		{ "outErrors",		KSTAT_DATA_UINT32 },
29222 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29223 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29224 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29225 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29226 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29227 		{ "outEchos",		KSTAT_DATA_UINT32 },
29228 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29229 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29230 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29231 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29232 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29233 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29234 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29235 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29236 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29237 		{ "outDrops",		KSTAT_DATA_UINT32 },
29238 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29239 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29240 	};
29241 
29242 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29243 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29244 	if (ksp == NULL || ksp->ks_data == NULL)
29245 		return (NULL);
29246 
29247 	bcopy(&template, ksp->ks_data, sizeof (template));
29248 
29249 	ksp->ks_update = icmp_kstat_update;
29250 	ksp->ks_private = (void *)(uintptr_t)stackid;
29251 
29252 	kstat_install(ksp);
29253 	return (ksp);
29254 }
29255 
29256 static void
29257 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29258 {
29259 	if (ksp != NULL) {
29260 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29261 		kstat_delete_netstack(ksp, stackid);
29262 	}
29263 }
29264 
29265 static int
29266 icmp_kstat_update(kstat_t *kp, int rw)
29267 {
29268 	icmp_named_kstat_t *icmpkp;
29269 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29270 	netstack_t	*ns;
29271 	ip_stack_t	*ipst;
29272 
29273 	if ((kp == NULL) || (kp->ks_data == NULL))
29274 		return (EIO);
29275 
29276 	if (rw == KSTAT_WRITE)
29277 		return (EACCES);
29278 
29279 	ns = netstack_find_by_stackid(stackid);
29280 	if (ns == NULL)
29281 		return (-1);
29282 	ipst = ns->netstack_ip;
29283 	if (ipst == NULL) {
29284 		netstack_rele(ns);
29285 		return (-1);
29286 	}
29287 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29288 
29289 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29290 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29291 	icmpkp->inDestUnreachs.value.ui32 =
29292 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29293 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29294 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29295 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29296 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29297 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29298 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29299 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29300 	icmpkp->inTimestampReps.value.ui32 =
29301 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29302 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29303 	icmpkp->inAddrMaskReps.value.ui32 =
29304 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29305 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29306 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29307 	icmpkp->outDestUnreachs.value.ui32 =
29308 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29309 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29310 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29311 	icmpkp->outSrcQuenchs.value.ui32 =
29312 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29313 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29314 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29315 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29316 	icmpkp->outTimestamps.value.ui32 =
29317 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29318 	icmpkp->outTimestampReps.value.ui32 =
29319 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29320 	icmpkp->outAddrMasks.value.ui32 =
29321 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29322 	icmpkp->outAddrMaskReps.value.ui32 =
29323 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29324 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29325 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29326 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29327 	icmpkp->outFragNeeded.value.ui32 =
29328 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29329 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29330 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29331 	icmpkp->inBadRedirects.value.ui32 =
29332 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29333 
29334 	netstack_rele(ns);
29335 	return (0);
29336 }
29337 
29338 /*
29339  * This is the fanout function for raw socket opened for SCTP.  Note
29340  * that it is called after SCTP checks that there is no socket which
29341  * wants a packet.  Then before SCTP handles this out of the blue packet,
29342  * this function is called to see if there is any raw socket for SCTP.
29343  * If there is and it is bound to the correct address, the packet will
29344  * be sent to that socket.  Note that only one raw socket can be bound to
29345  * a port.  This is assured in ipcl_sctp_hash_insert();
29346  */
29347 void
29348 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29349     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29350     zoneid_t zoneid)
29351 {
29352 	conn_t		*connp;
29353 	queue_t		*rq;
29354 	mblk_t		*first_mp;
29355 	boolean_t	secure;
29356 	ip6_t		*ip6h;
29357 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29358 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29359 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29360 	boolean_t	sctp_csum_err = B_FALSE;
29361 
29362 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29363 		sctp_csum_err = B_TRUE;
29364 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29365 	}
29366 
29367 	first_mp = mp;
29368 	if (mctl_present) {
29369 		mp = first_mp->b_cont;
29370 		secure = ipsec_in_is_secure(first_mp);
29371 		ASSERT(mp != NULL);
29372 	} else {
29373 		secure = B_FALSE;
29374 	}
29375 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29376 
29377 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29378 	if (connp == NULL) {
29379 		/*
29380 		 * Although raw sctp is not summed, OOB chunks must be.
29381 		 * Drop the packet here if the sctp checksum failed.
29382 		 */
29383 		if (sctp_csum_err) {
29384 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29385 			freemsg(first_mp);
29386 			return;
29387 		}
29388 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29389 		return;
29390 	}
29391 	rq = connp->conn_rq;
29392 	if (!canputnext(rq)) {
29393 		CONN_DEC_REF(connp);
29394 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29395 		freemsg(first_mp);
29396 		return;
29397 	}
29398 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29399 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29400 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29401 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29402 		if (first_mp == NULL) {
29403 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29404 			CONN_DEC_REF(connp);
29405 			return;
29406 		}
29407 	}
29408 	/*
29409 	 * We probably should not send M_CTL message up to
29410 	 * raw socket.
29411 	 */
29412 	if (mctl_present)
29413 		freeb(first_mp);
29414 
29415 	/* Initiate IPPF processing here if needed. */
29416 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29417 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29418 		ip_process(IPP_LOCAL_IN, &mp,
29419 		    recv_ill->ill_phyint->phyint_ifindex);
29420 		if (mp == NULL) {
29421 			CONN_DEC_REF(connp);
29422 			return;
29423 		}
29424 	}
29425 
29426 	if (connp->conn_recvif || connp->conn_recvslla ||
29427 	    ((connp->conn_ip_recvpktinfo ||
29428 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29429 	    (flags & IP_FF_IPINFO))) {
29430 		int in_flags = 0;
29431 
29432 		/*
29433 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29434 		 * IPF_RECVIF.
29435 		 */
29436 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29437 			in_flags = IPF_RECVIF;
29438 		}
29439 		if (connp->conn_recvslla) {
29440 			in_flags |= IPF_RECVSLLA;
29441 		}
29442 		if (isv4) {
29443 			mp = ip_add_info(mp, recv_ill, in_flags,
29444 			    IPCL_ZONEID(connp), ipst);
29445 		} else {
29446 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29447 			if (mp == NULL) {
29448 				BUMP_MIB(recv_ill->ill_ip_mib,
29449 				    ipIfStatsInDiscards);
29450 				CONN_DEC_REF(connp);
29451 				return;
29452 			}
29453 		}
29454 	}
29455 
29456 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29457 	/*
29458 	 * We are sending the IPSEC_IN message also up. Refer
29459 	 * to comments above this function.
29460 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29461 	 */
29462 	(connp->conn_recv)(connp, mp, NULL);
29463 	CONN_DEC_REF(connp);
29464 }
29465 
29466 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29467 {									\
29468 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29469 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29470 }
29471 /*
29472  * This function should be called only if all packet processing
29473  * including fragmentation is complete. Callers of this function
29474  * must set mp->b_prev to one of these values:
29475  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29476  * prior to handing over the mp as first argument to this function.
29477  *
29478  * If the ire passed by caller is incomplete, this function
29479  * queues the packet and if necessary, sends ARP request and bails.
29480  * If the ire passed is fully resolved, we simply prepend
29481  * the link-layer header to the packet, do ipsec hw acceleration
29482  * work if necessary, and send the packet out on the wire.
29483  *
29484  * NOTE: IPsec will only call this function with fully resolved
29485  * ires if hw acceleration is involved.
29486  * TODO list :
29487  * 	a Handle M_MULTIDATA so that
29488  *	  tcp_multisend->tcp_multisend_data can
29489  *	  call ip_xmit_v4 directly
29490  *	b Handle post-ARP work for fragments so that
29491  *	  ip_wput_frag can call this function.
29492  */
29493 ipxmit_state_t
29494 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29495     boolean_t flow_ctl_enabled, conn_t *connp)
29496 {
29497 	nce_t		*arpce;
29498 	ipha_t		*ipha;
29499 	queue_t		*q;
29500 	int		ill_index;
29501 	mblk_t		*nxt_mp, *first_mp;
29502 	boolean_t	xmit_drop = B_FALSE;
29503 	ip_proc_t	proc;
29504 	ill_t		*out_ill;
29505 	int		pkt_len;
29506 
29507 	arpce = ire->ire_nce;
29508 	ASSERT(arpce != NULL);
29509 
29510 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29511 
29512 	mutex_enter(&arpce->nce_lock);
29513 	switch (arpce->nce_state) {
29514 	case ND_REACHABLE:
29515 		/* If there are other queued packets, queue this packet */
29516 		if (arpce->nce_qd_mp != NULL) {
29517 			if (mp != NULL)
29518 				nce_queue_mp_common(arpce, mp, B_FALSE);
29519 			mp = arpce->nce_qd_mp;
29520 		}
29521 		arpce->nce_qd_mp = NULL;
29522 		mutex_exit(&arpce->nce_lock);
29523 
29524 		/*
29525 		 * Flush the queue.  In the common case, where the
29526 		 * ARP is already resolved,  it will go through the
29527 		 * while loop only once.
29528 		 */
29529 		while (mp != NULL) {
29530 
29531 			nxt_mp = mp->b_next;
29532 			mp->b_next = NULL;
29533 			ASSERT(mp->b_datap->db_type != M_CTL);
29534 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29535 			/*
29536 			 * This info is needed for IPQOS to do COS marking
29537 			 * in ip_wput_attach_llhdr->ip_process.
29538 			 */
29539 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29540 			mp->b_prev = NULL;
29541 
29542 			/* set up ill index for outbound qos processing */
29543 			out_ill = ire_to_ill(ire);
29544 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29545 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29546 			    ill_index, &ipha);
29547 			if (first_mp == NULL) {
29548 				xmit_drop = B_TRUE;
29549 				BUMP_MIB(out_ill->ill_ip_mib,
29550 				    ipIfStatsOutDiscards);
29551 				goto next_mp;
29552 			}
29553 
29554 			/* non-ipsec hw accel case */
29555 			if (io == NULL || !io->ipsec_out_accelerated) {
29556 				/* send it */
29557 				q = ire->ire_stq;
29558 				if (proc == IPP_FWD_OUT) {
29559 					UPDATE_IB_PKT_COUNT(ire);
29560 				} else {
29561 					UPDATE_OB_PKT_COUNT(ire);
29562 				}
29563 				ire->ire_last_used_time = lbolt;
29564 
29565 				if (flow_ctl_enabled || canputnext(q)) {
29566 					if (proc == IPP_FWD_OUT) {
29567 
29568 					BUMP_MIB(out_ill->ill_ip_mib,
29569 					    ipIfStatsHCOutForwDatagrams);
29570 
29571 					}
29572 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29573 					    pkt_len);
29574 
29575 					DTRACE_IP7(send, mblk_t *, first_mp,
29576 					    conn_t *, NULL, void_ip_t *, ipha,
29577 					    __dtrace_ipsr_ill_t *, out_ill,
29578 					    ipha_t *, ipha, ip6_t *, NULL, int,
29579 					    0);
29580 
29581 					ILL_SEND_TX(out_ill,
29582 					    ire, connp, first_mp, 0, connp);
29583 				} else {
29584 					BUMP_MIB(out_ill->ill_ip_mib,
29585 					    ipIfStatsOutDiscards);
29586 					xmit_drop = B_TRUE;
29587 					freemsg(first_mp);
29588 				}
29589 			} else {
29590 				/*
29591 				 * Safety Pup says: make sure this
29592 				 *  is going to the right interface!
29593 				 */
29594 				ill_t *ill1 =
29595 				    (ill_t *)ire->ire_stq->q_ptr;
29596 				int ifindex =
29597 				    ill1->ill_phyint->phyint_ifindex;
29598 				if (ifindex !=
29599 				    io->ipsec_out_capab_ill_index) {
29600 					xmit_drop = B_TRUE;
29601 					freemsg(mp);
29602 				} else {
29603 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29604 					    pkt_len);
29605 
29606 					DTRACE_IP7(send, mblk_t *, first_mp,
29607 					    conn_t *, NULL, void_ip_t *, ipha,
29608 					    __dtrace_ipsr_ill_t *, ill1,
29609 					    ipha_t *, ipha, ip6_t *, NULL,
29610 					    int, 0);
29611 
29612 					ipsec_hw_putnext(ire->ire_stq, mp);
29613 				}
29614 			}
29615 next_mp:
29616 			mp = nxt_mp;
29617 		} /* while (mp != NULL) */
29618 		if (xmit_drop)
29619 			return (SEND_FAILED);
29620 		else
29621 			return (SEND_PASSED);
29622 
29623 	case ND_INITIAL:
29624 	case ND_INCOMPLETE:
29625 
29626 		/*
29627 		 * While we do send off packets to dests that
29628 		 * use fully-resolved CGTP routes, we do not
29629 		 * handle unresolved CGTP routes.
29630 		 */
29631 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29632 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29633 
29634 		if (mp != NULL) {
29635 			/* queue the packet */
29636 			nce_queue_mp_common(arpce, mp, B_FALSE);
29637 		}
29638 
29639 		if (arpce->nce_state == ND_INCOMPLETE) {
29640 			mutex_exit(&arpce->nce_lock);
29641 			DTRACE_PROBE3(ip__xmit__incomplete,
29642 			    (ire_t *), ire, (mblk_t *), mp,
29643 			    (ipsec_out_t *), io);
29644 			return (LOOKUP_IN_PROGRESS);
29645 		}
29646 
29647 		arpce->nce_state = ND_INCOMPLETE;
29648 		mutex_exit(&arpce->nce_lock);
29649 
29650 		/*
29651 		 * Note that ire_add() (called from ire_forward())
29652 		 * holds a ref on the ire until ARP is completed.
29653 		 */
29654 		ire_arpresolve(ire);
29655 		return (LOOKUP_IN_PROGRESS);
29656 	default:
29657 		ASSERT(0);
29658 		mutex_exit(&arpce->nce_lock);
29659 		return (LLHDR_RESLV_FAILED);
29660 	}
29661 }
29662 
29663 #undef	UPDATE_IP_MIB_OB_COUNTERS
29664 
29665 /*
29666  * Return B_TRUE if the buffers differ in length or content.
29667  * This is used for comparing extension header buffers.
29668  * Note that an extension header would be declared different
29669  * even if all that changed was the next header value in that header i.e.
29670  * what really changed is the next extension header.
29671  */
29672 boolean_t
29673 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29674     uint_t blen)
29675 {
29676 	if (!b_valid)
29677 		blen = 0;
29678 
29679 	if (alen != blen)
29680 		return (B_TRUE);
29681 	if (alen == 0)
29682 		return (B_FALSE);	/* Both zero length */
29683 	return (bcmp(abuf, bbuf, alen));
29684 }
29685 
29686 /*
29687  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29688  * Return B_FALSE if memory allocation fails - don't change any state!
29689  */
29690 boolean_t
29691 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29692     const void *src, uint_t srclen)
29693 {
29694 	void *dst;
29695 
29696 	if (!src_valid)
29697 		srclen = 0;
29698 
29699 	ASSERT(*dstlenp == 0);
29700 	if (src != NULL && srclen != 0) {
29701 		dst = mi_alloc(srclen, BPRI_MED);
29702 		if (dst == NULL)
29703 			return (B_FALSE);
29704 	} else {
29705 		dst = NULL;
29706 	}
29707 	if (*dstp != NULL)
29708 		mi_free(*dstp);
29709 	*dstp = dst;
29710 	*dstlenp = dst == NULL ? 0 : srclen;
29711 	return (B_TRUE);
29712 }
29713 
29714 /*
29715  * Replace what is in *dst, *dstlen with the source.
29716  * Assumes ip_allocbuf has already been called.
29717  */
29718 void
29719 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29720     const void *src, uint_t srclen)
29721 {
29722 	if (!src_valid)
29723 		srclen = 0;
29724 
29725 	ASSERT(*dstlenp == srclen);
29726 	if (src != NULL && srclen != 0)
29727 		bcopy(src, *dstp, srclen);
29728 }
29729 
29730 /*
29731  * Free the storage pointed to by the members of an ip6_pkt_t.
29732  */
29733 void
29734 ip6_pkt_free(ip6_pkt_t *ipp)
29735 {
29736 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29737 
29738 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29739 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29740 		ipp->ipp_hopopts = NULL;
29741 		ipp->ipp_hopoptslen = 0;
29742 	}
29743 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29744 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29745 		ipp->ipp_rtdstopts = NULL;
29746 		ipp->ipp_rtdstoptslen = 0;
29747 	}
29748 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29749 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29750 		ipp->ipp_dstopts = NULL;
29751 		ipp->ipp_dstoptslen = 0;
29752 	}
29753 	if (ipp->ipp_fields & IPPF_RTHDR) {
29754 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29755 		ipp->ipp_rthdr = NULL;
29756 		ipp->ipp_rthdrlen = 0;
29757 	}
29758 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29759 	    IPPF_RTHDR);
29760 }
29761 
29762 zoneid_t
29763 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29764     zoneid_t lookup_zoneid)
29765 {
29766 	ire_t		*ire;
29767 	int		ire_flags = MATCH_IRE_TYPE;
29768 	zoneid_t	zoneid = ALL_ZONES;
29769 
29770 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29771 		return (ALL_ZONES);
29772 
29773 	if (lookup_zoneid != ALL_ZONES)
29774 		ire_flags |= MATCH_IRE_ZONEONLY;
29775 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29776 	    lookup_zoneid, NULL, ire_flags, ipst);
29777 	if (ire != NULL) {
29778 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29779 		ire_refrele(ire);
29780 	}
29781 	return (zoneid);
29782 }
29783 
29784 zoneid_t
29785 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29786     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29787 {
29788 	ire_t		*ire;
29789 	int		ire_flags = MATCH_IRE_TYPE;
29790 	zoneid_t	zoneid = ALL_ZONES;
29791 	ipif_t		*ipif_arg = NULL;
29792 
29793 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29794 		return (ALL_ZONES);
29795 
29796 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29797 		ire_flags |= MATCH_IRE_ILL;
29798 		ipif_arg = ill->ill_ipif;
29799 	}
29800 	if (lookup_zoneid != ALL_ZONES)
29801 		ire_flags |= MATCH_IRE_ZONEONLY;
29802 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29803 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29804 	if (ire != NULL) {
29805 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29806 		ire_refrele(ire);
29807 	}
29808 	return (zoneid);
29809 }
29810 
29811 /*
29812  * IP obserability hook support functions.
29813  */
29814 static void
29815 ipobs_init(ip_stack_t *ipst)
29816 {
29817 	netid_t id;
29818 
29819 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
29820 
29821 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
29822 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
29823 
29824 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
29825 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
29826 }
29827 
29828 static void
29829 ipobs_fini(ip_stack_t *ipst)
29830 {
29831 
29832 	net_protocol_release(ipst->ips_ip4_observe_pr);
29833 	net_protocol_release(ipst->ips_ip6_observe_pr);
29834 }
29835 
29836 /*
29837  * hook_pkt_observe_t is composed in network byte order so that the
29838  * entire mblk_t chain handed into hook_run can be used as-is.
29839  * The caveat is that use of the fields, such as the zone fields,
29840  * requires conversion into host byte order first.
29841  */
29842 void
29843 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29844     const ill_t *ill, ip_stack_t *ipst)
29845 {
29846 	hook_pkt_observe_t *hdr;
29847 	uint64_t grifindex;
29848 	mblk_t *imp;
29849 
29850 	imp = allocb(sizeof (*hdr), BPRI_HI);
29851 	if (imp == NULL)
29852 		return;
29853 
29854 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
29855 	/*
29856 	 * b_wptr is set to make the apparent size of the data in the mblk_t
29857 	 * to exclude the pointers at the end of hook_pkt_observer_t.
29858 	 */
29859 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
29860 	imp->b_cont = mp;
29861 
29862 	ASSERT(DB_TYPE(mp) == M_DATA);
29863 
29864 	if (IS_UNDER_IPMP(ill))
29865 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29866 	else
29867 		grifindex = 0;
29868 
29869 	hdr->hpo_version = 1;
29870 	hdr->hpo_htype = htype;
29871 	hdr->hpo_pktlen = htons((ushort_t)msgdsize(mp));
29872 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
29873 	hdr->hpo_grifindex = htonl(grifindex);
29874 	hdr->hpo_zsrc = htonl(zsrc);
29875 	hdr->hpo_zdst = htonl(zdst);
29876 	hdr->hpo_pkt = imp;
29877 	hdr->hpo_ctx = ipst->ips_netstack;
29878 
29879 	if (ill->ill_isv6) {
29880 		hdr->hpo_family = AF_INET6;
29881 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
29882 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
29883 	} else {
29884 		hdr->hpo_family = AF_INET;
29885 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
29886 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
29887 	}
29888 
29889 	imp->b_cont = NULL;
29890 	freemsg(imp);
29891 }
29892