xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision 8bab47abcb471dffa36ddbf409a8ef5303398ddf)
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 	/*
5711 	 * Perform cleanup for special interfaces (loopback and IPMP).
5712 	 */
5713 	ip_interface_cleanup(ipst);
5714 
5715 	/*
5716 	 * The *_hook_shutdown()s start the process of notifying any
5717 	 * consumers that things are going away.... nothing is destroyed.
5718 	 */
5719 	ipv4_hook_shutdown(ipst);
5720 	ipv6_hook_shutdown(ipst);
5721 
5722 	mutex_enter(&ipst->ips_capab_taskq_lock);
5723 	ipst->ips_capab_taskq_quit = B_TRUE;
5724 	cv_signal(&ipst->ips_capab_taskq_cv);
5725 	mutex_exit(&ipst->ips_capab_taskq_lock);
5726 
5727 	mutex_enter(&ipst->ips_mrt_lock);
5728 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5729 	cv_signal(&ipst->ips_mrt_cv);
5730 	mutex_exit(&ipst->ips_mrt_lock);
5731 }
5732 
5733 /*
5734  * Free the IP stack instance.
5735  */
5736 static void
5737 ip_stack_fini(netstackid_t stackid, void *arg)
5738 {
5739 	ip_stack_t *ipst = (ip_stack_t *)arg;
5740 	int ret;
5741 
5742 #ifdef NS_DEBUG
5743 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5744 #endif
5745 	/*
5746 	 * At this point, all of the notifications that the events and
5747 	 * protocols are going away have been run, meaning that we can
5748 	 * now set about starting to clean things up.
5749 	 */
5750 	ipobs_fini(ipst);
5751 	ipv4_hook_destroy(ipst);
5752 	ipv6_hook_destroy(ipst);
5753 	ip_net_destroy(ipst);
5754 
5755 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5756 	cv_destroy(&ipst->ips_capab_taskq_cv);
5757 
5758 	mutex_enter(&ipst->ips_mrt_lock);
5759 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5760 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5761 	mutex_destroy(&ipst->ips_mrt_lock);
5762 	cv_destroy(&ipst->ips_mrt_cv);
5763 	cv_destroy(&ipst->ips_mrt_done_cv);
5764 
5765 	ipmp_destroy(ipst);
5766 	rw_destroy(&ipst->ips_srcid_lock);
5767 
5768 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5769 	ipst->ips_ip_mibkp = NULL;
5770 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5771 	ipst->ips_icmp_mibkp = NULL;
5772 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5773 	ipst->ips_ip_kstat = NULL;
5774 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5775 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5776 	ipst->ips_ip6_kstat = NULL;
5777 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5778 
5779 	nd_free(&ipst->ips_ip_g_nd);
5780 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5781 	ipst->ips_param_arr = NULL;
5782 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5783 	ipst->ips_ndp_arr = NULL;
5784 
5785 	ip_mrouter_stack_destroy(ipst);
5786 
5787 	mutex_destroy(&ipst->ips_ip_mi_lock);
5788 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5789 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5790 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5791 
5792 	ret = untimeout(ipst->ips_igmp_timeout_id);
5793 	if (ret == -1) {
5794 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5795 	} else {
5796 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5797 		ipst->ips_igmp_timeout_id = 0;
5798 	}
5799 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5800 	if (ret == -1) {
5801 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5802 	} else {
5803 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5804 		ipst->ips_igmp_slowtimeout_id = 0;
5805 	}
5806 	ret = untimeout(ipst->ips_mld_timeout_id);
5807 	if (ret == -1) {
5808 		ASSERT(ipst->ips_mld_timeout_id == 0);
5809 	} else {
5810 		ASSERT(ipst->ips_mld_timeout_id != 0);
5811 		ipst->ips_mld_timeout_id = 0;
5812 	}
5813 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5814 	if (ret == -1) {
5815 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5816 	} else {
5817 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5818 		ipst->ips_mld_slowtimeout_id = 0;
5819 	}
5820 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5821 	if (ret == -1) {
5822 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5823 	} else {
5824 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5825 		ipst->ips_ip_ire_expire_id = 0;
5826 	}
5827 
5828 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5829 	mutex_destroy(&ipst->ips_mld_timer_lock);
5830 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5831 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5832 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5833 	rw_destroy(&ipst->ips_ill_g_lock);
5834 
5835 	ip_ire_fini(ipst);
5836 	ip6_asp_free(ipst);
5837 	conn_drain_fini(ipst);
5838 	ipcl_destroy(ipst);
5839 
5840 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5841 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5842 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5843 	ipst->ips_ndp4 = NULL;
5844 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5845 	ipst->ips_ndp6 = NULL;
5846 
5847 	if (ipst->ips_loopback_ksp != NULL) {
5848 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5849 		ipst->ips_loopback_ksp = NULL;
5850 	}
5851 
5852 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5853 	ipst->ips_phyint_g_list = NULL;
5854 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5855 	ipst->ips_ill_g_heads = NULL;
5856 
5857 	ldi_ident_release(ipst->ips_ldi_ident);
5858 	kmem_free(ipst, sizeof (*ipst));
5859 }
5860 
5861 /*
5862  * This function is called from the TSD destructor, and is used to debug
5863  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5864  * details.
5865  */
5866 static void
5867 ip_thread_exit(void *phash)
5868 {
5869 	th_hash_t *thh = phash;
5870 
5871 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5872 	list_remove(&ip_thread_list, thh);
5873 	rw_exit(&ip_thread_rwlock);
5874 	mod_hash_destroy_hash(thh->thh_hash);
5875 	kmem_free(thh, sizeof (*thh));
5876 }
5877 
5878 /*
5879  * Called when the IP kernel module is loaded into the kernel
5880  */
5881 void
5882 ip_ddi_init(void)
5883 {
5884 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5885 
5886 	/*
5887 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5888 	 * initial devices: ip, ip6, tcp, tcp6.
5889 	 */
5890 	/*
5891 	 * If this is a 64-bit kernel, then create two separate arenas -
5892 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5893 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5894 	 */
5895 	ip_minor_arena_la = NULL;
5896 	ip_minor_arena_sa = NULL;
5897 #if defined(_LP64)
5898 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5899 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5900 		cmn_err(CE_PANIC,
5901 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5902 	}
5903 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5904 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5905 		cmn_err(CE_PANIC,
5906 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5907 	}
5908 #else
5909 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5910 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5911 		cmn_err(CE_PANIC,
5912 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5913 	}
5914 #endif
5915 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5916 
5917 	ipcl_g_init();
5918 	ip_ire_g_init();
5919 	ip_net_g_init();
5920 
5921 #ifdef DEBUG
5922 	tsd_create(&ip_thread_data, ip_thread_exit);
5923 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5924 	list_create(&ip_thread_list, sizeof (th_hash_t),
5925 	    offsetof(th_hash_t, thh_link));
5926 #endif
5927 
5928 	/*
5929 	 * We want to be informed each time a stack is created or
5930 	 * destroyed in the kernel, so we can maintain the
5931 	 * set of udp_stack_t's.
5932 	 */
5933 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5934 	    ip_stack_fini);
5935 
5936 	ipsec_policy_g_init();
5937 	tcp_ddi_g_init();
5938 	sctp_ddi_g_init();
5939 
5940 	tnet_init();
5941 
5942 	udp_ddi_g_init();
5943 	rts_ddi_g_init();
5944 	icmp_ddi_g_init();
5945 }
5946 
5947 /*
5948  * Initialize the IP stack instance.
5949  */
5950 static void *
5951 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5952 {
5953 	ip_stack_t	*ipst;
5954 	ipparam_t	*pa;
5955 	ipndp_t		*na;
5956 	major_t		major;
5957 
5958 #ifdef NS_DEBUG
5959 	printf("ip_stack_init(stack %d)\n", stackid);
5960 #endif
5961 
5962 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5963 	ipst->ips_netstack = ns;
5964 
5965 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5966 	    KM_SLEEP);
5967 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5968 	    KM_SLEEP);
5969 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5970 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5971 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5972 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5973 
5974 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5975 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5976 	ipst->ips_igmp_deferred_next = INFINITY;
5977 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5978 	ipst->ips_mld_deferred_next = INFINITY;
5979 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5980 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5981 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5982 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5983 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5984 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5985 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5986 
5987 	ipcl_init(ipst);
5988 	ip_ire_init(ipst);
5989 	ip6_asp_init(ipst);
5990 	ipif_init(ipst);
5991 	conn_drain_init(ipst);
5992 	ip_mrouter_stack_init(ipst);
5993 
5994 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5995 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5996 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
5997 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
5998 
5999 	ipst->ips_ip_multirt_log_interval = 1000;
6000 
6001 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6002 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6003 	ipst->ips_ill_index = 1;
6004 
6005 	ipst->ips_saved_ip_g_forward = -1;
6006 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6007 
6008 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6009 	ipst->ips_param_arr = pa;
6010 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6011 
6012 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6013 	ipst->ips_ndp_arr = na;
6014 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6015 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6016 	    (caddr_t)&ipst->ips_ip_g_forward;
6017 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6018 	    (caddr_t)&ipst->ips_ipv6_forward;
6019 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6020 	    "ip_cgtp_filter") == 0);
6021 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6022 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6023 
6024 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6025 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6026 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6027 
6028 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6029 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6030 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6031 	ipst->ips_ip6_kstat =
6032 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6033 
6034 	ipst->ips_ip_src_id = 1;
6035 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6036 
6037 	ip_net_init(ipst, ns);
6038 	ipv4_hook_init(ipst);
6039 	ipv6_hook_init(ipst);
6040 	ipmp_init(ipst);
6041 	ipobs_init(ipst);
6042 
6043 	/*
6044 	 * Create the taskq dispatcher thread and initialize related stuff.
6045 	 */
6046 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6047 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6048 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6049 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6050 
6051 	/*
6052 	 * Create the mcast_restart_timers_thread() worker thread.
6053 	 */
6054 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6055 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6056 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6057 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6058 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6059 
6060 	major = mod_name_to_major(INET_NAME);
6061 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6062 	return (ipst);
6063 }
6064 
6065 /*
6066  * Allocate and initialize a DLPI template of the specified length.  (May be
6067  * called as writer.)
6068  */
6069 mblk_t *
6070 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6071 {
6072 	mblk_t	*mp;
6073 
6074 	mp = allocb(len, BPRI_MED);
6075 	if (!mp)
6076 		return (NULL);
6077 
6078 	/*
6079 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6080 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6081 	 * that other DLPI are M_PROTO.
6082 	 */
6083 	if (prim == DL_INFO_REQ) {
6084 		mp->b_datap->db_type = M_PCPROTO;
6085 	} else {
6086 		mp->b_datap->db_type = M_PROTO;
6087 	}
6088 
6089 	mp->b_wptr = mp->b_rptr + len;
6090 	bzero(mp->b_rptr, len);
6091 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6092 	return (mp);
6093 }
6094 
6095 /*
6096  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6097  */
6098 mblk_t *
6099 ip_dlnotify_alloc(uint_t notification, uint_t data)
6100 {
6101 	dl_notify_ind_t	*notifyp;
6102 	mblk_t		*mp;
6103 
6104 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6105 		return (NULL);
6106 
6107 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6108 	notifyp->dl_notification = notification;
6109 	notifyp->dl_data = data;
6110 	return (mp);
6111 }
6112 
6113 /*
6114  * Debug formatting routine.  Returns a character string representation of the
6115  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6116  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6117  *
6118  * Once the ndd table-printing interfaces are removed, this can be changed to
6119  * standard dotted-decimal form.
6120  */
6121 char *
6122 ip_dot_addr(ipaddr_t addr, char *buf)
6123 {
6124 	uint8_t *ap = (uint8_t *)&addr;
6125 
6126 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6127 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6128 	return (buf);
6129 }
6130 
6131 /*
6132  * Write the given MAC address as a printable string in the usual colon-
6133  * separated format.
6134  */
6135 const char *
6136 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6137 {
6138 	char *bp;
6139 
6140 	if (alen == 0 || buflen < 4)
6141 		return ("?");
6142 	bp = buf;
6143 	for (;;) {
6144 		/*
6145 		 * If there are more MAC address bytes available, but we won't
6146 		 * have any room to print them, then add "..." to the string
6147 		 * instead.  See below for the 'magic number' explanation.
6148 		 */
6149 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6150 			(void) strcpy(bp, "...");
6151 			break;
6152 		}
6153 		(void) sprintf(bp, "%02x", *addr++);
6154 		bp += 2;
6155 		if (--alen == 0)
6156 			break;
6157 		*bp++ = ':';
6158 		buflen -= 3;
6159 		/*
6160 		 * At this point, based on the first 'if' statement above,
6161 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6162 		 * buflen >= 4.  The first case leaves room for the final "xx"
6163 		 * number and trailing NUL byte.  The second leaves room for at
6164 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6165 		 * that statement.
6166 		 */
6167 	}
6168 	return (buf);
6169 }
6170 
6171 /*
6172  * Send an ICMP error after patching up the packet appropriately.  Returns
6173  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6174  */
6175 static boolean_t
6176 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6177     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6178     zoneid_t zoneid, ip_stack_t *ipst)
6179 {
6180 	ipha_t *ipha;
6181 	mblk_t *first_mp;
6182 	boolean_t secure;
6183 	unsigned char db_type;
6184 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6185 
6186 	first_mp = mp;
6187 	if (mctl_present) {
6188 		mp = mp->b_cont;
6189 		secure = ipsec_in_is_secure(first_mp);
6190 		ASSERT(mp != NULL);
6191 	} else {
6192 		/*
6193 		 * If this is an ICMP error being reported - which goes
6194 		 * up as M_CTLs, we need to convert them to M_DATA till
6195 		 * we finish checking with global policy because
6196 		 * ipsec_check_global_policy() assumes M_DATA as clear
6197 		 * and M_CTL as secure.
6198 		 */
6199 		db_type = DB_TYPE(mp);
6200 		DB_TYPE(mp) = M_DATA;
6201 		secure = B_FALSE;
6202 	}
6203 	/*
6204 	 * We are generating an icmp error for some inbound packet.
6205 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6206 	 * Before we generate an error, check with global policy
6207 	 * to see whether this is allowed to enter the system. As
6208 	 * there is no "conn", we are checking with global policy.
6209 	 */
6210 	ipha = (ipha_t *)mp->b_rptr;
6211 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6212 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6213 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6214 		if (first_mp == NULL)
6215 			return (B_FALSE);
6216 	}
6217 
6218 	if (!mctl_present)
6219 		DB_TYPE(mp) = db_type;
6220 
6221 	if (flags & IP_FF_SEND_ICMP) {
6222 		if (flags & IP_FF_HDR_COMPLETE) {
6223 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6224 				freemsg(first_mp);
6225 				return (B_TRUE);
6226 			}
6227 		}
6228 		if (flags & IP_FF_CKSUM) {
6229 			/*
6230 			 * Have to correct checksum since
6231 			 * the packet might have been
6232 			 * fragmented and the reassembly code in ip_rput
6233 			 * does not restore the IP checksum.
6234 			 */
6235 			ipha->ipha_hdr_checksum = 0;
6236 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6237 		}
6238 		switch (icmp_type) {
6239 		case ICMP_DEST_UNREACHABLE:
6240 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6241 			    ipst);
6242 			break;
6243 		default:
6244 			freemsg(first_mp);
6245 			break;
6246 		}
6247 	} else {
6248 		freemsg(first_mp);
6249 		return (B_FALSE);
6250 	}
6251 
6252 	return (B_TRUE);
6253 }
6254 
6255 /*
6256  * Used to send an ICMP error message when a packet is received for
6257  * a protocol that is not supported. The mblk passed as argument
6258  * is consumed by this function.
6259  */
6260 void
6261 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6262     ip_stack_t *ipst)
6263 {
6264 	mblk_t *mp;
6265 	ipha_t *ipha;
6266 	ill_t *ill;
6267 	ipsec_in_t *ii;
6268 
6269 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6270 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6271 
6272 	mp = ipsec_mp->b_cont;
6273 	ipsec_mp->b_cont = NULL;
6274 	ipha = (ipha_t *)mp->b_rptr;
6275 	/* Get ill from index in ipsec_in_t. */
6276 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6277 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6278 	    ipst);
6279 	if (ill != NULL) {
6280 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6281 			if (ip_fanout_send_icmp(q, mp, flags,
6282 			    ICMP_DEST_UNREACHABLE,
6283 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6284 				BUMP_MIB(ill->ill_ip_mib,
6285 				    ipIfStatsInUnknownProtos);
6286 			}
6287 		} else {
6288 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6289 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6290 			    0, B_FALSE, zoneid, ipst)) {
6291 				BUMP_MIB(ill->ill_ip_mib,
6292 				    ipIfStatsInUnknownProtos);
6293 			}
6294 		}
6295 		ill_refrele(ill);
6296 	} else { /* re-link for the freemsg() below. */
6297 		ipsec_mp->b_cont = mp;
6298 	}
6299 
6300 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6301 	freemsg(ipsec_mp);
6302 }
6303 
6304 /*
6305  * See if the inbound datagram has had IPsec processing applied to it.
6306  */
6307 boolean_t
6308 ipsec_in_is_secure(mblk_t *ipsec_mp)
6309 {
6310 	ipsec_in_t *ii;
6311 
6312 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6313 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6314 
6315 	if (ii->ipsec_in_loopback) {
6316 		return (ii->ipsec_in_secure);
6317 	} else {
6318 		return (ii->ipsec_in_ah_sa != NULL ||
6319 		    ii->ipsec_in_esp_sa != NULL ||
6320 		    ii->ipsec_in_decaps);
6321 	}
6322 }
6323 
6324 /*
6325  * Handle protocols with which IP is less intimate.  There
6326  * can be more than one stream bound to a particular
6327  * protocol.  When this is the case, normally each one gets a copy
6328  * of any incoming packets.
6329  *
6330  * IPsec NOTE :
6331  *
6332  * Don't allow a secure packet going up a non-secure connection.
6333  * We don't allow this because
6334  *
6335  * 1) Reply might go out in clear which will be dropped at
6336  *    the sending side.
6337  * 2) If the reply goes out in clear it will give the
6338  *    adversary enough information for getting the key in
6339  *    most of the cases.
6340  *
6341  * Moreover getting a secure packet when we expect clear
6342  * implies that SA's were added without checking for
6343  * policy on both ends. This should not happen once ISAKMP
6344  * is used to negotiate SAs as SAs will be added only after
6345  * verifying the policy.
6346  *
6347  * IPQoS Notes:
6348  * Once we have determined the client, invoke IPPF processing.
6349  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6350  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6351  * ip_policy will be false.
6352  *
6353  * Zones notes:
6354  * Currently only applications in the global zone can create raw sockets for
6355  * protocols other than ICMP. So unlike the broadcast / multicast case of
6356  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6357  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6358  */
6359 static void
6360 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6361     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6362     zoneid_t zoneid)
6363 {
6364 	queue_t	*rq;
6365 	mblk_t	*mp1, *first_mp1;
6366 	uint_t	protocol = ipha->ipha_protocol;
6367 	ipaddr_t dst;
6368 	mblk_t *first_mp = mp;
6369 	boolean_t secure;
6370 	uint32_t ill_index;
6371 	conn_t	*connp, *first_connp, *next_connp;
6372 	connf_t	*connfp;
6373 	boolean_t shared_addr;
6374 	mib2_ipIfStatsEntry_t *mibptr;
6375 	ip_stack_t *ipst = recv_ill->ill_ipst;
6376 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6377 
6378 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6379 	if (mctl_present) {
6380 		mp = first_mp->b_cont;
6381 		secure = ipsec_in_is_secure(first_mp);
6382 		ASSERT(mp != NULL);
6383 	} else {
6384 		secure = B_FALSE;
6385 	}
6386 	dst = ipha->ipha_dst;
6387 	shared_addr = (zoneid == ALL_ZONES);
6388 	if (shared_addr) {
6389 		/*
6390 		 * We don't allow multilevel ports for raw IP, so no need to
6391 		 * check for that here.
6392 		 */
6393 		zoneid = tsol_packet_to_zoneid(mp);
6394 	}
6395 
6396 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6397 	mutex_enter(&connfp->connf_lock);
6398 	connp = connfp->connf_head;
6399 	for (connp = connfp->connf_head; connp != NULL;
6400 	    connp = connp->conn_next) {
6401 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6402 		    zoneid) &&
6403 		    (!is_system_labeled() ||
6404 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6405 		    connp))) {
6406 			break;
6407 		}
6408 	}
6409 
6410 	if (connp == NULL) {
6411 		/*
6412 		 * No one bound to these addresses.  Is
6413 		 * there a client that wants all
6414 		 * unclaimed datagrams?
6415 		 */
6416 		mutex_exit(&connfp->connf_lock);
6417 		/*
6418 		 * Check for IPPROTO_ENCAP...
6419 		 */
6420 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6421 			/*
6422 			 * If an IPsec mblk is here on a multicast
6423 			 * tunnel (using ip_mroute stuff), check policy here,
6424 			 * THEN ship off to ip_mroute_decap().
6425 			 *
6426 			 * BTW,  If I match a configured IP-in-IP
6427 			 * tunnel, this path will not be reached, and
6428 			 * ip_mroute_decap will never be called.
6429 			 */
6430 			first_mp = ipsec_check_global_policy(first_mp, connp,
6431 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6432 			if (first_mp != NULL) {
6433 				if (mctl_present)
6434 					freeb(first_mp);
6435 				ip_mroute_decap(q, mp, ill);
6436 			} /* Else we already freed everything! */
6437 		} else {
6438 			/*
6439 			 * Otherwise send an ICMP protocol unreachable.
6440 			 */
6441 			if (ip_fanout_send_icmp(q, first_mp, flags,
6442 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6443 			    mctl_present, zoneid, ipst)) {
6444 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6445 			}
6446 		}
6447 		return;
6448 	}
6449 
6450 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6451 
6452 	CONN_INC_REF(connp);
6453 	first_connp = connp;
6454 	connp = connp->conn_next;
6455 
6456 	for (;;) {
6457 		while (connp != NULL) {
6458 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6459 			    flags, zoneid) &&
6460 			    (!is_system_labeled() ||
6461 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6462 			    shared_addr, connp)))
6463 				break;
6464 			connp = connp->conn_next;
6465 		}
6466 
6467 		/*
6468 		 * Copy the packet.
6469 		 */
6470 		if (connp == NULL ||
6471 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6472 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6473 			/*
6474 			 * No more interested clients or memory
6475 			 * allocation failed
6476 			 */
6477 			connp = first_connp;
6478 			break;
6479 		}
6480 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6481 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6482 		CONN_INC_REF(connp);
6483 		mutex_exit(&connfp->connf_lock);
6484 		rq = connp->conn_rq;
6485 
6486 		/*
6487 		 * Check flow control
6488 		 */
6489 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6490 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6491 			if (flags & IP_FF_RAWIP) {
6492 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6493 			} else {
6494 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6495 			}
6496 
6497 			freemsg(first_mp1);
6498 		} else {
6499 			/*
6500 			 * Enforce policy like any other conn_t.  Note that
6501 			 * IP-in-IP packets don't come through here, but
6502 			 * through ip_iptun_input() or
6503 			 * icmp_inbound_iptun_fanout().  IPsec policy for such
6504 			 * packets is enforced in the iptun module.
6505 			 */
6506 			if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6507 			    secure) {
6508 				first_mp1 = ipsec_check_inbound_policy
6509 				    (first_mp1, connp, ipha, NULL,
6510 				    mctl_present);
6511 			}
6512 			if (first_mp1 != NULL) {
6513 				int in_flags = 0;
6514 				/*
6515 				 * ip_fanout_proto also gets called from
6516 				 * icmp_inbound_error_fanout, in which case
6517 				 * the msg type is M_CTL.  Don't add info
6518 				 * in this case for the time being. In future
6519 				 * when there is a need for knowing the
6520 				 * inbound iface index for ICMP error msgs,
6521 				 * then this can be changed.
6522 				 */
6523 				if (connp->conn_recvif)
6524 					in_flags = IPF_RECVIF;
6525 				/*
6526 				 * The ULP may support IP_RECVPKTINFO for both
6527 				 * IP v4 and v6 so pass the appropriate argument
6528 				 * based on conn IP version.
6529 				 */
6530 				if (connp->conn_ip_recvpktinfo) {
6531 					if (connp->conn_af_isv6) {
6532 						/*
6533 						 * V6 only needs index
6534 						 */
6535 						in_flags |= IPF_RECVIF;
6536 					} else {
6537 						/*
6538 						 * V4 needs index +
6539 						 * matching address.
6540 						 */
6541 						in_flags |= IPF_RECVADDR;
6542 					}
6543 				}
6544 				if ((in_flags != 0) &&
6545 				    (mp->b_datap->db_type != M_CTL)) {
6546 					/*
6547 					 * the actual data will be
6548 					 * contained in b_cont upon
6549 					 * successful return of the
6550 					 * following call else
6551 					 * original mblk is returned
6552 					 */
6553 					ASSERT(recv_ill != NULL);
6554 					mp1 = ip_add_info(mp1, recv_ill,
6555 					    in_flags, IPCL_ZONEID(connp), ipst);
6556 				}
6557 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6558 				if (mctl_present)
6559 					freeb(first_mp1);
6560 				(connp->conn_recv)(connp, mp1, NULL);
6561 			}
6562 		}
6563 		mutex_enter(&connfp->connf_lock);
6564 		/* Follow the next pointer before releasing the conn. */
6565 		next_connp = connp->conn_next;
6566 		CONN_DEC_REF(connp);
6567 		connp = next_connp;
6568 	}
6569 
6570 	/* Last one.  Send it upstream. */
6571 	mutex_exit(&connfp->connf_lock);
6572 
6573 	/*
6574 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6575 	 * will be set to false.
6576 	 */
6577 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6578 		ill_index = ill->ill_phyint->phyint_ifindex;
6579 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6580 		if (mp == NULL) {
6581 			CONN_DEC_REF(connp);
6582 			if (mctl_present) {
6583 				freeb(first_mp);
6584 			}
6585 			return;
6586 		}
6587 	}
6588 
6589 	rq = connp->conn_rq;
6590 	/*
6591 	 * Check flow control
6592 	 */
6593 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6594 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6595 		if (flags & IP_FF_RAWIP) {
6596 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6597 		} else {
6598 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6599 		}
6600 
6601 		freemsg(first_mp);
6602 	} else {
6603 		ASSERT(!IPCL_IS_IPTUN(connp));
6604 
6605 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6606 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6607 			    ipha, NULL, mctl_present);
6608 		}
6609 
6610 		if (first_mp != NULL) {
6611 			int in_flags = 0;
6612 
6613 			/*
6614 			 * ip_fanout_proto also gets called
6615 			 * from icmp_inbound_error_fanout, in
6616 			 * which case the msg type is M_CTL.
6617 			 * Don't add info in this case for time
6618 			 * being. In future when there is a
6619 			 * need for knowing the inbound iface
6620 			 * index for ICMP error msgs, then this
6621 			 * can be changed
6622 			 */
6623 			if (connp->conn_recvif)
6624 				in_flags = IPF_RECVIF;
6625 			if (connp->conn_ip_recvpktinfo) {
6626 				if (connp->conn_af_isv6) {
6627 					/*
6628 					 * V6 only needs index
6629 					 */
6630 					in_flags |= IPF_RECVIF;
6631 				} else {
6632 					/*
6633 					 * V4 needs index +
6634 					 * matching address.
6635 					 */
6636 					in_flags |= IPF_RECVADDR;
6637 				}
6638 			}
6639 			if ((in_flags != 0) &&
6640 			    (mp->b_datap->db_type != M_CTL)) {
6641 
6642 				/*
6643 				 * the actual data will be contained in
6644 				 * b_cont upon successful return
6645 				 * of the following call else original
6646 				 * mblk is returned
6647 				 */
6648 				ASSERT(recv_ill != NULL);
6649 				mp = ip_add_info(mp, recv_ill,
6650 				    in_flags, IPCL_ZONEID(connp), ipst);
6651 			}
6652 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6653 			(connp->conn_recv)(connp, mp, NULL);
6654 			if (mctl_present)
6655 				freeb(first_mp);
6656 		}
6657 	}
6658 	CONN_DEC_REF(connp);
6659 }
6660 
6661 /*
6662  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6663  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6664  * the correct squeue, in this case the same squeue as a valid listener with
6665  * no current connection state for the packet we are processing. The function
6666  * is called for synchronizing both IPv4 and IPv6.
6667  */
6668 void
6669 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6670     tcp_stack_t *tcps, conn_t *connp)
6671 {
6672 	mblk_t *rst_mp;
6673 	tcp_xmit_reset_event_t *eventp;
6674 
6675 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6676 
6677 	if (rst_mp == NULL) {
6678 		freemsg(mp);
6679 		return;
6680 	}
6681 
6682 	rst_mp->b_datap->db_type = M_PROTO;
6683 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6684 
6685 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6686 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6687 	eventp->tcp_xre_iphdrlen = hdrlen;
6688 	eventp->tcp_xre_zoneid = zoneid;
6689 	eventp->tcp_xre_tcps = tcps;
6690 
6691 	rst_mp->b_cont = mp;
6692 	mp = rst_mp;
6693 
6694 	/*
6695 	 * Increment the connref, this ref will be released by the squeue
6696 	 * framework.
6697 	 */
6698 	CONN_INC_REF(connp);
6699 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6700 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6701 }
6702 
6703 /*
6704  * Fanout for TCP packets
6705  * The caller puts <fport, lport> in the ports parameter.
6706  *
6707  * IPQoS Notes
6708  * Before sending it to the client, invoke IPPF processing.
6709  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6710  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6711  * ip_policy is false.
6712  */
6713 static void
6714 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6715     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6716 {
6717 	mblk_t  *first_mp;
6718 	boolean_t secure;
6719 	uint32_t ill_index;
6720 	int	ip_hdr_len;
6721 	tcph_t	*tcph;
6722 	boolean_t syn_present = B_FALSE;
6723 	conn_t	*connp;
6724 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6725 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6726 
6727 	ASSERT(recv_ill != NULL);
6728 
6729 	first_mp = mp;
6730 	if (mctl_present) {
6731 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6732 		mp = first_mp->b_cont;
6733 		secure = ipsec_in_is_secure(first_mp);
6734 		ASSERT(mp != NULL);
6735 	} else {
6736 		secure = B_FALSE;
6737 	}
6738 
6739 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6740 
6741 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6742 	    zoneid, ipst)) == NULL) {
6743 		/*
6744 		 * No connected connection or listener. Send a
6745 		 * TH_RST via tcp_xmit_listeners_reset.
6746 		 */
6747 
6748 		/* Initiate IPPf processing, if needed. */
6749 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6750 			uint32_t ill_index;
6751 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6752 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6753 			if (first_mp == NULL)
6754 				return;
6755 		}
6756 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6757 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6758 		    zoneid));
6759 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6760 		    ipst->ips_netstack->netstack_tcp, NULL);
6761 		return;
6762 	}
6763 
6764 	/*
6765 	 * Allocate the SYN for the TCP connection here itself
6766 	 */
6767 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6768 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6769 		if (IPCL_IS_TCP(connp)) {
6770 			squeue_t *sqp;
6771 
6772 			/*
6773 			 * If the queue belongs to a conn, and fused tcp
6774 			 * loopback is enabled, assign the eager's squeue
6775 			 * to be that of the active connect's. Note that
6776 			 * we don't check for IP_FF_LOOPBACK here since this
6777 			 * routine gets called only for loopback (unlike the
6778 			 * IPv6 counterpart).
6779 			 */
6780 			if (do_tcp_fusion &&
6781 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6782 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6783 			    !secure &&
6784 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6785 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6786 				sqp = Q_TO_CONN(q)->conn_sqp;
6787 			} else {
6788 				sqp = IP_SQUEUE_GET(lbolt);
6789 			}
6790 
6791 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6792 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6793 			syn_present = B_TRUE;
6794 		}
6795 	}
6796 
6797 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6798 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6799 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6800 		if ((flags & TH_RST) || (flags & TH_URG)) {
6801 			CONN_DEC_REF(connp);
6802 			freemsg(first_mp);
6803 			return;
6804 		}
6805 		if (flags & TH_ACK) {
6806 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6807 			    ipst->ips_netstack->netstack_tcp, connp);
6808 			CONN_DEC_REF(connp);
6809 			return;
6810 		}
6811 
6812 		CONN_DEC_REF(connp);
6813 		freemsg(first_mp);
6814 		return;
6815 	}
6816 
6817 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6818 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6819 		    NULL, mctl_present);
6820 		if (first_mp == NULL) {
6821 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6822 			CONN_DEC_REF(connp);
6823 			return;
6824 		}
6825 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6826 			ASSERT(syn_present);
6827 			if (mctl_present) {
6828 				ASSERT(first_mp != mp);
6829 				first_mp->b_datap->db_struioflag |=
6830 				    STRUIO_POLICY;
6831 			} else {
6832 				ASSERT(first_mp == mp);
6833 				mp->b_datap->db_struioflag &=
6834 				    ~STRUIO_EAGER;
6835 				mp->b_datap->db_struioflag |=
6836 				    STRUIO_POLICY;
6837 			}
6838 		} else {
6839 			/*
6840 			 * Discard first_mp early since we're dealing with a
6841 			 * fully-connected conn_t and tcp doesn't do policy in
6842 			 * this case.
6843 			 */
6844 			if (mctl_present) {
6845 				freeb(first_mp);
6846 				mctl_present = B_FALSE;
6847 			}
6848 			first_mp = mp;
6849 		}
6850 	}
6851 
6852 	/*
6853 	 * Initiate policy processing here if needed. If we get here from
6854 	 * icmp_inbound_error_fanout, ip_policy is false.
6855 	 */
6856 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6857 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6858 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6859 		if (mp == NULL) {
6860 			CONN_DEC_REF(connp);
6861 			if (mctl_present)
6862 				freeb(first_mp);
6863 			return;
6864 		} else if (mctl_present) {
6865 			ASSERT(first_mp != mp);
6866 			first_mp->b_cont = mp;
6867 		} else {
6868 			first_mp = mp;
6869 		}
6870 	}
6871 
6872 	/* Handle socket options. */
6873 	if (!syn_present &&
6874 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6875 		/* Add header */
6876 		ASSERT(recv_ill != NULL);
6877 		/*
6878 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6879 		 * IPF_RECVIF.
6880 		 */
6881 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6882 		    ipst);
6883 		if (mp == NULL) {
6884 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6885 			CONN_DEC_REF(connp);
6886 			if (mctl_present)
6887 				freeb(first_mp);
6888 			return;
6889 		} else if (mctl_present) {
6890 			/*
6891 			 * ip_add_info might return a new mp.
6892 			 */
6893 			ASSERT(first_mp != mp);
6894 			first_mp->b_cont = mp;
6895 		} else {
6896 			first_mp = mp;
6897 		}
6898 	}
6899 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6900 	if (IPCL_IS_TCP(connp)) {
6901 		/* do not drain, certain use cases can blow the stack */
6902 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6903 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
6904 	} else {
6905 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6906 		(connp->conn_recv)(connp, first_mp, NULL);
6907 		CONN_DEC_REF(connp);
6908 	}
6909 }
6910 
6911 /*
6912  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6913  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6914  * is not consumed.
6915  *
6916  * One of four things can happen, all of which affect the passed-in mblk:
6917  *
6918  * 1.) ICMP messages that go through here just get returned TRUE.
6919  *
6920  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6921  *
6922  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6923  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6924  *
6925  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6926  */
6927 static boolean_t
6928 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6929     ipsec_stack_t *ipss)
6930 {
6931 	int shift, plen, iph_len;
6932 	ipha_t *ipha;
6933 	udpha_t *udpha;
6934 	uint32_t *spi;
6935 	uint32_t esp_ports;
6936 	uint8_t *orptr;
6937 	boolean_t free_ire;
6938 
6939 	if (DB_TYPE(mp) == M_CTL) {
6940 		/*
6941 		 * ICMP message with UDP inside.  Don't bother stripping, just
6942 		 * send it up.
6943 		 *
6944 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6945 		 * to ignore errors set by ICMP anyway ('cause they might be
6946 		 * forged), but that's the app's decision, not ours.
6947 		 */
6948 
6949 		/* Bunch of reality checks for DEBUG kernels... */
6950 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6951 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6952 
6953 		return (B_TRUE);
6954 	}
6955 
6956 	ipha = (ipha_t *)mp->b_rptr;
6957 	iph_len = IPH_HDR_LENGTH(ipha);
6958 	plen = ntohs(ipha->ipha_length);
6959 
6960 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6961 		/*
6962 		 * Most likely a keepalive for the benefit of an intervening
6963 		 * NAT.  These aren't for us, per se, so drop it.
6964 		 *
6965 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6966 		 * byte packets (keepalives are 1-byte), but we'll drop them
6967 		 * also.
6968 		 */
6969 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6970 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6971 		return (B_FALSE);
6972 	}
6973 
6974 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6975 		/* might as well pull it all up - it might be ESP. */
6976 		if (!pullupmsg(mp, -1)) {
6977 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6978 			    DROPPER(ipss, ipds_esp_nomem),
6979 			    &ipss->ipsec_dropper);
6980 			return (B_FALSE);
6981 		}
6982 
6983 		ipha = (ipha_t *)mp->b_rptr;
6984 	}
6985 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6986 	if (*spi == 0) {
6987 		/* UDP packet - remove 0-spi. */
6988 		shift = sizeof (uint32_t);
6989 	} else {
6990 		/* ESP-in-UDP packet - reduce to ESP. */
6991 		ipha->ipha_protocol = IPPROTO_ESP;
6992 		shift = sizeof (udpha_t);
6993 	}
6994 
6995 	/* Fix IP header */
6996 	ipha->ipha_length = htons(plen - shift);
6997 	ipha->ipha_hdr_checksum = 0;
6998 
6999 	orptr = mp->b_rptr;
7000 	mp->b_rptr += shift;
7001 
7002 	udpha = (udpha_t *)(orptr + iph_len);
7003 	if (*spi == 0) {
7004 		ASSERT((uint8_t *)ipha == orptr);
7005 		udpha->uha_length = htons(plen - shift - iph_len);
7006 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7007 		esp_ports = 0;
7008 	} else {
7009 		esp_ports = *((uint32_t *)udpha);
7010 		ASSERT(esp_ports != 0);
7011 	}
7012 	ovbcopy(orptr, orptr + shift, iph_len);
7013 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7014 		ipha = (ipha_t *)(orptr + shift);
7015 
7016 		free_ire = (ire == NULL);
7017 		if (free_ire) {
7018 			/* Re-acquire ire. */
7019 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7020 			    ipss->ipsec_netstack->netstack_ip);
7021 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7022 				if (ire != NULL)
7023 					ire_refrele(ire);
7024 				/*
7025 				 * Do a regular freemsg(), as this is an IP
7026 				 * error (no local route) not an IPsec one.
7027 				 */
7028 				freemsg(mp);
7029 			}
7030 		}
7031 
7032 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7033 		if (free_ire)
7034 			ire_refrele(ire);
7035 	}
7036 
7037 	return (esp_ports == 0);
7038 }
7039 
7040 /*
7041  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7042  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7043  * Caller is responsible for dropping references to the conn, and freeing
7044  * first_mp.
7045  *
7046  * IPQoS Notes
7047  * Before sending it to the client, invoke IPPF processing. Policy processing
7048  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7049  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7050  * ip_wput_local, ip_policy is false.
7051  */
7052 static void
7053 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7054     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7055     boolean_t ip_policy)
7056 {
7057 	boolean_t	mctl_present = (first_mp != NULL);
7058 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7059 	uint32_t	ill_index;
7060 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7061 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7062 
7063 	ASSERT(ill != NULL);
7064 
7065 	if (mctl_present)
7066 		first_mp->b_cont = mp;
7067 	else
7068 		first_mp = mp;
7069 
7070 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7071 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7072 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7073 		freemsg(first_mp);
7074 		return;
7075 	}
7076 
7077 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7078 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7079 		    NULL, mctl_present);
7080 		/* Freed by ipsec_check_inbound_policy(). */
7081 		if (first_mp == NULL) {
7082 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7083 			return;
7084 		}
7085 	}
7086 	if (mctl_present)
7087 		freeb(first_mp);
7088 
7089 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7090 	if (connp->conn_udp->udp_nat_t_endpoint) {
7091 		if (mctl_present) {
7092 			/* mctl_present *shouldn't* happen. */
7093 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7094 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7095 			    &ipss->ipsec_dropper);
7096 			return;
7097 		}
7098 
7099 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7100 			return;
7101 	}
7102 
7103 	/* Handle options. */
7104 	if (connp->conn_recvif)
7105 		in_flags = IPF_RECVIF;
7106 	/*
7107 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7108 	 * passed to ip_add_info is based on IP version of connp.
7109 	 */
7110 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7111 		if (connp->conn_af_isv6) {
7112 			/*
7113 			 * V6 only needs index
7114 			 */
7115 			in_flags |= IPF_RECVIF;
7116 		} else {
7117 			/*
7118 			 * V4 needs index + matching address.
7119 			 */
7120 			in_flags |= IPF_RECVADDR;
7121 		}
7122 	}
7123 
7124 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7125 		in_flags |= IPF_RECVSLLA;
7126 
7127 	/*
7128 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7129 	 * freed if the packet is dropped. The caller will do so.
7130 	 */
7131 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7132 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7133 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7134 		if (mp == NULL) {
7135 			return;
7136 		}
7137 	}
7138 	if ((in_flags != 0) &&
7139 	    (mp->b_datap->db_type != M_CTL)) {
7140 		/*
7141 		 * The actual data will be contained in b_cont
7142 		 * upon successful return of the following call
7143 		 * else original mblk is returned
7144 		 */
7145 		ASSERT(recv_ill != NULL);
7146 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7147 		    ipst);
7148 	}
7149 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7150 	/* Send it upstream */
7151 	(connp->conn_recv)(connp, mp, NULL);
7152 }
7153 
7154 /*
7155  * Fanout for UDP packets.
7156  * The caller puts <fport, lport> in the ports parameter.
7157  *
7158  * If SO_REUSEADDR is set all multicast and broadcast packets
7159  * will be delivered to all streams bound to the same port.
7160  *
7161  * Zones notes:
7162  * Multicast and broadcast packets will be distributed to streams in all zones.
7163  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7164  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7165  * packets. To maintain this behavior with multiple zones, the conns are grouped
7166  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7167  * each zone. If unset, all the following conns in the same zone are skipped.
7168  */
7169 static void
7170 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7171     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7172     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7173 {
7174 	uint32_t	dstport, srcport;
7175 	ipaddr_t	dst;
7176 	mblk_t		*first_mp;
7177 	boolean_t	secure;
7178 	in6_addr_t	v6src;
7179 	conn_t		*connp;
7180 	connf_t		*connfp;
7181 	conn_t		*first_connp;
7182 	conn_t		*next_connp;
7183 	mblk_t		*mp1, *first_mp1;
7184 	ipaddr_t	src;
7185 	zoneid_t	last_zoneid;
7186 	boolean_t	reuseaddr;
7187 	boolean_t	shared_addr;
7188 	boolean_t	unlabeled;
7189 	ip_stack_t	*ipst;
7190 
7191 	ASSERT(recv_ill != NULL);
7192 	ipst = recv_ill->ill_ipst;
7193 
7194 	first_mp = mp;
7195 	if (mctl_present) {
7196 		mp = first_mp->b_cont;
7197 		first_mp->b_cont = NULL;
7198 		secure = ipsec_in_is_secure(first_mp);
7199 		ASSERT(mp != NULL);
7200 	} else {
7201 		first_mp = NULL;
7202 		secure = B_FALSE;
7203 	}
7204 
7205 	/* Extract ports in net byte order */
7206 	dstport = htons(ntohl(ports) & 0xFFFF);
7207 	srcport = htons(ntohl(ports) >> 16);
7208 	dst = ipha->ipha_dst;
7209 	src = ipha->ipha_src;
7210 
7211 	unlabeled = B_FALSE;
7212 	if (is_system_labeled())
7213 		/* Cred cannot be null on IPv4 */
7214 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7215 		    TSLF_UNLABELED) != 0;
7216 	shared_addr = (zoneid == ALL_ZONES);
7217 	if (shared_addr) {
7218 		/*
7219 		 * No need to handle exclusive-stack zones since ALL_ZONES
7220 		 * only applies to the shared stack.
7221 		 */
7222 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7223 		/*
7224 		 * If no shared MLP is found, tsol_mlp_findzone returns
7225 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7226 		 * search for the zone based on the packet label.
7227 		 *
7228 		 * If there is such a zone, we prefer to find a
7229 		 * connection in it.  Otherwise, we look for a
7230 		 * MAC-exempt connection in any zone whose label
7231 		 * dominates the default label on the packet.
7232 		 */
7233 		if (zoneid == ALL_ZONES)
7234 			zoneid = tsol_packet_to_zoneid(mp);
7235 		else
7236 			unlabeled = B_FALSE;
7237 	}
7238 
7239 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7240 	mutex_enter(&connfp->connf_lock);
7241 	connp = connfp->connf_head;
7242 	if (!broadcast && !CLASSD(dst)) {
7243 		/*
7244 		 * Not broadcast or multicast. Send to the one (first)
7245 		 * client we find. No need to check conn_wantpacket()
7246 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7247 		 * IPv4 unicast packets.
7248 		 */
7249 		while ((connp != NULL) &&
7250 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7251 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7252 		    !(unlabeled && connp->conn_mac_exempt && shared_addr)))) {
7253 			/*
7254 			 * We keep searching since the conn did not match,
7255 			 * or its zone did not match and it is not either
7256 			 * an allzones conn or a mac exempt conn (if the
7257 			 * sender is unlabeled.)
7258 			 */
7259 			connp = connp->conn_next;
7260 		}
7261 
7262 		if (connp == NULL ||
7263 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7264 			goto notfound;
7265 
7266 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7267 
7268 		if (is_system_labeled() &&
7269 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7270 		    connp))
7271 			goto notfound;
7272 
7273 		CONN_INC_REF(connp);
7274 		mutex_exit(&connfp->connf_lock);
7275 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7276 		    flags, recv_ill, ip_policy);
7277 		IP_STAT(ipst, ip_udp_fannorm);
7278 		CONN_DEC_REF(connp);
7279 		return;
7280 	}
7281 
7282 	/*
7283 	 * Broadcast and multicast case
7284 	 *
7285 	 * Need to check conn_wantpacket().
7286 	 * If SO_REUSEADDR has been set on the first we send the
7287 	 * packet to all clients that have joined the group and
7288 	 * match the port.
7289 	 */
7290 
7291 	while (connp != NULL) {
7292 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7293 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7294 		    (!is_system_labeled() ||
7295 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7296 		    connp)))
7297 			break;
7298 		connp = connp->conn_next;
7299 	}
7300 
7301 	if (connp == NULL ||
7302 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7303 		goto notfound;
7304 
7305 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7306 
7307 	first_connp = connp;
7308 	/*
7309 	 * When SO_REUSEADDR is not set, send the packet only to the first
7310 	 * matching connection in its zone by keeping track of the zoneid.
7311 	 */
7312 	reuseaddr = first_connp->conn_reuseaddr;
7313 	last_zoneid = first_connp->conn_zoneid;
7314 
7315 	CONN_INC_REF(connp);
7316 	connp = connp->conn_next;
7317 	for (;;) {
7318 		while (connp != NULL) {
7319 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7320 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7321 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7322 			    (!is_system_labeled() ||
7323 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7324 			    shared_addr, connp)))
7325 				break;
7326 			connp = connp->conn_next;
7327 		}
7328 		/*
7329 		 * Just copy the data part alone. The mctl part is
7330 		 * needed just for verifying policy and it is never
7331 		 * sent up.
7332 		 */
7333 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7334 		    ((mp1 = copymsg(mp)) == NULL))) {
7335 			/*
7336 			 * No more interested clients or memory
7337 			 * allocation failed
7338 			 */
7339 			connp = first_connp;
7340 			break;
7341 		}
7342 		if (connp->conn_zoneid != last_zoneid) {
7343 			/*
7344 			 * Update the zoneid so that the packet isn't sent to
7345 			 * any more conns in the same zone unless SO_REUSEADDR
7346 			 * is set.
7347 			 */
7348 			reuseaddr = connp->conn_reuseaddr;
7349 			last_zoneid = connp->conn_zoneid;
7350 		}
7351 		if (first_mp != NULL) {
7352 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7353 			    ipsec_info_type == IPSEC_IN);
7354 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7355 			    ipst->ips_netstack);
7356 			if (first_mp1 == NULL) {
7357 				freemsg(mp1);
7358 				connp = first_connp;
7359 				break;
7360 			}
7361 		} else {
7362 			first_mp1 = NULL;
7363 		}
7364 		CONN_INC_REF(connp);
7365 		mutex_exit(&connfp->connf_lock);
7366 		/*
7367 		 * IPQoS notes: We don't send the packet for policy
7368 		 * processing here, will do it for the last one (below).
7369 		 * i.e. we do it per-packet now, but if we do policy
7370 		 * processing per-conn, then we would need to do it
7371 		 * here too.
7372 		 */
7373 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7374 		    ipha, flags, recv_ill, B_FALSE);
7375 		mutex_enter(&connfp->connf_lock);
7376 		/* Follow the next pointer before releasing the conn. */
7377 		next_connp = connp->conn_next;
7378 		IP_STAT(ipst, ip_udp_fanmb);
7379 		CONN_DEC_REF(connp);
7380 		connp = next_connp;
7381 	}
7382 
7383 	/* Last one.  Send it upstream. */
7384 	mutex_exit(&connfp->connf_lock);
7385 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7386 	    recv_ill, ip_policy);
7387 	IP_STAT(ipst, ip_udp_fanmb);
7388 	CONN_DEC_REF(connp);
7389 	return;
7390 
7391 notfound:
7392 
7393 	mutex_exit(&connfp->connf_lock);
7394 	IP_STAT(ipst, ip_udp_fanothers);
7395 	/*
7396 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7397 	 * have already been matched above, since they live in the IPv4
7398 	 * fanout tables. This implies we only need to
7399 	 * check for IPv6 in6addr_any endpoints here.
7400 	 * Thus we compare using ipv6_all_zeros instead of the destination
7401 	 * address, except for the multicast group membership lookup which
7402 	 * uses the IPv4 destination.
7403 	 */
7404 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7405 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7406 	mutex_enter(&connfp->connf_lock);
7407 	connp = connfp->connf_head;
7408 	if (!broadcast && !CLASSD(dst)) {
7409 		while (connp != NULL) {
7410 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7411 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7412 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7413 			    !connp->conn_ipv6_v6only)
7414 				break;
7415 			connp = connp->conn_next;
7416 		}
7417 
7418 		if (connp != NULL && is_system_labeled() &&
7419 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7420 		    connp))
7421 			connp = NULL;
7422 
7423 		if (connp == NULL ||
7424 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7425 			/*
7426 			 * No one bound to this port.  Is
7427 			 * there a client that wants all
7428 			 * unclaimed datagrams?
7429 			 */
7430 			mutex_exit(&connfp->connf_lock);
7431 
7432 			if (mctl_present)
7433 				first_mp->b_cont = mp;
7434 			else
7435 				first_mp = mp;
7436 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7437 			    connf_head != NULL) {
7438 				ip_fanout_proto(q, first_mp, ill, ipha,
7439 				    flags | IP_FF_RAWIP, mctl_present,
7440 				    ip_policy, recv_ill, zoneid);
7441 			} else {
7442 				if (ip_fanout_send_icmp(q, first_mp, flags,
7443 				    ICMP_DEST_UNREACHABLE,
7444 				    ICMP_PORT_UNREACHABLE,
7445 				    mctl_present, zoneid, ipst)) {
7446 					BUMP_MIB(ill->ill_ip_mib,
7447 					    udpIfStatsNoPorts);
7448 				}
7449 			}
7450 			return;
7451 		}
7452 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7453 
7454 		CONN_INC_REF(connp);
7455 		mutex_exit(&connfp->connf_lock);
7456 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7457 		    flags, recv_ill, ip_policy);
7458 		CONN_DEC_REF(connp);
7459 		return;
7460 	}
7461 	/*
7462 	 * IPv4 multicast packet being delivered to an AF_INET6
7463 	 * in6addr_any endpoint.
7464 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7465 	 * and not conn_wantpacket_v6() since any multicast membership is
7466 	 * for an IPv4-mapped multicast address.
7467 	 * The packet is sent to all clients in all zones that have joined the
7468 	 * group and match the port.
7469 	 */
7470 	while (connp != NULL) {
7471 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7472 		    srcport, v6src) &&
7473 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7474 		    (!is_system_labeled() ||
7475 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7476 		    connp)))
7477 			break;
7478 		connp = connp->conn_next;
7479 	}
7480 
7481 	if (connp == NULL ||
7482 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7483 		/*
7484 		 * No one bound to this port.  Is
7485 		 * there a client that wants all
7486 		 * unclaimed datagrams?
7487 		 */
7488 		mutex_exit(&connfp->connf_lock);
7489 
7490 		if (mctl_present)
7491 			first_mp->b_cont = mp;
7492 		else
7493 			first_mp = mp;
7494 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7495 		    NULL) {
7496 			ip_fanout_proto(q, first_mp, ill, ipha,
7497 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7498 			    recv_ill, zoneid);
7499 		} else {
7500 			/*
7501 			 * We used to attempt to send an icmp error here, but
7502 			 * since this is known to be a multicast packet
7503 			 * and we don't send icmp errors in response to
7504 			 * multicast, just drop the packet and give up sooner.
7505 			 */
7506 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7507 			freemsg(first_mp);
7508 		}
7509 		return;
7510 	}
7511 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7512 
7513 	first_connp = connp;
7514 
7515 	CONN_INC_REF(connp);
7516 	connp = connp->conn_next;
7517 	for (;;) {
7518 		while (connp != NULL) {
7519 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7520 			    ipv6_all_zeros, srcport, v6src) &&
7521 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7522 			    (!is_system_labeled() ||
7523 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7524 			    shared_addr, connp)))
7525 				break;
7526 			connp = connp->conn_next;
7527 		}
7528 		/*
7529 		 * Just copy the data part alone. The mctl part is
7530 		 * needed just for verifying policy and it is never
7531 		 * sent up.
7532 		 */
7533 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7534 		    ((mp1 = copymsg(mp)) == NULL))) {
7535 			/*
7536 			 * No more intested clients or memory
7537 			 * allocation failed
7538 			 */
7539 			connp = first_connp;
7540 			break;
7541 		}
7542 		if (first_mp != NULL) {
7543 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7544 			    ipsec_info_type == IPSEC_IN);
7545 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7546 			    ipst->ips_netstack);
7547 			if (first_mp1 == NULL) {
7548 				freemsg(mp1);
7549 				connp = first_connp;
7550 				break;
7551 			}
7552 		} else {
7553 			first_mp1 = NULL;
7554 		}
7555 		CONN_INC_REF(connp);
7556 		mutex_exit(&connfp->connf_lock);
7557 		/*
7558 		 * IPQoS notes: We don't send the packet for policy
7559 		 * processing here, will do it for the last one (below).
7560 		 * i.e. we do it per-packet now, but if we do policy
7561 		 * processing per-conn, then we would need to do it
7562 		 * here too.
7563 		 */
7564 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7565 		    ipha, flags, recv_ill, B_FALSE);
7566 		mutex_enter(&connfp->connf_lock);
7567 		/* Follow the next pointer before releasing the conn. */
7568 		next_connp = connp->conn_next;
7569 		CONN_DEC_REF(connp);
7570 		connp = next_connp;
7571 	}
7572 
7573 	/* Last one.  Send it upstream. */
7574 	mutex_exit(&connfp->connf_lock);
7575 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7576 	    recv_ill, ip_policy);
7577 	CONN_DEC_REF(connp);
7578 }
7579 
7580 /*
7581  * Complete the ip_wput header so that it
7582  * is possible to generate ICMP
7583  * errors.
7584  */
7585 int
7586 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7587 {
7588 	ire_t *ire;
7589 
7590 	if (ipha->ipha_src == INADDR_ANY) {
7591 		ire = ire_lookup_local(zoneid, ipst);
7592 		if (ire == NULL) {
7593 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7594 			return (1);
7595 		}
7596 		ipha->ipha_src = ire->ire_addr;
7597 		ire_refrele(ire);
7598 	}
7599 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7600 	ipha->ipha_hdr_checksum = 0;
7601 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7602 	return (0);
7603 }
7604 
7605 /*
7606  * Nobody should be sending
7607  * packets up this stream
7608  */
7609 static void
7610 ip_lrput(queue_t *q, mblk_t *mp)
7611 {
7612 	mblk_t *mp1;
7613 
7614 	switch (mp->b_datap->db_type) {
7615 	case M_FLUSH:
7616 		/* Turn around */
7617 		if (*mp->b_rptr & FLUSHW) {
7618 			*mp->b_rptr &= ~FLUSHR;
7619 			qreply(q, mp);
7620 			return;
7621 		}
7622 		break;
7623 	}
7624 	/* Could receive messages that passed through ar_rput */
7625 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7626 		mp1->b_prev = mp1->b_next = NULL;
7627 	freemsg(mp);
7628 }
7629 
7630 /* Nobody should be sending packets down this stream */
7631 /* ARGSUSED */
7632 void
7633 ip_lwput(queue_t *q, mblk_t *mp)
7634 {
7635 	freemsg(mp);
7636 }
7637 
7638 /*
7639  * Move the first hop in any source route to ipha_dst and remove that part of
7640  * the source route.  Called by other protocols.  Errors in option formatting
7641  * are ignored - will be handled by ip_wput_options Return the final
7642  * destination (either ipha_dst or the last entry in a source route.)
7643  */
7644 ipaddr_t
7645 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7646 {
7647 	ipoptp_t	opts;
7648 	uchar_t		*opt;
7649 	uint8_t		optval;
7650 	uint8_t		optlen;
7651 	ipaddr_t	dst;
7652 	int		i;
7653 	ire_t		*ire;
7654 	ip_stack_t	*ipst = ns->netstack_ip;
7655 
7656 	ip2dbg(("ip_massage_options\n"));
7657 	dst = ipha->ipha_dst;
7658 	for (optval = ipoptp_first(&opts, ipha);
7659 	    optval != IPOPT_EOL;
7660 	    optval = ipoptp_next(&opts)) {
7661 		opt = opts.ipoptp_cur;
7662 		switch (optval) {
7663 			uint8_t off;
7664 		case IPOPT_SSRR:
7665 		case IPOPT_LSRR:
7666 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7667 				ip1dbg(("ip_massage_options: bad src route\n"));
7668 				break;
7669 			}
7670 			optlen = opts.ipoptp_len;
7671 			off = opt[IPOPT_OFFSET];
7672 			off--;
7673 		redo_srr:
7674 			if (optlen < IP_ADDR_LEN ||
7675 			    off > optlen - IP_ADDR_LEN) {
7676 				/* End of source route */
7677 				ip1dbg(("ip_massage_options: end of SR\n"));
7678 				break;
7679 			}
7680 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7681 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7682 			    ntohl(dst)));
7683 			/*
7684 			 * Check if our address is present more than
7685 			 * once as consecutive hops in source route.
7686 			 * XXX verify per-interface ip_forwarding
7687 			 * for source route?
7688 			 */
7689 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7690 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7691 			if (ire != NULL) {
7692 				ire_refrele(ire);
7693 				off += IP_ADDR_LEN;
7694 				goto redo_srr;
7695 			}
7696 			if (dst == htonl(INADDR_LOOPBACK)) {
7697 				ip1dbg(("ip_massage_options: loopback addr in "
7698 				    "source route!\n"));
7699 				break;
7700 			}
7701 			/*
7702 			 * Update ipha_dst to be the first hop and remove the
7703 			 * first hop from the source route (by overwriting
7704 			 * part of the option with NOP options).
7705 			 */
7706 			ipha->ipha_dst = dst;
7707 			/* Put the last entry in dst */
7708 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7709 			    3;
7710 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7711 
7712 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7713 			    ntohl(dst)));
7714 			/* Move down and overwrite */
7715 			opt[IP_ADDR_LEN] = opt[0];
7716 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7717 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7718 			for (i = 0; i < IP_ADDR_LEN; i++)
7719 				opt[i] = IPOPT_NOP;
7720 			break;
7721 		}
7722 	}
7723 	return (dst);
7724 }
7725 
7726 /*
7727  * Return the network mask
7728  * associated with the specified address.
7729  */
7730 ipaddr_t
7731 ip_net_mask(ipaddr_t addr)
7732 {
7733 	uchar_t	*up = (uchar_t *)&addr;
7734 	ipaddr_t mask = 0;
7735 	uchar_t	*maskp = (uchar_t *)&mask;
7736 
7737 #if defined(__i386) || defined(__amd64)
7738 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7739 #endif
7740 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7741 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7742 #endif
7743 	if (CLASSD(addr)) {
7744 		maskp[0] = 0xF0;
7745 		return (mask);
7746 	}
7747 
7748 	/* We assume Class E default netmask to be 32 */
7749 	if (CLASSE(addr))
7750 		return (0xffffffffU);
7751 
7752 	if (addr == 0)
7753 		return (0);
7754 	maskp[0] = 0xFF;
7755 	if ((up[0] & 0x80) == 0)
7756 		return (mask);
7757 
7758 	maskp[1] = 0xFF;
7759 	if ((up[0] & 0xC0) == 0x80)
7760 		return (mask);
7761 
7762 	maskp[2] = 0xFF;
7763 	if ((up[0] & 0xE0) == 0xC0)
7764 		return (mask);
7765 
7766 	/* Otherwise return no mask */
7767 	return ((ipaddr_t)0);
7768 }
7769 
7770 /*
7771  * Helper ill lookup function used by IPsec.
7772  */
7773 ill_t *
7774 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7775 {
7776 	ill_t *ret_ill;
7777 
7778 	ASSERT(ifindex != 0);
7779 
7780 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7781 	    ipst);
7782 	if (ret_ill == NULL) {
7783 		if (isv6) {
7784 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7785 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7786 			    ifindex));
7787 		} else {
7788 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7789 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7790 			    ifindex));
7791 		}
7792 		freemsg(first_mp);
7793 		return (NULL);
7794 	}
7795 	return (ret_ill);
7796 }
7797 
7798 /*
7799  * IPv4 -
7800  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7801  * out a packet to a destination address for which we do not have specific
7802  * (or sufficient) routing information.
7803  *
7804  * NOTE : These are the scopes of some of the variables that point at IRE,
7805  *	  which needs to be followed while making any future modifications
7806  *	  to avoid memory leaks.
7807  *
7808  *	- ire and sire are the entries looked up initially by
7809  *	  ire_ftable_lookup.
7810  *	- ipif_ire is used to hold the interface ire associated with
7811  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7812  *	  it before branching out to error paths.
7813  *	- save_ire is initialized before ire_create, so that ire returned
7814  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7815  *	  before breaking out of the switch.
7816  *
7817  *	Thus on failures, we have to REFRELE only ire and sire, if they
7818  *	are not NULL.
7819  */
7820 void
7821 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7822     zoneid_t zoneid, ip_stack_t *ipst)
7823 {
7824 	areq_t	*areq;
7825 	ipaddr_t gw = 0;
7826 	ire_t	*ire = NULL;
7827 	mblk_t	*res_mp;
7828 	ipaddr_t *addrp;
7829 	ipaddr_t nexthop_addr;
7830 	ipif_t  *src_ipif = NULL;
7831 	ill_t	*dst_ill = NULL;
7832 	ipha_t  *ipha;
7833 	ire_t	*sire = NULL;
7834 	mblk_t	*first_mp;
7835 	ire_t	*save_ire;
7836 	ushort_t ire_marks = 0;
7837 	boolean_t mctl_present;
7838 	ipsec_out_t *io;
7839 	mblk_t	*saved_mp;
7840 	mblk_t	*copy_mp = NULL;
7841 	mblk_t	*xmit_mp = NULL;
7842 	ipaddr_t save_dst;
7843 	uint32_t multirt_flags =
7844 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7845 	boolean_t multirt_is_resolvable;
7846 	boolean_t multirt_resolve_next;
7847 	boolean_t unspec_src;
7848 	boolean_t ip_nexthop = B_FALSE;
7849 	tsol_ire_gw_secattr_t *attrp = NULL;
7850 	tsol_gcgrp_t *gcgrp = NULL;
7851 	tsol_gcgrp_addr_t ga;
7852 	int multirt_res_failures = 0;
7853 	int multirt_res_attempts = 0;
7854 	int multirt_already_resolved = 0;
7855 	boolean_t multirt_no_icmp_error = B_FALSE;
7856 
7857 	if (ip_debug > 2) {
7858 		/* ip1dbg */
7859 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7860 	}
7861 
7862 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7863 	if (mctl_present) {
7864 		io = (ipsec_out_t *)first_mp->b_rptr;
7865 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7866 		ASSERT(zoneid == io->ipsec_out_zoneid);
7867 		ASSERT(zoneid != ALL_ZONES);
7868 	}
7869 
7870 	ipha = (ipha_t *)mp->b_rptr;
7871 
7872 	/* All multicast lookups come through ip_newroute_ipif() */
7873 	if (CLASSD(dst)) {
7874 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7875 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7876 		freemsg(first_mp);
7877 		return;
7878 	}
7879 
7880 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7881 		ip_nexthop = B_TRUE;
7882 		nexthop_addr = io->ipsec_out_nexthop_addr;
7883 	}
7884 	/*
7885 	 * If this IRE is created for forwarding or it is not for
7886 	 * traffic for congestion controlled protocols, mark it as temporary.
7887 	 */
7888 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7889 		ire_marks |= IRE_MARK_TEMPORARY;
7890 
7891 	/*
7892 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7893 	 * chain until it gets the most specific information available.
7894 	 * For example, we know that there is no IRE_CACHE for this dest,
7895 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7896 	 * ire_ftable_lookup will look up the gateway, etc.
7897 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7898 	 * to the destination, of equal netmask length in the forward table,
7899 	 * will be recursively explored. If no information is available
7900 	 * for the final gateway of that route, we force the returned ire
7901 	 * to be equal to sire using MATCH_IRE_PARENT.
7902 	 * At least, in this case we have a starting point (in the buckets)
7903 	 * to look for other routes to the destination in the forward table.
7904 	 * This is actually used only for multirouting, where a list
7905 	 * of routes has to be processed in sequence.
7906 	 *
7907 	 * In the process of coming up with the most specific information,
7908 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7909 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7910 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7911 	 * Two caveats when handling incomplete ire's in ip_newroute:
7912 	 * - we should be careful when accessing its ire_nce (specifically
7913 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7914 	 * - not all legacy code path callers are prepared to handle
7915 	 *   incomplete ire's, so we should not create/add incomplete
7916 	 *   ire_cache entries here. (See discussion about temporary solution
7917 	 *   further below).
7918 	 *
7919 	 * In order to minimize packet dropping, and to preserve existing
7920 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7921 	 * gateway, and instead use the IF_RESOLVER ire to send out
7922 	 * another request to ARP (this is achieved by passing the
7923 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7924 	 * arp response comes back in ip_wput_nondata, we will create
7925 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7926 	 *
7927 	 * Note that this is a temporary solution; the correct solution is
7928 	 * to create an incomplete  per-dst ire_cache entry, and send the
7929 	 * packet out when the gw's nce is resolved. In order to achieve this,
7930 	 * all packet processing must have been completed prior to calling
7931 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7932 	 * to be modified to accomodate this solution.
7933 	 */
7934 	if (ip_nexthop) {
7935 		/*
7936 		 * The first time we come here, we look for an IRE_INTERFACE
7937 		 * entry for the specified nexthop, set the dst to be the
7938 		 * nexthop address and create an IRE_CACHE entry for the
7939 		 * nexthop. The next time around, we are able to find an
7940 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7941 		 * nexthop address and create an IRE_CACHE entry for the
7942 		 * destination address via the specified nexthop.
7943 		 */
7944 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7945 		    msg_getlabel(mp), ipst);
7946 		if (ire != NULL) {
7947 			gw = nexthop_addr;
7948 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7949 		} else {
7950 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7951 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7952 			    msg_getlabel(mp),
7953 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7954 			    ipst);
7955 			if (ire != NULL) {
7956 				dst = nexthop_addr;
7957 			}
7958 		}
7959 	} else {
7960 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7961 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
7962 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7963 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7964 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7965 		    ipst);
7966 	}
7967 
7968 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7969 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7970 
7971 	/*
7972 	 * This loop is run only once in most cases.
7973 	 * We loop to resolve further routes only when the destination
7974 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7975 	 */
7976 	do {
7977 		/* Clear the previous iteration's values */
7978 		if (src_ipif != NULL) {
7979 			ipif_refrele(src_ipif);
7980 			src_ipif = NULL;
7981 		}
7982 		if (dst_ill != NULL) {
7983 			ill_refrele(dst_ill);
7984 			dst_ill = NULL;
7985 		}
7986 
7987 		multirt_resolve_next = B_FALSE;
7988 		/*
7989 		 * We check if packets have to be multirouted.
7990 		 * In this case, given the current <ire, sire> couple,
7991 		 * we look for the next suitable <ire, sire>.
7992 		 * This check is done in ire_multirt_lookup(),
7993 		 * which applies various criteria to find the next route
7994 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7995 		 * unchanged if it detects it has not been tried yet.
7996 		 */
7997 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7998 			ip3dbg(("ip_newroute: starting next_resolution "
7999 			    "with first_mp %p, tag %d\n",
8000 			    (void *)first_mp,
8001 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8002 
8003 			ASSERT(sire != NULL);
8004 			multirt_is_resolvable =
8005 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8006 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
8007 
8008 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8009 			    "multirt_already_resolved %d, "
8010 			    "multirt_res_attempts %d, multirt_res_failures %d, "
8011 			    "ire %p, sire %p\n", multirt_is_resolvable,
8012 			    multirt_already_resolved, multirt_res_attempts,
8013 			    multirt_res_failures, (void *)ire, (void *)sire));
8014 
8015 			if (!multirt_is_resolvable) {
8016 				/*
8017 				 * No more multirt route to resolve; give up
8018 				 * (all routes resolved or no more
8019 				 * resolvable routes).
8020 				 */
8021 				if (ire != NULL) {
8022 					ire_refrele(ire);
8023 					ire = NULL;
8024 				}
8025 				/*
8026 				 * Generate ICMP error only if all attempts to
8027 				 * resolve multirt route failed and there is no
8028 				 * already resolved one.  Don't generate ICMP
8029 				 * error when:
8030 				 *
8031 				 *  1) there was no attempt to resolve
8032 				 *  2) at least one attempt passed
8033 				 *  3) a multirt route is already resolved
8034 				 *
8035 				 *  Case 1) may occur due to multiple
8036 				 *    resolution attempts during single
8037 				 *    ip_multirt_resolution_interval.
8038 				 *
8039 				 *  Case 2-3) means that CGTP destination is
8040 				 *    reachable via one link so we don't want to
8041 				 *    generate ICMP host unreachable error.
8042 				 */
8043 				if (multirt_res_attempts == 0 ||
8044 				    multirt_res_failures <
8045 				    multirt_res_attempts ||
8046 				    multirt_already_resolved > 0)
8047 					multirt_no_icmp_error = B_TRUE;
8048 			} else {
8049 				ASSERT(sire != NULL);
8050 				ASSERT(ire != NULL);
8051 
8052 				multirt_res_attempts++;
8053 			}
8054 		}
8055 
8056 		if (ire == NULL) {
8057 			if (ip_debug > 3) {
8058 				/* ip2dbg */
8059 				pr_addr_dbg("ip_newroute: "
8060 				    "can't resolve %s\n", AF_INET, &dst);
8061 			}
8062 			ip3dbg(("ip_newroute: "
8063 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8064 			    (void *)ire, (void *)sire,
8065 			    (int)multirt_no_icmp_error));
8066 
8067 			if (sire != NULL) {
8068 				ire_refrele(sire);
8069 				sire = NULL;
8070 			}
8071 
8072 			if (multirt_no_icmp_error) {
8073 				/* There is no need to report an ICMP error. */
8074 				MULTIRT_DEBUG_UNTAG(first_mp);
8075 				freemsg(first_mp);
8076 				return;
8077 			}
8078 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8079 			    RTA_DST, ipst);
8080 			goto icmp_err_ret;
8081 		}
8082 
8083 		/*
8084 		 * Verify that the returned IRE does not have either
8085 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8086 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8087 		 */
8088 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8089 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8090 			goto icmp_err_ret;
8091 		}
8092 		/*
8093 		 * Increment the ire_ob_pkt_count field for ire if it is an
8094 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8095 		 * increment the same for the parent IRE, sire, if it is some
8096 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8097 		 */
8098 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8099 			UPDATE_OB_PKT_COUNT(ire);
8100 			ire->ire_last_used_time = lbolt;
8101 		}
8102 
8103 		if (sire != NULL) {
8104 			gw = sire->ire_gateway_addr;
8105 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8106 			    IRE_INTERFACE)) == 0);
8107 			UPDATE_OB_PKT_COUNT(sire);
8108 			sire->ire_last_used_time = lbolt;
8109 		}
8110 		/*
8111 		 * We have a route to reach the destination.  Find the
8112 		 * appropriate ill, then get a source address using
8113 		 * ipif_select_source().
8114 		 *
8115 		 * If we are here trying to create an IRE_CACHE for an offlink
8116 		 * destination and have an IRE_CACHE entry for VNI, then use
8117 		 * ire_stq instead since VNI's queue is a black hole.
8118 		 */
8119 		if ((ire->ire_type == IRE_CACHE) &&
8120 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8121 			dst_ill = ire->ire_stq->q_ptr;
8122 			ill_refhold(dst_ill);
8123 		} else {
8124 			ill_t *ill = ire->ire_ipif->ipif_ill;
8125 
8126 			if (IS_IPMP(ill)) {
8127 				dst_ill =
8128 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8129 			} else {
8130 				dst_ill = ill;
8131 				ill_refhold(dst_ill);
8132 			}
8133 		}
8134 
8135 		if (dst_ill == NULL) {
8136 			if (ip_debug > 2) {
8137 				pr_addr_dbg("ip_newroute: no dst "
8138 				    "ill for dst %s\n", AF_INET, &dst);
8139 			}
8140 			goto icmp_err_ret;
8141 		}
8142 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8143 
8144 		/*
8145 		 * Pick the best source address from dst_ill.
8146 		 *
8147 		 * 1) Try to pick the source address from the destination
8148 		 *    route. Clustering assumes that when we have multiple
8149 		 *    prefixes hosted on an interface, the prefix of the
8150 		 *    source address matches the prefix of the destination
8151 		 *    route. We do this only if the address is not
8152 		 *    DEPRECATED.
8153 		 *
8154 		 * 2) If the conn is in a different zone than the ire, we
8155 		 *    need to pick a source address from the right zone.
8156 		 */
8157 		ASSERT(src_ipif == NULL);
8158 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8159 			/*
8160 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8161 			 * Check that the ipif matching the requested source
8162 			 * address still exists.
8163 			 */
8164 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8165 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8166 		}
8167 
8168 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8169 
8170 		if (src_ipif == NULL &&
8171 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8172 			ire_marks |= IRE_MARK_USESRC_CHECK;
8173 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8174 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8175 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8176 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8177 			    ire->ire_zoneid != ALL_ZONES) ||
8178 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8179 				/*
8180 				 * If the destination is reachable via a
8181 				 * given gateway, the selected source address
8182 				 * should be in the same subnet as the gateway.
8183 				 * Otherwise, the destination is not reachable.
8184 				 *
8185 				 * If there are no interfaces on the same subnet
8186 				 * as the destination, ipif_select_source gives
8187 				 * first non-deprecated interface which might be
8188 				 * on a different subnet than the gateway.
8189 				 * This is not desirable. Hence pass the dst_ire
8190 				 * source address to ipif_select_source.
8191 				 * It is sure that the destination is reachable
8192 				 * with the dst_ire source address subnet.
8193 				 * So passing dst_ire source address to
8194 				 * ipif_select_source will make sure that the
8195 				 * selected source will be on the same subnet
8196 				 * as dst_ire source address.
8197 				 */
8198 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8199 
8200 				src_ipif = ipif_select_source(dst_ill, saddr,
8201 				    zoneid);
8202 				if (src_ipif == NULL) {
8203 					/*
8204 					 * In the case of multirouting, it may
8205 					 * happen that ipif_select_source fails
8206 					 * as DAD may disallow use of the
8207 					 * particular source interface.  Anyway,
8208 					 * we need to continue and attempt to
8209 					 * resolve other multirt routes.
8210 					 */
8211 					if ((sire != NULL) &&
8212 					    (sire->ire_flags & RTF_MULTIRT)) {
8213 						ire_refrele(ire);
8214 						ire = NULL;
8215 						multirt_resolve_next = B_TRUE;
8216 						multirt_res_failures++;
8217 						continue;
8218 					}
8219 
8220 					if (ip_debug > 2) {
8221 						pr_addr_dbg("ip_newroute: "
8222 						    "no src for dst %s ",
8223 						    AF_INET, &dst);
8224 						printf("on interface %s\n",
8225 						    dst_ill->ill_name);
8226 					}
8227 					goto icmp_err_ret;
8228 				}
8229 			} else {
8230 				src_ipif = ire->ire_ipif;
8231 				ASSERT(src_ipif != NULL);
8232 				/* hold src_ipif for uniformity */
8233 				ipif_refhold(src_ipif);
8234 			}
8235 		}
8236 
8237 		/*
8238 		 * Assign a source address while we have the conn.
8239 		 * We can't have ip_wput_ire pick a source address when the
8240 		 * packet returns from arp since we need to look at
8241 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8242 		 * going through arp.
8243 		 *
8244 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8245 		 *	  it uses ip6i to store this information.
8246 		 */
8247 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8248 			ipha->ipha_src = src_ipif->ipif_src_addr;
8249 
8250 		if (ip_debug > 3) {
8251 			/* ip2dbg */
8252 			pr_addr_dbg("ip_newroute: first hop %s\n",
8253 			    AF_INET, &gw);
8254 		}
8255 		ip2dbg(("\tire type %s (%d)\n",
8256 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8257 
8258 		/*
8259 		 * The TTL of multirouted packets is bounded by the
8260 		 * ip_multirt_ttl ndd variable.
8261 		 */
8262 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8263 			/* Force TTL of multirouted packets */
8264 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8265 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8266 				ip2dbg(("ip_newroute: forcing multirt TTL "
8267 				    "to %d (was %d), dst 0x%08x\n",
8268 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8269 				    ntohl(sire->ire_addr)));
8270 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8271 			}
8272 		}
8273 		/*
8274 		 * At this point in ip_newroute(), ire is either the
8275 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8276 		 * destination or an IRE_INTERFACE type that should be used
8277 		 * to resolve an on-subnet destination or an on-subnet
8278 		 * next-hop gateway.
8279 		 *
8280 		 * In the IRE_CACHE case, we have the following :
8281 		 *
8282 		 * 1) src_ipif - used for getting a source address.
8283 		 *
8284 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8285 		 *    means packets using this IRE_CACHE will go out on
8286 		 *    dst_ill.
8287 		 *
8288 		 * 3) The IRE sire will point to the prefix that is the
8289 		 *    longest  matching route for the destination. These
8290 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8291 		 *
8292 		 *    The newly created IRE_CACHE entry for the off-subnet
8293 		 *    destination is tied to both the prefix route and the
8294 		 *    interface route used to resolve the next-hop gateway
8295 		 *    via the ire_phandle and ire_ihandle fields,
8296 		 *    respectively.
8297 		 *
8298 		 * In the IRE_INTERFACE case, we have the following :
8299 		 *
8300 		 * 1) src_ipif - used for getting a source address.
8301 		 *
8302 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8303 		 *    means packets using the IRE_CACHE that we will build
8304 		 *    here will go out on dst_ill.
8305 		 *
8306 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8307 		 *    to be created will only be tied to the IRE_INTERFACE
8308 		 *    that was derived from the ire_ihandle field.
8309 		 *
8310 		 *    If sire is non-NULL, it means the destination is
8311 		 *    off-link and we will first create the IRE_CACHE for the
8312 		 *    gateway. Next time through ip_newroute, we will create
8313 		 *    the IRE_CACHE for the final destination as described
8314 		 *    above.
8315 		 *
8316 		 * In both cases, after the current resolution has been
8317 		 * completed (or possibly initialised, in the IRE_INTERFACE
8318 		 * case), the loop may be re-entered to attempt the resolution
8319 		 * of another RTF_MULTIRT route.
8320 		 *
8321 		 * When an IRE_CACHE entry for the off-subnet destination is
8322 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8323 		 * for further processing in emission loops.
8324 		 */
8325 		save_ire = ire;
8326 		switch (ire->ire_type) {
8327 		case IRE_CACHE: {
8328 			ire_t	*ipif_ire;
8329 
8330 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8331 			if (gw == 0)
8332 				gw = ire->ire_gateway_addr;
8333 			/*
8334 			 * We need 3 ire's to create a new cache ire for an
8335 			 * off-link destination from the cache ire of the
8336 			 * gateway.
8337 			 *
8338 			 *	1. The prefix ire 'sire' (Note that this does
8339 			 *	   not apply to the conn_nexthop_set case)
8340 			 *	2. The cache ire of the gateway 'ire'
8341 			 *	3. The interface ire 'ipif_ire'
8342 			 *
8343 			 * We have (1) and (2). We lookup (3) below.
8344 			 *
8345 			 * If there is no interface route to the gateway,
8346 			 * it is a race condition, where we found the cache
8347 			 * but the interface route has been deleted.
8348 			 */
8349 			if (ip_nexthop) {
8350 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8351 			} else {
8352 				ipif_ire =
8353 				    ire_ihandle_lookup_offlink(ire, sire);
8354 			}
8355 			if (ipif_ire == NULL) {
8356 				ip1dbg(("ip_newroute: "
8357 				    "ire_ihandle_lookup_offlink failed\n"));
8358 				goto icmp_err_ret;
8359 			}
8360 
8361 			/*
8362 			 * Check cached gateway IRE for any security
8363 			 * attributes; if found, associate the gateway
8364 			 * credentials group to the destination IRE.
8365 			 */
8366 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8367 				mutex_enter(&attrp->igsa_lock);
8368 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8369 					GCGRP_REFHOLD(gcgrp);
8370 				mutex_exit(&attrp->igsa_lock);
8371 			}
8372 
8373 			/*
8374 			 * XXX For the source of the resolver mp,
8375 			 * we are using the same DL_UNITDATA_REQ
8376 			 * (from save_ire->ire_nce->nce_res_mp)
8377 			 * though the save_ire is not pointing at the same ill.
8378 			 * This is incorrect. We need to send it up to the
8379 			 * resolver to get the right res_mp. For ethernets
8380 			 * this may be okay (ill_type == DL_ETHER).
8381 			 */
8382 
8383 			ire = ire_create(
8384 			    (uchar_t *)&dst,		/* dest address */
8385 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8386 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8387 			    (uchar_t *)&gw,		/* gateway address */
8388 			    &save_ire->ire_max_frag,
8389 			    save_ire->ire_nce,		/* src nce */
8390 			    dst_ill->ill_rq,		/* recv-from queue */
8391 			    dst_ill->ill_wq,		/* send-to queue */
8392 			    IRE_CACHE,			/* IRE type */
8393 			    src_ipif,
8394 			    (sire != NULL) ?
8395 			    sire->ire_mask : 0, 	/* Parent mask */
8396 			    (sire != NULL) ?
8397 			    sire->ire_phandle : 0,	/* Parent handle */
8398 			    ipif_ire->ire_ihandle,	/* Interface handle */
8399 			    (sire != NULL) ? (sire->ire_flags &
8400 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8401 			    (sire != NULL) ?
8402 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8403 			    NULL,
8404 			    gcgrp,
8405 			    ipst);
8406 
8407 			if (ire == NULL) {
8408 				if (gcgrp != NULL) {
8409 					GCGRP_REFRELE(gcgrp);
8410 					gcgrp = NULL;
8411 				}
8412 				ire_refrele(ipif_ire);
8413 				ire_refrele(save_ire);
8414 				break;
8415 			}
8416 
8417 			/* reference now held by IRE */
8418 			gcgrp = NULL;
8419 
8420 			ire->ire_marks |= ire_marks;
8421 
8422 			/*
8423 			 * Prevent sire and ipif_ire from getting deleted.
8424 			 * The newly created ire is tied to both of them via
8425 			 * the phandle and ihandle respectively.
8426 			 */
8427 			if (sire != NULL) {
8428 				IRB_REFHOLD(sire->ire_bucket);
8429 				/* Has it been removed already ? */
8430 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8431 					IRB_REFRELE(sire->ire_bucket);
8432 					ire_refrele(ipif_ire);
8433 					ire_refrele(save_ire);
8434 					break;
8435 				}
8436 			}
8437 
8438 			IRB_REFHOLD(ipif_ire->ire_bucket);
8439 			/* Has it been removed already ? */
8440 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8441 				IRB_REFRELE(ipif_ire->ire_bucket);
8442 				if (sire != NULL)
8443 					IRB_REFRELE(sire->ire_bucket);
8444 				ire_refrele(ipif_ire);
8445 				ire_refrele(save_ire);
8446 				break;
8447 			}
8448 
8449 			xmit_mp = first_mp;
8450 			/*
8451 			 * In the case of multirouting, a copy
8452 			 * of the packet is done before its sending.
8453 			 * The copy is used to attempt another
8454 			 * route resolution, in a next loop.
8455 			 */
8456 			if (ire->ire_flags & RTF_MULTIRT) {
8457 				copy_mp = copymsg(first_mp);
8458 				if (copy_mp != NULL) {
8459 					xmit_mp = copy_mp;
8460 					MULTIRT_DEBUG_TAG(first_mp);
8461 				}
8462 			}
8463 
8464 			ire_add_then_send(q, ire, xmit_mp);
8465 			ire_refrele(save_ire);
8466 
8467 			/* Assert that sire is not deleted yet. */
8468 			if (sire != NULL) {
8469 				ASSERT(sire->ire_ptpn != NULL);
8470 				IRB_REFRELE(sire->ire_bucket);
8471 			}
8472 
8473 			/* Assert that ipif_ire is not deleted yet. */
8474 			ASSERT(ipif_ire->ire_ptpn != NULL);
8475 			IRB_REFRELE(ipif_ire->ire_bucket);
8476 			ire_refrele(ipif_ire);
8477 
8478 			/*
8479 			 * If copy_mp is not NULL, multirouting was
8480 			 * requested. We loop to initiate a next
8481 			 * route resolution attempt, starting from sire.
8482 			 */
8483 			if (copy_mp != NULL) {
8484 				/*
8485 				 * Search for the next unresolved
8486 				 * multirt route.
8487 				 */
8488 				copy_mp = NULL;
8489 				ipif_ire = NULL;
8490 				ire = NULL;
8491 				multirt_resolve_next = B_TRUE;
8492 				continue;
8493 			}
8494 			if (sire != NULL)
8495 				ire_refrele(sire);
8496 			ipif_refrele(src_ipif);
8497 			ill_refrele(dst_ill);
8498 			return;
8499 		}
8500 		case IRE_IF_NORESOLVER: {
8501 			if (dst_ill->ill_resolver_mp == NULL) {
8502 				ip1dbg(("ip_newroute: dst_ill %p "
8503 				    "for IRE_IF_NORESOLVER ire %p has "
8504 				    "no ill_resolver_mp\n",
8505 				    (void *)dst_ill, (void *)ire));
8506 				break;
8507 			}
8508 
8509 			/*
8510 			 * TSol note: We are creating the ire cache for the
8511 			 * destination 'dst'. If 'dst' is offlink, going
8512 			 * through the first hop 'gw', the security attributes
8513 			 * of 'dst' must be set to point to the gateway
8514 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8515 			 * is possible that 'dst' is a potential gateway that is
8516 			 * referenced by some route that has some security
8517 			 * attributes. Thus in the former case, we need to do a
8518 			 * gcgrp_lookup of 'gw' while in the latter case we
8519 			 * need to do gcgrp_lookup of 'dst' itself.
8520 			 */
8521 			ga.ga_af = AF_INET;
8522 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8523 			    &ga.ga_addr);
8524 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8525 
8526 			ire = ire_create(
8527 			    (uchar_t *)&dst,		/* dest address */
8528 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8529 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8530 			    (uchar_t *)&gw,		/* gateway address */
8531 			    &save_ire->ire_max_frag,
8532 			    NULL,			/* no src nce */
8533 			    dst_ill->ill_rq,		/* recv-from queue */
8534 			    dst_ill->ill_wq,		/* send-to queue */
8535 			    IRE_CACHE,
8536 			    src_ipif,
8537 			    save_ire->ire_mask,		/* Parent mask */
8538 			    (sire != NULL) ?		/* Parent handle */
8539 			    sire->ire_phandle : 0,
8540 			    save_ire->ire_ihandle,	/* Interface handle */
8541 			    (sire != NULL) ? sire->ire_flags &
8542 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8543 			    &(save_ire->ire_uinfo),
8544 			    NULL,
8545 			    gcgrp,
8546 			    ipst);
8547 
8548 			if (ire == NULL) {
8549 				if (gcgrp != NULL) {
8550 					GCGRP_REFRELE(gcgrp);
8551 					gcgrp = NULL;
8552 				}
8553 				ire_refrele(save_ire);
8554 				break;
8555 			}
8556 
8557 			/* reference now held by IRE */
8558 			gcgrp = NULL;
8559 
8560 			ire->ire_marks |= ire_marks;
8561 
8562 			/* Prevent save_ire from getting deleted */
8563 			IRB_REFHOLD(save_ire->ire_bucket);
8564 			/* Has it been removed already ? */
8565 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8566 				IRB_REFRELE(save_ire->ire_bucket);
8567 				ire_refrele(save_ire);
8568 				break;
8569 			}
8570 
8571 			/*
8572 			 * In the case of multirouting, a copy
8573 			 * of the packet is made before it is sent.
8574 			 * The copy is used in the next
8575 			 * loop to attempt another resolution.
8576 			 */
8577 			xmit_mp = first_mp;
8578 			if ((sire != NULL) &&
8579 			    (sire->ire_flags & RTF_MULTIRT)) {
8580 				copy_mp = copymsg(first_mp);
8581 				if (copy_mp != NULL) {
8582 					xmit_mp = copy_mp;
8583 					MULTIRT_DEBUG_TAG(first_mp);
8584 				}
8585 			}
8586 			ire_add_then_send(q, ire, xmit_mp);
8587 
8588 			/* Assert that it is not deleted yet. */
8589 			ASSERT(save_ire->ire_ptpn != NULL);
8590 			IRB_REFRELE(save_ire->ire_bucket);
8591 			ire_refrele(save_ire);
8592 
8593 			if (copy_mp != NULL) {
8594 				/*
8595 				 * If we found a (no)resolver, we ignore any
8596 				 * trailing top priority IRE_CACHE in further
8597 				 * loops. This ensures that we do not omit any
8598 				 * (no)resolver.
8599 				 * This IRE_CACHE, if any, will be processed
8600 				 * by another thread entering ip_newroute().
8601 				 * IRE_CACHE entries, if any, will be processed
8602 				 * by another thread entering ip_newroute(),
8603 				 * (upon resolver response, for instance).
8604 				 * This aims to force parallel multirt
8605 				 * resolutions as soon as a packet must be sent.
8606 				 * In the best case, after the tx of only one
8607 				 * packet, all reachable routes are resolved.
8608 				 * Otherwise, the resolution of all RTF_MULTIRT
8609 				 * routes would require several emissions.
8610 				 */
8611 				multirt_flags &= ~MULTIRT_CACHEGW;
8612 
8613 				/*
8614 				 * Search for the next unresolved multirt
8615 				 * route.
8616 				 */
8617 				copy_mp = NULL;
8618 				save_ire = NULL;
8619 				ire = NULL;
8620 				multirt_resolve_next = B_TRUE;
8621 				continue;
8622 			}
8623 
8624 			/*
8625 			 * Don't need sire anymore
8626 			 */
8627 			if (sire != NULL)
8628 				ire_refrele(sire);
8629 
8630 			ipif_refrele(src_ipif);
8631 			ill_refrele(dst_ill);
8632 			return;
8633 		}
8634 		case IRE_IF_RESOLVER:
8635 			/*
8636 			 * We can't build an IRE_CACHE yet, but at least we
8637 			 * found a resolver that can help.
8638 			 */
8639 			res_mp = dst_ill->ill_resolver_mp;
8640 			if (!OK_RESOLVER_MP(res_mp))
8641 				break;
8642 
8643 			/*
8644 			 * To be at this point in the code with a non-zero gw
8645 			 * means that dst is reachable through a gateway that
8646 			 * we have never resolved.  By changing dst to the gw
8647 			 * addr we resolve the gateway first.
8648 			 * When ire_add_then_send() tries to put the IP dg
8649 			 * to dst, it will reenter ip_newroute() at which
8650 			 * time we will find the IRE_CACHE for the gw and
8651 			 * create another IRE_CACHE in case IRE_CACHE above.
8652 			 */
8653 			if (gw != INADDR_ANY) {
8654 				/*
8655 				 * The source ipif that was determined above was
8656 				 * relative to the destination address, not the
8657 				 * gateway's. If src_ipif was not taken out of
8658 				 * the IRE_IF_RESOLVER entry, we'll need to call
8659 				 * ipif_select_source() again.
8660 				 */
8661 				if (src_ipif != ire->ire_ipif) {
8662 					ipif_refrele(src_ipif);
8663 					src_ipif = ipif_select_source(dst_ill,
8664 					    gw, zoneid);
8665 					/*
8666 					 * In the case of multirouting, it may
8667 					 * happen that ipif_select_source fails
8668 					 * as DAD may disallow use of the
8669 					 * particular source interface.  Anyway,
8670 					 * we need to continue and attempt to
8671 					 * resolve other multirt routes.
8672 					 */
8673 					if (src_ipif == NULL) {
8674 						if (sire != NULL &&
8675 						    (sire->ire_flags &
8676 						    RTF_MULTIRT)) {
8677 							ire_refrele(ire);
8678 							ire = NULL;
8679 							multirt_resolve_next =
8680 							    B_TRUE;
8681 							multirt_res_failures++;
8682 							continue;
8683 						}
8684 						if (ip_debug > 2) {
8685 							pr_addr_dbg(
8686 							    "ip_newroute: no "
8687 							    "src for gw %s ",
8688 							    AF_INET, &gw);
8689 							printf("on "
8690 							    "interface %s\n",
8691 							    dst_ill->ill_name);
8692 						}
8693 						goto icmp_err_ret;
8694 					}
8695 				}
8696 				save_dst = dst;
8697 				dst = gw;
8698 				gw = INADDR_ANY;
8699 			}
8700 
8701 			/*
8702 			 * We obtain a partial IRE_CACHE which we will pass
8703 			 * along with the resolver query.  When the response
8704 			 * comes back it will be there ready for us to add.
8705 			 * The ire_max_frag is atomically set under the
8706 			 * irebucket lock in ire_add_v[46].
8707 			 */
8708 
8709 			ire = ire_create_mp(
8710 			    (uchar_t *)&dst,		/* dest address */
8711 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8712 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8713 			    (uchar_t *)&gw,		/* gateway address */
8714 			    NULL,			/* ire_max_frag */
8715 			    NULL,			/* no src nce */
8716 			    dst_ill->ill_rq,		/* recv-from queue */
8717 			    dst_ill->ill_wq,		/* send-to queue */
8718 			    IRE_CACHE,
8719 			    src_ipif,			/* Interface ipif */
8720 			    save_ire->ire_mask,		/* Parent mask */
8721 			    0,
8722 			    save_ire->ire_ihandle,	/* Interface handle */
8723 			    0,				/* flags if any */
8724 			    &(save_ire->ire_uinfo),
8725 			    NULL,
8726 			    NULL,
8727 			    ipst);
8728 
8729 			if (ire == NULL) {
8730 				ire_refrele(save_ire);
8731 				break;
8732 			}
8733 
8734 			if ((sire != NULL) &&
8735 			    (sire->ire_flags & RTF_MULTIRT)) {
8736 				copy_mp = copymsg(first_mp);
8737 				if (copy_mp != NULL)
8738 					MULTIRT_DEBUG_TAG(copy_mp);
8739 			}
8740 
8741 			ire->ire_marks |= ire_marks;
8742 
8743 			/*
8744 			 * Construct message chain for the resolver
8745 			 * of the form:
8746 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8747 			 * Packet could contain a IPSEC_OUT mp.
8748 			 *
8749 			 * NOTE : ire will be added later when the response
8750 			 * comes back from ARP. If the response does not
8751 			 * come back, ARP frees the packet. For this reason,
8752 			 * we can't REFHOLD the bucket of save_ire to prevent
8753 			 * deletions. We may not be able to REFRELE the bucket
8754 			 * if the response never comes back. Thus, before
8755 			 * adding the ire, ire_add_v4 will make sure that the
8756 			 * interface route does not get deleted. This is the
8757 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8758 			 * where we can always prevent deletions because of
8759 			 * the synchronous nature of adding IRES i.e
8760 			 * ire_add_then_send is called after creating the IRE.
8761 			 */
8762 			ASSERT(ire->ire_mp != NULL);
8763 			ire->ire_mp->b_cont = first_mp;
8764 			/* Have saved_mp handy, for cleanup if canput fails */
8765 			saved_mp = mp;
8766 			mp = copyb(res_mp);
8767 			if (mp == NULL) {
8768 				/* Prepare for cleanup */
8769 				mp = saved_mp; /* pkt */
8770 				ire_delete(ire); /* ire_mp */
8771 				ire = NULL;
8772 				ire_refrele(save_ire);
8773 				if (copy_mp != NULL) {
8774 					MULTIRT_DEBUG_UNTAG(copy_mp);
8775 					freemsg(copy_mp);
8776 					copy_mp = NULL;
8777 				}
8778 				break;
8779 			}
8780 			linkb(mp, ire->ire_mp);
8781 
8782 			/*
8783 			 * Fill in the source and dest addrs for the resolver.
8784 			 * NOTE: this depends on memory layouts imposed by
8785 			 * ill_init().
8786 			 */
8787 			areq = (areq_t *)mp->b_rptr;
8788 			addrp = (ipaddr_t *)((char *)areq +
8789 			    areq->areq_sender_addr_offset);
8790 			*addrp = save_ire->ire_src_addr;
8791 
8792 			ire_refrele(save_ire);
8793 			addrp = (ipaddr_t *)((char *)areq +
8794 			    areq->areq_target_addr_offset);
8795 			*addrp = dst;
8796 			/* Up to the resolver. */
8797 			if (canputnext(dst_ill->ill_rq) &&
8798 			    !(dst_ill->ill_arp_closing)) {
8799 				putnext(dst_ill->ill_rq, mp);
8800 				ire = NULL;
8801 				if (copy_mp != NULL) {
8802 					/*
8803 					 * If we found a resolver, we ignore
8804 					 * any trailing top priority IRE_CACHE
8805 					 * in the further loops. This ensures
8806 					 * that we do not omit any resolver.
8807 					 * IRE_CACHE entries, if any, will be
8808 					 * processed next time we enter
8809 					 * ip_newroute().
8810 					 */
8811 					multirt_flags &= ~MULTIRT_CACHEGW;
8812 					/*
8813 					 * Search for the next unresolved
8814 					 * multirt route.
8815 					 */
8816 					first_mp = copy_mp;
8817 					copy_mp = NULL;
8818 					/* Prepare the next resolution loop. */
8819 					mp = first_mp;
8820 					EXTRACT_PKT_MP(mp, first_mp,
8821 					    mctl_present);
8822 					if (mctl_present)
8823 						io = (ipsec_out_t *)
8824 						    first_mp->b_rptr;
8825 					ipha = (ipha_t *)mp->b_rptr;
8826 
8827 					ASSERT(sire != NULL);
8828 
8829 					dst = save_dst;
8830 					multirt_resolve_next = B_TRUE;
8831 					continue;
8832 				}
8833 
8834 				if (sire != NULL)
8835 					ire_refrele(sire);
8836 
8837 				/*
8838 				 * The response will come back in ip_wput
8839 				 * with db_type IRE_DB_TYPE.
8840 				 */
8841 				ipif_refrele(src_ipif);
8842 				ill_refrele(dst_ill);
8843 				return;
8844 			} else {
8845 				/* Prepare for cleanup */
8846 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8847 				    mp);
8848 				mp->b_cont = NULL;
8849 				freeb(mp); /* areq */
8850 				/*
8851 				 * this is an ire that is not added to the
8852 				 * cache. ire_freemblk will handle the release
8853 				 * of any resources associated with the ire.
8854 				 */
8855 				ire_delete(ire); /* ire_mp */
8856 				mp = saved_mp; /* pkt */
8857 				ire = NULL;
8858 				if (copy_mp != NULL) {
8859 					MULTIRT_DEBUG_UNTAG(copy_mp);
8860 					freemsg(copy_mp);
8861 					copy_mp = NULL;
8862 				}
8863 				break;
8864 			}
8865 		default:
8866 			break;
8867 		}
8868 	} while (multirt_resolve_next);
8869 
8870 	ip1dbg(("ip_newroute: dropped\n"));
8871 	/* Did this packet originate externally? */
8872 	if (mp->b_prev) {
8873 		mp->b_next = NULL;
8874 		mp->b_prev = NULL;
8875 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8876 	} else {
8877 		if (dst_ill != NULL) {
8878 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8879 		} else {
8880 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8881 		}
8882 	}
8883 	ASSERT(copy_mp == NULL);
8884 	MULTIRT_DEBUG_UNTAG(first_mp);
8885 	freemsg(first_mp);
8886 	if (ire != NULL)
8887 		ire_refrele(ire);
8888 	if (sire != NULL)
8889 		ire_refrele(sire);
8890 	if (src_ipif != NULL)
8891 		ipif_refrele(src_ipif);
8892 	if (dst_ill != NULL)
8893 		ill_refrele(dst_ill);
8894 	return;
8895 
8896 icmp_err_ret:
8897 	ip1dbg(("ip_newroute: no route\n"));
8898 	if (src_ipif != NULL)
8899 		ipif_refrele(src_ipif);
8900 	if (dst_ill != NULL)
8901 		ill_refrele(dst_ill);
8902 	if (sire != NULL)
8903 		ire_refrele(sire);
8904 	/* Did this packet originate externally? */
8905 	if (mp->b_prev) {
8906 		mp->b_next = NULL;
8907 		mp->b_prev = NULL;
8908 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8909 		q = WR(q);
8910 	} else {
8911 		/*
8912 		 * There is no outgoing ill, so just increment the
8913 		 * system MIB.
8914 		 */
8915 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8916 		/*
8917 		 * Since ip_wput() isn't close to finished, we fill
8918 		 * in enough of the header for credible error reporting.
8919 		 */
8920 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8921 			/* Failed */
8922 			MULTIRT_DEBUG_UNTAG(first_mp);
8923 			freemsg(first_mp);
8924 			if (ire != NULL)
8925 				ire_refrele(ire);
8926 			return;
8927 		}
8928 	}
8929 
8930 	/*
8931 	 * At this point we will have ire only if RTF_BLACKHOLE
8932 	 * or RTF_REJECT flags are set on the IRE. It will not
8933 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8934 	 */
8935 	if (ire != NULL) {
8936 		if (ire->ire_flags & RTF_BLACKHOLE) {
8937 			ire_refrele(ire);
8938 			MULTIRT_DEBUG_UNTAG(first_mp);
8939 			freemsg(first_mp);
8940 			return;
8941 		}
8942 		ire_refrele(ire);
8943 	}
8944 	if (ip_source_routed(ipha, ipst)) {
8945 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8946 		    zoneid, ipst);
8947 		return;
8948 	}
8949 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8950 }
8951 
8952 ip_opt_info_t zero_info;
8953 
8954 /*
8955  * IPv4 -
8956  * ip_newroute_ipif is called by ip_wput_multicast and
8957  * ip_rput_forward_multicast whenever we need to send
8958  * out a packet to a destination address for which we do not have specific
8959  * routing information. It is used when the packet will be sent out
8960  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8961  * socket option is set or icmp error message wants to go out on a particular
8962  * interface for a unicast packet.
8963  *
8964  * In most cases, the destination address is resolved thanks to the ipif
8965  * intrinsic resolver. However, there are some cases where the call to
8966  * ip_newroute_ipif must take into account the potential presence of
8967  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8968  * that uses the interface. This is specified through flags,
8969  * which can be a combination of:
8970  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8971  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8972  *   and flags. Additionally, the packet source address has to be set to
8973  *   the specified address. The caller is thus expected to set this flag
8974  *   if the packet has no specific source address yet.
8975  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8976  *   flag, the resulting ire will inherit the flag. All unresolved routes
8977  *   to the destination must be explored in the same call to
8978  *   ip_newroute_ipif().
8979  */
8980 static void
8981 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8982     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8983 {
8984 	areq_t	*areq;
8985 	ire_t	*ire = NULL;
8986 	mblk_t	*res_mp;
8987 	ipaddr_t *addrp;
8988 	mblk_t *first_mp;
8989 	ire_t	*save_ire = NULL;
8990 	ipif_t	*src_ipif = NULL;
8991 	ushort_t ire_marks = 0;
8992 	ill_t	*dst_ill = NULL;
8993 	ipha_t *ipha;
8994 	mblk_t	*saved_mp;
8995 	ire_t   *fire = NULL;
8996 	mblk_t  *copy_mp = NULL;
8997 	boolean_t multirt_resolve_next;
8998 	boolean_t unspec_src;
8999 	ipaddr_t ipha_dst;
9000 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9001 
9002 	/*
9003 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9004 	 * here for uniformity
9005 	 */
9006 	ipif_refhold(ipif);
9007 
9008 	/*
9009 	 * This loop is run only once in most cases.
9010 	 * We loop to resolve further routes only when the destination
9011 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9012 	 */
9013 	do {
9014 		if (dst_ill != NULL) {
9015 			ill_refrele(dst_ill);
9016 			dst_ill = NULL;
9017 		}
9018 		if (src_ipif != NULL) {
9019 			ipif_refrele(src_ipif);
9020 			src_ipif = NULL;
9021 		}
9022 		multirt_resolve_next = B_FALSE;
9023 
9024 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9025 		    ipif->ipif_ill->ill_name));
9026 
9027 		first_mp = mp;
9028 		if (DB_TYPE(mp) == M_CTL)
9029 			mp = mp->b_cont;
9030 		ipha = (ipha_t *)mp->b_rptr;
9031 
9032 		/*
9033 		 * Save the packet destination address, we may need it after
9034 		 * the packet has been consumed.
9035 		 */
9036 		ipha_dst = ipha->ipha_dst;
9037 
9038 		/*
9039 		 * If the interface is a pt-pt interface we look for an
9040 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9041 		 * local_address and the pt-pt destination address. Otherwise
9042 		 * we just match the local address.
9043 		 * NOTE: dst could be different than ipha->ipha_dst in case
9044 		 * of sending igmp multicast packets over a point-to-point
9045 		 * connection.
9046 		 * Thus we must be careful enough to check ipha_dst to be a
9047 		 * multicast address, otherwise it will take xmit_if path for
9048 		 * multicast packets resulting into kernel stack overflow by
9049 		 * repeated calls to ip_newroute_ipif from ire_send().
9050 		 */
9051 		if (CLASSD(ipha_dst) &&
9052 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9053 			goto err_ret;
9054 		}
9055 
9056 		/*
9057 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9058 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9059 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9060 		 * propagate its flags to the new ire.
9061 		 */
9062 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9063 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9064 			ip2dbg(("ip_newroute_ipif: "
9065 			    "ipif_lookup_multi_ire("
9066 			    "ipif %p, dst %08x) = fire %p\n",
9067 			    (void *)ipif, ntohl(dst), (void *)fire));
9068 		}
9069 
9070 		/*
9071 		 * Note: While we pick a dst_ill we are really only
9072 		 * interested in the ill for load spreading. The source
9073 		 * ipif is determined by source address selection below.
9074 		 */
9075 		if (IS_IPMP(ipif->ipif_ill)) {
9076 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9077 
9078 			if (CLASSD(ipha_dst))
9079 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9080 			else
9081 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9082 		} else {
9083 			dst_ill = ipif->ipif_ill;
9084 			ill_refhold(dst_ill);
9085 		}
9086 
9087 		if (dst_ill == NULL) {
9088 			if (ip_debug > 2) {
9089 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9090 				    "for dst %s\n", AF_INET, &dst);
9091 			}
9092 			goto err_ret;
9093 		}
9094 
9095 		/*
9096 		 * Pick a source address preferring non-deprecated ones.
9097 		 * Unlike ip_newroute, we don't do any source address
9098 		 * selection here since for multicast it really does not help
9099 		 * in inbound load spreading as in the unicast case.
9100 		 */
9101 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9102 		    (fire->ire_flags & RTF_SETSRC)) {
9103 			/*
9104 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9105 			 * on that interface. This ire has RTF_SETSRC flag, so
9106 			 * the source address of the packet must be changed.
9107 			 * Check that the ipif matching the requested source
9108 			 * address still exists.
9109 			 */
9110 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9111 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9112 		}
9113 
9114 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9115 
9116 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9117 		    (IS_IPMP(ipif->ipif_ill) ||
9118 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9119 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9120 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9121 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9122 		    (src_ipif == NULL) &&
9123 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9124 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9125 			if (src_ipif == NULL) {
9126 				if (ip_debug > 2) {
9127 					/* ip1dbg */
9128 					pr_addr_dbg("ip_newroute_ipif: "
9129 					    "no src for dst %s",
9130 					    AF_INET, &dst);
9131 				}
9132 				ip1dbg((" on interface %s\n",
9133 				    dst_ill->ill_name));
9134 				goto err_ret;
9135 			}
9136 			ipif_refrele(ipif);
9137 			ipif = src_ipif;
9138 			ipif_refhold(ipif);
9139 		}
9140 		if (src_ipif == NULL) {
9141 			src_ipif = ipif;
9142 			ipif_refhold(src_ipif);
9143 		}
9144 
9145 		/*
9146 		 * Assign a source address while we have the conn.
9147 		 * We can't have ip_wput_ire pick a source address when the
9148 		 * packet returns from arp since conn_unspec_src might be set
9149 		 * and we lose the conn when going through arp.
9150 		 */
9151 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9152 			ipha->ipha_src = src_ipif->ipif_src_addr;
9153 
9154 		/*
9155 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9156 		 * that the outgoing interface does not have an interface ire.
9157 		 */
9158 		if (CLASSD(ipha_dst) && (connp == NULL ||
9159 		    connp->conn_outgoing_ill == NULL) &&
9160 		    infop->ip_opt_ill_index == 0) {
9161 			/* ipif_to_ire returns an held ire */
9162 			ire = ipif_to_ire(ipif);
9163 			if (ire == NULL)
9164 				goto err_ret;
9165 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9166 				goto err_ret;
9167 			save_ire = ire;
9168 
9169 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9170 			    "flags %04x\n",
9171 			    (void *)ire, (void *)ipif, flags));
9172 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9173 			    (fire->ire_flags & RTF_MULTIRT)) {
9174 				/*
9175 				 * As requested by flags, an IRE_OFFSUBNET was
9176 				 * looked up on that interface. This ire has
9177 				 * RTF_MULTIRT flag, so the resolution loop will
9178 				 * be re-entered to resolve additional routes on
9179 				 * other interfaces. For that purpose, a copy of
9180 				 * the packet is performed at this point.
9181 				 */
9182 				fire->ire_last_used_time = lbolt;
9183 				copy_mp = copymsg(first_mp);
9184 				if (copy_mp) {
9185 					MULTIRT_DEBUG_TAG(copy_mp);
9186 				}
9187 			}
9188 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9189 			    (fire->ire_flags & RTF_SETSRC)) {
9190 				/*
9191 				 * As requested by flags, an IRE_OFFSUBET was
9192 				 * looked up on that interface. This ire has
9193 				 * RTF_SETSRC flag, so the source address of the
9194 				 * packet must be changed.
9195 				 */
9196 				ipha->ipha_src = fire->ire_src_addr;
9197 			}
9198 		} else {
9199 			/*
9200 			 * The only ways we can come here are:
9201 			 * 1) IP_BOUND_IF socket option is set
9202 			 * 2) SO_DONTROUTE socket option is set
9203 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9204 			 * In all cases, the new ire will not be added
9205 			 * into cache table.
9206 			 */
9207 			ASSERT(connp == NULL || connp->conn_dontroute ||
9208 			    connp->conn_outgoing_ill != NULL ||
9209 			    infop->ip_opt_ill_index != 0);
9210 			ire_marks |= IRE_MARK_NOADD;
9211 		}
9212 
9213 		switch (ipif->ipif_net_type) {
9214 		case IRE_IF_NORESOLVER: {
9215 			/* We have what we need to build an IRE_CACHE. */
9216 
9217 			if (dst_ill->ill_resolver_mp == NULL) {
9218 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9219 				    "for IRE_IF_NORESOLVER ire %p has "
9220 				    "no ill_resolver_mp\n",
9221 				    (void *)dst_ill, (void *)ire));
9222 				break;
9223 			}
9224 
9225 			/*
9226 			 * The new ire inherits the IRE_OFFSUBNET flags
9227 			 * and source address, if this was requested.
9228 			 */
9229 			ire = ire_create(
9230 			    (uchar_t *)&dst,		/* dest address */
9231 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9232 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9233 			    NULL,			/* gateway address */
9234 			    &ipif->ipif_mtu,
9235 			    NULL,			/* no src nce */
9236 			    dst_ill->ill_rq,		/* recv-from queue */
9237 			    dst_ill->ill_wq,		/* send-to queue */
9238 			    IRE_CACHE,
9239 			    src_ipif,
9240 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9241 			    (fire != NULL) ?		/* Parent handle */
9242 			    fire->ire_phandle : 0,
9243 			    (save_ire != NULL) ?	/* Interface handle */
9244 			    save_ire->ire_ihandle : 0,
9245 			    (fire != NULL) ?
9246 			    (fire->ire_flags &
9247 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9248 			    (save_ire == NULL ? &ire_uinfo_null :
9249 			    &save_ire->ire_uinfo),
9250 			    NULL,
9251 			    NULL,
9252 			    ipst);
9253 
9254 			if (ire == NULL) {
9255 				if (save_ire != NULL)
9256 					ire_refrele(save_ire);
9257 				break;
9258 			}
9259 
9260 			ire->ire_marks |= ire_marks;
9261 
9262 			/*
9263 			 * If IRE_MARK_NOADD is set then we need to convert
9264 			 * the max_fragp to a useable value now. This is
9265 			 * normally done in ire_add_v[46]. We also need to
9266 			 * associate the ire with an nce (normally would be
9267 			 * done in ip_wput_nondata()).
9268 			 *
9269 			 * Note that IRE_MARK_NOADD packets created here
9270 			 * do not have a non-null ire_mp pointer. The null
9271 			 * value of ire_bucket indicates that they were
9272 			 * never added.
9273 			 */
9274 			if (ire->ire_marks & IRE_MARK_NOADD) {
9275 				uint_t  max_frag;
9276 
9277 				max_frag = *ire->ire_max_fragp;
9278 				ire->ire_max_fragp = NULL;
9279 				ire->ire_max_frag = max_frag;
9280 
9281 				if ((ire->ire_nce = ndp_lookup_v4(
9282 				    ire_to_ill(ire),
9283 				    (ire->ire_gateway_addr != INADDR_ANY ?
9284 				    &ire->ire_gateway_addr : &ire->ire_addr),
9285 				    B_FALSE)) == NULL) {
9286 					if (save_ire != NULL)
9287 						ire_refrele(save_ire);
9288 					break;
9289 				}
9290 				ASSERT(ire->ire_nce->nce_state ==
9291 				    ND_REACHABLE);
9292 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9293 			}
9294 
9295 			/* Prevent save_ire from getting deleted */
9296 			if (save_ire != NULL) {
9297 				IRB_REFHOLD(save_ire->ire_bucket);
9298 				/* Has it been removed already ? */
9299 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9300 					IRB_REFRELE(save_ire->ire_bucket);
9301 					ire_refrele(save_ire);
9302 					break;
9303 				}
9304 			}
9305 
9306 			ire_add_then_send(q, ire, first_mp);
9307 
9308 			/* Assert that save_ire is not deleted yet. */
9309 			if (save_ire != NULL) {
9310 				ASSERT(save_ire->ire_ptpn != NULL);
9311 				IRB_REFRELE(save_ire->ire_bucket);
9312 				ire_refrele(save_ire);
9313 				save_ire = NULL;
9314 			}
9315 			if (fire != NULL) {
9316 				ire_refrele(fire);
9317 				fire = NULL;
9318 			}
9319 
9320 			/*
9321 			 * the resolution loop is re-entered if this
9322 			 * was requested through flags and if we
9323 			 * actually are in a multirouting case.
9324 			 */
9325 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9326 				boolean_t need_resolve =
9327 				    ire_multirt_need_resolve(ipha_dst,
9328 				    msg_getlabel(copy_mp), ipst);
9329 				if (!need_resolve) {
9330 					MULTIRT_DEBUG_UNTAG(copy_mp);
9331 					freemsg(copy_mp);
9332 					copy_mp = NULL;
9333 				} else {
9334 					/*
9335 					 * ipif_lookup_group() calls
9336 					 * ire_lookup_multi() that uses
9337 					 * ire_ftable_lookup() to find
9338 					 * an IRE_INTERFACE for the group.
9339 					 * In the multirt case,
9340 					 * ire_lookup_multi() then invokes
9341 					 * ire_multirt_lookup() to find
9342 					 * the next resolvable ire.
9343 					 * As a result, we obtain an new
9344 					 * interface, derived from the
9345 					 * next ire.
9346 					 */
9347 					ipif_refrele(ipif);
9348 					ipif = ipif_lookup_group(ipha_dst,
9349 					    zoneid, ipst);
9350 					ip2dbg(("ip_newroute_ipif: "
9351 					    "multirt dst %08x, ipif %p\n",
9352 					    htonl(dst), (void *)ipif));
9353 					if (ipif != NULL) {
9354 						mp = copy_mp;
9355 						copy_mp = NULL;
9356 						multirt_resolve_next = B_TRUE;
9357 						continue;
9358 					} else {
9359 						freemsg(copy_mp);
9360 					}
9361 				}
9362 			}
9363 			if (ipif != NULL)
9364 				ipif_refrele(ipif);
9365 			ill_refrele(dst_ill);
9366 			ipif_refrele(src_ipif);
9367 			return;
9368 		}
9369 		case IRE_IF_RESOLVER:
9370 			/*
9371 			 * We can't build an IRE_CACHE yet, but at least
9372 			 * we found a resolver that can help.
9373 			 */
9374 			res_mp = dst_ill->ill_resolver_mp;
9375 			if (!OK_RESOLVER_MP(res_mp))
9376 				break;
9377 
9378 			/*
9379 			 * We obtain a partial IRE_CACHE which we will pass
9380 			 * along with the resolver query.  When the response
9381 			 * comes back it will be there ready for us to add.
9382 			 * The new ire inherits the IRE_OFFSUBNET flags
9383 			 * and source address, if this was requested.
9384 			 * The ire_max_frag is atomically set under the
9385 			 * irebucket lock in ire_add_v[46]. Only in the
9386 			 * case of IRE_MARK_NOADD, we set it here itself.
9387 			 */
9388 			ire = ire_create_mp(
9389 			    (uchar_t *)&dst,		/* dest address */
9390 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9391 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9392 			    NULL,			/* gateway address */
9393 			    (ire_marks & IRE_MARK_NOADD) ?
9394 			    ipif->ipif_mtu : 0,		/* max_frag */
9395 			    NULL,			/* no src nce */
9396 			    dst_ill->ill_rq,		/* recv-from queue */
9397 			    dst_ill->ill_wq,		/* send-to queue */
9398 			    IRE_CACHE,
9399 			    src_ipif,
9400 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9401 			    (fire != NULL) ?		/* Parent handle */
9402 			    fire->ire_phandle : 0,
9403 			    (save_ire != NULL) ?	/* Interface handle */
9404 			    save_ire->ire_ihandle : 0,
9405 			    (fire != NULL) ?		/* flags if any */
9406 			    (fire->ire_flags &
9407 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9408 			    (save_ire == NULL ? &ire_uinfo_null :
9409 			    &save_ire->ire_uinfo),
9410 			    NULL,
9411 			    NULL,
9412 			    ipst);
9413 
9414 			if (save_ire != NULL) {
9415 				ire_refrele(save_ire);
9416 				save_ire = NULL;
9417 			}
9418 			if (ire == NULL)
9419 				break;
9420 
9421 			ire->ire_marks |= ire_marks;
9422 			/*
9423 			 * Construct message chain for the resolver of the
9424 			 * form:
9425 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9426 			 *
9427 			 * NOTE : ire will be added later when the response
9428 			 * comes back from ARP. If the response does not
9429 			 * come back, ARP frees the packet. For this reason,
9430 			 * we can't REFHOLD the bucket of save_ire to prevent
9431 			 * deletions. We may not be able to REFRELE the
9432 			 * bucket if the response never comes back.
9433 			 * Thus, before adding the ire, ire_add_v4 will make
9434 			 * sure that the interface route does not get deleted.
9435 			 * This is the only case unlike ip_newroute_v6,
9436 			 * ip_newroute_ipif_v6 where we can always prevent
9437 			 * deletions because ire_add_then_send is called after
9438 			 * creating the IRE.
9439 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9440 			 * does not add this IRE into the IRE CACHE.
9441 			 */
9442 			ASSERT(ire->ire_mp != NULL);
9443 			ire->ire_mp->b_cont = first_mp;
9444 			/* Have saved_mp handy, for cleanup if canput fails */
9445 			saved_mp = mp;
9446 			mp = copyb(res_mp);
9447 			if (mp == NULL) {
9448 				/* Prepare for cleanup */
9449 				mp = saved_mp; /* pkt */
9450 				ire_delete(ire); /* ire_mp */
9451 				ire = NULL;
9452 				if (copy_mp != NULL) {
9453 					MULTIRT_DEBUG_UNTAG(copy_mp);
9454 					freemsg(copy_mp);
9455 					copy_mp = NULL;
9456 				}
9457 				break;
9458 			}
9459 			linkb(mp, ire->ire_mp);
9460 
9461 			/*
9462 			 * Fill in the source and dest addrs for the resolver.
9463 			 * NOTE: this depends on memory layouts imposed by
9464 			 * ill_init().  There are corner cases above where we
9465 			 * might've created the IRE with an INADDR_ANY source
9466 			 * address (e.g., if the zeroth ipif on an underlying
9467 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9468 			 * on the ill has a usable test address).  If so, tell
9469 			 * ARP to use ipha_src as its sender address.
9470 			 */
9471 			areq = (areq_t *)mp->b_rptr;
9472 			addrp = (ipaddr_t *)((char *)areq +
9473 			    areq->areq_sender_addr_offset);
9474 			if (ire->ire_src_addr != INADDR_ANY)
9475 				*addrp = ire->ire_src_addr;
9476 			else
9477 				*addrp = ipha->ipha_src;
9478 			addrp = (ipaddr_t *)((char *)areq +
9479 			    areq->areq_target_addr_offset);
9480 			*addrp = dst;
9481 			/* Up to the resolver. */
9482 			if (canputnext(dst_ill->ill_rq) &&
9483 			    !(dst_ill->ill_arp_closing)) {
9484 				putnext(dst_ill->ill_rq, mp);
9485 				/*
9486 				 * The response will come back in ip_wput
9487 				 * with db_type IRE_DB_TYPE.
9488 				 */
9489 			} else {
9490 				mp->b_cont = NULL;
9491 				freeb(mp); /* areq */
9492 				ire_delete(ire); /* ire_mp */
9493 				saved_mp->b_next = NULL;
9494 				saved_mp->b_prev = NULL;
9495 				freemsg(first_mp); /* pkt */
9496 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9497 			}
9498 
9499 			if (fire != NULL) {
9500 				ire_refrele(fire);
9501 				fire = NULL;
9502 			}
9503 
9504 			/*
9505 			 * The resolution loop is re-entered if this was
9506 			 * requested through flags and we actually are
9507 			 * in a multirouting case.
9508 			 */
9509 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9510 				boolean_t need_resolve =
9511 				    ire_multirt_need_resolve(ipha_dst,
9512 				    msg_getlabel(copy_mp), ipst);
9513 				if (!need_resolve) {
9514 					MULTIRT_DEBUG_UNTAG(copy_mp);
9515 					freemsg(copy_mp);
9516 					copy_mp = NULL;
9517 				} else {
9518 					/*
9519 					 * ipif_lookup_group() calls
9520 					 * ire_lookup_multi() that uses
9521 					 * ire_ftable_lookup() to find
9522 					 * an IRE_INTERFACE for the group.
9523 					 * In the multirt case,
9524 					 * ire_lookup_multi() then invokes
9525 					 * ire_multirt_lookup() to find
9526 					 * the next resolvable ire.
9527 					 * As a result, we obtain an new
9528 					 * interface, derived from the
9529 					 * next ire.
9530 					 */
9531 					ipif_refrele(ipif);
9532 					ipif = ipif_lookup_group(ipha_dst,
9533 					    zoneid, ipst);
9534 					if (ipif != NULL) {
9535 						mp = copy_mp;
9536 						copy_mp = NULL;
9537 						multirt_resolve_next = B_TRUE;
9538 						continue;
9539 					} else {
9540 						freemsg(copy_mp);
9541 					}
9542 				}
9543 			}
9544 			if (ipif != NULL)
9545 				ipif_refrele(ipif);
9546 			ill_refrele(dst_ill);
9547 			ipif_refrele(src_ipif);
9548 			return;
9549 		default:
9550 			break;
9551 		}
9552 	} while (multirt_resolve_next);
9553 
9554 err_ret:
9555 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9556 	if (fire != NULL)
9557 		ire_refrele(fire);
9558 	ipif_refrele(ipif);
9559 	/* Did this packet originate externally? */
9560 	if (dst_ill != NULL)
9561 		ill_refrele(dst_ill);
9562 	if (src_ipif != NULL)
9563 		ipif_refrele(src_ipif);
9564 	if (mp->b_prev || mp->b_next) {
9565 		mp->b_next = NULL;
9566 		mp->b_prev = NULL;
9567 	} else {
9568 		/*
9569 		 * Since ip_wput() isn't close to finished, we fill
9570 		 * in enough of the header for credible error reporting.
9571 		 */
9572 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9573 			/* Failed */
9574 			freemsg(first_mp);
9575 			if (ire != NULL)
9576 				ire_refrele(ire);
9577 			return;
9578 		}
9579 	}
9580 	/*
9581 	 * At this point we will have ire only if RTF_BLACKHOLE
9582 	 * or RTF_REJECT flags are set on the IRE. It will not
9583 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9584 	 */
9585 	if (ire != NULL) {
9586 		if (ire->ire_flags & RTF_BLACKHOLE) {
9587 			ire_refrele(ire);
9588 			freemsg(first_mp);
9589 			return;
9590 		}
9591 		ire_refrele(ire);
9592 	}
9593 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9594 }
9595 
9596 /* Name/Value Table Lookup Routine */
9597 char *
9598 ip_nv_lookup(nv_t *nv, int value)
9599 {
9600 	if (!nv)
9601 		return (NULL);
9602 	for (; nv->nv_name; nv++) {
9603 		if (nv->nv_value == value)
9604 			return (nv->nv_name);
9605 	}
9606 	return ("unknown");
9607 }
9608 
9609 /*
9610  * This is a module open, i.e. this is a control stream for access
9611  * to a DLPI device.  We allocate an ill_t as the instance data in
9612  * this case.
9613  */
9614 int
9615 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9616 {
9617 	ill_t	*ill;
9618 	int	err;
9619 	zoneid_t zoneid;
9620 	netstack_t *ns;
9621 	ip_stack_t *ipst;
9622 
9623 	/*
9624 	 * Prevent unprivileged processes from pushing IP so that
9625 	 * they can't send raw IP.
9626 	 */
9627 	if (secpolicy_net_rawaccess(credp) != 0)
9628 		return (EPERM);
9629 
9630 	ns = netstack_find_by_cred(credp);
9631 	ASSERT(ns != NULL);
9632 	ipst = ns->netstack_ip;
9633 	ASSERT(ipst != NULL);
9634 
9635 	/*
9636 	 * For exclusive stacks we set the zoneid to zero
9637 	 * to make IP operate as if in the global zone.
9638 	 */
9639 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9640 		zoneid = GLOBAL_ZONEID;
9641 	else
9642 		zoneid = crgetzoneid(credp);
9643 
9644 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9645 	q->q_ptr = WR(q)->q_ptr = ill;
9646 	ill->ill_ipst = ipst;
9647 	ill->ill_zoneid = zoneid;
9648 
9649 	/*
9650 	 * ill_init initializes the ill fields and then sends down
9651 	 * down a DL_INFO_REQ after calling qprocson.
9652 	 */
9653 	err = ill_init(q, ill);
9654 	if (err != 0) {
9655 		mi_free(ill);
9656 		netstack_rele(ipst->ips_netstack);
9657 		q->q_ptr = NULL;
9658 		WR(q)->q_ptr = NULL;
9659 		return (err);
9660 	}
9661 
9662 	/* ill_init initializes the ipsq marking this thread as writer */
9663 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9664 	/* Wait for the DL_INFO_ACK */
9665 	mutex_enter(&ill->ill_lock);
9666 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9667 		/*
9668 		 * Return value of 0 indicates a pending signal.
9669 		 */
9670 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9671 		if (err == 0) {
9672 			mutex_exit(&ill->ill_lock);
9673 			(void) ip_close(q, 0);
9674 			return (EINTR);
9675 		}
9676 	}
9677 	mutex_exit(&ill->ill_lock);
9678 
9679 	/*
9680 	 * ip_rput_other could have set an error  in ill_error on
9681 	 * receipt of M_ERROR.
9682 	 */
9683 
9684 	err = ill->ill_error;
9685 	if (err != 0) {
9686 		(void) ip_close(q, 0);
9687 		return (err);
9688 	}
9689 
9690 	ill->ill_credp = credp;
9691 	crhold(credp);
9692 
9693 	mutex_enter(&ipst->ips_ip_mi_lock);
9694 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9695 	    credp);
9696 	mutex_exit(&ipst->ips_ip_mi_lock);
9697 	if (err) {
9698 		(void) ip_close(q, 0);
9699 		return (err);
9700 	}
9701 	return (0);
9702 }
9703 
9704 /* For /dev/ip aka AF_INET open */
9705 int
9706 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9707 {
9708 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9709 }
9710 
9711 /* For /dev/ip6 aka AF_INET6 open */
9712 int
9713 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9714 {
9715 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9716 }
9717 
9718 /* IP open routine. */
9719 int
9720 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9721     boolean_t isv6)
9722 {
9723 	conn_t 		*connp;
9724 	major_t		maj;
9725 	zoneid_t	zoneid;
9726 	netstack_t	*ns;
9727 	ip_stack_t	*ipst;
9728 
9729 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9730 
9731 	/* Allow reopen. */
9732 	if (q->q_ptr != NULL)
9733 		return (0);
9734 
9735 	if (sflag & MODOPEN) {
9736 		/* This is a module open */
9737 		return (ip_modopen(q, devp, flag, sflag, credp));
9738 	}
9739 
9740 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9741 		/*
9742 		 * Non streams based socket looking for a stream
9743 		 * to access IP
9744 		 */
9745 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9746 		    credp, isv6));
9747 	}
9748 
9749 	ns = netstack_find_by_cred(credp);
9750 	ASSERT(ns != NULL);
9751 	ipst = ns->netstack_ip;
9752 	ASSERT(ipst != NULL);
9753 
9754 	/*
9755 	 * For exclusive stacks we set the zoneid to zero
9756 	 * to make IP operate as if in the global zone.
9757 	 */
9758 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9759 		zoneid = GLOBAL_ZONEID;
9760 	else
9761 		zoneid = crgetzoneid(credp);
9762 
9763 	/*
9764 	 * We are opening as a device. This is an IP client stream, and we
9765 	 * allocate an conn_t as the instance data.
9766 	 */
9767 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9768 
9769 	/*
9770 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9771 	 * done by netstack_find_by_cred()
9772 	 */
9773 	netstack_rele(ipst->ips_netstack);
9774 
9775 	connp->conn_zoneid = zoneid;
9776 	connp->conn_sqp = NULL;
9777 	connp->conn_initial_sqp = NULL;
9778 	connp->conn_final_sqp = NULL;
9779 
9780 	connp->conn_upq = q;
9781 	q->q_ptr = WR(q)->q_ptr = connp;
9782 
9783 	if (flag & SO_SOCKSTR)
9784 		connp->conn_flags |= IPCL_SOCKET;
9785 
9786 	/* Minor tells us which /dev entry was opened */
9787 	if (isv6) {
9788 		connp->conn_af_isv6 = B_TRUE;
9789 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9790 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9791 	} else {
9792 		connp->conn_af_isv6 = B_FALSE;
9793 		connp->conn_pkt_isv6 = B_FALSE;
9794 	}
9795 
9796 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9797 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9798 		connp->conn_minor_arena = ip_minor_arena_la;
9799 	} else {
9800 		/*
9801 		 * Either minor numbers in the large arena were exhausted
9802 		 * or a non socket application is doing the open.
9803 		 * Try to allocate from the small arena.
9804 		 */
9805 		if ((connp->conn_dev =
9806 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9807 			/* CONN_DEC_REF takes care of netstack_rele() */
9808 			q->q_ptr = WR(q)->q_ptr = NULL;
9809 			CONN_DEC_REF(connp);
9810 			return (EBUSY);
9811 		}
9812 		connp->conn_minor_arena = ip_minor_arena_sa;
9813 	}
9814 
9815 	maj = getemajor(*devp);
9816 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9817 
9818 	/*
9819 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9820 	 */
9821 	connp->conn_cred = credp;
9822 
9823 	/*
9824 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9825 	 */
9826 	connp->conn_recv = ip_conn_input;
9827 
9828 	crhold(connp->conn_cred);
9829 
9830 	/*
9831 	 * If the caller has the process-wide flag set, then default to MAC
9832 	 * exempt mode.  This allows read-down to unlabeled hosts.
9833 	 */
9834 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9835 		connp->conn_mac_exempt = B_TRUE;
9836 
9837 	connp->conn_rq = q;
9838 	connp->conn_wq = WR(q);
9839 
9840 	/* Non-zero default values */
9841 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9842 
9843 	/*
9844 	 * Make the conn globally visible to walkers
9845 	 */
9846 	ASSERT(connp->conn_ref == 1);
9847 	mutex_enter(&connp->conn_lock);
9848 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9849 	mutex_exit(&connp->conn_lock);
9850 
9851 	qprocson(q);
9852 
9853 	return (0);
9854 }
9855 
9856 /*
9857  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9858  * Note that there is no race since either ip_output function works - it
9859  * is just an optimization to enter the best ip_output routine directly.
9860  */
9861 void
9862 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9863     ip_stack_t *ipst)
9864 {
9865 	if (isv6)  {
9866 		if (bump_mib) {
9867 			BUMP_MIB(&ipst->ips_ip6_mib,
9868 			    ipIfStatsOutSwitchIPVersion);
9869 		}
9870 		connp->conn_send = ip_output_v6;
9871 		connp->conn_pkt_isv6 = B_TRUE;
9872 	} else {
9873 		if (bump_mib) {
9874 			BUMP_MIB(&ipst->ips_ip_mib,
9875 			    ipIfStatsOutSwitchIPVersion);
9876 		}
9877 		connp->conn_send = ip_output;
9878 		connp->conn_pkt_isv6 = B_FALSE;
9879 	}
9880 
9881 }
9882 
9883 /*
9884  * See if IPsec needs loading because of the options in mp.
9885  */
9886 static boolean_t
9887 ipsec_opt_present(mblk_t *mp)
9888 {
9889 	uint8_t *optcp, *next_optcp, *opt_endcp;
9890 	struct opthdr *opt;
9891 	struct T_opthdr *topt;
9892 	int opthdr_len;
9893 	t_uscalar_t optname, optlevel;
9894 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9895 	ipsec_req_t *ipsr;
9896 
9897 	/*
9898 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9899 	 * return TRUE.
9900 	 */
9901 
9902 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9903 	opt_endcp = optcp + tor->OPT_length;
9904 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9905 		opthdr_len = sizeof (struct T_opthdr);
9906 	} else {		/* O_OPTMGMT_REQ */
9907 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9908 		opthdr_len = sizeof (struct opthdr);
9909 	}
9910 	for (; optcp < opt_endcp; optcp = next_optcp) {
9911 		if (optcp + opthdr_len > opt_endcp)
9912 			return (B_FALSE);	/* Not enough option header. */
9913 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9914 			topt = (struct T_opthdr *)optcp;
9915 			optlevel = topt->level;
9916 			optname = topt->name;
9917 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9918 		} else {
9919 			opt = (struct opthdr *)optcp;
9920 			optlevel = opt->level;
9921 			optname = opt->name;
9922 			next_optcp = optcp + opthdr_len +
9923 			    _TPI_ALIGN_OPT(opt->len);
9924 		}
9925 		if ((next_optcp < optcp) || /* wraparound pointer space */
9926 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9927 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9928 			return (B_FALSE); /* bad option buffer */
9929 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9930 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9931 			/*
9932 			 * Check to see if it's an all-bypass or all-zeroes
9933 			 * IPsec request.  Don't bother loading IPsec if
9934 			 * the socket doesn't want to use it.  (A good example
9935 			 * is a bypass request.)
9936 			 *
9937 			 * Basically, if any of the non-NEVER bits are set,
9938 			 * load IPsec.
9939 			 */
9940 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9941 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9942 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9943 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9944 			    != 0)
9945 				return (B_TRUE);
9946 		}
9947 	}
9948 	return (B_FALSE);
9949 }
9950 
9951 /*
9952  * If conn is is waiting for ipsec to finish loading, kick it.
9953  */
9954 /* ARGSUSED */
9955 static void
9956 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9957 {
9958 	t_scalar_t	optreq_prim;
9959 	mblk_t		*mp;
9960 	cred_t		*cr;
9961 	int		err = 0;
9962 
9963 	/*
9964 	 * This function is called, after ipsec loading is complete.
9965 	 * Since IP checks exclusively and atomically (i.e it prevents
9966 	 * ipsec load from completing until ip_optcom_req completes)
9967 	 * whether ipsec load is complete, there cannot be a race with IP
9968 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9969 	 */
9970 	mutex_enter(&connp->conn_lock);
9971 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9972 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9973 		mp = connp->conn_ipsec_opt_mp;
9974 		connp->conn_ipsec_opt_mp = NULL;
9975 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9976 		mutex_exit(&connp->conn_lock);
9977 
9978 		/*
9979 		 * All Solaris components should pass a db_credp
9980 		 * for this TPI message, hence we ASSERT.
9981 		 * But in case there is some other M_PROTO that looks
9982 		 * like a TPI message sent by some other kernel
9983 		 * component, we check and return an error.
9984 		 */
9985 		cr = msg_getcred(mp, NULL);
9986 		ASSERT(cr != NULL);
9987 		if (cr == NULL) {
9988 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
9989 			if (mp != NULL)
9990 				qreply(connp->conn_wq, mp);
9991 			return;
9992 		}
9993 
9994 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9995 
9996 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9997 		if (optreq_prim == T_OPTMGMT_REQ) {
9998 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9999 			    &ip_opt_obj, B_FALSE);
10000 		} else {
10001 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10002 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10003 			    &ip_opt_obj, B_FALSE);
10004 		}
10005 		if (err != EINPROGRESS)
10006 			CONN_OPER_PENDING_DONE(connp);
10007 		return;
10008 	}
10009 	mutex_exit(&connp->conn_lock);
10010 }
10011 
10012 /*
10013  * Called from the ipsec_loader thread, outside any perimeter, to tell
10014  * ip qenable any of the queues waiting for the ipsec loader to
10015  * complete.
10016  */
10017 void
10018 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10019 {
10020 	netstack_t *ns = ipss->ipsec_netstack;
10021 
10022 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10023 }
10024 
10025 /*
10026  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10027  * determines the grp on which it has to become exclusive, queues the mp
10028  * and IPSQ draining restarts the optmgmt
10029  */
10030 static boolean_t
10031 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10032 {
10033 	conn_t *connp = Q_TO_CONN(q);
10034 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10035 
10036 	/*
10037 	 * Take IPsec requests and treat them special.
10038 	 */
10039 	if (ipsec_opt_present(mp)) {
10040 		/* First check if IPsec is loaded. */
10041 		mutex_enter(&ipss->ipsec_loader_lock);
10042 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10043 			mutex_exit(&ipss->ipsec_loader_lock);
10044 			return (B_FALSE);
10045 		}
10046 		mutex_enter(&connp->conn_lock);
10047 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10048 
10049 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10050 		connp->conn_ipsec_opt_mp = mp;
10051 		mutex_exit(&connp->conn_lock);
10052 		mutex_exit(&ipss->ipsec_loader_lock);
10053 
10054 		ipsec_loader_loadnow(ipss);
10055 		return (B_TRUE);
10056 	}
10057 	return (B_FALSE);
10058 }
10059 
10060 /*
10061  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10062  * all of them are copied to the conn_t. If the req is "zero", the policy is
10063  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10064  * fields.
10065  * We keep only the latest setting of the policy and thus policy setting
10066  * is not incremental/cumulative.
10067  *
10068  * Requests to set policies with multiple alternative actions will
10069  * go through a different API.
10070  */
10071 int
10072 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10073 {
10074 	uint_t ah_req = 0;
10075 	uint_t esp_req = 0;
10076 	uint_t se_req = 0;
10077 	ipsec_act_t *actp = NULL;
10078 	uint_t nact;
10079 	ipsec_policy_head_t *ph;
10080 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
10081 	int error = 0;
10082 	netstack_t	*ns = connp->conn_netstack;
10083 	ip_stack_t	*ipst = ns->netstack_ip;
10084 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10085 
10086 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10087 
10088 	/*
10089 	 * The IP_SEC_OPT option does not allow variable length parameters,
10090 	 * hence a request cannot be NULL.
10091 	 */
10092 	if (req == NULL)
10093 		return (EINVAL);
10094 
10095 	ah_req = req->ipsr_ah_req;
10096 	esp_req = req->ipsr_esp_req;
10097 	se_req = req->ipsr_self_encap_req;
10098 
10099 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10100 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10101 		return (EINVAL);
10102 
10103 	/*
10104 	 * Are we dealing with a request to reset the policy (i.e.
10105 	 * zero requests).
10106 	 */
10107 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10108 	    (esp_req & REQ_MASK) == 0 &&
10109 	    (se_req & REQ_MASK) == 0);
10110 
10111 	if (!is_pol_reset) {
10112 		/*
10113 		 * If we couldn't load IPsec, fail with "protocol
10114 		 * not supported".
10115 		 * IPsec may not have been loaded for a request with zero
10116 		 * policies, so we don't fail in this case.
10117 		 */
10118 		mutex_enter(&ipss->ipsec_loader_lock);
10119 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10120 			mutex_exit(&ipss->ipsec_loader_lock);
10121 			return (EPROTONOSUPPORT);
10122 		}
10123 		mutex_exit(&ipss->ipsec_loader_lock);
10124 
10125 		/*
10126 		 * Test for valid requests. Invalid algorithms
10127 		 * need to be tested by IPsec code because new
10128 		 * algorithms can be added dynamically.
10129 		 */
10130 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10131 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10132 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10133 			return (EINVAL);
10134 		}
10135 
10136 		/*
10137 		 * Only privileged users can issue these
10138 		 * requests.
10139 		 */
10140 		if (((ah_req & IPSEC_PREF_NEVER) ||
10141 		    (esp_req & IPSEC_PREF_NEVER) ||
10142 		    (se_req & IPSEC_PREF_NEVER)) &&
10143 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10144 			return (EPERM);
10145 		}
10146 
10147 		/*
10148 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10149 		 * are mutually exclusive.
10150 		 */
10151 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10152 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10153 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10154 			/* Both of them are set */
10155 			return (EINVAL);
10156 		}
10157 	}
10158 
10159 	mutex_enter(&connp->conn_lock);
10160 
10161 	/*
10162 	 * If we have already cached policies in ip_bind_connected*(), don't
10163 	 * let them change now. We cache policies for connections
10164 	 * whose src,dst [addr, port] is known.
10165 	 */
10166 	if (connp->conn_policy_cached) {
10167 		mutex_exit(&connp->conn_lock);
10168 		return (EINVAL);
10169 	}
10170 
10171 	/*
10172 	 * We have a zero policies, reset the connection policy if already
10173 	 * set. This will cause the connection to inherit the
10174 	 * global policy, if any.
10175 	 */
10176 	if (is_pol_reset) {
10177 		if (connp->conn_policy != NULL) {
10178 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10179 			connp->conn_policy = NULL;
10180 		}
10181 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10182 		connp->conn_in_enforce_policy = B_FALSE;
10183 		connp->conn_out_enforce_policy = B_FALSE;
10184 		mutex_exit(&connp->conn_lock);
10185 		return (0);
10186 	}
10187 
10188 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10189 	    ipst->ips_netstack);
10190 	if (ph == NULL)
10191 		goto enomem;
10192 
10193 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10194 	if (actp == NULL)
10195 		goto enomem;
10196 
10197 	/*
10198 	 * Always insert IPv4 policy entries, since they can also apply to
10199 	 * ipv6 sockets being used in ipv4-compat mode.
10200 	 */
10201 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10202 	    IPSEC_TYPE_INBOUND, ns))
10203 		goto enomem;
10204 	is_pol_inserted = B_TRUE;
10205 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
10206 	    IPSEC_TYPE_OUTBOUND, ns))
10207 		goto enomem;
10208 
10209 	/*
10210 	 * We're looking at a v6 socket, also insert the v6-specific
10211 	 * entries.
10212 	 */
10213 	if (connp->conn_af_isv6) {
10214 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10215 		    IPSEC_TYPE_INBOUND, ns))
10216 			goto enomem;
10217 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
10218 		    IPSEC_TYPE_OUTBOUND, ns))
10219 			goto enomem;
10220 	}
10221 
10222 	ipsec_actvec_free(actp, nact);
10223 
10224 	/*
10225 	 * If the requests need security, set enforce_policy.
10226 	 * If the requests are IPSEC_PREF_NEVER, one should
10227 	 * still set conn_out_enforce_policy so that an ipsec_out
10228 	 * gets attached in ip_wput. This is needed so that
10229 	 * for connections that we don't cache policy in ip_bind,
10230 	 * if global policy matches in ip_wput_attach_policy, we
10231 	 * don't wrongly inherit global policy. Similarly, we need
10232 	 * to set conn_in_enforce_policy also so that we don't verify
10233 	 * policy wrongly.
10234 	 */
10235 	if ((ah_req & REQ_MASK) != 0 ||
10236 	    (esp_req & REQ_MASK) != 0 ||
10237 	    (se_req & REQ_MASK) != 0) {
10238 		connp->conn_in_enforce_policy = B_TRUE;
10239 		connp->conn_out_enforce_policy = B_TRUE;
10240 		connp->conn_flags |= IPCL_CHECK_POLICY;
10241 	}
10242 
10243 	mutex_exit(&connp->conn_lock);
10244 	return (error);
10245 #undef REQ_MASK
10246 
10247 	/*
10248 	 * Common memory-allocation-failure exit path.
10249 	 */
10250 enomem:
10251 	mutex_exit(&connp->conn_lock);
10252 	if (actp != NULL)
10253 		ipsec_actvec_free(actp, nact);
10254 	if (is_pol_inserted)
10255 		ipsec_polhead_flush(ph, ns);
10256 	return (ENOMEM);
10257 }
10258 
10259 /*
10260  * Only for options that pass in an IP addr. Currently only V4 options
10261  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10262  * So this function assumes level is IPPROTO_IP
10263  */
10264 int
10265 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10266     mblk_t *first_mp)
10267 {
10268 	ipif_t *ipif = NULL;
10269 	int error;
10270 	ill_t *ill;
10271 	int zoneid;
10272 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10273 
10274 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10275 
10276 	if (addr != INADDR_ANY || checkonly) {
10277 		ASSERT(connp != NULL);
10278 		zoneid = IPCL_ZONEID(connp);
10279 		if (option == IP_NEXTHOP) {
10280 			ipif = ipif_lookup_onlink_addr(addr,
10281 			    connp->conn_zoneid, ipst);
10282 		} else {
10283 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10284 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10285 			    &error, ipst);
10286 		}
10287 		if (ipif == NULL) {
10288 			if (error == EINPROGRESS)
10289 				return (error);
10290 			if ((option == IP_MULTICAST_IF) ||
10291 			    (option == IP_NEXTHOP))
10292 				return (EHOSTUNREACH);
10293 			else
10294 				return (EINVAL);
10295 		} else if (checkonly) {
10296 			if (option == IP_MULTICAST_IF) {
10297 				ill = ipif->ipif_ill;
10298 				/* not supported by the virtual network iface */
10299 				if (IS_VNI(ill)) {
10300 					ipif_refrele(ipif);
10301 					return (EINVAL);
10302 				}
10303 			}
10304 			ipif_refrele(ipif);
10305 			return (0);
10306 		}
10307 		ill = ipif->ipif_ill;
10308 		mutex_enter(&connp->conn_lock);
10309 		mutex_enter(&ill->ill_lock);
10310 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10311 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10312 			mutex_exit(&ill->ill_lock);
10313 			mutex_exit(&connp->conn_lock);
10314 			ipif_refrele(ipif);
10315 			return (option == IP_MULTICAST_IF ?
10316 			    EHOSTUNREACH : EINVAL);
10317 		}
10318 	} else {
10319 		mutex_enter(&connp->conn_lock);
10320 	}
10321 
10322 	/* None of the options below are supported on the VNI */
10323 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10324 		mutex_exit(&ill->ill_lock);
10325 		mutex_exit(&connp->conn_lock);
10326 		ipif_refrele(ipif);
10327 		return (EINVAL);
10328 	}
10329 
10330 	switch (option) {
10331 	case IP_MULTICAST_IF:
10332 		connp->conn_multicast_ipif = ipif;
10333 		break;
10334 	case IP_NEXTHOP:
10335 		connp->conn_nexthop_v4 = addr;
10336 		connp->conn_nexthop_set = B_TRUE;
10337 		break;
10338 	}
10339 
10340 	if (ipif != NULL) {
10341 		mutex_exit(&ill->ill_lock);
10342 		mutex_exit(&connp->conn_lock);
10343 		ipif_refrele(ipif);
10344 		return (0);
10345 	}
10346 	mutex_exit(&connp->conn_lock);
10347 	/* We succeded in cleared the option */
10348 	return (0);
10349 }
10350 
10351 /*
10352  * For options that pass in an ifindex specifying the ill. V6 options always
10353  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10354  */
10355 int
10356 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10357     int level, int option, mblk_t *first_mp)
10358 {
10359 	ill_t *ill = NULL;
10360 	int error = 0;
10361 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10362 
10363 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10364 	if (ifindex != 0) {
10365 		ASSERT(connp != NULL);
10366 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10367 		    first_mp, ip_restart_optmgmt, &error, ipst);
10368 		if (ill != NULL) {
10369 			if (checkonly) {
10370 				/* not supported by the virtual network iface */
10371 				if (IS_VNI(ill)) {
10372 					ill_refrele(ill);
10373 					return (EINVAL);
10374 				}
10375 				ill_refrele(ill);
10376 				return (0);
10377 			}
10378 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10379 			    0, NULL)) {
10380 				ill_refrele(ill);
10381 				ill = NULL;
10382 				mutex_enter(&connp->conn_lock);
10383 				goto setit;
10384 			}
10385 			mutex_enter(&connp->conn_lock);
10386 			mutex_enter(&ill->ill_lock);
10387 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10388 				mutex_exit(&ill->ill_lock);
10389 				mutex_exit(&connp->conn_lock);
10390 				ill_refrele(ill);
10391 				ill = NULL;
10392 				mutex_enter(&connp->conn_lock);
10393 			}
10394 			goto setit;
10395 		} else if (error == EINPROGRESS) {
10396 			return (error);
10397 		} else {
10398 			error = 0;
10399 		}
10400 	}
10401 	mutex_enter(&connp->conn_lock);
10402 setit:
10403 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10404 
10405 	/*
10406 	 * The options below assume that the ILL (if any) transmits and/or
10407 	 * receives traffic. Neither of which is true for the virtual network
10408 	 * interface, so fail setting these on a VNI.
10409 	 */
10410 	if (IS_VNI(ill)) {
10411 		ASSERT(ill != NULL);
10412 		mutex_exit(&ill->ill_lock);
10413 		mutex_exit(&connp->conn_lock);
10414 		ill_refrele(ill);
10415 		return (EINVAL);
10416 	}
10417 
10418 	if (level == IPPROTO_IP) {
10419 		switch (option) {
10420 		case IP_BOUND_IF:
10421 			connp->conn_incoming_ill = ill;
10422 			connp->conn_outgoing_ill = ill;
10423 			break;
10424 
10425 		case IP_MULTICAST_IF:
10426 			/*
10427 			 * This option is an internal special. The socket
10428 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10429 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10430 			 * specifies an ifindex and we try first on V6 ill's.
10431 			 * If we don't find one, we they try using on v4 ill's
10432 			 * intenally and we come here.
10433 			 */
10434 			if (!checkonly && ill != NULL) {
10435 				ipif_t	*ipif;
10436 				ipif = ill->ill_ipif;
10437 
10438 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10439 					mutex_exit(&ill->ill_lock);
10440 					mutex_exit(&connp->conn_lock);
10441 					ill_refrele(ill);
10442 					ill = NULL;
10443 					mutex_enter(&connp->conn_lock);
10444 				} else {
10445 					connp->conn_multicast_ipif = ipif;
10446 				}
10447 			}
10448 			break;
10449 
10450 		case IP_DHCPINIT_IF:
10451 			if (connp->conn_dhcpinit_ill != NULL) {
10452 				/*
10453 				 * We've locked the conn so conn_cleanup_ill()
10454 				 * cannot clear conn_dhcpinit_ill -- so it's
10455 				 * safe to access the ill.
10456 				 */
10457 				ill_t *oill = connp->conn_dhcpinit_ill;
10458 
10459 				ASSERT(oill->ill_dhcpinit != 0);
10460 				atomic_dec_32(&oill->ill_dhcpinit);
10461 				connp->conn_dhcpinit_ill = NULL;
10462 			}
10463 
10464 			if (ill != NULL) {
10465 				connp->conn_dhcpinit_ill = ill;
10466 				atomic_inc_32(&ill->ill_dhcpinit);
10467 			}
10468 			break;
10469 		}
10470 	} else {
10471 		switch (option) {
10472 		case IPV6_BOUND_IF:
10473 			connp->conn_incoming_ill = ill;
10474 			connp->conn_outgoing_ill = ill;
10475 			break;
10476 
10477 		case IPV6_MULTICAST_IF:
10478 			/*
10479 			 * Set conn_multicast_ill to be the IPv6 ill.
10480 			 * Set conn_multicast_ipif to be an IPv4 ipif
10481 			 * for ifindex to make IPv4 mapped addresses
10482 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10483 			 * Even if no IPv6 ill exists for the ifindex
10484 			 * we need to check for an IPv4 ifindex in order
10485 			 * for this to work with mapped addresses. In that
10486 			 * case only set conn_multicast_ipif.
10487 			 */
10488 			if (!checkonly) {
10489 				if (ifindex == 0) {
10490 					connp->conn_multicast_ill = NULL;
10491 					connp->conn_multicast_ipif = NULL;
10492 				} else if (ill != NULL) {
10493 					connp->conn_multicast_ill = ill;
10494 				}
10495 			}
10496 			break;
10497 		}
10498 	}
10499 
10500 	if (ill != NULL) {
10501 		mutex_exit(&ill->ill_lock);
10502 		mutex_exit(&connp->conn_lock);
10503 		ill_refrele(ill);
10504 		return (0);
10505 	}
10506 	mutex_exit(&connp->conn_lock);
10507 	/*
10508 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10509 	 * locate the ill and could not set the option (ifindex != 0)
10510 	 */
10511 	return (ifindex == 0 ? 0 : EINVAL);
10512 }
10513 
10514 /* This routine sets socket options. */
10515 /* ARGSUSED */
10516 int
10517 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10518     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10519     void *dummy, cred_t *cr, mblk_t *first_mp)
10520 {
10521 	int		*i1 = (int *)invalp;
10522 	conn_t		*connp = Q_TO_CONN(q);
10523 	int		error = 0;
10524 	boolean_t	checkonly;
10525 	ire_t		*ire;
10526 	boolean_t	found;
10527 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10528 
10529 	switch (optset_context) {
10530 
10531 	case SETFN_OPTCOM_CHECKONLY:
10532 		checkonly = B_TRUE;
10533 		/*
10534 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10535 		 * inlen != 0 implies value supplied and
10536 		 * 	we have to "pretend" to set it.
10537 		 * inlen == 0 implies that there is no
10538 		 * 	value part in T_CHECK request and just validation
10539 		 * done elsewhere should be enough, we just return here.
10540 		 */
10541 		if (inlen == 0) {
10542 			*outlenp = 0;
10543 			return (0);
10544 		}
10545 		break;
10546 	case SETFN_OPTCOM_NEGOTIATE:
10547 	case SETFN_UD_NEGOTIATE:
10548 	case SETFN_CONN_NEGOTIATE:
10549 		checkonly = B_FALSE;
10550 		break;
10551 	default:
10552 		/*
10553 		 * We should never get here
10554 		 */
10555 		*outlenp = 0;
10556 		return (EINVAL);
10557 	}
10558 
10559 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10560 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10561 
10562 	/*
10563 	 * For fixed length options, no sanity check
10564 	 * of passed in length is done. It is assumed *_optcom_req()
10565 	 * routines do the right thing.
10566 	 */
10567 
10568 	switch (level) {
10569 	case SOL_SOCKET:
10570 		/*
10571 		 * conn_lock protects the bitfields, and is used to
10572 		 * set the fields atomically.
10573 		 */
10574 		switch (name) {
10575 		case SO_BROADCAST:
10576 			if (!checkonly) {
10577 				/* TODO: use value someplace? */
10578 				mutex_enter(&connp->conn_lock);
10579 				connp->conn_broadcast = *i1 ? 1 : 0;
10580 				mutex_exit(&connp->conn_lock);
10581 			}
10582 			break;	/* goto sizeof (int) option return */
10583 		case SO_USELOOPBACK:
10584 			if (!checkonly) {
10585 				/* TODO: use value someplace? */
10586 				mutex_enter(&connp->conn_lock);
10587 				connp->conn_loopback = *i1 ? 1 : 0;
10588 				mutex_exit(&connp->conn_lock);
10589 			}
10590 			break;	/* goto sizeof (int) option return */
10591 		case SO_DONTROUTE:
10592 			if (!checkonly) {
10593 				mutex_enter(&connp->conn_lock);
10594 				connp->conn_dontroute = *i1 ? 1 : 0;
10595 				mutex_exit(&connp->conn_lock);
10596 			}
10597 			break;	/* goto sizeof (int) option return */
10598 		case SO_REUSEADDR:
10599 			if (!checkonly) {
10600 				mutex_enter(&connp->conn_lock);
10601 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10602 				mutex_exit(&connp->conn_lock);
10603 			}
10604 			break;	/* goto sizeof (int) option return */
10605 		case SO_PROTOTYPE:
10606 			if (!checkonly) {
10607 				mutex_enter(&connp->conn_lock);
10608 				connp->conn_proto = *i1;
10609 				mutex_exit(&connp->conn_lock);
10610 			}
10611 			break;	/* goto sizeof (int) option return */
10612 		case SO_ALLZONES:
10613 			if (!checkonly) {
10614 				mutex_enter(&connp->conn_lock);
10615 				if (IPCL_IS_BOUND(connp)) {
10616 					mutex_exit(&connp->conn_lock);
10617 					return (EINVAL);
10618 				}
10619 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10620 				mutex_exit(&connp->conn_lock);
10621 			}
10622 			break;	/* goto sizeof (int) option return */
10623 		case SO_ANON_MLP:
10624 			if (!checkonly) {
10625 				mutex_enter(&connp->conn_lock);
10626 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10627 				mutex_exit(&connp->conn_lock);
10628 			}
10629 			break;	/* goto sizeof (int) option return */
10630 		case SO_MAC_EXEMPT:
10631 			if (secpolicy_net_mac_aware(cr) != 0 ||
10632 			    IPCL_IS_BOUND(connp))
10633 				return (EACCES);
10634 			if (!checkonly) {
10635 				mutex_enter(&connp->conn_lock);
10636 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10637 				mutex_exit(&connp->conn_lock);
10638 			}
10639 			break;	/* goto sizeof (int) option return */
10640 		default:
10641 			/*
10642 			 * "soft" error (negative)
10643 			 * option not handled at this level
10644 			 * Note: Do not modify *outlenp
10645 			 */
10646 			return (-EINVAL);
10647 		}
10648 		break;
10649 	case IPPROTO_IP:
10650 		switch (name) {
10651 		case IP_NEXTHOP:
10652 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10653 				return (EPERM);
10654 			/* FALLTHRU */
10655 		case IP_MULTICAST_IF: {
10656 			ipaddr_t addr = *i1;
10657 
10658 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10659 			    first_mp);
10660 			if (error != 0)
10661 				return (error);
10662 			break;	/* goto sizeof (int) option return */
10663 		}
10664 
10665 		case IP_MULTICAST_TTL:
10666 			/* Recorded in transport above IP */
10667 			*outvalp = *invalp;
10668 			*outlenp = sizeof (uchar_t);
10669 			return (0);
10670 		case IP_MULTICAST_LOOP:
10671 			if (!checkonly) {
10672 				mutex_enter(&connp->conn_lock);
10673 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10674 				mutex_exit(&connp->conn_lock);
10675 			}
10676 			*outvalp = *invalp;
10677 			*outlenp = sizeof (uchar_t);
10678 			return (0);
10679 		case IP_ADD_MEMBERSHIP:
10680 		case MCAST_JOIN_GROUP:
10681 		case IP_DROP_MEMBERSHIP:
10682 		case MCAST_LEAVE_GROUP: {
10683 			struct ip_mreq *mreqp;
10684 			struct group_req *greqp;
10685 			ire_t *ire;
10686 			boolean_t done = B_FALSE;
10687 			ipaddr_t group, ifaddr;
10688 			struct sockaddr_in *sin;
10689 			uint32_t *ifindexp;
10690 			boolean_t mcast_opt = B_TRUE;
10691 			mcast_record_t fmode;
10692 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10693 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10694 
10695 			switch (name) {
10696 			case IP_ADD_MEMBERSHIP:
10697 				mcast_opt = B_FALSE;
10698 				/* FALLTHRU */
10699 			case MCAST_JOIN_GROUP:
10700 				fmode = MODE_IS_EXCLUDE;
10701 				optfn = ip_opt_add_group;
10702 				break;
10703 
10704 			case IP_DROP_MEMBERSHIP:
10705 				mcast_opt = B_FALSE;
10706 				/* FALLTHRU */
10707 			case MCAST_LEAVE_GROUP:
10708 				fmode = MODE_IS_INCLUDE;
10709 				optfn = ip_opt_delete_group;
10710 				break;
10711 			}
10712 
10713 			if (mcast_opt) {
10714 				greqp = (struct group_req *)i1;
10715 				sin = (struct sockaddr_in *)&greqp->gr_group;
10716 				if (sin->sin_family != AF_INET) {
10717 					*outlenp = 0;
10718 					return (ENOPROTOOPT);
10719 				}
10720 				group = (ipaddr_t)sin->sin_addr.s_addr;
10721 				ifaddr = INADDR_ANY;
10722 				ifindexp = &greqp->gr_interface;
10723 			} else {
10724 				mreqp = (struct ip_mreq *)i1;
10725 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10726 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10727 				ifindexp = NULL;
10728 			}
10729 
10730 			/*
10731 			 * In the multirouting case, we need to replicate
10732 			 * the request on all interfaces that will take part
10733 			 * in replication.  We do so because multirouting is
10734 			 * reflective, thus we will probably receive multi-
10735 			 * casts on those interfaces.
10736 			 * The ip_multirt_apply_membership() succeeds if the
10737 			 * operation succeeds on at least one interface.
10738 			 */
10739 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10740 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10741 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10742 			if (ire != NULL) {
10743 				if (ire->ire_flags & RTF_MULTIRT) {
10744 					error = ip_multirt_apply_membership(
10745 					    optfn, ire, connp, checkonly, group,
10746 					    fmode, INADDR_ANY, first_mp);
10747 					done = B_TRUE;
10748 				}
10749 				ire_refrele(ire);
10750 			}
10751 			if (!done) {
10752 				error = optfn(connp, checkonly, group, ifaddr,
10753 				    ifindexp, fmode, INADDR_ANY, first_mp);
10754 			}
10755 			if (error) {
10756 				/*
10757 				 * EINPROGRESS is a soft error, needs retry
10758 				 * so don't make *outlenp zero.
10759 				 */
10760 				if (error != EINPROGRESS)
10761 					*outlenp = 0;
10762 				return (error);
10763 			}
10764 			/* OK return - copy input buffer into output buffer */
10765 			if (invalp != outvalp) {
10766 				/* don't trust bcopy for identical src/dst */
10767 				bcopy(invalp, outvalp, inlen);
10768 			}
10769 			*outlenp = inlen;
10770 			return (0);
10771 		}
10772 		case IP_BLOCK_SOURCE:
10773 		case IP_UNBLOCK_SOURCE:
10774 		case IP_ADD_SOURCE_MEMBERSHIP:
10775 		case IP_DROP_SOURCE_MEMBERSHIP:
10776 		case MCAST_BLOCK_SOURCE:
10777 		case MCAST_UNBLOCK_SOURCE:
10778 		case MCAST_JOIN_SOURCE_GROUP:
10779 		case MCAST_LEAVE_SOURCE_GROUP: {
10780 			struct ip_mreq_source *imreqp;
10781 			struct group_source_req *gsreqp;
10782 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10783 			uint32_t ifindex = 0;
10784 			mcast_record_t fmode;
10785 			struct sockaddr_in *sin;
10786 			ire_t *ire;
10787 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10788 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10789 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10790 
10791 			switch (name) {
10792 			case IP_BLOCK_SOURCE:
10793 				mcast_opt = B_FALSE;
10794 				/* FALLTHRU */
10795 			case MCAST_BLOCK_SOURCE:
10796 				fmode = MODE_IS_EXCLUDE;
10797 				optfn = ip_opt_add_group;
10798 				break;
10799 
10800 			case IP_UNBLOCK_SOURCE:
10801 				mcast_opt = B_FALSE;
10802 				/* FALLTHRU */
10803 			case MCAST_UNBLOCK_SOURCE:
10804 				fmode = MODE_IS_EXCLUDE;
10805 				optfn = ip_opt_delete_group;
10806 				break;
10807 
10808 			case IP_ADD_SOURCE_MEMBERSHIP:
10809 				mcast_opt = B_FALSE;
10810 				/* FALLTHRU */
10811 			case MCAST_JOIN_SOURCE_GROUP:
10812 				fmode = MODE_IS_INCLUDE;
10813 				optfn = ip_opt_add_group;
10814 				break;
10815 
10816 			case IP_DROP_SOURCE_MEMBERSHIP:
10817 				mcast_opt = B_FALSE;
10818 				/* FALLTHRU */
10819 			case MCAST_LEAVE_SOURCE_GROUP:
10820 				fmode = MODE_IS_INCLUDE;
10821 				optfn = ip_opt_delete_group;
10822 				break;
10823 			}
10824 
10825 			if (mcast_opt) {
10826 				gsreqp = (struct group_source_req *)i1;
10827 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10828 					*outlenp = 0;
10829 					return (ENOPROTOOPT);
10830 				}
10831 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10832 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10833 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10834 				src = (ipaddr_t)sin->sin_addr.s_addr;
10835 				ifindex = gsreqp->gsr_interface;
10836 			} else {
10837 				imreqp = (struct ip_mreq_source *)i1;
10838 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10839 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10840 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10841 			}
10842 
10843 			/*
10844 			 * In the multirouting case, we need to replicate
10845 			 * the request as noted in the mcast cases above.
10846 			 */
10847 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10848 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10849 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10850 			if (ire != NULL) {
10851 				if (ire->ire_flags & RTF_MULTIRT) {
10852 					error = ip_multirt_apply_membership(
10853 					    optfn, ire, connp, checkonly, grp,
10854 					    fmode, src, first_mp);
10855 					done = B_TRUE;
10856 				}
10857 				ire_refrele(ire);
10858 			}
10859 			if (!done) {
10860 				error = optfn(connp, checkonly, grp, ifaddr,
10861 				    &ifindex, fmode, src, first_mp);
10862 			}
10863 			if (error != 0) {
10864 				/*
10865 				 * EINPROGRESS is a soft error, needs retry
10866 				 * so don't make *outlenp zero.
10867 				 */
10868 				if (error != EINPROGRESS)
10869 					*outlenp = 0;
10870 				return (error);
10871 			}
10872 			/* OK return - copy input buffer into output buffer */
10873 			if (invalp != outvalp) {
10874 				bcopy(invalp, outvalp, inlen);
10875 			}
10876 			*outlenp = inlen;
10877 			return (0);
10878 		}
10879 		case IP_SEC_OPT:
10880 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10881 			if (error != 0) {
10882 				*outlenp = 0;
10883 				return (error);
10884 			}
10885 			break;
10886 		case IP_HDRINCL:
10887 		case IP_OPTIONS:
10888 		case T_IP_OPTIONS:
10889 		case IP_TOS:
10890 		case T_IP_TOS:
10891 		case IP_TTL:
10892 		case IP_RECVDSTADDR:
10893 		case IP_RECVOPTS:
10894 			/* OK return - copy input buffer into output buffer */
10895 			if (invalp != outvalp) {
10896 				/* don't trust bcopy for identical src/dst */
10897 				bcopy(invalp, outvalp, inlen);
10898 			}
10899 			*outlenp = inlen;
10900 			return (0);
10901 		case IP_RECVIF:
10902 			/* Retrieve the inbound interface index */
10903 			if (!checkonly) {
10904 				mutex_enter(&connp->conn_lock);
10905 				connp->conn_recvif = *i1 ? 1 : 0;
10906 				mutex_exit(&connp->conn_lock);
10907 			}
10908 			break;	/* goto sizeof (int) option return */
10909 		case IP_RECVPKTINFO:
10910 			if (!checkonly) {
10911 				mutex_enter(&connp->conn_lock);
10912 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10913 				mutex_exit(&connp->conn_lock);
10914 			}
10915 			break;	/* goto sizeof (int) option return */
10916 		case IP_RECVSLLA:
10917 			/* Retrieve the source link layer address */
10918 			if (!checkonly) {
10919 				mutex_enter(&connp->conn_lock);
10920 				connp->conn_recvslla = *i1 ? 1 : 0;
10921 				mutex_exit(&connp->conn_lock);
10922 			}
10923 			break;	/* goto sizeof (int) option return */
10924 		case MRT_INIT:
10925 		case MRT_DONE:
10926 		case MRT_ADD_VIF:
10927 		case MRT_DEL_VIF:
10928 		case MRT_ADD_MFC:
10929 		case MRT_DEL_MFC:
10930 		case MRT_ASSERT:
10931 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10932 				*outlenp = 0;
10933 				return (error);
10934 			}
10935 			error = ip_mrouter_set((int)name, q, checkonly,
10936 			    (uchar_t *)invalp, inlen, first_mp);
10937 			if (error) {
10938 				*outlenp = 0;
10939 				return (error);
10940 			}
10941 			/* OK return - copy input buffer into output buffer */
10942 			if (invalp != outvalp) {
10943 				/* don't trust bcopy for identical src/dst */
10944 				bcopy(invalp, outvalp, inlen);
10945 			}
10946 			*outlenp = inlen;
10947 			return (0);
10948 		case IP_BOUND_IF:
10949 		case IP_DHCPINIT_IF:
10950 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10951 			    level, name, first_mp);
10952 			if (error != 0)
10953 				return (error);
10954 			break; 		/* goto sizeof (int) option return */
10955 
10956 		case IP_UNSPEC_SRC:
10957 			/* Allow sending with a zero source address */
10958 			if (!checkonly) {
10959 				mutex_enter(&connp->conn_lock);
10960 				connp->conn_unspec_src = *i1 ? 1 : 0;
10961 				mutex_exit(&connp->conn_lock);
10962 			}
10963 			break;	/* goto sizeof (int) option return */
10964 		default:
10965 			/*
10966 			 * "soft" error (negative)
10967 			 * option not handled at this level
10968 			 * Note: Do not modify *outlenp
10969 			 */
10970 			return (-EINVAL);
10971 		}
10972 		break;
10973 	case IPPROTO_IPV6:
10974 		switch (name) {
10975 		case IPV6_BOUND_IF:
10976 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10977 			    level, name, first_mp);
10978 			if (error != 0)
10979 				return (error);
10980 			break; 		/* goto sizeof (int) option return */
10981 
10982 		case IPV6_MULTICAST_IF:
10983 			/*
10984 			 * The only possible errors are EINPROGRESS and
10985 			 * EINVAL. EINPROGRESS will be restarted and is not
10986 			 * a hard error. We call this option on both V4 and V6
10987 			 * If both return EINVAL, then this call returns
10988 			 * EINVAL. If at least one of them succeeds we
10989 			 * return success.
10990 			 */
10991 			found = B_FALSE;
10992 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10993 			    level, name, first_mp);
10994 			if (error == EINPROGRESS)
10995 				return (error);
10996 			if (error == 0)
10997 				found = B_TRUE;
10998 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10999 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11000 			if (error == 0)
11001 				found = B_TRUE;
11002 			if (!found)
11003 				return (error);
11004 			break; 		/* goto sizeof (int) option return */
11005 
11006 		case IPV6_MULTICAST_HOPS:
11007 			/* Recorded in transport above IP */
11008 			break;	/* goto sizeof (int) option return */
11009 		case IPV6_MULTICAST_LOOP:
11010 			if (!checkonly) {
11011 				mutex_enter(&connp->conn_lock);
11012 				connp->conn_multicast_loop = *i1;
11013 				mutex_exit(&connp->conn_lock);
11014 			}
11015 			break;	/* goto sizeof (int) option return */
11016 		case IPV6_JOIN_GROUP:
11017 		case MCAST_JOIN_GROUP:
11018 		case IPV6_LEAVE_GROUP:
11019 		case MCAST_LEAVE_GROUP: {
11020 			struct ipv6_mreq *ip_mreqp;
11021 			struct group_req *greqp;
11022 			ire_t *ire;
11023 			boolean_t done = B_FALSE;
11024 			in6_addr_t groupv6;
11025 			uint32_t ifindex;
11026 			boolean_t mcast_opt = B_TRUE;
11027 			mcast_record_t fmode;
11028 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11029 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11030 
11031 			switch (name) {
11032 			case IPV6_JOIN_GROUP:
11033 				mcast_opt = B_FALSE;
11034 				/* FALLTHRU */
11035 			case MCAST_JOIN_GROUP:
11036 				fmode = MODE_IS_EXCLUDE;
11037 				optfn = ip_opt_add_group_v6;
11038 				break;
11039 
11040 			case IPV6_LEAVE_GROUP:
11041 				mcast_opt = B_FALSE;
11042 				/* FALLTHRU */
11043 			case MCAST_LEAVE_GROUP:
11044 				fmode = MODE_IS_INCLUDE;
11045 				optfn = ip_opt_delete_group_v6;
11046 				break;
11047 			}
11048 
11049 			if (mcast_opt) {
11050 				struct sockaddr_in *sin;
11051 				struct sockaddr_in6 *sin6;
11052 				greqp = (struct group_req *)i1;
11053 				if (greqp->gr_group.ss_family == AF_INET) {
11054 					sin = (struct sockaddr_in *)
11055 					    &(greqp->gr_group);
11056 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11057 					    &groupv6);
11058 				} else {
11059 					sin6 = (struct sockaddr_in6 *)
11060 					    &(greqp->gr_group);
11061 					groupv6 = sin6->sin6_addr;
11062 				}
11063 				ifindex = greqp->gr_interface;
11064 			} else {
11065 				ip_mreqp = (struct ipv6_mreq *)i1;
11066 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11067 				ifindex = ip_mreqp->ipv6mr_interface;
11068 			}
11069 			/*
11070 			 * In the multirouting case, we need to replicate
11071 			 * the request on all interfaces that will take part
11072 			 * in replication.  We do so because multirouting is
11073 			 * reflective, thus we will probably receive multi-
11074 			 * casts on those interfaces.
11075 			 * The ip_multirt_apply_membership_v6() succeeds if
11076 			 * the operation succeeds on at least one interface.
11077 			 */
11078 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11079 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11080 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11081 			if (ire != NULL) {
11082 				if (ire->ire_flags & RTF_MULTIRT) {
11083 					error = ip_multirt_apply_membership_v6(
11084 					    optfn, ire, connp, checkonly,
11085 					    &groupv6, fmode, &ipv6_all_zeros,
11086 					    first_mp);
11087 					done = B_TRUE;
11088 				}
11089 				ire_refrele(ire);
11090 			}
11091 			if (!done) {
11092 				error = optfn(connp, checkonly, &groupv6,
11093 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11094 			}
11095 			if (error) {
11096 				/*
11097 				 * EINPROGRESS is a soft error, needs retry
11098 				 * so don't make *outlenp zero.
11099 				 */
11100 				if (error != EINPROGRESS)
11101 					*outlenp = 0;
11102 				return (error);
11103 			}
11104 			/* OK return - copy input buffer into output buffer */
11105 			if (invalp != outvalp) {
11106 				/* don't trust bcopy for identical src/dst */
11107 				bcopy(invalp, outvalp, inlen);
11108 			}
11109 			*outlenp = inlen;
11110 			return (0);
11111 		}
11112 		case MCAST_BLOCK_SOURCE:
11113 		case MCAST_UNBLOCK_SOURCE:
11114 		case MCAST_JOIN_SOURCE_GROUP:
11115 		case MCAST_LEAVE_SOURCE_GROUP: {
11116 			struct group_source_req *gsreqp;
11117 			in6_addr_t v6grp, v6src;
11118 			uint32_t ifindex;
11119 			mcast_record_t fmode;
11120 			ire_t *ire;
11121 			boolean_t done = B_FALSE;
11122 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11123 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11124 
11125 			switch (name) {
11126 			case MCAST_BLOCK_SOURCE:
11127 				fmode = MODE_IS_EXCLUDE;
11128 				optfn = ip_opt_add_group_v6;
11129 				break;
11130 			case MCAST_UNBLOCK_SOURCE:
11131 				fmode = MODE_IS_EXCLUDE;
11132 				optfn = ip_opt_delete_group_v6;
11133 				break;
11134 			case MCAST_JOIN_SOURCE_GROUP:
11135 				fmode = MODE_IS_INCLUDE;
11136 				optfn = ip_opt_add_group_v6;
11137 				break;
11138 			case MCAST_LEAVE_SOURCE_GROUP:
11139 				fmode = MODE_IS_INCLUDE;
11140 				optfn = ip_opt_delete_group_v6;
11141 				break;
11142 			}
11143 
11144 			gsreqp = (struct group_source_req *)i1;
11145 			ifindex = gsreqp->gsr_interface;
11146 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11147 				struct sockaddr_in *s;
11148 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11149 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11150 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11151 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11152 			} else {
11153 				struct sockaddr_in6 *s6;
11154 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11155 				v6grp = s6->sin6_addr;
11156 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11157 				v6src = s6->sin6_addr;
11158 			}
11159 
11160 			/*
11161 			 * In the multirouting case, we need to replicate
11162 			 * the request as noted in the mcast cases above.
11163 			 */
11164 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11165 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11166 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11167 			if (ire != NULL) {
11168 				if (ire->ire_flags & RTF_MULTIRT) {
11169 					error = ip_multirt_apply_membership_v6(
11170 					    optfn, ire, connp, checkonly,
11171 					    &v6grp, fmode, &v6src, first_mp);
11172 					done = B_TRUE;
11173 				}
11174 				ire_refrele(ire);
11175 			}
11176 			if (!done) {
11177 				error = optfn(connp, checkonly, &v6grp,
11178 				    ifindex, fmode, &v6src, first_mp);
11179 			}
11180 			if (error != 0) {
11181 				/*
11182 				 * EINPROGRESS is a soft error, needs retry
11183 				 * so don't make *outlenp zero.
11184 				 */
11185 				if (error != EINPROGRESS)
11186 					*outlenp = 0;
11187 				return (error);
11188 			}
11189 			/* OK return - copy input buffer into output buffer */
11190 			if (invalp != outvalp) {
11191 				bcopy(invalp, outvalp, inlen);
11192 			}
11193 			*outlenp = inlen;
11194 			return (0);
11195 		}
11196 		case IPV6_UNICAST_HOPS:
11197 			/* Recorded in transport above IP */
11198 			break;	/* goto sizeof (int) option return */
11199 		case IPV6_UNSPEC_SRC:
11200 			/* Allow sending with a zero source address */
11201 			if (!checkonly) {
11202 				mutex_enter(&connp->conn_lock);
11203 				connp->conn_unspec_src = *i1 ? 1 : 0;
11204 				mutex_exit(&connp->conn_lock);
11205 			}
11206 			break;	/* goto sizeof (int) option return */
11207 		case IPV6_RECVPKTINFO:
11208 			if (!checkonly) {
11209 				mutex_enter(&connp->conn_lock);
11210 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11211 				mutex_exit(&connp->conn_lock);
11212 			}
11213 			break;	/* goto sizeof (int) option return */
11214 		case IPV6_RECVTCLASS:
11215 			if (!checkonly) {
11216 				if (*i1 < 0 || *i1 > 1) {
11217 					return (EINVAL);
11218 				}
11219 				mutex_enter(&connp->conn_lock);
11220 				connp->conn_ipv6_recvtclass = *i1;
11221 				mutex_exit(&connp->conn_lock);
11222 			}
11223 			break;
11224 		case IPV6_RECVPATHMTU:
11225 			if (!checkonly) {
11226 				if (*i1 < 0 || *i1 > 1) {
11227 					return (EINVAL);
11228 				}
11229 				mutex_enter(&connp->conn_lock);
11230 				connp->conn_ipv6_recvpathmtu = *i1;
11231 				mutex_exit(&connp->conn_lock);
11232 			}
11233 			break;
11234 		case IPV6_RECVHOPLIMIT:
11235 			if (!checkonly) {
11236 				mutex_enter(&connp->conn_lock);
11237 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11238 				mutex_exit(&connp->conn_lock);
11239 			}
11240 			break;	/* goto sizeof (int) option return */
11241 		case IPV6_RECVHOPOPTS:
11242 			if (!checkonly) {
11243 				mutex_enter(&connp->conn_lock);
11244 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11245 				mutex_exit(&connp->conn_lock);
11246 			}
11247 			break;	/* goto sizeof (int) option return */
11248 		case IPV6_RECVDSTOPTS:
11249 			if (!checkonly) {
11250 				mutex_enter(&connp->conn_lock);
11251 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11252 				mutex_exit(&connp->conn_lock);
11253 			}
11254 			break;	/* goto sizeof (int) option return */
11255 		case IPV6_RECVRTHDR:
11256 			if (!checkonly) {
11257 				mutex_enter(&connp->conn_lock);
11258 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11259 				mutex_exit(&connp->conn_lock);
11260 			}
11261 			break;	/* goto sizeof (int) option return */
11262 		case IPV6_RECVRTHDRDSTOPTS:
11263 			if (!checkonly) {
11264 				mutex_enter(&connp->conn_lock);
11265 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11266 				mutex_exit(&connp->conn_lock);
11267 			}
11268 			break;	/* goto sizeof (int) option return */
11269 		case IPV6_PKTINFO:
11270 			if (inlen == 0)
11271 				return (-EINVAL);	/* clearing option */
11272 			error = ip6_set_pktinfo(cr, connp,
11273 			    (struct in6_pktinfo *)invalp);
11274 			if (error != 0)
11275 				*outlenp = 0;
11276 			else
11277 				*outlenp = inlen;
11278 			return (error);
11279 		case IPV6_NEXTHOP: {
11280 			struct sockaddr_in6 *sin6;
11281 
11282 			/* Verify that the nexthop is reachable */
11283 			if (inlen == 0)
11284 				return (-EINVAL);	/* clearing option */
11285 
11286 			sin6 = (struct sockaddr_in6 *)invalp;
11287 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11288 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11289 			    NULL, MATCH_IRE_DEFAULT, ipst);
11290 
11291 			if (ire == NULL) {
11292 				*outlenp = 0;
11293 				return (EHOSTUNREACH);
11294 			}
11295 			ire_refrele(ire);
11296 			return (-EINVAL);
11297 		}
11298 		case IPV6_SEC_OPT:
11299 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11300 			if (error != 0) {
11301 				*outlenp = 0;
11302 				return (error);
11303 			}
11304 			break;
11305 		case IPV6_SRC_PREFERENCES: {
11306 			/*
11307 			 * This is implemented strictly in the ip module
11308 			 * (here and in tcp_opt_*() to accomodate tcp
11309 			 * sockets).  Modules above ip pass this option
11310 			 * down here since ip is the only one that needs to
11311 			 * be aware of source address preferences.
11312 			 *
11313 			 * This socket option only affects connected
11314 			 * sockets that haven't already bound to a specific
11315 			 * IPv6 address.  In other words, sockets that
11316 			 * don't call bind() with an address other than the
11317 			 * unspecified address and that call connect().
11318 			 * ip_bind_connected_v6() passes these preferences
11319 			 * to the ipif_select_source_v6() function.
11320 			 */
11321 			if (inlen != sizeof (uint32_t))
11322 				return (EINVAL);
11323 			error = ip6_set_src_preferences(connp,
11324 			    *(uint32_t *)invalp);
11325 			if (error != 0) {
11326 				*outlenp = 0;
11327 				return (error);
11328 			} else {
11329 				*outlenp = sizeof (uint32_t);
11330 			}
11331 			break;
11332 		}
11333 		case IPV6_V6ONLY:
11334 			if (*i1 < 0 || *i1 > 1) {
11335 				return (EINVAL);
11336 			}
11337 			mutex_enter(&connp->conn_lock);
11338 			connp->conn_ipv6_v6only = *i1;
11339 			mutex_exit(&connp->conn_lock);
11340 			break;
11341 		default:
11342 			return (-EINVAL);
11343 		}
11344 		break;
11345 	default:
11346 		/*
11347 		 * "soft" error (negative)
11348 		 * option not handled at this level
11349 		 * Note: Do not modify *outlenp
11350 		 */
11351 		return (-EINVAL);
11352 	}
11353 	/*
11354 	 * Common case of return from an option that is sizeof (int)
11355 	 */
11356 	*(int *)outvalp = *i1;
11357 	*outlenp = sizeof (int);
11358 	return (0);
11359 }
11360 
11361 /*
11362  * This routine gets default values of certain options whose default
11363  * values are maintained by protocol specific code
11364  */
11365 /* ARGSUSED */
11366 int
11367 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11368 {
11369 	int *i1 = (int *)ptr;
11370 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11371 
11372 	switch (level) {
11373 	case IPPROTO_IP:
11374 		switch (name) {
11375 		case IP_MULTICAST_TTL:
11376 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11377 			return (sizeof (uchar_t));
11378 		case IP_MULTICAST_LOOP:
11379 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11380 			return (sizeof (uchar_t));
11381 		default:
11382 			return (-1);
11383 		}
11384 	case IPPROTO_IPV6:
11385 		switch (name) {
11386 		case IPV6_UNICAST_HOPS:
11387 			*i1 = ipst->ips_ipv6_def_hops;
11388 			return (sizeof (int));
11389 		case IPV6_MULTICAST_HOPS:
11390 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11391 			return (sizeof (int));
11392 		case IPV6_MULTICAST_LOOP:
11393 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11394 			return (sizeof (int));
11395 		case IPV6_V6ONLY:
11396 			*i1 = 1;
11397 			return (sizeof (int));
11398 		default:
11399 			return (-1);
11400 		}
11401 	default:
11402 		return (-1);
11403 	}
11404 	/* NOTREACHED */
11405 }
11406 
11407 /*
11408  * Given a destination address and a pointer to where to put the information
11409  * this routine fills in the mtuinfo.
11410  */
11411 int
11412 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11413     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11414 {
11415 	ire_t *ire;
11416 	ip_stack_t	*ipst = ns->netstack_ip;
11417 
11418 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11419 		return (-1);
11420 
11421 	bzero(mtuinfo, sizeof (*mtuinfo));
11422 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11423 	mtuinfo->ip6m_addr.sin6_port = port;
11424 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11425 
11426 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11427 	if (ire != NULL) {
11428 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11429 		ire_refrele(ire);
11430 	} else {
11431 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11432 	}
11433 	return (sizeof (struct ip6_mtuinfo));
11434 }
11435 
11436 /*
11437  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11438  * checking of cred and that ip_g_mrouter is set should be done and
11439  * isn't.  This doesn't matter as the error checking is done properly for the
11440  * other MRT options coming in through ip_opt_set.
11441  */
11442 int
11443 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11444 {
11445 	conn_t		*connp = Q_TO_CONN(q);
11446 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11447 
11448 	switch (level) {
11449 	case IPPROTO_IP:
11450 		switch (name) {
11451 		case MRT_VERSION:
11452 		case MRT_ASSERT:
11453 			(void) ip_mrouter_get(name, q, ptr);
11454 			return (sizeof (int));
11455 		case IP_SEC_OPT:
11456 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11457 		case IP_NEXTHOP:
11458 			if (connp->conn_nexthop_set) {
11459 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11460 				return (sizeof (ipaddr_t));
11461 			} else
11462 				return (0);
11463 		case IP_RECVPKTINFO:
11464 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11465 			return (sizeof (int));
11466 		default:
11467 			break;
11468 		}
11469 		break;
11470 	case IPPROTO_IPV6:
11471 		switch (name) {
11472 		case IPV6_SEC_OPT:
11473 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11474 		case IPV6_SRC_PREFERENCES: {
11475 			return (ip6_get_src_preferences(connp,
11476 			    (uint32_t *)ptr));
11477 		}
11478 		case IPV6_V6ONLY:
11479 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11480 			return (sizeof (int));
11481 		case IPV6_PATHMTU:
11482 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11483 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11484 		default:
11485 			break;
11486 		}
11487 		break;
11488 	default:
11489 		break;
11490 	}
11491 	return (-1);
11492 }
11493 /* Named Dispatch routine to get a current value out of our parameter table. */
11494 /* ARGSUSED */
11495 static int
11496 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11497 {
11498 	ipparam_t *ippa = (ipparam_t *)cp;
11499 
11500 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11501 	return (0);
11502 }
11503 
11504 /* ARGSUSED */
11505 static int
11506 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11507 {
11508 
11509 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11510 	return (0);
11511 }
11512 
11513 /*
11514  * Set ip{,6}_forwarding values.  This means walking through all of the
11515  * ill's and toggling their forwarding values.
11516  */
11517 /* ARGSUSED */
11518 static int
11519 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11520 {
11521 	long new_value;
11522 	int *forwarding_value = (int *)cp;
11523 	ill_t *ill;
11524 	boolean_t isv6;
11525 	ill_walk_context_t ctx;
11526 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11527 
11528 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11529 
11530 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11531 	    new_value < 0 || new_value > 1) {
11532 		return (EINVAL);
11533 	}
11534 
11535 	*forwarding_value = new_value;
11536 
11537 	/*
11538 	 * Regardless of the current value of ip_forwarding, set all per-ill
11539 	 * values of ip_forwarding to the value being set.
11540 	 *
11541 	 * Bring all the ill's up to date with the new global value.
11542 	 */
11543 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11544 
11545 	if (isv6)
11546 		ill = ILL_START_WALK_V6(&ctx, ipst);
11547 	else
11548 		ill = ILL_START_WALK_V4(&ctx, ipst);
11549 
11550 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11551 		(void) ill_forward_set(ill, new_value != 0);
11552 
11553 	rw_exit(&ipst->ips_ill_g_lock);
11554 	return (0);
11555 }
11556 
11557 /*
11558  * Walk through the param array specified registering each element with the
11559  * Named Dispatch handler. This is called only during init. So it is ok
11560  * not to acquire any locks
11561  */
11562 static boolean_t
11563 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11564     ipndp_t *ipnd, size_t ipnd_cnt)
11565 {
11566 	for (; ippa_cnt-- > 0; ippa++) {
11567 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11568 			if (!nd_load(ndp, ippa->ip_param_name,
11569 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11570 				nd_free(ndp);
11571 				return (B_FALSE);
11572 			}
11573 		}
11574 	}
11575 
11576 	for (; ipnd_cnt-- > 0; ipnd++) {
11577 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11578 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11579 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11580 			    ipnd->ip_ndp_data)) {
11581 				nd_free(ndp);
11582 				return (B_FALSE);
11583 			}
11584 		}
11585 	}
11586 
11587 	return (B_TRUE);
11588 }
11589 
11590 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11591 /* ARGSUSED */
11592 static int
11593 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11594 {
11595 	long		new_value;
11596 	ipparam_t	*ippa = (ipparam_t *)cp;
11597 
11598 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11599 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11600 		return (EINVAL);
11601 	}
11602 	ippa->ip_param_value = new_value;
11603 	return (0);
11604 }
11605 
11606 /*
11607  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11608  * When an ipf is passed here for the first time, if
11609  * we already have in-order fragments on the queue, we convert from the fast-
11610  * path reassembly scheme to the hard-case scheme.  From then on, additional
11611  * fragments are reassembled here.  We keep track of the start and end offsets
11612  * of each piece, and the number of holes in the chain.  When the hole count
11613  * goes to zero, we are done!
11614  *
11615  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11616  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11617  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11618  * after the call to ip_reassemble().
11619  */
11620 int
11621 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11622     size_t msg_len)
11623 {
11624 	uint_t	end;
11625 	mblk_t	*next_mp;
11626 	mblk_t	*mp1;
11627 	uint_t	offset;
11628 	boolean_t incr_dups = B_TRUE;
11629 	boolean_t offset_zero_seen = B_FALSE;
11630 	boolean_t pkt_boundary_checked = B_FALSE;
11631 
11632 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11633 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11634 
11635 	/* Add in byte count */
11636 	ipf->ipf_count += msg_len;
11637 	if (ipf->ipf_end) {
11638 		/*
11639 		 * We were part way through in-order reassembly, but now there
11640 		 * is a hole.  We walk through messages already queued, and
11641 		 * mark them for hard case reassembly.  We know that up till
11642 		 * now they were in order starting from offset zero.
11643 		 */
11644 		offset = 0;
11645 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11646 			IP_REASS_SET_START(mp1, offset);
11647 			if (offset == 0) {
11648 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11649 				offset = -ipf->ipf_nf_hdr_len;
11650 			}
11651 			offset += mp1->b_wptr - mp1->b_rptr;
11652 			IP_REASS_SET_END(mp1, offset);
11653 		}
11654 		/* One hole at the end. */
11655 		ipf->ipf_hole_cnt = 1;
11656 		/* Brand it as a hard case, forever. */
11657 		ipf->ipf_end = 0;
11658 	}
11659 	/* Walk through all the new pieces. */
11660 	do {
11661 		end = start + (mp->b_wptr - mp->b_rptr);
11662 		/*
11663 		 * If start is 0, decrease 'end' only for the first mblk of
11664 		 * the fragment. Otherwise 'end' can get wrong value in the
11665 		 * second pass of the loop if first mblk is exactly the
11666 		 * size of ipf_nf_hdr_len.
11667 		 */
11668 		if (start == 0 && !offset_zero_seen) {
11669 			/* First segment */
11670 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11671 			end -= ipf->ipf_nf_hdr_len;
11672 			offset_zero_seen = B_TRUE;
11673 		}
11674 		next_mp = mp->b_cont;
11675 		/*
11676 		 * We are checking to see if there is any interesing data
11677 		 * to process.  If there isn't and the mblk isn't the
11678 		 * one which carries the unfragmentable header then we
11679 		 * drop it.  It's possible to have just the unfragmentable
11680 		 * header come through without any data.  That needs to be
11681 		 * saved.
11682 		 *
11683 		 * If the assert at the top of this function holds then the
11684 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11685 		 * is infrequently traveled enough that the test is left in
11686 		 * to protect against future code changes which break that
11687 		 * invariant.
11688 		 */
11689 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11690 			/* Empty.  Blast it. */
11691 			IP_REASS_SET_START(mp, 0);
11692 			IP_REASS_SET_END(mp, 0);
11693 			/*
11694 			 * If the ipf points to the mblk we are about to free,
11695 			 * update ipf to point to the next mblk (or NULL
11696 			 * if none).
11697 			 */
11698 			if (ipf->ipf_mp->b_cont == mp)
11699 				ipf->ipf_mp->b_cont = next_mp;
11700 			freeb(mp);
11701 			continue;
11702 		}
11703 		mp->b_cont = NULL;
11704 		IP_REASS_SET_START(mp, start);
11705 		IP_REASS_SET_END(mp, end);
11706 		if (!ipf->ipf_tail_mp) {
11707 			ipf->ipf_tail_mp = mp;
11708 			ipf->ipf_mp->b_cont = mp;
11709 			if (start == 0 || !more) {
11710 				ipf->ipf_hole_cnt = 1;
11711 				/*
11712 				 * if the first fragment comes in more than one
11713 				 * mblk, this loop will be executed for each
11714 				 * mblk. Need to adjust hole count so exiting
11715 				 * this routine will leave hole count at 1.
11716 				 */
11717 				if (next_mp)
11718 					ipf->ipf_hole_cnt++;
11719 			} else
11720 				ipf->ipf_hole_cnt = 2;
11721 			continue;
11722 		} else if (ipf->ipf_last_frag_seen && !more &&
11723 		    !pkt_boundary_checked) {
11724 			/*
11725 			 * We check datagram boundary only if this fragment
11726 			 * claims to be the last fragment and we have seen a
11727 			 * last fragment in the past too. We do this only
11728 			 * once for a given fragment.
11729 			 *
11730 			 * start cannot be 0 here as fragments with start=0
11731 			 * and MF=0 gets handled as a complete packet. These
11732 			 * fragments should not reach here.
11733 			 */
11734 
11735 			if (start + msgdsize(mp) !=
11736 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11737 				/*
11738 				 * We have two fragments both of which claim
11739 				 * to be the last fragment but gives conflicting
11740 				 * information about the whole datagram size.
11741 				 * Something fishy is going on. Drop the
11742 				 * fragment and free up the reassembly list.
11743 				 */
11744 				return (IP_REASS_FAILED);
11745 			}
11746 
11747 			/*
11748 			 * We shouldn't come to this code block again for this
11749 			 * particular fragment.
11750 			 */
11751 			pkt_boundary_checked = B_TRUE;
11752 		}
11753 
11754 		/* New stuff at or beyond tail? */
11755 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11756 		if (start >= offset) {
11757 			if (ipf->ipf_last_frag_seen) {
11758 				/* current fragment is beyond last fragment */
11759 				return (IP_REASS_FAILED);
11760 			}
11761 			/* Link it on end. */
11762 			ipf->ipf_tail_mp->b_cont = mp;
11763 			ipf->ipf_tail_mp = mp;
11764 			if (more) {
11765 				if (start != offset)
11766 					ipf->ipf_hole_cnt++;
11767 			} else if (start == offset && next_mp == NULL)
11768 					ipf->ipf_hole_cnt--;
11769 			continue;
11770 		}
11771 		mp1 = ipf->ipf_mp->b_cont;
11772 		offset = IP_REASS_START(mp1);
11773 		/* New stuff at the front? */
11774 		if (start < offset) {
11775 			if (start == 0) {
11776 				if (end >= offset) {
11777 					/* Nailed the hole at the begining. */
11778 					ipf->ipf_hole_cnt--;
11779 				}
11780 			} else if (end < offset) {
11781 				/*
11782 				 * A hole, stuff, and a hole where there used
11783 				 * to be just a hole.
11784 				 */
11785 				ipf->ipf_hole_cnt++;
11786 			}
11787 			mp->b_cont = mp1;
11788 			/* Check for overlap. */
11789 			while (end > offset) {
11790 				if (end < IP_REASS_END(mp1)) {
11791 					mp->b_wptr -= end - offset;
11792 					IP_REASS_SET_END(mp, offset);
11793 					BUMP_MIB(ill->ill_ip_mib,
11794 					    ipIfStatsReasmPartDups);
11795 					break;
11796 				}
11797 				/* Did we cover another hole? */
11798 				if ((mp1->b_cont &&
11799 				    IP_REASS_END(mp1) !=
11800 				    IP_REASS_START(mp1->b_cont) &&
11801 				    end >= IP_REASS_START(mp1->b_cont)) ||
11802 				    (!ipf->ipf_last_frag_seen && !more)) {
11803 					ipf->ipf_hole_cnt--;
11804 				}
11805 				/* Clip out mp1. */
11806 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11807 					/*
11808 					 * After clipping out mp1, this guy
11809 					 * is now hanging off the end.
11810 					 */
11811 					ipf->ipf_tail_mp = mp;
11812 				}
11813 				IP_REASS_SET_START(mp1, 0);
11814 				IP_REASS_SET_END(mp1, 0);
11815 				/* Subtract byte count */
11816 				ipf->ipf_count -= mp1->b_datap->db_lim -
11817 				    mp1->b_datap->db_base;
11818 				freeb(mp1);
11819 				BUMP_MIB(ill->ill_ip_mib,
11820 				    ipIfStatsReasmPartDups);
11821 				mp1 = mp->b_cont;
11822 				if (!mp1)
11823 					break;
11824 				offset = IP_REASS_START(mp1);
11825 			}
11826 			ipf->ipf_mp->b_cont = mp;
11827 			continue;
11828 		}
11829 		/*
11830 		 * The new piece starts somewhere between the start of the head
11831 		 * and before the end of the tail.
11832 		 */
11833 		for (; mp1; mp1 = mp1->b_cont) {
11834 			offset = IP_REASS_END(mp1);
11835 			if (start < offset) {
11836 				if (end <= offset) {
11837 					/* Nothing new. */
11838 					IP_REASS_SET_START(mp, 0);
11839 					IP_REASS_SET_END(mp, 0);
11840 					/* Subtract byte count */
11841 					ipf->ipf_count -= mp->b_datap->db_lim -
11842 					    mp->b_datap->db_base;
11843 					if (incr_dups) {
11844 						ipf->ipf_num_dups++;
11845 						incr_dups = B_FALSE;
11846 					}
11847 					freeb(mp);
11848 					BUMP_MIB(ill->ill_ip_mib,
11849 					    ipIfStatsReasmDuplicates);
11850 					break;
11851 				}
11852 				/*
11853 				 * Trim redundant stuff off beginning of new
11854 				 * piece.
11855 				 */
11856 				IP_REASS_SET_START(mp, offset);
11857 				mp->b_rptr += offset - start;
11858 				BUMP_MIB(ill->ill_ip_mib,
11859 				    ipIfStatsReasmPartDups);
11860 				start = offset;
11861 				if (!mp1->b_cont) {
11862 					/*
11863 					 * After trimming, this guy is now
11864 					 * hanging off the end.
11865 					 */
11866 					mp1->b_cont = mp;
11867 					ipf->ipf_tail_mp = mp;
11868 					if (!more) {
11869 						ipf->ipf_hole_cnt--;
11870 					}
11871 					break;
11872 				}
11873 			}
11874 			if (start >= IP_REASS_START(mp1->b_cont))
11875 				continue;
11876 			/* Fill a hole */
11877 			if (start > offset)
11878 				ipf->ipf_hole_cnt++;
11879 			mp->b_cont = mp1->b_cont;
11880 			mp1->b_cont = mp;
11881 			mp1 = mp->b_cont;
11882 			offset = IP_REASS_START(mp1);
11883 			if (end >= offset) {
11884 				ipf->ipf_hole_cnt--;
11885 				/* Check for overlap. */
11886 				while (end > offset) {
11887 					if (end < IP_REASS_END(mp1)) {
11888 						mp->b_wptr -= end - offset;
11889 						IP_REASS_SET_END(mp, offset);
11890 						/*
11891 						 * TODO we might bump
11892 						 * this up twice if there is
11893 						 * overlap at both ends.
11894 						 */
11895 						BUMP_MIB(ill->ill_ip_mib,
11896 						    ipIfStatsReasmPartDups);
11897 						break;
11898 					}
11899 					/* Did we cover another hole? */
11900 					if ((mp1->b_cont &&
11901 					    IP_REASS_END(mp1)
11902 					    != IP_REASS_START(mp1->b_cont) &&
11903 					    end >=
11904 					    IP_REASS_START(mp1->b_cont)) ||
11905 					    (!ipf->ipf_last_frag_seen &&
11906 					    !more)) {
11907 						ipf->ipf_hole_cnt--;
11908 					}
11909 					/* Clip out mp1. */
11910 					if ((mp->b_cont = mp1->b_cont) ==
11911 					    NULL) {
11912 						/*
11913 						 * After clipping out mp1,
11914 						 * this guy is now hanging
11915 						 * off the end.
11916 						 */
11917 						ipf->ipf_tail_mp = mp;
11918 					}
11919 					IP_REASS_SET_START(mp1, 0);
11920 					IP_REASS_SET_END(mp1, 0);
11921 					/* Subtract byte count */
11922 					ipf->ipf_count -=
11923 					    mp1->b_datap->db_lim -
11924 					    mp1->b_datap->db_base;
11925 					freeb(mp1);
11926 					BUMP_MIB(ill->ill_ip_mib,
11927 					    ipIfStatsReasmPartDups);
11928 					mp1 = mp->b_cont;
11929 					if (!mp1)
11930 						break;
11931 					offset = IP_REASS_START(mp1);
11932 				}
11933 			}
11934 			break;
11935 		}
11936 	} while (start = end, mp = next_mp);
11937 
11938 	/* Fragment just processed could be the last one. Remember this fact */
11939 	if (!more)
11940 		ipf->ipf_last_frag_seen = B_TRUE;
11941 
11942 	/* Still got holes? */
11943 	if (ipf->ipf_hole_cnt)
11944 		return (IP_REASS_PARTIAL);
11945 	/* Clean up overloaded fields to avoid upstream disasters. */
11946 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11947 		IP_REASS_SET_START(mp1, 0);
11948 		IP_REASS_SET_END(mp1, 0);
11949 	}
11950 	return (IP_REASS_COMPLETE);
11951 }
11952 
11953 /*
11954  * ipsec processing for the fast path, used for input UDP Packets
11955  * Returns true if ready for passup to UDP.
11956  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
11957  * was an ESP-in-UDP packet, etc.).
11958  */
11959 static boolean_t
11960 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11961     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
11962 {
11963 	uint32_t	ill_index;
11964 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11965 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11966 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11967 	udp_t		*udp = connp->conn_udp;
11968 
11969 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11970 	/* The ill_index of the incoming ILL */
11971 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11972 
11973 	/* pass packet up to the transport */
11974 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11975 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11976 		    NULL, mctl_present);
11977 		if (*first_mpp == NULL) {
11978 			return (B_FALSE);
11979 		}
11980 	}
11981 
11982 	/* Initiate IPPF processing for fastpath UDP */
11983 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11984 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11985 		if (*mpp == NULL) {
11986 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11987 			    "deferred/dropped during IPPF processing\n"));
11988 			return (B_FALSE);
11989 		}
11990 	}
11991 	/*
11992 	 * Remove 0-spi if it's 0, or move everything behind
11993 	 * the UDP header over it and forward to ESP via
11994 	 * ip_proto_input().
11995 	 */
11996 	if (udp->udp_nat_t_endpoint) {
11997 		if (mctl_present) {
11998 			/* mctl_present *shouldn't* happen. */
11999 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12000 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12001 			    &ipss->ipsec_dropper);
12002 			*first_mpp = NULL;
12003 			return (B_FALSE);
12004 		}
12005 
12006 		/* "ill" is "recv_ill" in actuality. */
12007 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12008 			return (B_FALSE);
12009 
12010 		/* Else continue like a normal UDP packet. */
12011 	}
12012 
12013 	/*
12014 	 * We make the checks as below since we are in the fast path
12015 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12016 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12017 	 */
12018 	if (connp->conn_recvif || connp->conn_recvslla ||
12019 	    connp->conn_ip_recvpktinfo) {
12020 		if (connp->conn_recvif) {
12021 			in_flags = IPF_RECVIF;
12022 		}
12023 		/*
12024 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12025 		 * so the flag passed to ip_add_info is based on IP version
12026 		 * of connp.
12027 		 */
12028 		if (connp->conn_ip_recvpktinfo) {
12029 			if (connp->conn_af_isv6) {
12030 				/*
12031 				 * V6 only needs index
12032 				 */
12033 				in_flags |= IPF_RECVIF;
12034 			} else {
12035 				/*
12036 				 * V4 needs index + matching address.
12037 				 */
12038 				in_flags |= IPF_RECVADDR;
12039 			}
12040 		}
12041 		if (connp->conn_recvslla) {
12042 			in_flags |= IPF_RECVSLLA;
12043 		}
12044 		/*
12045 		 * since in_flags are being set ill will be
12046 		 * referenced in ip_add_info, so it better not
12047 		 * be NULL.
12048 		 */
12049 		/*
12050 		 * the actual data will be contained in b_cont
12051 		 * upon successful return of the following call.
12052 		 * If the call fails then the original mblk is
12053 		 * returned.
12054 		 */
12055 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12056 		    ipst);
12057 	}
12058 
12059 	return (B_TRUE);
12060 }
12061 
12062 /*
12063  * Fragmentation reassembly.  Each ILL has a hash table for
12064  * queuing packets undergoing reassembly for all IPIFs
12065  * associated with the ILL.  The hash is based on the packet
12066  * IP ident field.  The ILL frag hash table was allocated
12067  * as a timer block at the time the ILL was created.  Whenever
12068  * there is anything on the reassembly queue, the timer will
12069  * be running.  Returns B_TRUE if successful else B_FALSE;
12070  * frees mp on failure.
12071  */
12072 static boolean_t
12073 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12074     uint32_t *cksum_val, uint16_t *cksum_flags)
12075 {
12076 	uint32_t	frag_offset_flags;
12077 	mblk_t		*mp = *mpp;
12078 	mblk_t		*t_mp;
12079 	ipaddr_t	dst;
12080 	uint8_t		proto = ipha->ipha_protocol;
12081 	uint32_t	sum_val;
12082 	uint16_t	sum_flags;
12083 	ipf_t		*ipf;
12084 	ipf_t		**ipfp;
12085 	ipfb_t		*ipfb;
12086 	uint16_t	ident;
12087 	uint32_t	offset;
12088 	ipaddr_t	src;
12089 	uint_t		hdr_length;
12090 	uint32_t	end;
12091 	mblk_t		*mp1;
12092 	mblk_t		*tail_mp;
12093 	size_t		count;
12094 	size_t		msg_len;
12095 	uint8_t		ecn_info = 0;
12096 	uint32_t	packet_size;
12097 	boolean_t	pruned = B_FALSE;
12098 	ip_stack_t *ipst = ill->ill_ipst;
12099 
12100 	if (cksum_val != NULL)
12101 		*cksum_val = 0;
12102 	if (cksum_flags != NULL)
12103 		*cksum_flags = 0;
12104 
12105 	/*
12106 	 * Drop the fragmented as early as possible, if
12107 	 * we don't have resource(s) to re-assemble.
12108 	 */
12109 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12110 		freemsg(mp);
12111 		return (B_FALSE);
12112 	}
12113 
12114 	/* Check for fragmentation offset; return if there's none */
12115 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12116 	    (IPH_MF | IPH_OFFSET)) == 0)
12117 		return (B_TRUE);
12118 
12119 	/*
12120 	 * We utilize hardware computed checksum info only for UDP since
12121 	 * IP fragmentation is a normal occurrence for the protocol.  In
12122 	 * addition, checksum offload support for IP fragments carrying
12123 	 * UDP payload is commonly implemented across network adapters.
12124 	 */
12125 	ASSERT(recv_ill != NULL);
12126 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12127 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12128 		mblk_t *mp1 = mp->b_cont;
12129 		int32_t len;
12130 
12131 		/* Record checksum information from the packet */
12132 		sum_val = (uint32_t)DB_CKSUM16(mp);
12133 		sum_flags = DB_CKSUMFLAGS(mp);
12134 
12135 		/* IP payload offset from beginning of mblk */
12136 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12137 
12138 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12139 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12140 		    offset >= DB_CKSUMSTART(mp) &&
12141 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12142 			uint32_t adj;
12143 			/*
12144 			 * Partial checksum has been calculated by hardware
12145 			 * and attached to the packet; in addition, any
12146 			 * prepended extraneous data is even byte aligned.
12147 			 * If any such data exists, we adjust the checksum;
12148 			 * this would also handle any postpended data.
12149 			 */
12150 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12151 			    mp, mp1, len, adj);
12152 
12153 			/* One's complement subtract extraneous checksum */
12154 			if (adj >= sum_val)
12155 				sum_val = ~(adj - sum_val) & 0xFFFF;
12156 			else
12157 				sum_val -= adj;
12158 		}
12159 	} else {
12160 		sum_val = 0;
12161 		sum_flags = 0;
12162 	}
12163 
12164 	/* Clear hardware checksumming flag */
12165 	DB_CKSUMFLAGS(mp) = 0;
12166 
12167 	ident = ipha->ipha_ident;
12168 	offset = (frag_offset_flags << 3) & 0xFFFF;
12169 	src = ipha->ipha_src;
12170 	dst = ipha->ipha_dst;
12171 	hdr_length = IPH_HDR_LENGTH(ipha);
12172 	end = ntohs(ipha->ipha_length) - hdr_length;
12173 
12174 	/* If end == 0 then we have a packet with no data, so just free it */
12175 	if (end == 0) {
12176 		freemsg(mp);
12177 		return (B_FALSE);
12178 	}
12179 
12180 	/* Record the ECN field info. */
12181 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12182 	if (offset != 0) {
12183 		/*
12184 		 * If this isn't the first piece, strip the header, and
12185 		 * add the offset to the end value.
12186 		 */
12187 		mp->b_rptr += hdr_length;
12188 		end += offset;
12189 	}
12190 
12191 	msg_len = MBLKSIZE(mp);
12192 	tail_mp = mp;
12193 	while (tail_mp->b_cont != NULL) {
12194 		tail_mp = tail_mp->b_cont;
12195 		msg_len += MBLKSIZE(tail_mp);
12196 	}
12197 
12198 	/* If the reassembly list for this ILL will get too big, prune it */
12199 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12200 	    ipst->ips_ip_reass_queue_bytes) {
12201 		ill_frag_prune(ill,
12202 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12203 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12204 		pruned = B_TRUE;
12205 	}
12206 
12207 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12208 	mutex_enter(&ipfb->ipfb_lock);
12209 
12210 	ipfp = &ipfb->ipfb_ipf;
12211 	/* Try to find an existing fragment queue for this packet. */
12212 	for (;;) {
12213 		ipf = ipfp[0];
12214 		if (ipf != NULL) {
12215 			/*
12216 			 * It has to match on ident and src/dst address.
12217 			 */
12218 			if (ipf->ipf_ident == ident &&
12219 			    ipf->ipf_src == src &&
12220 			    ipf->ipf_dst == dst &&
12221 			    ipf->ipf_protocol == proto) {
12222 				/*
12223 				 * If we have received too many
12224 				 * duplicate fragments for this packet
12225 				 * free it.
12226 				 */
12227 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12228 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12229 					freemsg(mp);
12230 					mutex_exit(&ipfb->ipfb_lock);
12231 					return (B_FALSE);
12232 				}
12233 				/* Found it. */
12234 				break;
12235 			}
12236 			ipfp = &ipf->ipf_hash_next;
12237 			continue;
12238 		}
12239 
12240 		/*
12241 		 * If we pruned the list, do we want to store this new
12242 		 * fragment?. We apply an optimization here based on the
12243 		 * fact that most fragments will be received in order.
12244 		 * So if the offset of this incoming fragment is zero,
12245 		 * it is the first fragment of a new packet. We will
12246 		 * keep it.  Otherwise drop the fragment, as we have
12247 		 * probably pruned the packet already (since the
12248 		 * packet cannot be found).
12249 		 */
12250 		if (pruned && offset != 0) {
12251 			mutex_exit(&ipfb->ipfb_lock);
12252 			freemsg(mp);
12253 			return (B_FALSE);
12254 		}
12255 
12256 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12257 			/*
12258 			 * Too many fragmented packets in this hash
12259 			 * bucket. Free the oldest.
12260 			 */
12261 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12262 		}
12263 
12264 		/* New guy.  Allocate a frag message. */
12265 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12266 		if (mp1 == NULL) {
12267 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12268 			freemsg(mp);
12269 reass_done:
12270 			mutex_exit(&ipfb->ipfb_lock);
12271 			return (B_FALSE);
12272 		}
12273 
12274 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12275 		mp1->b_cont = mp;
12276 
12277 		/* Initialize the fragment header. */
12278 		ipf = (ipf_t *)mp1->b_rptr;
12279 		ipf->ipf_mp = mp1;
12280 		ipf->ipf_ptphn = ipfp;
12281 		ipfp[0] = ipf;
12282 		ipf->ipf_hash_next = NULL;
12283 		ipf->ipf_ident = ident;
12284 		ipf->ipf_protocol = proto;
12285 		ipf->ipf_src = src;
12286 		ipf->ipf_dst = dst;
12287 		ipf->ipf_nf_hdr_len = 0;
12288 		/* Record reassembly start time. */
12289 		ipf->ipf_timestamp = gethrestime_sec();
12290 		/* Record ipf generation and account for frag header */
12291 		ipf->ipf_gen = ill->ill_ipf_gen++;
12292 		ipf->ipf_count = MBLKSIZE(mp1);
12293 		ipf->ipf_last_frag_seen = B_FALSE;
12294 		ipf->ipf_ecn = ecn_info;
12295 		ipf->ipf_num_dups = 0;
12296 		ipfb->ipfb_frag_pkts++;
12297 		ipf->ipf_checksum = 0;
12298 		ipf->ipf_checksum_flags = 0;
12299 
12300 		/* Store checksum value in fragment header */
12301 		if (sum_flags != 0) {
12302 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12303 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12304 			ipf->ipf_checksum = sum_val;
12305 			ipf->ipf_checksum_flags = sum_flags;
12306 		}
12307 
12308 		/*
12309 		 * We handle reassembly two ways.  In the easy case,
12310 		 * where all the fragments show up in order, we do
12311 		 * minimal bookkeeping, and just clip new pieces on
12312 		 * the end.  If we ever see a hole, then we go off
12313 		 * to ip_reassemble which has to mark the pieces and
12314 		 * keep track of the number of holes, etc.  Obviously,
12315 		 * the point of having both mechanisms is so we can
12316 		 * handle the easy case as efficiently as possible.
12317 		 */
12318 		if (offset == 0) {
12319 			/* Easy case, in-order reassembly so far. */
12320 			ipf->ipf_count += msg_len;
12321 			ipf->ipf_tail_mp = tail_mp;
12322 			/*
12323 			 * Keep track of next expected offset in
12324 			 * ipf_end.
12325 			 */
12326 			ipf->ipf_end = end;
12327 			ipf->ipf_nf_hdr_len = hdr_length;
12328 		} else {
12329 			/* Hard case, hole at the beginning. */
12330 			ipf->ipf_tail_mp = NULL;
12331 			/*
12332 			 * ipf_end == 0 means that we have given up
12333 			 * on easy reassembly.
12334 			 */
12335 			ipf->ipf_end = 0;
12336 
12337 			/* Forget checksum offload from now on */
12338 			ipf->ipf_checksum_flags = 0;
12339 
12340 			/*
12341 			 * ipf_hole_cnt is set by ip_reassemble.
12342 			 * ipf_count is updated by ip_reassemble.
12343 			 * No need to check for return value here
12344 			 * as we don't expect reassembly to complete
12345 			 * or fail for the first fragment itself.
12346 			 */
12347 			(void) ip_reassemble(mp, ipf,
12348 			    (frag_offset_flags & IPH_OFFSET) << 3,
12349 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12350 		}
12351 		/* Update per ipfb and ill byte counts */
12352 		ipfb->ipfb_count += ipf->ipf_count;
12353 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12354 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12355 		/* If the frag timer wasn't already going, start it. */
12356 		mutex_enter(&ill->ill_lock);
12357 		ill_frag_timer_start(ill);
12358 		mutex_exit(&ill->ill_lock);
12359 		goto reass_done;
12360 	}
12361 
12362 	/*
12363 	 * If the packet's flag has changed (it could be coming up
12364 	 * from an interface different than the previous, therefore
12365 	 * possibly different checksum capability), then forget about
12366 	 * any stored checksum states.  Otherwise add the value to
12367 	 * the existing one stored in the fragment header.
12368 	 */
12369 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12370 		sum_val += ipf->ipf_checksum;
12371 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12372 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12373 		ipf->ipf_checksum = sum_val;
12374 	} else if (ipf->ipf_checksum_flags != 0) {
12375 		/* Forget checksum offload from now on */
12376 		ipf->ipf_checksum_flags = 0;
12377 	}
12378 
12379 	/*
12380 	 * We have a new piece of a datagram which is already being
12381 	 * reassembled.  Update the ECN info if all IP fragments
12382 	 * are ECN capable.  If there is one which is not, clear
12383 	 * all the info.  If there is at least one which has CE
12384 	 * code point, IP needs to report that up to transport.
12385 	 */
12386 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12387 		if (ecn_info == IPH_ECN_CE)
12388 			ipf->ipf_ecn = IPH_ECN_CE;
12389 	} else {
12390 		ipf->ipf_ecn = IPH_ECN_NECT;
12391 	}
12392 	if (offset && ipf->ipf_end == offset) {
12393 		/* The new fragment fits at the end */
12394 		ipf->ipf_tail_mp->b_cont = mp;
12395 		/* Update the byte count */
12396 		ipf->ipf_count += msg_len;
12397 		/* Update per ipfb and ill byte counts */
12398 		ipfb->ipfb_count += msg_len;
12399 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12400 		atomic_add_32(&ill->ill_frag_count, msg_len);
12401 		if (frag_offset_flags & IPH_MF) {
12402 			/* More to come. */
12403 			ipf->ipf_end = end;
12404 			ipf->ipf_tail_mp = tail_mp;
12405 			goto reass_done;
12406 		}
12407 	} else {
12408 		/* Go do the hard cases. */
12409 		int ret;
12410 
12411 		if (offset == 0)
12412 			ipf->ipf_nf_hdr_len = hdr_length;
12413 
12414 		/* Save current byte count */
12415 		count = ipf->ipf_count;
12416 		ret = ip_reassemble(mp, ipf,
12417 		    (frag_offset_flags & IPH_OFFSET) << 3,
12418 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12419 		/* Count of bytes added and subtracted (freeb()ed) */
12420 		count = ipf->ipf_count - count;
12421 		if (count) {
12422 			/* Update per ipfb and ill byte counts */
12423 			ipfb->ipfb_count += count;
12424 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12425 			atomic_add_32(&ill->ill_frag_count, count);
12426 		}
12427 		if (ret == IP_REASS_PARTIAL) {
12428 			goto reass_done;
12429 		} else if (ret == IP_REASS_FAILED) {
12430 			/* Reassembly failed. Free up all resources */
12431 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12432 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12433 				IP_REASS_SET_START(t_mp, 0);
12434 				IP_REASS_SET_END(t_mp, 0);
12435 			}
12436 			freemsg(mp);
12437 			goto reass_done;
12438 		}
12439 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12440 	}
12441 	/*
12442 	 * We have completed reassembly.  Unhook the frag header from
12443 	 * the reassembly list.
12444 	 *
12445 	 * Before we free the frag header, record the ECN info
12446 	 * to report back to the transport.
12447 	 */
12448 	ecn_info = ipf->ipf_ecn;
12449 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12450 	ipfp = ipf->ipf_ptphn;
12451 
12452 	/* We need to supply these to caller */
12453 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12454 		sum_val = ipf->ipf_checksum;
12455 	else
12456 		sum_val = 0;
12457 
12458 	mp1 = ipf->ipf_mp;
12459 	count = ipf->ipf_count;
12460 	ipf = ipf->ipf_hash_next;
12461 	if (ipf != NULL)
12462 		ipf->ipf_ptphn = ipfp;
12463 	ipfp[0] = ipf;
12464 	atomic_add_32(&ill->ill_frag_count, -count);
12465 	ASSERT(ipfb->ipfb_count >= count);
12466 	ipfb->ipfb_count -= count;
12467 	ipfb->ipfb_frag_pkts--;
12468 	mutex_exit(&ipfb->ipfb_lock);
12469 	/* Ditch the frag header. */
12470 	mp = mp1->b_cont;
12471 
12472 	freeb(mp1);
12473 
12474 	/* Restore original IP length in header. */
12475 	packet_size = (uint32_t)msgdsize(mp);
12476 	if (packet_size > IP_MAXPACKET) {
12477 		freemsg(mp);
12478 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12479 		return (B_FALSE);
12480 	}
12481 
12482 	if (DB_REF(mp) > 1) {
12483 		mblk_t *mp2 = copymsg(mp);
12484 
12485 		freemsg(mp);
12486 		if (mp2 == NULL) {
12487 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12488 			return (B_FALSE);
12489 		}
12490 		mp = mp2;
12491 	}
12492 	ipha = (ipha_t *)mp->b_rptr;
12493 
12494 	ipha->ipha_length = htons((uint16_t)packet_size);
12495 	/* We're now complete, zip the frag state */
12496 	ipha->ipha_fragment_offset_and_flags = 0;
12497 	/* Record the ECN info. */
12498 	ipha->ipha_type_of_service &= 0xFC;
12499 	ipha->ipha_type_of_service |= ecn_info;
12500 	*mpp = mp;
12501 
12502 	/* Reassembly is successful; return checksum information if needed */
12503 	if (cksum_val != NULL)
12504 		*cksum_val = sum_val;
12505 	if (cksum_flags != NULL)
12506 		*cksum_flags = sum_flags;
12507 
12508 	return (B_TRUE);
12509 }
12510 
12511 /*
12512  * Perform ip header check sum update local options.
12513  * return B_TRUE if all is well, else return B_FALSE and release
12514  * the mp. caller is responsible for decrementing ire ref cnt.
12515  */
12516 static boolean_t
12517 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12518     ip_stack_t *ipst)
12519 {
12520 	mblk_t		*first_mp;
12521 	boolean_t	mctl_present;
12522 	uint16_t	sum;
12523 
12524 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12525 	/*
12526 	 * Don't do the checksum if it has gone through AH/ESP
12527 	 * processing.
12528 	 */
12529 	if (!mctl_present) {
12530 		sum = ip_csum_hdr(ipha);
12531 		if (sum != 0) {
12532 			if (ill != NULL) {
12533 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12534 			} else {
12535 				BUMP_MIB(&ipst->ips_ip_mib,
12536 				    ipIfStatsInCksumErrs);
12537 			}
12538 			freemsg(first_mp);
12539 			return (B_FALSE);
12540 		}
12541 	}
12542 
12543 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12544 		if (mctl_present)
12545 			freeb(first_mp);
12546 		return (B_FALSE);
12547 	}
12548 
12549 	return (B_TRUE);
12550 }
12551 
12552 /*
12553  * All udp packet are delivered to the local host via this routine.
12554  */
12555 void
12556 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12557     ill_t *recv_ill)
12558 {
12559 	uint32_t	sum;
12560 	uint32_t	u1;
12561 	boolean_t	mctl_present;
12562 	conn_t		*connp;
12563 	mblk_t		*first_mp;
12564 	uint16_t	*up;
12565 	ill_t		*ill = (ill_t *)q->q_ptr;
12566 	uint16_t	reass_hck_flags = 0;
12567 	ip_stack_t	*ipst;
12568 
12569 	ASSERT(recv_ill != NULL);
12570 	ipst = recv_ill->ill_ipst;
12571 
12572 #define	rptr    ((uchar_t *)ipha)
12573 
12574 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12575 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12576 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12577 	ASSERT(ill != NULL);
12578 
12579 	/*
12580 	 * FAST PATH for udp packets
12581 	 */
12582 
12583 	/* u1 is # words of IP options */
12584 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12585 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12586 
12587 	/* IP options present */
12588 	if (u1 != 0)
12589 		goto ipoptions;
12590 
12591 	/* Check the IP header checksum.  */
12592 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12593 		/* Clear the IP header h/w cksum flag */
12594 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12595 	} else if (!mctl_present) {
12596 		/*
12597 		 * Don't verify header checksum if this packet is coming
12598 		 * back from AH/ESP as we already did it.
12599 		 */
12600 #define	uph	((uint16_t *)ipha)
12601 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12602 		    uph[6] + uph[7] + uph[8] + uph[9];
12603 #undef	uph
12604 		/* finish doing IP checksum */
12605 		sum = (sum & 0xFFFF) + (sum >> 16);
12606 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12607 		if (sum != 0 && sum != 0xFFFF) {
12608 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12609 			freemsg(first_mp);
12610 			return;
12611 		}
12612 	}
12613 
12614 	/*
12615 	 * Count for SNMP of inbound packets for ire.
12616 	 * if mctl is present this might be a secure packet and
12617 	 * has already been counted for in ip_proto_input().
12618 	 */
12619 	if (!mctl_present) {
12620 		UPDATE_IB_PKT_COUNT(ire);
12621 		ire->ire_last_used_time = lbolt;
12622 	}
12623 
12624 	/* packet part of fragmented IP packet? */
12625 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12626 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12627 		goto fragmented;
12628 	}
12629 
12630 	/* u1 = IP header length (20 bytes) */
12631 	u1 = IP_SIMPLE_HDR_LENGTH;
12632 
12633 	/* packet does not contain complete IP & UDP headers */
12634 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12635 		goto udppullup;
12636 
12637 	/* up points to UDP header */
12638 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12639 #define	iphs    ((uint16_t *)ipha)
12640 
12641 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12642 	if (up[3] != 0) {
12643 		mblk_t *mp1 = mp->b_cont;
12644 		boolean_t cksum_err;
12645 		uint16_t hck_flags = 0;
12646 
12647 		/* Pseudo-header checksum */
12648 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12649 		    iphs[9] + up[2];
12650 
12651 		/*
12652 		 * Revert to software checksum calculation if the interface
12653 		 * isn't capable of checksum offload or if IPsec is present.
12654 		 */
12655 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12656 			hck_flags = DB_CKSUMFLAGS(mp);
12657 
12658 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12659 			IP_STAT(ipst, ip_in_sw_cksum);
12660 
12661 		IP_CKSUM_RECV(hck_flags, u1,
12662 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12663 		    (int32_t)((uchar_t *)up - rptr),
12664 		    mp, mp1, cksum_err);
12665 
12666 		if (cksum_err) {
12667 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12668 			if (hck_flags & HCK_FULLCKSUM)
12669 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12670 			else if (hck_flags & HCK_PARTIALCKSUM)
12671 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12672 			else
12673 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12674 
12675 			freemsg(first_mp);
12676 			return;
12677 		}
12678 	}
12679 
12680 	/* Non-fragmented broadcast or multicast packet? */
12681 	if (ire->ire_type == IRE_BROADCAST)
12682 		goto udpslowpath;
12683 
12684 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12685 	    ire->ire_zoneid, ipst)) != NULL) {
12686 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12687 		IP_STAT(ipst, ip_udp_fast_path);
12688 
12689 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12690 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12691 			freemsg(mp);
12692 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12693 		} else {
12694 			if (!mctl_present) {
12695 				BUMP_MIB(ill->ill_ip_mib,
12696 				    ipIfStatsHCInDelivers);
12697 			}
12698 			/*
12699 			 * mp and first_mp can change.
12700 			 */
12701 			if (ip_udp_check(q, connp, recv_ill,
12702 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12703 				/* Send it upstream */
12704 				(connp->conn_recv)(connp, mp, NULL);
12705 			}
12706 		}
12707 		/*
12708 		 * freeb() cannot deal with null mblk being passed
12709 		 * in and first_mp can be set to null in the call
12710 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12711 		 */
12712 		if (mctl_present && first_mp != NULL) {
12713 			freeb(first_mp);
12714 		}
12715 		CONN_DEC_REF(connp);
12716 		return;
12717 	}
12718 
12719 	/*
12720 	 * if we got here we know the packet is not fragmented and
12721 	 * has no options. The classifier could not find a conn_t and
12722 	 * most likely its an icmp packet so send it through slow path.
12723 	 */
12724 
12725 	goto udpslowpath;
12726 
12727 ipoptions:
12728 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12729 		goto slow_done;
12730 	}
12731 
12732 	UPDATE_IB_PKT_COUNT(ire);
12733 	ire->ire_last_used_time = lbolt;
12734 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12735 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12736 fragmented:
12737 		/*
12738 		 * "sum" and "reass_hck_flags" are non-zero if the
12739 		 * reassembled packet has a valid hardware computed
12740 		 * checksum information associated with it.
12741 		 */
12742 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12743 		    &reass_hck_flags)) {
12744 			goto slow_done;
12745 		}
12746 
12747 		/*
12748 		 * Make sure that first_mp points back to mp as
12749 		 * the mp we came in with could have changed in
12750 		 * ip_rput_fragment().
12751 		 */
12752 		ASSERT(!mctl_present);
12753 		ipha = (ipha_t *)mp->b_rptr;
12754 		first_mp = mp;
12755 	}
12756 
12757 	/* Now we have a complete datagram, destined for this machine. */
12758 	u1 = IPH_HDR_LENGTH(ipha);
12759 	/* Pull up the UDP header, if necessary. */
12760 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12761 udppullup:
12762 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12763 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12764 			freemsg(first_mp);
12765 			goto slow_done;
12766 		}
12767 		ipha = (ipha_t *)mp->b_rptr;
12768 	}
12769 
12770 	/*
12771 	 * Validate the checksum for the reassembled packet; for the
12772 	 * pullup case we calculate the payload checksum in software.
12773 	 */
12774 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12775 	if (up[3] != 0) {
12776 		boolean_t cksum_err;
12777 
12778 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12779 			IP_STAT(ipst, ip_in_sw_cksum);
12780 
12781 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12782 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12783 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12784 		    iphs[9] + up[2], sum, cksum_err);
12785 
12786 		if (cksum_err) {
12787 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12788 
12789 			if (reass_hck_flags & HCK_FULLCKSUM)
12790 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12791 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12792 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12793 			else
12794 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12795 
12796 			freemsg(first_mp);
12797 			goto slow_done;
12798 		}
12799 	}
12800 udpslowpath:
12801 
12802 	/* Clear hardware checksum flag to be safe */
12803 	DB_CKSUMFLAGS(mp) = 0;
12804 
12805 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12806 	    (ire->ire_type == IRE_BROADCAST),
12807 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12808 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12809 
12810 slow_done:
12811 	IP_STAT(ipst, ip_udp_slow_path);
12812 	return;
12813 
12814 #undef  iphs
12815 #undef  rptr
12816 }
12817 
12818 static boolean_t
12819 ip_iptun_input(mblk_t *ipsec_mp, mblk_t *data_mp, ipha_t *ipha, ill_t *ill,
12820     ire_t *ire, ip_stack_t *ipst)
12821 {
12822 	conn_t	*connp;
12823 
12824 	ASSERT(ipsec_mp == NULL || ipsec_mp->b_cont == data_mp);
12825 
12826 	if ((connp = ipcl_classify_v4(data_mp, ipha->ipha_protocol,
12827 	    IP_SIMPLE_HDR_LENGTH, ire->ire_zoneid, ipst)) != NULL) {
12828 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12829 		connp->conn_recv(connp, ipsec_mp != NULL ? ipsec_mp : data_mp,
12830 		    NULL);
12831 		CONN_DEC_REF(connp);
12832 		return (B_TRUE);
12833 	}
12834 	return (B_FALSE);
12835 }
12836 
12837 /* ARGSUSED */
12838 static mblk_t *
12839 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12840     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12841     ill_rx_ring_t *ill_ring)
12842 {
12843 	conn_t		*connp;
12844 	uint32_t	sum;
12845 	uint32_t	u1;
12846 	uint16_t	*up;
12847 	int		offset;
12848 	ssize_t		len;
12849 	mblk_t		*mp1;
12850 	boolean_t	syn_present = B_FALSE;
12851 	tcph_t		*tcph;
12852 	uint_t		tcph_flags;
12853 	uint_t		ip_hdr_len;
12854 	ill_t		*ill = (ill_t *)q->q_ptr;
12855 	zoneid_t	zoneid = ire->ire_zoneid;
12856 	boolean_t	cksum_err;
12857 	uint16_t	hck_flags = 0;
12858 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12859 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12860 
12861 #define	rptr	((uchar_t *)ipha)
12862 
12863 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12864 	ASSERT(ill != NULL);
12865 
12866 	/*
12867 	 * FAST PATH for tcp packets
12868 	 */
12869 
12870 	/* u1 is # words of IP options */
12871 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12872 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12873 
12874 	/* IP options present */
12875 	if (u1) {
12876 		goto ipoptions;
12877 	} else if (!mctl_present) {
12878 		/* Check the IP header checksum.  */
12879 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12880 			/* Clear the IP header h/w cksum flag */
12881 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12882 		} else if (!mctl_present) {
12883 			/*
12884 			 * Don't verify header checksum if this packet
12885 			 * is coming back from AH/ESP as we already did it.
12886 			 */
12887 #define	uph	((uint16_t *)ipha)
12888 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12889 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12890 #undef	uph
12891 			/* finish doing IP checksum */
12892 			sum = (sum & 0xFFFF) + (sum >> 16);
12893 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12894 			if (sum != 0 && sum != 0xFFFF) {
12895 				BUMP_MIB(ill->ill_ip_mib,
12896 				    ipIfStatsInCksumErrs);
12897 				goto error;
12898 			}
12899 		}
12900 	}
12901 
12902 	if (!mctl_present) {
12903 		UPDATE_IB_PKT_COUNT(ire);
12904 		ire->ire_last_used_time = lbolt;
12905 	}
12906 
12907 	/* packet part of fragmented IP packet? */
12908 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12909 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12910 		goto fragmented;
12911 	}
12912 
12913 	/* u1 = IP header length (20 bytes) */
12914 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12915 
12916 	/* does packet contain IP+TCP headers? */
12917 	len = mp->b_wptr - rptr;
12918 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12919 		IP_STAT(ipst, ip_tcppullup);
12920 		goto tcppullup;
12921 	}
12922 
12923 	/* TCP options present? */
12924 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12925 
12926 	/*
12927 	 * If options need to be pulled up, then goto tcpoptions.
12928 	 * otherwise we are still in the fast path
12929 	 */
12930 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12931 		IP_STAT(ipst, ip_tcpoptions);
12932 		goto tcpoptions;
12933 	}
12934 
12935 	/* multiple mblks of tcp data? */
12936 	if ((mp1 = mp->b_cont) != NULL) {
12937 		IP_STAT(ipst, ip_multipkttcp);
12938 		len += msgdsize(mp1);
12939 	}
12940 
12941 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12942 
12943 	/* part of pseudo checksum */
12944 
12945 	/* TCP datagram length */
12946 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12947 
12948 #define	iphs    ((uint16_t *)ipha)
12949 
12950 #ifdef	_BIG_ENDIAN
12951 	u1 += IPPROTO_TCP;
12952 #else
12953 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12954 #endif
12955 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12956 
12957 	/*
12958 	 * Revert to software checksum calculation if the interface
12959 	 * isn't capable of checksum offload or if IPsec is present.
12960 	 */
12961 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12962 		hck_flags = DB_CKSUMFLAGS(mp);
12963 
12964 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12965 		IP_STAT(ipst, ip_in_sw_cksum);
12966 
12967 	IP_CKSUM_RECV(hck_flags, u1,
12968 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12969 	    (int32_t)((uchar_t *)up - rptr),
12970 	    mp, mp1, cksum_err);
12971 
12972 	if (cksum_err) {
12973 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12974 
12975 		if (hck_flags & HCK_FULLCKSUM)
12976 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12977 		else if (hck_flags & HCK_PARTIALCKSUM)
12978 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12979 		else
12980 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12981 
12982 		goto error;
12983 	}
12984 
12985 try_again:
12986 
12987 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12988 	    zoneid, ipst)) == NULL) {
12989 		/* Send the TH_RST */
12990 		goto no_conn;
12991 	}
12992 
12993 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12994 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
12995 
12996 	/*
12997 	 * TCP FAST PATH for AF_INET socket.
12998 	 *
12999 	 * TCP fast path to avoid extra work. An AF_INET socket type
13000 	 * does not have facility to receive extra information via
13001 	 * ip_process or ip_add_info. Also, when the connection was
13002 	 * established, we made a check if this connection is impacted
13003 	 * by any global IPsec policy or per connection policy (a
13004 	 * policy that comes in effect later will not apply to this
13005 	 * connection). Since all this can be determined at the
13006 	 * connection establishment time, a quick check of flags
13007 	 * can avoid extra work.
13008 	 */
13009 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13010 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13011 		ASSERT(first_mp == mp);
13012 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13013 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13014 			SET_SQUEUE(mp, tcp_rput_data, connp);
13015 			return (mp);
13016 		}
13017 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13018 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13019 		SET_SQUEUE(mp, tcp_input, connp);
13020 		return (mp);
13021 	}
13022 
13023 	if (tcph_flags == TH_SYN) {
13024 		if (IPCL_IS_TCP(connp)) {
13025 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13026 			DB_CKSUMSTART(mp) =
13027 			    (intptr_t)ip_squeue_get(ill_ring);
13028 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13029 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13030 				BUMP_MIB(ill->ill_ip_mib,
13031 				    ipIfStatsHCInDelivers);
13032 				SET_SQUEUE(mp, connp->conn_recv, connp);
13033 				return (mp);
13034 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13035 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13036 				BUMP_MIB(ill->ill_ip_mib,
13037 				    ipIfStatsHCInDelivers);
13038 				ip_squeue_enter_unbound++;
13039 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13040 				    connp);
13041 				return (mp);
13042 			}
13043 			syn_present = B_TRUE;
13044 		}
13045 	}
13046 
13047 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13048 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13049 
13050 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13051 		/* No need to send this packet to TCP */
13052 		if ((flags & TH_RST) || (flags & TH_URG)) {
13053 			CONN_DEC_REF(connp);
13054 			freemsg(first_mp);
13055 			return (NULL);
13056 		}
13057 		if (flags & TH_ACK) {
13058 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13059 			    ipst->ips_netstack->netstack_tcp, connp);
13060 			CONN_DEC_REF(connp);
13061 			return (NULL);
13062 		}
13063 
13064 		CONN_DEC_REF(connp);
13065 		freemsg(first_mp);
13066 		return (NULL);
13067 	}
13068 
13069 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13070 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13071 		    ipha, NULL, mctl_present);
13072 		if (first_mp == NULL) {
13073 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13074 			CONN_DEC_REF(connp);
13075 			return (NULL);
13076 		}
13077 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13078 			ASSERT(syn_present);
13079 			if (mctl_present) {
13080 				ASSERT(first_mp != mp);
13081 				first_mp->b_datap->db_struioflag |=
13082 				    STRUIO_POLICY;
13083 			} else {
13084 				ASSERT(first_mp == mp);
13085 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13086 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13087 			}
13088 		} else {
13089 			/*
13090 			 * Discard first_mp early since we're dealing with a
13091 			 * fully-connected conn_t and tcp doesn't do policy in
13092 			 * this case.
13093 			 */
13094 			if (mctl_present) {
13095 				freeb(first_mp);
13096 				mctl_present = B_FALSE;
13097 			}
13098 			first_mp = mp;
13099 		}
13100 	}
13101 
13102 	/* Initiate IPPF processing for fastpath */
13103 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13104 		uint32_t	ill_index;
13105 
13106 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13107 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13108 		if (mp == NULL) {
13109 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13110 			    "deferred/dropped during IPPF processing\n"));
13111 			CONN_DEC_REF(connp);
13112 			if (mctl_present)
13113 				freeb(first_mp);
13114 			return (NULL);
13115 		} else if (mctl_present) {
13116 			/*
13117 			 * ip_process might return a new mp.
13118 			 */
13119 			ASSERT(first_mp != mp);
13120 			first_mp->b_cont = mp;
13121 		} else {
13122 			first_mp = mp;
13123 		}
13124 
13125 	}
13126 
13127 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13128 		/*
13129 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13130 		 * make sure IPF_RECVIF is passed to ip_add_info.
13131 		 */
13132 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13133 		    IPCL_ZONEID(connp), ipst);
13134 		if (mp == NULL) {
13135 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13136 			CONN_DEC_REF(connp);
13137 			if (mctl_present)
13138 				freeb(first_mp);
13139 			return (NULL);
13140 		} else if (mctl_present) {
13141 			/*
13142 			 * ip_add_info might return a new mp.
13143 			 */
13144 			ASSERT(first_mp != mp);
13145 			first_mp->b_cont = mp;
13146 		} else {
13147 			first_mp = mp;
13148 		}
13149 	}
13150 
13151 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13152 	if (IPCL_IS_TCP(connp)) {
13153 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13154 		return (first_mp);
13155 	} else {
13156 		/* SOCK_RAW, IPPROTO_TCP case */
13157 		(connp->conn_recv)(connp, first_mp, NULL);
13158 		CONN_DEC_REF(connp);
13159 		return (NULL);
13160 	}
13161 
13162 no_conn:
13163 	/* Initiate IPPf processing, if needed. */
13164 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13165 		uint32_t ill_index;
13166 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13167 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13168 		if (first_mp == NULL) {
13169 			return (NULL);
13170 		}
13171 	}
13172 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13173 
13174 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13175 	    ipst->ips_netstack->netstack_tcp, NULL);
13176 	return (NULL);
13177 ipoptions:
13178 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13179 		goto slow_done;
13180 	}
13181 
13182 	UPDATE_IB_PKT_COUNT(ire);
13183 	ire->ire_last_used_time = lbolt;
13184 
13185 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13186 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13187 fragmented:
13188 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13189 			if (mctl_present)
13190 				freeb(first_mp);
13191 			goto slow_done;
13192 		}
13193 		/*
13194 		 * Make sure that first_mp points back to mp as
13195 		 * the mp we came in with could have changed in
13196 		 * ip_rput_fragment().
13197 		 */
13198 		ASSERT(!mctl_present);
13199 		ipha = (ipha_t *)mp->b_rptr;
13200 		first_mp = mp;
13201 	}
13202 
13203 	/* Now we have a complete datagram, destined for this machine. */
13204 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13205 
13206 	len = mp->b_wptr - mp->b_rptr;
13207 	/* Pull up a minimal TCP header, if necessary. */
13208 	if (len < (u1 + 20)) {
13209 tcppullup:
13210 		if (!pullupmsg(mp, u1 + 20)) {
13211 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13212 			goto error;
13213 		}
13214 		ipha = (ipha_t *)mp->b_rptr;
13215 		len = mp->b_wptr - mp->b_rptr;
13216 	}
13217 
13218 	/*
13219 	 * Extract the offset field from the TCP header.  As usual, we
13220 	 * try to help the compiler more than the reader.
13221 	 */
13222 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13223 	if (offset != 5) {
13224 tcpoptions:
13225 		if (offset < 5) {
13226 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13227 			goto error;
13228 		}
13229 		/*
13230 		 * There must be TCP options.
13231 		 * Make sure we can grab them.
13232 		 */
13233 		offset <<= 2;
13234 		offset += u1;
13235 		if (len < offset) {
13236 			if (!pullupmsg(mp, offset)) {
13237 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13238 				goto error;
13239 			}
13240 			ipha = (ipha_t *)mp->b_rptr;
13241 			len = mp->b_wptr - rptr;
13242 		}
13243 	}
13244 
13245 	/* Get the total packet length in len, including headers. */
13246 	if (mp->b_cont)
13247 		len = msgdsize(mp);
13248 
13249 	/*
13250 	 * Check the TCP checksum by pulling together the pseudo-
13251 	 * header checksum, and passing it to ip_csum to be added in
13252 	 * with the TCP datagram.
13253 	 *
13254 	 * Since we are not using the hwcksum if available we must
13255 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13256 	 * If either of these fails along the way the mblk is freed.
13257 	 * If this logic ever changes and mblk is reused to say send
13258 	 * ICMP's back, then this flag may need to be cleared in
13259 	 * other places as well.
13260 	 */
13261 	DB_CKSUMFLAGS(mp) = 0;
13262 
13263 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13264 
13265 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13266 #ifdef	_BIG_ENDIAN
13267 	u1 += IPPROTO_TCP;
13268 #else
13269 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13270 #endif
13271 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13272 	/*
13273 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13274 	 */
13275 	IP_STAT(ipst, ip_in_sw_cksum);
13276 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13277 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13278 		goto error;
13279 	}
13280 
13281 	IP_STAT(ipst, ip_tcp_slow_path);
13282 	goto try_again;
13283 #undef  iphs
13284 #undef  rptr
13285 
13286 error:
13287 	freemsg(first_mp);
13288 slow_done:
13289 	return (NULL);
13290 }
13291 
13292 /* ARGSUSED */
13293 static void
13294 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13295     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13296 {
13297 	conn_t		*connp;
13298 	uint32_t	sum;
13299 	uint32_t	u1;
13300 	ssize_t		len;
13301 	sctp_hdr_t	*sctph;
13302 	zoneid_t	zoneid = ire->ire_zoneid;
13303 	uint32_t	pktsum;
13304 	uint32_t	calcsum;
13305 	uint32_t	ports;
13306 	in6_addr_t	map_src, map_dst;
13307 	ill_t		*ill = (ill_t *)q->q_ptr;
13308 	ip_stack_t	*ipst;
13309 	sctp_stack_t	*sctps;
13310 	boolean_t	sctp_csum_err = B_FALSE;
13311 
13312 	ASSERT(recv_ill != NULL);
13313 	ipst = recv_ill->ill_ipst;
13314 	sctps = ipst->ips_netstack->netstack_sctp;
13315 
13316 #define	rptr	((uchar_t *)ipha)
13317 
13318 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13319 	ASSERT(ill != NULL);
13320 
13321 	/* u1 is # words of IP options */
13322 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13323 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13324 
13325 	/* IP options present */
13326 	if (u1 > 0) {
13327 		goto ipoptions;
13328 	} else {
13329 		/* Check the IP header checksum.  */
13330 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13331 		    !mctl_present) {
13332 #define	uph	((uint16_t *)ipha)
13333 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13334 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13335 #undef	uph
13336 			/* finish doing IP checksum */
13337 			sum = (sum & 0xFFFF) + (sum >> 16);
13338 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13339 			/*
13340 			 * Don't verify header checksum if this packet
13341 			 * is coming back from AH/ESP as we already did it.
13342 			 */
13343 			if (sum != 0 && sum != 0xFFFF) {
13344 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13345 				goto error;
13346 			}
13347 		}
13348 		/*
13349 		 * Since there is no SCTP h/w cksum support yet, just
13350 		 * clear the flag.
13351 		 */
13352 		DB_CKSUMFLAGS(mp) = 0;
13353 	}
13354 
13355 	/*
13356 	 * Don't verify header checksum if this packet is coming
13357 	 * back from AH/ESP as we already did it.
13358 	 */
13359 	if (!mctl_present) {
13360 		UPDATE_IB_PKT_COUNT(ire);
13361 		ire->ire_last_used_time = lbolt;
13362 	}
13363 
13364 	/* packet part of fragmented IP packet? */
13365 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13366 	if (u1 & (IPH_MF | IPH_OFFSET))
13367 		goto fragmented;
13368 
13369 	/* u1 = IP header length (20 bytes) */
13370 	u1 = IP_SIMPLE_HDR_LENGTH;
13371 
13372 find_sctp_client:
13373 	/* Pullup if we don't have the sctp common header. */
13374 	len = MBLKL(mp);
13375 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13376 		if (mp->b_cont == NULL ||
13377 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13378 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13379 			goto error;
13380 		}
13381 		ipha = (ipha_t *)mp->b_rptr;
13382 		len = MBLKL(mp);
13383 	}
13384 
13385 	sctph = (sctp_hdr_t *)(rptr + u1);
13386 #ifdef	DEBUG
13387 	if (!skip_sctp_cksum) {
13388 #endif
13389 		pktsum = sctph->sh_chksum;
13390 		sctph->sh_chksum = 0;
13391 		calcsum = sctp_cksum(mp, u1);
13392 		sctph->sh_chksum = pktsum;
13393 		if (calcsum != pktsum)
13394 			sctp_csum_err = B_TRUE;
13395 #ifdef	DEBUG	/* skip_sctp_cksum */
13396 	}
13397 #endif
13398 	/* get the ports */
13399 	ports = *(uint32_t *)&sctph->sh_sport;
13400 
13401 	IRE_REFRELE(ire);
13402 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13403 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13404 	if (sctp_csum_err) {
13405 		/*
13406 		 * No potential sctp checksum errors go to the Sun
13407 		 * sctp stack however they might be Adler-32 summed
13408 		 * packets a userland stack bound to a raw IP socket
13409 		 * could reasonably use. Note though that Adler-32 is
13410 		 * a long deprecated algorithm and customer sctp
13411 		 * networks should eventually migrate to CRC-32 at
13412 		 * which time this facility should be removed.
13413 		 */
13414 		flags |= IP_FF_SCTP_CSUM_ERR;
13415 		goto no_conn;
13416 	}
13417 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13418 	    sctps)) == NULL) {
13419 		/* Check for raw socket or OOTB handling */
13420 		goto no_conn;
13421 	}
13422 
13423 	/* Found a client; up it goes */
13424 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13425 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13426 	return;
13427 
13428 no_conn:
13429 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13430 	    ports, mctl_present, flags, B_TRUE, zoneid);
13431 	return;
13432 
13433 ipoptions:
13434 	DB_CKSUMFLAGS(mp) = 0;
13435 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13436 		goto slow_done;
13437 
13438 	UPDATE_IB_PKT_COUNT(ire);
13439 	ire->ire_last_used_time = lbolt;
13440 
13441 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13442 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13443 fragmented:
13444 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13445 			goto slow_done;
13446 		/*
13447 		 * Make sure that first_mp points back to mp as
13448 		 * the mp we came in with could have changed in
13449 		 * ip_rput_fragment().
13450 		 */
13451 		ASSERT(!mctl_present);
13452 		ipha = (ipha_t *)mp->b_rptr;
13453 		first_mp = mp;
13454 	}
13455 
13456 	/* Now we have a complete datagram, destined for this machine. */
13457 	u1 = IPH_HDR_LENGTH(ipha);
13458 	goto find_sctp_client;
13459 #undef  iphs
13460 #undef  rptr
13461 
13462 error:
13463 	freemsg(first_mp);
13464 slow_done:
13465 	IRE_REFRELE(ire);
13466 }
13467 
13468 #define	VER_BITS	0xF0
13469 #define	VERSION_6	0x60
13470 
13471 static boolean_t
13472 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13473     ipaddr_t *dstp, ip_stack_t *ipst)
13474 {
13475 	uint_t	opt_len;
13476 	ipha_t *ipha;
13477 	ssize_t len;
13478 	uint_t	pkt_len;
13479 
13480 	ASSERT(ill != NULL);
13481 	IP_STAT(ipst, ip_ipoptions);
13482 	ipha = *iphapp;
13483 
13484 #define	rptr    ((uchar_t *)ipha)
13485 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13486 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13487 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13488 		freemsg(mp);
13489 		return (B_FALSE);
13490 	}
13491 
13492 	/* multiple mblk or too short */
13493 	pkt_len = ntohs(ipha->ipha_length);
13494 
13495 	/* Get the number of words of IP options in the IP header. */
13496 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13497 	if (opt_len) {
13498 		/* IP Options present!  Validate and process. */
13499 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13500 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13501 			goto done;
13502 		}
13503 		/*
13504 		 * Recompute complete header length and make sure we
13505 		 * have access to all of it.
13506 		 */
13507 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13508 		if (len > (mp->b_wptr - rptr)) {
13509 			if (len > pkt_len) {
13510 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13511 				goto done;
13512 			}
13513 			if (!pullupmsg(mp, len)) {
13514 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13515 				goto done;
13516 			}
13517 			ipha = (ipha_t *)mp->b_rptr;
13518 		}
13519 		/*
13520 		 * Go off to ip_rput_options which returns the next hop
13521 		 * destination address, which may have been affected
13522 		 * by source routing.
13523 		 */
13524 		IP_STAT(ipst, ip_opt);
13525 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13526 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13527 			return (B_FALSE);
13528 		}
13529 	}
13530 	*iphapp = ipha;
13531 	return (B_TRUE);
13532 done:
13533 	/* clear b_prev - used by ip_mroute_decap */
13534 	mp->b_prev = NULL;
13535 	freemsg(mp);
13536 	return (B_FALSE);
13537 #undef  rptr
13538 }
13539 
13540 /*
13541  * Deal with the fact that there is no ire for the destination.
13542  */
13543 static ire_t *
13544 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13545 {
13546 	ipha_t	*ipha;
13547 	ill_t	*ill;
13548 	ire_t	*ire;
13549 	ip_stack_t *ipst;
13550 	enum	ire_forward_action ret_action;
13551 
13552 	ipha = (ipha_t *)mp->b_rptr;
13553 	ill = (ill_t *)q->q_ptr;
13554 
13555 	ASSERT(ill != NULL);
13556 	ipst = ill->ill_ipst;
13557 
13558 	/*
13559 	 * No IRE for this destination, so it can't be for us.
13560 	 * Unless we are forwarding, drop the packet.
13561 	 * We have to let source routed packets through
13562 	 * since we don't yet know if they are 'ping -l'
13563 	 * packets i.e. if they will go out over the
13564 	 * same interface as they came in on.
13565 	 */
13566 	if (ll_multicast) {
13567 		freemsg(mp);
13568 		return (NULL);
13569 	}
13570 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13571 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13572 		freemsg(mp);
13573 		return (NULL);
13574 	}
13575 
13576 	/*
13577 	 * Mark this packet as having originated externally.
13578 	 *
13579 	 * For non-forwarding code path, ire_send later double
13580 	 * checks this interface to see if it is still exists
13581 	 * post-ARP resolution.
13582 	 *
13583 	 * Also, IPQOS uses this to differentiate between
13584 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13585 	 * QOS packet processing in ip_wput_attach_llhdr().
13586 	 * The QoS module can mark the b_band for a fastpath message
13587 	 * or the dl_priority field in a unitdata_req header for
13588 	 * CoS marking. This info can only be found in
13589 	 * ip_wput_attach_llhdr().
13590 	 */
13591 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13592 	/*
13593 	 * Clear the indication that this may have a hardware checksum
13594 	 * as we are not using it
13595 	 */
13596 	DB_CKSUMFLAGS(mp) = 0;
13597 
13598 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13599 	    msg_getlabel(mp), ipst);
13600 
13601 	if (ire == NULL && ret_action == Forward_check_multirt) {
13602 		/* Let ip_newroute handle CGTP  */
13603 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13604 		return (NULL);
13605 	}
13606 
13607 	if (ire != NULL)
13608 		return (ire);
13609 
13610 	mp->b_prev = mp->b_next = 0;
13611 
13612 	if (ret_action == Forward_blackhole) {
13613 		freemsg(mp);
13614 		return (NULL);
13615 	}
13616 	/* send icmp unreachable */
13617 	q = WR(q);
13618 	/* Sent by forwarding path, and router is global zone */
13619 	if (ip_source_routed(ipha, ipst)) {
13620 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13621 		    GLOBAL_ZONEID, ipst);
13622 	} else {
13623 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13624 		    ipst);
13625 	}
13626 
13627 	return (NULL);
13628 
13629 }
13630 
13631 /*
13632  * check ip header length and align it.
13633  */
13634 static boolean_t
13635 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13636 {
13637 	ssize_t len;
13638 	ill_t *ill;
13639 	ipha_t	*ipha;
13640 
13641 	len = MBLKL(mp);
13642 
13643 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13644 		ill = (ill_t *)q->q_ptr;
13645 
13646 		if (!OK_32PTR(mp->b_rptr))
13647 			IP_STAT(ipst, ip_notaligned1);
13648 		else
13649 			IP_STAT(ipst, ip_notaligned2);
13650 		/* Guard against bogus device drivers */
13651 		if (len < 0) {
13652 			/* clear b_prev - used by ip_mroute_decap */
13653 			mp->b_prev = NULL;
13654 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13655 			freemsg(mp);
13656 			return (B_FALSE);
13657 		}
13658 
13659 		if (ip_rput_pullups++ == 0) {
13660 			ipha = (ipha_t *)mp->b_rptr;
13661 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13662 			    "ip_check_and_align_header: %s forced us to "
13663 			    " pullup pkt, hdr len %ld, hdr addr %p",
13664 			    ill->ill_name, len, (void *)ipha);
13665 		}
13666 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13667 			/* clear b_prev - used by ip_mroute_decap */
13668 			mp->b_prev = NULL;
13669 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13670 			freemsg(mp);
13671 			return (B_FALSE);
13672 		}
13673 	}
13674 	return (B_TRUE);
13675 }
13676 
13677 /*
13678  * Handle the situation where a packet came in on `ill' but matched an IRE
13679  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13680  * for interface statistics.
13681  */
13682 ire_t *
13683 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13684 {
13685 	ire_t		*new_ire;
13686 	ill_t		*ire_ill;
13687 	uint_t		ifindex;
13688 	ip_stack_t	*ipst = ill->ill_ipst;
13689 	boolean_t	strict_check = B_FALSE;
13690 
13691 	/*
13692 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13693 	 * issue (e.g. packet received on an underlying interface matched an
13694 	 * IRE_LOCAL on its associated group interface).
13695 	 */
13696 	if (ire->ire_rfq != NULL &&
13697 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13698 		return (ire);
13699 	}
13700 
13701 	/*
13702 	 * Do another ire lookup here, using the ingress ill, to see if the
13703 	 * interface is in a usesrc group.
13704 	 * As long as the ills belong to the same group, we don't consider
13705 	 * them to be arriving on the wrong interface. Thus, if the switch
13706 	 * is doing inbound load spreading, we won't drop packets when the
13707 	 * ip*_strict_dst_multihoming switch is on.
13708 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13709 	 * where the local address may not be unique. In this case we were
13710 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13711 	 * actually returned. The new lookup, which is more specific, should
13712 	 * only find the IRE_LOCAL associated with the ingress ill if one
13713 	 * exists.
13714 	 */
13715 
13716 	if (ire->ire_ipversion == IPV4_VERSION) {
13717 		if (ipst->ips_ip_strict_dst_multihoming)
13718 			strict_check = B_TRUE;
13719 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13720 		    ill->ill_ipif, ALL_ZONES, NULL,
13721 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13722 	} else {
13723 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13724 		if (ipst->ips_ipv6_strict_dst_multihoming)
13725 			strict_check = B_TRUE;
13726 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13727 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13728 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13729 	}
13730 	/*
13731 	 * If the same ire that was returned in ip_input() is found then this
13732 	 * is an indication that usesrc groups are in use. The packet
13733 	 * arrived on a different ill in the group than the one associated with
13734 	 * the destination address.  If a different ire was found then the same
13735 	 * IP address must be hosted on multiple ills. This is possible with
13736 	 * unnumbered point2point interfaces. We switch to use this new ire in
13737 	 * order to have accurate interface statistics.
13738 	 */
13739 	if (new_ire != NULL) {
13740 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13741 			ire_refrele(ire);
13742 			ire = new_ire;
13743 		} else {
13744 			ire_refrele(new_ire);
13745 		}
13746 		return (ire);
13747 	} else if ((ire->ire_rfq == NULL) &&
13748 	    (ire->ire_ipversion == IPV4_VERSION)) {
13749 		/*
13750 		 * The best match could have been the original ire which
13751 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13752 		 * the strict multihoming checks are irrelevant as we consider
13753 		 * local addresses hosted on lo0 to be interface agnostic. We
13754 		 * only expect a null ire_rfq on IREs which are associated with
13755 		 * lo0 hence we can return now.
13756 		 */
13757 		return (ire);
13758 	}
13759 
13760 	/*
13761 	 * Chase pointers once and store locally.
13762 	 */
13763 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13764 	    (ill_t *)(ire->ire_rfq->q_ptr);
13765 	ifindex = ill->ill_usesrc_ifindex;
13766 
13767 	/*
13768 	 * Check if it's a legal address on the 'usesrc' interface.
13769 	 */
13770 	if ((ifindex != 0) && (ire_ill != NULL) &&
13771 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13772 		return (ire);
13773 	}
13774 
13775 	/*
13776 	 * If the ip*_strict_dst_multihoming switch is on then we can
13777 	 * only accept this packet if the interface is marked as routing.
13778 	 */
13779 	if (!(strict_check))
13780 		return (ire);
13781 
13782 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13783 	    ILLF_ROUTER) != 0) {
13784 		return (ire);
13785 	}
13786 
13787 	ire_refrele(ire);
13788 	return (NULL);
13789 }
13790 
13791 /*
13792  *
13793  * This is the fast forward path. If we are here, we dont need to
13794  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13795  * needed to find the nexthop in this case is much simpler
13796  */
13797 ire_t *
13798 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13799 {
13800 	ipha_t	*ipha;
13801 	ire_t	*src_ire;
13802 	ill_t	*stq_ill;
13803 	uint_t	hlen;
13804 	uint_t	pkt_len;
13805 	uint32_t sum;
13806 	queue_t	*dev_q;
13807 	ip_stack_t *ipst = ill->ill_ipst;
13808 	mblk_t *fpmp;
13809 	enum	ire_forward_action ret_action;
13810 
13811 	ipha = (ipha_t *)mp->b_rptr;
13812 
13813 	if (ire != NULL &&
13814 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13815 	    ire->ire_zoneid != ALL_ZONES) {
13816 		/*
13817 		 * Should only use IREs that are visible to the global
13818 		 * zone for forwarding.
13819 		 */
13820 		ire_refrele(ire);
13821 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13822 		/*
13823 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13824 		 * transient cases. In such case, just drop the packet
13825 		 */
13826 		if (ire != NULL && ire->ire_type != IRE_CACHE)
13827 			goto indiscard;
13828 	}
13829 
13830 	/*
13831 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13832 	 * The loopback address check for both src and dst has already
13833 	 * been checked in ip_input
13834 	 */
13835 
13836 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13837 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13838 		goto drop;
13839 	}
13840 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13841 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13842 
13843 	if (src_ire != NULL) {
13844 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13845 		ire_refrele(src_ire);
13846 		goto drop;
13847 	}
13848 
13849 	/* No ire cache of nexthop. So first create one  */
13850 	if (ire == NULL) {
13851 
13852 		ire = ire_forward_simple(dst, &ret_action, ipst);
13853 
13854 		/*
13855 		 * We only come to ip_fast_forward if ip_cgtp_filter
13856 		 * is not set. So ire_forward() should not return with
13857 		 * Forward_check_multirt as the next action.
13858 		 */
13859 		ASSERT(ret_action != Forward_check_multirt);
13860 		if (ire == NULL) {
13861 			/* An attempt was made to forward the packet */
13862 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13863 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13864 			mp->b_prev = mp->b_next = 0;
13865 			/* send icmp unreachable */
13866 			/* Sent by forwarding path, and router is global zone */
13867 			if (ret_action == Forward_ret_icmp_err) {
13868 				if (ip_source_routed(ipha, ipst)) {
13869 					icmp_unreachable(ill->ill_wq, mp,
13870 					    ICMP_SOURCE_ROUTE_FAILED,
13871 					    GLOBAL_ZONEID, ipst);
13872 				} else {
13873 					icmp_unreachable(ill->ill_wq, mp,
13874 					    ICMP_HOST_UNREACHABLE,
13875 					    GLOBAL_ZONEID, ipst);
13876 				}
13877 			} else {
13878 				freemsg(mp);
13879 			}
13880 			return (NULL);
13881 		}
13882 	}
13883 
13884 	/*
13885 	 * Forwarding fastpath exception case:
13886 	 * If any of the following are true, we take the slowpath:
13887 	 *	o forwarding is not enabled
13888 	 *	o incoming and outgoing interface are the same, or in the same
13889 	 *	  IPMP group.
13890 	 *	o corresponding ire is in incomplete state
13891 	 *	o packet needs fragmentation
13892 	 *	o ARP cache is not resolved
13893 	 *
13894 	 * The codeflow from here on is thus:
13895 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13896 	 */
13897 	pkt_len = ntohs(ipha->ipha_length);
13898 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13899 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13900 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13901 	    (ire->ire_nce == NULL) ||
13902 	    (pkt_len > ire->ire_max_frag) ||
13903 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13904 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13905 	    ipha->ipha_ttl <= 1) {
13906 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13907 		    ipha, ill, B_FALSE, B_TRUE);
13908 		return (ire);
13909 	}
13910 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13911 
13912 	DTRACE_PROBE4(ip4__forwarding__start,
13913 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13914 
13915 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13916 	    ipst->ips_ipv4firewall_forwarding,
13917 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13918 
13919 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13920 
13921 	if (mp == NULL)
13922 		goto drop;
13923 
13924 	mp->b_datap->db_struioun.cksum.flags = 0;
13925 	/* Adjust the checksum to reflect the ttl decrement. */
13926 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13927 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13928 	ipha->ipha_ttl--;
13929 
13930 	/*
13931 	 * Write the link layer header.  We can do this safely here,
13932 	 * because we have already tested to make sure that the IP
13933 	 * policy is not set, and that we have a fast path destination
13934 	 * header.
13935 	 */
13936 	mp->b_rptr -= hlen;
13937 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13938 
13939 	UPDATE_IB_PKT_COUNT(ire);
13940 	ire->ire_last_used_time = lbolt;
13941 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13942 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13943 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13944 
13945 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13946 		dev_q = ire->ire_stq->q_next;
13947 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13948 			goto indiscard;
13949 	}
13950 
13951 	DTRACE_PROBE4(ip4__physical__out__start,
13952 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13953 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13954 	    ipst->ips_ipv4firewall_physical_out,
13955 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13956 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13957 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13958 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13959 	    ip6_t *, NULL, int, 0);
13960 
13961 	if (mp != NULL) {
13962 		if (ipst->ips_ip4_observe.he_interested) {
13963 			zoneid_t szone;
13964 
13965 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13966 			    ipst, ALL_ZONES);
13967 			/*
13968 			 * The IP observability hook expects b_rptr to be
13969 			 * where the IP header starts, so advance past the
13970 			 * link layer header.
13971 			 */
13972 			mp->b_rptr += hlen;
13973 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
13974 			    ALL_ZONES, ill, ipst);
13975 			mp->b_rptr -= hlen;
13976 		}
13977 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
13978 	}
13979 	return (ire);
13980 
13981 indiscard:
13982 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13983 drop:
13984 	if (mp != NULL)
13985 		freemsg(mp);
13986 	return (ire);
13987 
13988 }
13989 
13990 /*
13991  * This function is called in the forwarding slowpath, when
13992  * either the ire lacks the link-layer address, or the packet needs
13993  * further processing(eg. fragmentation), before transmission.
13994  */
13995 
13996 static void
13997 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13998     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
13999 {
14000 	queue_t		*dev_q;
14001 	ire_t		*src_ire;
14002 	ip_stack_t	*ipst = ill->ill_ipst;
14003 	boolean_t	same_illgrp = B_FALSE;
14004 
14005 	ASSERT(ire->ire_stq != NULL);
14006 
14007 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14008 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14009 
14010 	/*
14011 	 * If the caller of this function is ip_fast_forward() skip the
14012 	 * next three checks as it does not apply.
14013 	 */
14014 	if (from_ip_fast_forward)
14015 		goto skip;
14016 
14017 	if (ll_multicast != 0) {
14018 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14019 		goto drop_pkt;
14020 	}
14021 
14022 	/*
14023 	 * check if ipha_src is a broadcast address. Note that this
14024 	 * check is redundant when we get here from ip_fast_forward()
14025 	 * which has already done this check. However, since we can
14026 	 * also get here from ip_rput_process_broadcast() or, for
14027 	 * for the slow path through ip_fast_forward(), we perform
14028 	 * the check again for code-reusability
14029 	 */
14030 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14031 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14032 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14033 		if (src_ire != NULL)
14034 			ire_refrele(src_ire);
14035 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14036 		ip2dbg(("ip_rput_process_forward: Received packet with"
14037 		    " bad src/dst address on %s\n", ill->ill_name));
14038 		goto drop_pkt;
14039 	}
14040 
14041 	/*
14042 	 * Check if we want to forward this one at this time.
14043 	 * We allow source routed packets on a host provided that
14044 	 * they go out the same ill or illgrp as they came in on.
14045 	 *
14046 	 * XXX To be quicker, we may wish to not chase pointers to
14047 	 * get the ILLF_ROUTER flag and instead store the
14048 	 * forwarding policy in the ire.  An unfortunate
14049 	 * side-effect of that would be requiring an ire flush
14050 	 * whenever the ILLF_ROUTER flag changes.
14051 	 */
14052 skip:
14053 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14054 
14055 	if (((ill->ill_flags &
14056 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14057 	    !(ip_source_routed(ipha, ipst) &&
14058 	    (ire->ire_rfq == q || same_illgrp))) {
14059 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14060 		if (ip_source_routed(ipha, ipst)) {
14061 			q = WR(q);
14062 			/*
14063 			 * Clear the indication that this may have
14064 			 * hardware checksum as we are not using it.
14065 			 */
14066 			DB_CKSUMFLAGS(mp) = 0;
14067 			/* Sent by forwarding path, and router is global zone */
14068 			icmp_unreachable(q, mp,
14069 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14070 			return;
14071 		}
14072 		goto drop_pkt;
14073 	}
14074 
14075 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14076 
14077 	/* Packet is being forwarded. Turning off hwcksum flag. */
14078 	DB_CKSUMFLAGS(mp) = 0;
14079 	if (ipst->ips_ip_g_send_redirects) {
14080 		/*
14081 		 * Check whether the incoming interface and outgoing
14082 		 * interface is part of the same group. If so,
14083 		 * send redirects.
14084 		 *
14085 		 * Check the source address to see if it originated
14086 		 * on the same logical subnet it is going back out on.
14087 		 * If so, we should be able to send it a redirect.
14088 		 * Avoid sending a redirect if the destination
14089 		 * is directly connected (i.e., ipha_dst is the same
14090 		 * as ire_gateway_addr or the ire_addr of the
14091 		 * nexthop IRE_CACHE ), or if the packet was source
14092 		 * routed out this interface.
14093 		 */
14094 		ipaddr_t src, nhop;
14095 		mblk_t	*mp1;
14096 		ire_t	*nhop_ire = NULL;
14097 
14098 		/*
14099 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14100 		 * If so, send redirects.
14101 		 */
14102 		if ((ire->ire_rfq == q || same_illgrp) &&
14103 		    !ip_source_routed(ipha, ipst)) {
14104 
14105 			nhop = (ire->ire_gateway_addr != 0 ?
14106 			    ire->ire_gateway_addr : ire->ire_addr);
14107 
14108 			if (ipha->ipha_dst == nhop) {
14109 				/*
14110 				 * We avoid sending a redirect if the
14111 				 * destination is directly connected
14112 				 * because it is possible that multiple
14113 				 * IP subnets may have been configured on
14114 				 * the link, and the source may not
14115 				 * be on the same subnet as ip destination,
14116 				 * even though they are on the same
14117 				 * physical link.
14118 				 */
14119 				goto sendit;
14120 			}
14121 
14122 			src = ipha->ipha_src;
14123 
14124 			/*
14125 			 * We look up the interface ire for the nexthop,
14126 			 * to see if ipha_src is in the same subnet
14127 			 * as the nexthop.
14128 			 *
14129 			 * Note that, if, in the future, IRE_CACHE entries
14130 			 * are obsoleted,  this lookup will not be needed,
14131 			 * as the ire passed to this function will be the
14132 			 * same as the nhop_ire computed below.
14133 			 */
14134 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14135 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14136 			    0, NULL, MATCH_IRE_TYPE, ipst);
14137 
14138 			if (nhop_ire != NULL) {
14139 				if ((src & nhop_ire->ire_mask) ==
14140 				    (nhop & nhop_ire->ire_mask)) {
14141 					/*
14142 					 * The source is directly connected.
14143 					 * Just copy the ip header (which is
14144 					 * in the first mblk)
14145 					 */
14146 					mp1 = copyb(mp);
14147 					if (mp1 != NULL) {
14148 						icmp_send_redirect(WR(q), mp1,
14149 						    nhop, ipst);
14150 					}
14151 				}
14152 				ire_refrele(nhop_ire);
14153 			}
14154 		}
14155 	}
14156 sendit:
14157 	dev_q = ire->ire_stq->q_next;
14158 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14159 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14160 		freemsg(mp);
14161 		return;
14162 	}
14163 
14164 	ip_rput_forward(ire, ipha, mp, ill);
14165 	return;
14166 
14167 drop_pkt:
14168 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14169 	freemsg(mp);
14170 }
14171 
14172 ire_t *
14173 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14174     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14175 {
14176 	queue_t		*q;
14177 	uint16_t	hcksumflags;
14178 	ip_stack_t	*ipst = ill->ill_ipst;
14179 
14180 	q = *qp;
14181 
14182 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14183 
14184 	/*
14185 	 * Clear the indication that this may have hardware
14186 	 * checksum as we are not using it for forwarding.
14187 	 */
14188 	hcksumflags = DB_CKSUMFLAGS(mp);
14189 	DB_CKSUMFLAGS(mp) = 0;
14190 
14191 	/*
14192 	 * Directed broadcast forwarding: if the packet came in over a
14193 	 * different interface then it is routed out over we can forward it.
14194 	 */
14195 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14196 		ire_refrele(ire);
14197 		freemsg(mp);
14198 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14199 		return (NULL);
14200 	}
14201 	/*
14202 	 * For multicast we have set dst to be INADDR_BROADCAST
14203 	 * for delivering to all STREAMS.
14204 	 */
14205 	if (!CLASSD(ipha->ipha_dst)) {
14206 		ire_t *new_ire;
14207 		ipif_t *ipif;
14208 
14209 		ipif = ipif_get_next_ipif(NULL, ill);
14210 		if (ipif == NULL) {
14211 discard:		ire_refrele(ire);
14212 			freemsg(mp);
14213 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14214 			return (NULL);
14215 		}
14216 		new_ire = ire_ctable_lookup(dst, 0, 0,
14217 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14218 		ipif_refrele(ipif);
14219 
14220 		if (new_ire != NULL) {
14221 			/*
14222 			 * If the matching IRE_BROADCAST is part of an IPMP
14223 			 * group, then drop the packet unless our ill has been
14224 			 * nominated to receive for the group.
14225 			 */
14226 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14227 			    new_ire->ire_rfq != q) {
14228 				ire_refrele(new_ire);
14229 				goto discard;
14230 			}
14231 
14232 			/*
14233 			 * In the special case of multirouted broadcast
14234 			 * packets, we unconditionally need to "gateway"
14235 			 * them to the appropriate interface here.
14236 			 * In the normal case, this cannot happen, because
14237 			 * there is no broadcast IRE tagged with the
14238 			 * RTF_MULTIRT flag.
14239 			 */
14240 			if (new_ire->ire_flags & RTF_MULTIRT) {
14241 				ire_refrele(new_ire);
14242 				if (ire->ire_rfq != NULL) {
14243 					q = ire->ire_rfq;
14244 					*qp = q;
14245 				}
14246 			} else {
14247 				ire_refrele(ire);
14248 				ire = new_ire;
14249 			}
14250 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14251 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14252 				/*
14253 				 * Free the message if
14254 				 * ip_g_forward_directed_bcast is turned
14255 				 * off for non-local broadcast.
14256 				 */
14257 				ire_refrele(ire);
14258 				freemsg(mp);
14259 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14260 				return (NULL);
14261 			}
14262 		} else {
14263 			/*
14264 			 * This CGTP packet successfully passed the
14265 			 * CGTP filter, but the related CGTP
14266 			 * broadcast IRE has not been found,
14267 			 * meaning that the redundant ipif is
14268 			 * probably down. However, if we discarded
14269 			 * this packet, its duplicate would be
14270 			 * filtered out by the CGTP filter so none
14271 			 * of them would get through. So we keep
14272 			 * going with this one.
14273 			 */
14274 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14275 			if (ire->ire_rfq != NULL) {
14276 				q = ire->ire_rfq;
14277 				*qp = q;
14278 			}
14279 		}
14280 	}
14281 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14282 		/*
14283 		 * Verify that there are not more then one
14284 		 * IRE_BROADCAST with this broadcast address which
14285 		 * has ire_stq set.
14286 		 * TODO: simplify, loop over all IRE's
14287 		 */
14288 		ire_t	*ire1;
14289 		int	num_stq = 0;
14290 		mblk_t	*mp1;
14291 
14292 		/* Find the first one with ire_stq set */
14293 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14294 		for (ire1 = ire; ire1 &&
14295 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14296 		    ire1 = ire1->ire_next)
14297 			;
14298 		if (ire1) {
14299 			ire_refrele(ire);
14300 			ire = ire1;
14301 			IRE_REFHOLD(ire);
14302 		}
14303 
14304 		/* Check if there are additional ones with stq set */
14305 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14306 			if (ire->ire_addr != ire1->ire_addr)
14307 				break;
14308 			if (ire1->ire_stq) {
14309 				num_stq++;
14310 				break;
14311 			}
14312 		}
14313 		rw_exit(&ire->ire_bucket->irb_lock);
14314 		if (num_stq == 1 && ire->ire_stq != NULL) {
14315 			ip1dbg(("ip_rput_process_broadcast: directed "
14316 			    "broadcast to 0x%x\n",
14317 			    ntohl(ire->ire_addr)));
14318 			mp1 = copymsg(mp);
14319 			if (mp1) {
14320 				switch (ipha->ipha_protocol) {
14321 				case IPPROTO_UDP:
14322 					ip_udp_input(q, mp1, ipha, ire, ill);
14323 					break;
14324 				default:
14325 					ip_proto_input(q, mp1, ipha, ire, ill,
14326 					    0);
14327 					break;
14328 				}
14329 			}
14330 			/*
14331 			 * Adjust ttl to 2 (1+1 - the forward engine
14332 			 * will decrement it by one.
14333 			 */
14334 			if (ip_csum_hdr(ipha)) {
14335 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14336 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14337 				freemsg(mp);
14338 				ire_refrele(ire);
14339 				return (NULL);
14340 			}
14341 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14342 			ipha->ipha_hdr_checksum = 0;
14343 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14344 			ip_rput_process_forward(q, mp, ire, ipha,
14345 			    ill, ll_multicast, B_FALSE);
14346 			ire_refrele(ire);
14347 			return (NULL);
14348 		}
14349 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14350 		    ntohl(ire->ire_addr)));
14351 	}
14352 
14353 	/* Restore any hardware checksum flags */
14354 	DB_CKSUMFLAGS(mp) = hcksumflags;
14355 	return (ire);
14356 }
14357 
14358 /* ARGSUSED */
14359 static boolean_t
14360 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14361     int *ll_multicast, ipaddr_t *dstp)
14362 {
14363 	ip_stack_t	*ipst = ill->ill_ipst;
14364 
14365 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14366 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14367 	    ntohs(ipha->ipha_length));
14368 
14369 	/*
14370 	 * So that we don't end up with dups, only one ill in an IPMP group is
14371 	 * nominated to receive multicast traffic.
14372 	 */
14373 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14374 		goto drop_pkt;
14375 
14376 	/*
14377 	 * Forward packets only if we have joined the allmulti
14378 	 * group on this interface.
14379 	 */
14380 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14381 		int retval;
14382 
14383 		/*
14384 		 * Clear the indication that this may have hardware
14385 		 * checksum as we are not using it.
14386 		 */
14387 		DB_CKSUMFLAGS(mp) = 0;
14388 		retval = ip_mforward(ill, ipha, mp);
14389 		/* ip_mforward updates mib variables if needed */
14390 		/* clear b_prev - used by ip_mroute_decap */
14391 		mp->b_prev = NULL;
14392 
14393 		switch (retval) {
14394 		case 0:
14395 			/*
14396 			 * pkt is okay and arrived on phyint.
14397 			 *
14398 			 * If we are running as a multicast router
14399 			 * we need to see all IGMP and/or PIM packets.
14400 			 */
14401 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14402 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14403 				goto done;
14404 			}
14405 			break;
14406 		case -1:
14407 			/* pkt is mal-formed, toss it */
14408 			goto drop_pkt;
14409 		case 1:
14410 			/* pkt is okay and arrived on a tunnel */
14411 			/*
14412 			 * If we are running a multicast router
14413 			 *  we need to see all igmp packets.
14414 			 */
14415 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14416 				*dstp = INADDR_BROADCAST;
14417 				*ll_multicast = 1;
14418 				return (B_FALSE);
14419 			}
14420 
14421 			goto drop_pkt;
14422 		}
14423 	}
14424 
14425 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14426 		/*
14427 		 * This might just be caused by the fact that
14428 		 * multiple IP Multicast addresses map to the same
14429 		 * link layer multicast - no need to increment counter!
14430 		 */
14431 		freemsg(mp);
14432 		return (B_TRUE);
14433 	}
14434 done:
14435 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14436 	/*
14437 	 * This assumes the we deliver to all streams for multicast
14438 	 * and broadcast packets.
14439 	 */
14440 	*dstp = INADDR_BROADCAST;
14441 	*ll_multicast = 1;
14442 	return (B_FALSE);
14443 drop_pkt:
14444 	ip2dbg(("ip_rput: drop pkt\n"));
14445 	freemsg(mp);
14446 	return (B_TRUE);
14447 }
14448 
14449 /*
14450  * This function is used to both return an indication of whether or not
14451  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14452  * and in doing so, determine whether or not it is broadcast vs multicast.
14453  * For it to be a broadcast packet, we must have the appropriate mblk_t
14454  * hanging off the ill_t.  If this is either not present or doesn't match
14455  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14456  * to be multicast.  Thus NICs that have no broadcast address (or no
14457  * capability for one, such as point to point links) cannot return as
14458  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14459  * the return values simplifies the current use of the return value of this
14460  * function, which is to pass through the multicast/broadcast characteristic
14461  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14462  * changing the return value to some other symbol demands the appropriate
14463  * "translation" when hpe_flags is set prior to calling hook_run() for
14464  * packet events.
14465  */
14466 int
14467 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14468 {
14469 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14470 	mblk_t *bmp;
14471 
14472 	if (ind->dl_group_address) {
14473 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14474 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14475 		    MBLKL(mb) &&
14476 		    (bmp = ill->ill_bcast_mp) != NULL) {
14477 			dl_unitdata_req_t *dlur;
14478 			uint8_t *bphys_addr;
14479 
14480 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14481 			if (ill->ill_sap_length < 0)
14482 				bphys_addr = (uchar_t *)dlur +
14483 				    dlur->dl_dest_addr_offset;
14484 			else
14485 				bphys_addr = (uchar_t *)dlur +
14486 				    dlur->dl_dest_addr_offset +
14487 				    ill->ill_sap_length;
14488 
14489 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14490 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14491 				return (HPE_BROADCAST);
14492 			}
14493 			return (HPE_MULTICAST);
14494 		}
14495 		return (HPE_MULTICAST);
14496 	}
14497 	return (0);
14498 }
14499 
14500 static boolean_t
14501 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14502     int *ll_multicast, mblk_t **mpp)
14503 {
14504 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14505 	boolean_t must_copy = B_FALSE;
14506 	struct iocblk   *iocp;
14507 	ipha_t		*ipha;
14508 	ip_stack_t	*ipst = ill->ill_ipst;
14509 
14510 #define	rptr    ((uchar_t *)ipha)
14511 
14512 	first_mp = *first_mpp;
14513 	mp = *mpp;
14514 
14515 	ASSERT(first_mp == mp);
14516 
14517 	/*
14518 	 * if db_ref > 1 then copymsg and free original. Packet may be
14519 	 * changed and do not want other entity who has a reference to this
14520 	 * message to trip over the changes. This is a blind change because
14521 	 * trying to catch all places that might change packet is too
14522 	 * difficult (since it may be a module above this one)
14523 	 *
14524 	 * This corresponds to the non-fast path case. We walk down the full
14525 	 * chain in this case, and check the db_ref count of all the dblks,
14526 	 * and do a copymsg if required. It is possible that the db_ref counts
14527 	 * of the data blocks in the mblk chain can be different.
14528 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14529 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14530 	 * 'snoop' is running.
14531 	 */
14532 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14533 		if (mp1->b_datap->db_ref > 1) {
14534 			must_copy = B_TRUE;
14535 			break;
14536 		}
14537 	}
14538 
14539 	if (must_copy) {
14540 		mp1 = copymsg(mp);
14541 		if (mp1 == NULL) {
14542 			for (mp1 = mp; mp1 != NULL;
14543 			    mp1 = mp1->b_cont) {
14544 				mp1->b_next = NULL;
14545 				mp1->b_prev = NULL;
14546 			}
14547 			freemsg(mp);
14548 			if (ill != NULL) {
14549 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14550 			} else {
14551 				BUMP_MIB(&ipst->ips_ip_mib,
14552 				    ipIfStatsInDiscards);
14553 			}
14554 			return (B_TRUE);
14555 		}
14556 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14557 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14558 			/* Copy b_prev - used by ip_mroute_decap */
14559 			to_mp->b_prev = from_mp->b_prev;
14560 			from_mp->b_prev = NULL;
14561 		}
14562 		*first_mpp = first_mp = mp1;
14563 		freemsg(mp);
14564 		mp = mp1;
14565 		*mpp = mp1;
14566 	}
14567 
14568 	ipha = (ipha_t *)mp->b_rptr;
14569 
14570 	/*
14571 	 * previous code has a case for M_DATA.
14572 	 * We want to check how that happens.
14573 	 */
14574 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14575 	switch (first_mp->b_datap->db_type) {
14576 	case M_PROTO:
14577 	case M_PCPROTO:
14578 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14579 		    DL_UNITDATA_IND) {
14580 			/* Go handle anything other than data elsewhere. */
14581 			ip_rput_dlpi(q, mp);
14582 			return (B_TRUE);
14583 		}
14584 
14585 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14586 		/* Ditch the DLPI header. */
14587 		mp1 = mp->b_cont;
14588 		ASSERT(first_mp == mp);
14589 		*first_mpp = mp1;
14590 		freeb(mp);
14591 		*mpp = mp1;
14592 		return (B_FALSE);
14593 	case M_IOCACK:
14594 		ip1dbg(("got iocack "));
14595 		iocp = (struct iocblk *)mp->b_rptr;
14596 		switch (iocp->ioc_cmd) {
14597 		case DL_IOC_HDR_INFO:
14598 			ill = (ill_t *)q->q_ptr;
14599 			ill_fastpath_ack(ill, mp);
14600 			return (B_TRUE);
14601 		default:
14602 			putnext(q, mp);
14603 			return (B_TRUE);
14604 		}
14605 		/* FALLTHRU */
14606 	case M_ERROR:
14607 	case M_HANGUP:
14608 		/*
14609 		 * Since this is on the ill stream we unconditionally
14610 		 * bump up the refcount
14611 		 */
14612 		ill_refhold(ill);
14613 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14614 		return (B_TRUE);
14615 	case M_CTL:
14616 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14617 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14618 		    IPHADA_M_CTL)) {
14619 			/*
14620 			 * It's an IPsec accelerated packet.
14621 			 * Make sure that the ill from which we received the
14622 			 * packet has enabled IPsec hardware acceleration.
14623 			 */
14624 			if (!(ill->ill_capabilities &
14625 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14626 				/* IPsec kstats: bean counter */
14627 				freemsg(mp);
14628 				return (B_TRUE);
14629 			}
14630 
14631 			/*
14632 			 * Make mp point to the mblk following the M_CTL,
14633 			 * then process according to type of mp.
14634 			 * After this processing, first_mp will point to
14635 			 * the data-attributes and mp to the pkt following
14636 			 * the M_CTL.
14637 			 */
14638 			mp = first_mp->b_cont;
14639 			if (mp == NULL) {
14640 				freemsg(first_mp);
14641 				return (B_TRUE);
14642 			}
14643 			/*
14644 			 * A Hardware Accelerated packet can only be M_DATA
14645 			 * ESP or AH packet.
14646 			 */
14647 			if (mp->b_datap->db_type != M_DATA) {
14648 				/* non-M_DATA IPsec accelerated packet */
14649 				IPSECHW_DEBUG(IPSECHW_PKT,
14650 				    ("non-M_DATA IPsec accelerated pkt\n"));
14651 				freemsg(first_mp);
14652 				return (B_TRUE);
14653 			}
14654 			ipha = (ipha_t *)mp->b_rptr;
14655 			if (ipha->ipha_protocol != IPPROTO_AH &&
14656 			    ipha->ipha_protocol != IPPROTO_ESP) {
14657 				IPSECHW_DEBUG(IPSECHW_PKT,
14658 				    ("non-M_DATA IPsec accelerated pkt\n"));
14659 				freemsg(first_mp);
14660 				return (B_TRUE);
14661 			}
14662 			*mpp = mp;
14663 			return (B_FALSE);
14664 		}
14665 		putnext(q, mp);
14666 		return (B_TRUE);
14667 	case M_IOCNAK:
14668 		ip1dbg(("got iocnak "));
14669 		iocp = (struct iocblk *)mp->b_rptr;
14670 		switch (iocp->ioc_cmd) {
14671 		case DL_IOC_HDR_INFO:
14672 			ip_rput_other(NULL, q, mp, NULL);
14673 			return (B_TRUE);
14674 		default:
14675 			break;
14676 		}
14677 		/* FALLTHRU */
14678 	default:
14679 		putnext(q, mp);
14680 		return (B_TRUE);
14681 	}
14682 }
14683 
14684 /* Read side put procedure.  Packets coming from the wire arrive here. */
14685 void
14686 ip_rput(queue_t *q, mblk_t *mp)
14687 {
14688 	ill_t	*ill;
14689 	union DL_primitives *dl;
14690 
14691 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14692 
14693 	ill = (ill_t *)q->q_ptr;
14694 
14695 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14696 		/*
14697 		 * If things are opening or closing, only accept high-priority
14698 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14699 		 * created; on close, things hanging off the ill may have been
14700 		 * freed already.)
14701 		 */
14702 		dl = (union DL_primitives *)mp->b_rptr;
14703 		if (DB_TYPE(mp) != M_PCPROTO ||
14704 		    dl->dl_primitive == DL_UNITDATA_IND) {
14705 			inet_freemsg(mp);
14706 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14707 			    "ip_rput_end: q %p (%S)", q, "uninit");
14708 			return;
14709 		}
14710 	}
14711 
14712 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14713 	    "ip_rput_end: q %p (%S)", q, "end");
14714 
14715 	ip_input(ill, NULL, mp, NULL);
14716 }
14717 
14718 static mblk_t *
14719 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14720 {
14721 	mblk_t *mp1;
14722 	boolean_t adjusted = B_FALSE;
14723 	ip_stack_t *ipst = ill->ill_ipst;
14724 
14725 	IP_STAT(ipst, ip_db_ref);
14726 	/*
14727 	 * The IP_RECVSLLA option depends on having the
14728 	 * link layer header. First check that:
14729 	 * a> the underlying device is of type ether,
14730 	 * since this option is currently supported only
14731 	 * over ethernet.
14732 	 * b> there is enough room to copy over the link
14733 	 * layer header.
14734 	 *
14735 	 * Once the checks are done, adjust rptr so that
14736 	 * the link layer header will be copied via
14737 	 * copymsg. Note that, IFT_ETHER may be returned
14738 	 * by some non-ethernet drivers but in this case
14739 	 * the second check will fail.
14740 	 */
14741 	if (ill->ill_type == IFT_ETHER &&
14742 	    (mp->b_rptr - mp->b_datap->db_base) >=
14743 	    sizeof (struct ether_header)) {
14744 		mp->b_rptr -= sizeof (struct ether_header);
14745 		adjusted = B_TRUE;
14746 	}
14747 	mp1 = copymsg(mp);
14748 
14749 	if (mp1 == NULL) {
14750 		mp->b_next = NULL;
14751 		/* clear b_prev - used by ip_mroute_decap */
14752 		mp->b_prev = NULL;
14753 		freemsg(mp);
14754 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14755 		return (NULL);
14756 	}
14757 
14758 	if (adjusted) {
14759 		/*
14760 		 * Copy is done. Restore the pointer in
14761 		 * the _new_ mblk
14762 		 */
14763 		mp1->b_rptr += sizeof (struct ether_header);
14764 	}
14765 
14766 	/* Copy b_prev - used by ip_mroute_decap */
14767 	mp1->b_prev = mp->b_prev;
14768 	mp->b_prev = NULL;
14769 
14770 	/* preserve the hardware checksum flags and data, if present */
14771 	if (DB_CKSUMFLAGS(mp) != 0) {
14772 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14773 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14774 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14775 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14776 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14777 	}
14778 
14779 	freemsg(mp);
14780 	return (mp1);
14781 }
14782 
14783 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14784 	if (tail != NULL)					\
14785 		tail->b_next = mp;				\
14786 	else							\
14787 		head = mp;					\
14788 	tail = mp;						\
14789 	cnt++;							\
14790 }
14791 
14792 /*
14793  * Direct read side procedure capable of dealing with chains. GLDv3 based
14794  * drivers call this function directly with mblk chains while STREAMS
14795  * read side procedure ip_rput() calls this for single packet with ip_ring
14796  * set to NULL to process one packet at a time.
14797  *
14798  * The ill will always be valid if this function is called directly from
14799  * the driver.
14800  *
14801  * If ip_input() is called from GLDv3:
14802  *
14803  *   - This must be a non-VLAN IP stream.
14804  *   - 'mp' is either an untagged or a special priority-tagged packet.
14805  *   - Any VLAN tag that was in the MAC header has been stripped.
14806  *
14807  * If the IP header in packet is not 32-bit aligned, every message in the
14808  * chain will be aligned before further operations. This is required on SPARC
14809  * platform.
14810  */
14811 /* ARGSUSED */
14812 void
14813 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14814     struct mac_header_info_s *mhip)
14815 {
14816 	ipaddr_t		dst = NULL;
14817 	ipaddr_t		prev_dst;
14818 	ire_t			*ire = NULL;
14819 	ipha_t			*ipha;
14820 	uint_t			pkt_len;
14821 	ssize_t			len;
14822 	uint_t			opt_len;
14823 	int			ll_multicast;
14824 	int			cgtp_flt_pkt;
14825 	queue_t			*q = ill->ill_rq;
14826 	squeue_t		*curr_sqp = NULL;
14827 	mblk_t 			*head = NULL;
14828 	mblk_t			*tail = NULL;
14829 	mblk_t			*first_mp;
14830 	int			cnt = 0;
14831 	ip_stack_t		*ipst = ill->ill_ipst;
14832 	mblk_t			*mp;
14833 	mblk_t			*dmp;
14834 	uint8_t			tag;
14835 
14836 	ASSERT(mp_chain != NULL);
14837 	ASSERT(ill != NULL);
14838 
14839 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14840 
14841 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14842 
14843 #define	rptr	((uchar_t *)ipha)
14844 
14845 	while (mp_chain != NULL) {
14846 		mp = mp_chain;
14847 		mp_chain = mp_chain->b_next;
14848 		mp->b_next = NULL;
14849 		ll_multicast = 0;
14850 
14851 		/*
14852 		 * We do ire caching from one iteration to
14853 		 * another. In the event the packet chain contains
14854 		 * all packets from the same dst, this caching saves
14855 		 * an ire_cache_lookup for each of the succeeding
14856 		 * packets in a packet chain.
14857 		 */
14858 		prev_dst = dst;
14859 
14860 		/*
14861 		 * if db_ref > 1 then copymsg and free original. Packet
14862 		 * may be changed and we do not want the other entity
14863 		 * who has a reference to this message to trip over the
14864 		 * changes. This is a blind change because trying to
14865 		 * catch all places that might change the packet is too
14866 		 * difficult.
14867 		 *
14868 		 * This corresponds to the fast path case, where we have
14869 		 * a chain of M_DATA mblks.  We check the db_ref count
14870 		 * of only the 1st data block in the mblk chain. There
14871 		 * doesn't seem to be a reason why a device driver would
14872 		 * send up data with varying db_ref counts in the mblk
14873 		 * chain. In any case the Fast path is a private
14874 		 * interface, and our drivers don't do such a thing.
14875 		 * Given the above assumption, there is no need to walk
14876 		 * down the entire mblk chain (which could have a
14877 		 * potential performance problem)
14878 		 *
14879 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14880 		 * to here because of exclusive ip stacks and vnics.
14881 		 * Packets transmitted from exclusive stack over vnic
14882 		 * can have db_ref > 1 and when it gets looped back to
14883 		 * another vnic in a different zone, you have ip_input()
14884 		 * getting dblks with db_ref > 1. So if someone
14885 		 * complains of TCP performance under this scenario,
14886 		 * take a serious look here on the impact of copymsg().
14887 		 */
14888 
14889 		if (DB_REF(mp) > 1) {
14890 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14891 				continue;
14892 		}
14893 
14894 		/*
14895 		 * Check and align the IP header.
14896 		 */
14897 		first_mp = mp;
14898 		if (DB_TYPE(mp) == M_DATA) {
14899 			dmp = mp;
14900 		} else if (DB_TYPE(mp) == M_PROTO &&
14901 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14902 			dmp = mp->b_cont;
14903 		} else {
14904 			dmp = NULL;
14905 		}
14906 		if (dmp != NULL) {
14907 			/*
14908 			 * IP header ptr not aligned?
14909 			 * OR IP header not complete in first mblk
14910 			 */
14911 			if (!OK_32PTR(dmp->b_rptr) ||
14912 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14913 				if (!ip_check_and_align_header(q, dmp, ipst))
14914 					continue;
14915 			}
14916 		}
14917 
14918 		/*
14919 		 * ip_input fast path
14920 		 */
14921 
14922 		/* mblk type is not M_DATA */
14923 		if (DB_TYPE(mp) != M_DATA) {
14924 			if (ip_rput_process_notdata(q, &first_mp, ill,
14925 			    &ll_multicast, &mp))
14926 				continue;
14927 
14928 			/*
14929 			 * The only way we can get here is if we had a
14930 			 * packet that was either a DL_UNITDATA_IND or
14931 			 * an M_CTL for an IPsec accelerated packet.
14932 			 *
14933 			 * In either case, the first_mp will point to
14934 			 * the leading M_PROTO or M_CTL.
14935 			 */
14936 			ASSERT(first_mp != NULL);
14937 		} else if (mhip != NULL) {
14938 			/*
14939 			 * ll_multicast is set here so that it is ready
14940 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14941 			 * manipulates ll_multicast in the same fashion when
14942 			 * called from ip_rput_process_notdata.
14943 			 */
14944 			switch (mhip->mhi_dsttype) {
14945 			case MAC_ADDRTYPE_MULTICAST :
14946 				ll_multicast = HPE_MULTICAST;
14947 				break;
14948 			case MAC_ADDRTYPE_BROADCAST :
14949 				ll_multicast = HPE_BROADCAST;
14950 				break;
14951 			default :
14952 				break;
14953 			}
14954 		}
14955 
14956 		/* Only M_DATA can come here and it is always aligned */
14957 		ASSERT(DB_TYPE(mp) == M_DATA);
14958 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14959 
14960 		ipha = (ipha_t *)mp->b_rptr;
14961 		len = mp->b_wptr - rptr;
14962 		pkt_len = ntohs(ipha->ipha_length);
14963 
14964 		/*
14965 		 * We must count all incoming packets, even if they end
14966 		 * up being dropped later on.
14967 		 */
14968 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14969 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14970 
14971 		/* multiple mblk or too short */
14972 		len -= pkt_len;
14973 		if (len != 0) {
14974 			/*
14975 			 * Make sure we have data length consistent
14976 			 * with the IP header.
14977 			 */
14978 			if (mp->b_cont == NULL) {
14979 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14980 					BUMP_MIB(ill->ill_ip_mib,
14981 					    ipIfStatsInHdrErrors);
14982 					ip2dbg(("ip_input: drop pkt\n"));
14983 					freemsg(mp);
14984 					continue;
14985 				}
14986 				mp->b_wptr = rptr + pkt_len;
14987 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14988 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14989 					BUMP_MIB(ill->ill_ip_mib,
14990 					    ipIfStatsInHdrErrors);
14991 					ip2dbg(("ip_input: drop pkt\n"));
14992 					freemsg(mp);
14993 					continue;
14994 				}
14995 				(void) adjmsg(mp, -len);
14996 				/*
14997 				 * adjmsg may have freed an mblk from the chain,
14998 				 * hence invalidate any hw checksum here. This
14999 				 * will force IP to calculate the checksum in
15000 				 * sw, but only for this packet.
15001 				 */
15002 				DB_CKSUMFLAGS(mp) = 0;
15003 				IP_STAT(ipst, ip_multimblk3);
15004 			}
15005 		}
15006 
15007 		/* Obtain the dst of the current packet */
15008 		dst = ipha->ipha_dst;
15009 
15010 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15011 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15012 		    ipha, ip6_t *, NULL, int, 0);
15013 
15014 		/*
15015 		 * The following test for loopback is faster than
15016 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15017 		 * operations.
15018 		 * Note that these addresses are always in network byte order
15019 		 */
15020 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15021 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15022 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15023 			freemsg(mp);
15024 			continue;
15025 		}
15026 
15027 		/*
15028 		 * The event for packets being received from a 'physical'
15029 		 * interface is placed after validation of the source and/or
15030 		 * destination address as being local so that packets can be
15031 		 * redirected to loopback addresses using ipnat.
15032 		 */
15033 		DTRACE_PROBE4(ip4__physical__in__start,
15034 		    ill_t *, ill, ill_t *, NULL,
15035 		    ipha_t *, ipha, mblk_t *, first_mp);
15036 
15037 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15038 		    ipst->ips_ipv4firewall_physical_in,
15039 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15040 
15041 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15042 
15043 		if (first_mp == NULL) {
15044 			continue;
15045 		}
15046 		dst = ipha->ipha_dst;
15047 		/*
15048 		 * Attach any necessary label information to
15049 		 * this packet
15050 		 */
15051 		if (is_system_labeled() &&
15052 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15053 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15054 			freemsg(mp);
15055 			continue;
15056 		}
15057 
15058 		if (ipst->ips_ip4_observe.he_interested) {
15059 			zoneid_t dzone;
15060 
15061 			/*
15062 			 * On the inbound path the src zone will be unknown as
15063 			 * this packet has come from the wire.
15064 			 */
15065 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15066 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15067 			    ill, ipst);
15068 		}
15069 
15070 		/*
15071 		 * Reuse the cached ire only if the ipha_dst of the previous
15072 		 * packet is the same as the current packet AND it is not
15073 		 * INADDR_ANY.
15074 		 */
15075 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15076 		    (ire != NULL)) {
15077 			ire_refrele(ire);
15078 			ire = NULL;
15079 		}
15080 
15081 		opt_len = ipha->ipha_version_and_hdr_length -
15082 		    IP_SIMPLE_HDR_VERSION;
15083 
15084 		/*
15085 		 * Check to see if we can take the fastpath.
15086 		 * That is possible if the following conditions are met
15087 		 *	o Tsol disabled
15088 		 *	o CGTP disabled
15089 		 *	o ipp_action_count is 0
15090 		 *	o no options in the packet
15091 		 *	o not a RSVP packet
15092 		 * 	o not a multicast packet
15093 		 *	o ill not in IP_DHCPINIT_IF mode
15094 		 */
15095 		if (!is_system_labeled() &&
15096 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15097 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15098 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15099 			if (ire == NULL)
15100 				ire = ire_cache_lookup_simple(dst, ipst);
15101 			/*
15102 			 * Unless forwarding is enabled, dont call
15103 			 * ip_fast_forward(). Incoming packet is for forwarding
15104 			 */
15105 			if ((ill->ill_flags & ILLF_ROUTER) &&
15106 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15107 				ire = ip_fast_forward(ire, dst, ill, mp);
15108 				continue;
15109 			}
15110 			/* incoming packet is for local consumption */
15111 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15112 				goto local;
15113 		}
15114 
15115 		/*
15116 		 * Disable ire caching for anything more complex
15117 		 * than the simple fast path case we checked for above.
15118 		 */
15119 		if (ire != NULL) {
15120 			ire_refrele(ire);
15121 			ire = NULL;
15122 		}
15123 
15124 		/*
15125 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15126 		 * server to unicast DHCP packets to a DHCP client using the
15127 		 * IP address it is offering to the client.  This can be
15128 		 * disabled through the "broadcast bit", but not all DHCP
15129 		 * servers honor that bit.  Therefore, to interoperate with as
15130 		 * many DHCP servers as possible, the DHCP client allows the
15131 		 * server to unicast, but we treat those packets as broadcast
15132 		 * here.  Note that we don't rewrite the packet itself since
15133 		 * (a) that would mess up the checksums and (b) the DHCP
15134 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15135 		 * hand it the packet regardless.
15136 		 */
15137 		if (ill->ill_dhcpinit != 0 &&
15138 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15139 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15140 			udpha_t *udpha;
15141 
15142 			/*
15143 			 * Reload ipha since pullupmsg() can change b_rptr.
15144 			 */
15145 			ipha = (ipha_t *)mp->b_rptr;
15146 			udpha = (udpha_t *)&ipha[1];
15147 
15148 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15149 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15150 				    mblk_t *, mp);
15151 				dst = INADDR_BROADCAST;
15152 			}
15153 		}
15154 
15155 		/* Full-blown slow path */
15156 		if (opt_len != 0) {
15157 			if (len != 0)
15158 				IP_STAT(ipst, ip_multimblk4);
15159 			else
15160 				IP_STAT(ipst, ip_ipoptions);
15161 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15162 			    &dst, ipst))
15163 				continue;
15164 		}
15165 
15166 		/*
15167 		 * Invoke the CGTP (multirouting) filtering module to process
15168 		 * the incoming packet. Packets identified as duplicates
15169 		 * must be discarded. Filtering is active only if the
15170 		 * the ip_cgtp_filter ndd variable is non-zero.
15171 		 */
15172 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15173 		if (ipst->ips_ip_cgtp_filter &&
15174 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15175 			netstackid_t stackid;
15176 
15177 			stackid = ipst->ips_netstack->netstack_stackid;
15178 			cgtp_flt_pkt =
15179 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15180 			    ill->ill_phyint->phyint_ifindex, mp);
15181 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15182 				freemsg(first_mp);
15183 				continue;
15184 			}
15185 		}
15186 
15187 		/*
15188 		 * If rsvpd is running, let RSVP daemon handle its processing
15189 		 * and forwarding of RSVP multicast/unicast packets.
15190 		 * If rsvpd is not running but mrouted is running, RSVP
15191 		 * multicast packets are forwarded as multicast traffic
15192 		 * and RSVP unicast packets are forwarded by unicast router.
15193 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15194 		 * packets are not forwarded, but the unicast packets are
15195 		 * forwarded like unicast traffic.
15196 		 */
15197 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15198 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15199 		    NULL) {
15200 			/* RSVP packet and rsvpd running. Treat as ours */
15201 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15202 			/*
15203 			 * This assumes that we deliver to all streams for
15204 			 * multicast and broadcast packets.
15205 			 * We have to force ll_multicast to 1 to handle the
15206 			 * M_DATA messages passed in from ip_mroute_decap.
15207 			 */
15208 			dst = INADDR_BROADCAST;
15209 			ll_multicast = 1;
15210 		} else if (CLASSD(dst)) {
15211 			/* packet is multicast */
15212 			mp->b_next = NULL;
15213 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15214 			    &ll_multicast, &dst))
15215 				continue;
15216 		}
15217 
15218 		if (ire == NULL) {
15219 			ire = ire_cache_lookup(dst, ALL_ZONES,
15220 			    msg_getlabel(mp), ipst);
15221 		}
15222 
15223 		if (ire != NULL && ire->ire_stq != NULL &&
15224 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15225 		    ire->ire_zoneid != ALL_ZONES) {
15226 			/*
15227 			 * Should only use IREs that are visible from the
15228 			 * global zone for forwarding.
15229 			 */
15230 			ire_refrele(ire);
15231 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15232 			    msg_getlabel(mp), ipst);
15233 		}
15234 
15235 		if (ire == NULL) {
15236 			/*
15237 			 * No IRE for this destination, so it can't be for us.
15238 			 * Unless we are forwarding, drop the packet.
15239 			 * We have to let source routed packets through
15240 			 * since we don't yet know if they are 'ping -l'
15241 			 * packets i.e. if they will go out over the
15242 			 * same interface as they came in on.
15243 			 */
15244 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15245 			if (ire == NULL)
15246 				continue;
15247 		}
15248 
15249 		/*
15250 		 * Broadcast IRE may indicate either broadcast or
15251 		 * multicast packet
15252 		 */
15253 		if (ire->ire_type == IRE_BROADCAST) {
15254 			/*
15255 			 * Skip broadcast checks if packet is UDP multicast;
15256 			 * we'd rather not enter ip_rput_process_broadcast()
15257 			 * unless the packet is broadcast for real, since
15258 			 * that routine is a no-op for multicast.
15259 			 */
15260 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15261 			    !CLASSD(ipha->ipha_dst)) {
15262 				ire = ip_rput_process_broadcast(&q, mp,
15263 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15264 				    ll_multicast);
15265 				if (ire == NULL)
15266 					continue;
15267 			}
15268 		} else if (ire->ire_stq != NULL) {
15269 			/* fowarding? */
15270 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15271 			    ll_multicast, B_FALSE);
15272 			/* ip_rput_process_forward consumed the packet */
15273 			continue;
15274 		}
15275 
15276 local:
15277 		/*
15278 		 * If the queue in the ire is different to the ingress queue
15279 		 * then we need to check to see if we can accept the packet.
15280 		 * Note that for multicast packets and broadcast packets sent
15281 		 * to a broadcast address which is shared between multiple
15282 		 * interfaces we should not do this since we just got a random
15283 		 * broadcast ire.
15284 		 */
15285 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15286 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15287 			if (ire == NULL) {
15288 				/* Drop packet */
15289 				BUMP_MIB(ill->ill_ip_mib,
15290 				    ipIfStatsForwProhibits);
15291 				freemsg(mp);
15292 				continue;
15293 			}
15294 			if (ire->ire_rfq != NULL)
15295 				q = ire->ire_rfq;
15296 		}
15297 
15298 		switch (ipha->ipha_protocol) {
15299 		case IPPROTO_TCP:
15300 			ASSERT(first_mp == mp);
15301 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15302 			    mp, 0, q, ip_ring)) != NULL) {
15303 				if (curr_sqp == NULL) {
15304 					curr_sqp = GET_SQUEUE(mp);
15305 					ASSERT(cnt == 0);
15306 					cnt++;
15307 					head = tail = mp;
15308 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15309 					ASSERT(tail != NULL);
15310 					cnt++;
15311 					tail->b_next = mp;
15312 					tail = mp;
15313 				} else {
15314 					/*
15315 					 * A different squeue. Send the
15316 					 * chain for the previous squeue on
15317 					 * its way. This shouldn't happen
15318 					 * often unless interrupt binding
15319 					 * changes.
15320 					 */
15321 					IP_STAT(ipst, ip_input_multi_squeue);
15322 					SQUEUE_ENTER(curr_sqp, head,
15323 					    tail, cnt, SQ_PROCESS, tag);
15324 					curr_sqp = GET_SQUEUE(mp);
15325 					head = mp;
15326 					tail = mp;
15327 					cnt = 1;
15328 				}
15329 			}
15330 			continue;
15331 		case IPPROTO_UDP:
15332 			ASSERT(first_mp == mp);
15333 			ip_udp_input(q, mp, ipha, ire, ill);
15334 			continue;
15335 		case IPPROTO_SCTP:
15336 			ASSERT(first_mp == mp);
15337 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15338 			    q, dst);
15339 			/* ire has been released by ip_sctp_input */
15340 			ire = NULL;
15341 			continue;
15342 		case IPPROTO_ENCAP:
15343 		case IPPROTO_IPV6:
15344 			ASSERT(first_mp == mp);
15345 			if (ip_iptun_input(NULL, mp, ipha, ill, ire, ipst))
15346 				break;
15347 			/*
15348 			 * If there was no IP tunnel data-link bound to
15349 			 * receive this packet, then we fall through to
15350 			 * allow potential raw sockets bound to either of
15351 			 * these protocols to pick it up.
15352 			 */
15353 		default:
15354 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15355 			continue;
15356 		}
15357 	}
15358 
15359 	if (ire != NULL)
15360 		ire_refrele(ire);
15361 
15362 	if (head != NULL)
15363 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15364 
15365 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15366 	    "ip_input_end: q %p (%S)", q, "end");
15367 #undef  rptr
15368 }
15369 
15370 /*
15371  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15372  * a chain of packets in the poll mode. The packets have gone through the
15373  * data link processing but not IP processing. For performance and latency
15374  * reasons, the squeue wants to process the chain in line instead of feeding
15375  * it back via ip_input path.
15376  *
15377  * So this is a light weight function which checks to see if the packets
15378  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15379  * but we still do the paranoid check) meant for local machine and we don't
15380  * have labels etc enabled. Packets that meet the criterion are returned to
15381  * the squeue and processed inline while the rest go via ip_input path.
15382  */
15383 /*ARGSUSED*/
15384 mblk_t *
15385 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15386     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15387 {
15388 	mblk_t 		*mp;
15389 	ipaddr_t	dst = NULL;
15390 	ipaddr_t	prev_dst;
15391 	ire_t		*ire = NULL;
15392 	ipha_t		*ipha;
15393 	uint_t		pkt_len;
15394 	ssize_t		len;
15395 	uint_t		opt_len;
15396 	queue_t		*q = ill->ill_rq;
15397 	squeue_t	*curr_sqp;
15398 	mblk_t 		*ahead = NULL;	/* Accepted head */
15399 	mblk_t		*atail = NULL;	/* Accepted tail */
15400 	uint_t		acnt = 0;	/* Accepted count */
15401 	mblk_t		*utail = NULL;	/* Unaccepted head */
15402 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15403 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15404 	ip_stack_t	*ipst = ill->ill_ipst;
15405 
15406 	*cnt = 0;
15407 
15408 	ASSERT(ill != NULL);
15409 	ASSERT(ip_ring != NULL);
15410 
15411 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15412 
15413 #define	rptr	((uchar_t *)ipha)
15414 
15415 	while (mp_chain != NULL) {
15416 		mp = mp_chain;
15417 		mp_chain = mp_chain->b_next;
15418 		mp->b_next = NULL;
15419 
15420 		/*
15421 		 * We do ire caching from one iteration to
15422 		 * another. In the event the packet chain contains
15423 		 * all packets from the same dst, this caching saves
15424 		 * an ire_cache_lookup for each of the succeeding
15425 		 * packets in a packet chain.
15426 		 */
15427 		prev_dst = dst;
15428 
15429 		ipha = (ipha_t *)mp->b_rptr;
15430 		len = mp->b_wptr - rptr;
15431 
15432 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15433 
15434 		/*
15435 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15436 		 * or doesn't have min len, reject.
15437 		 */
15438 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15439 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15440 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15441 			continue;
15442 		}
15443 
15444 		pkt_len = ntohs(ipha->ipha_length);
15445 		if (len != pkt_len) {
15446 			if (len > pkt_len) {
15447 				mp->b_wptr = rptr + pkt_len;
15448 			} else {
15449 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15450 				continue;
15451 			}
15452 		}
15453 
15454 		opt_len = ipha->ipha_version_and_hdr_length -
15455 		    IP_SIMPLE_HDR_VERSION;
15456 		dst = ipha->ipha_dst;
15457 
15458 		/* IP version bad or there are IP options */
15459 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15460 		    mp, &ipha, &dst, ipst)))
15461 			continue;
15462 
15463 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15464 		    (ipst->ips_ip_cgtp_filter &&
15465 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15466 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15467 			continue;
15468 		}
15469 
15470 		/*
15471 		 * Reuse the cached ire only if the ipha_dst of the previous
15472 		 * packet is the same as the current packet AND it is not
15473 		 * INADDR_ANY.
15474 		 */
15475 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15476 		    (ire != NULL)) {
15477 			ire_refrele(ire);
15478 			ire = NULL;
15479 		}
15480 
15481 		if (ire == NULL)
15482 			ire = ire_cache_lookup_simple(dst, ipst);
15483 
15484 		/*
15485 		 * Unless forwarding is enabled, dont call
15486 		 * ip_fast_forward(). Incoming packet is for forwarding
15487 		 */
15488 		if ((ill->ill_flags & ILLF_ROUTER) &&
15489 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15490 
15491 			DTRACE_PROBE4(ip4__physical__in__start,
15492 			    ill_t *, ill, ill_t *, NULL,
15493 			    ipha_t *, ipha, mblk_t *, mp);
15494 
15495 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15496 			    ipst->ips_ipv4firewall_physical_in,
15497 			    ill, NULL, ipha, mp, mp, 0, ipst);
15498 
15499 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15500 
15501 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15502 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15503 			    pkt_len);
15504 
15505 			if (mp != NULL)
15506 				ire = ip_fast_forward(ire, dst, ill, mp);
15507 			continue;
15508 		}
15509 
15510 		/* incoming packet is for local consumption */
15511 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15512 			goto local_accept;
15513 
15514 		/*
15515 		 * Disable ire caching for anything more complex
15516 		 * than the simple fast path case we checked for above.
15517 		 */
15518 		if (ire != NULL) {
15519 			ire_refrele(ire);
15520 			ire = NULL;
15521 		}
15522 
15523 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15524 		    ipst);
15525 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15526 		    ire->ire_stq != NULL) {
15527 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15528 			if (ire != NULL) {
15529 				ire_refrele(ire);
15530 				ire = NULL;
15531 			}
15532 			continue;
15533 		}
15534 
15535 local_accept:
15536 
15537 		if (ire->ire_rfq != q) {
15538 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15539 			if (ire != NULL) {
15540 				ire_refrele(ire);
15541 				ire = NULL;
15542 			}
15543 			continue;
15544 		}
15545 
15546 		/*
15547 		 * The event for packets being received from a 'physical'
15548 		 * interface is placed after validation of the source and/or
15549 		 * destination address as being local so that packets can be
15550 		 * redirected to loopback addresses using ipnat.
15551 		 */
15552 		DTRACE_PROBE4(ip4__physical__in__start,
15553 		    ill_t *, ill, ill_t *, NULL,
15554 		    ipha_t *, ipha, mblk_t *, mp);
15555 
15556 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15557 		    ipst->ips_ipv4firewall_physical_in,
15558 		    ill, NULL, ipha, mp, mp, 0, ipst);
15559 
15560 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15561 
15562 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15563 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15564 
15565 		if (mp != NULL &&
15566 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15567 		    0, q, ip_ring)) != NULL) {
15568 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15569 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15570 			} else {
15571 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15572 				    SQ_FILL, SQTAG_IP_INPUT);
15573 			}
15574 		}
15575 	}
15576 
15577 	if (ire != NULL)
15578 		ire_refrele(ire);
15579 
15580 	if (uhead != NULL)
15581 		ip_input(ill, ip_ring, uhead, NULL);
15582 
15583 	if (ahead != NULL) {
15584 		*last = atail;
15585 		*cnt = acnt;
15586 		return (ahead);
15587 	}
15588 
15589 	return (NULL);
15590 #undef  rptr
15591 }
15592 
15593 static void
15594 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15595     t_uscalar_t err)
15596 {
15597 	if (dl_err == DL_SYSERR) {
15598 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15599 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15600 		    ill->ill_name, dl_primstr(prim), err);
15601 		return;
15602 	}
15603 
15604 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15605 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15606 	    dl_errstr(dl_err));
15607 }
15608 
15609 /*
15610  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15611  * than DL_UNITDATA_IND messages. If we need to process this message
15612  * exclusively, we call qwriter_ip, in which case we also need to call
15613  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15614  */
15615 void
15616 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15617 {
15618 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15619 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15620 	ill_t		*ill = q->q_ptr;
15621 	t_uscalar_t	prim = dloa->dl_primitive;
15622 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15623 
15624 	ip1dbg(("ip_rput_dlpi"));
15625 
15626 	/*
15627 	 * If we received an ACK but didn't send a request for it, then it
15628 	 * can't be part of any pending operation; discard up-front.
15629 	 */
15630 	switch (prim) {
15631 	case DL_ERROR_ACK:
15632 		reqprim = dlea->dl_error_primitive;
15633 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15634 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15635 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15636 		    dlea->dl_unix_errno));
15637 		break;
15638 	case DL_OK_ACK:
15639 		reqprim = dloa->dl_correct_primitive;
15640 		break;
15641 	case DL_INFO_ACK:
15642 		reqprim = DL_INFO_REQ;
15643 		break;
15644 	case DL_BIND_ACK:
15645 		reqprim = DL_BIND_REQ;
15646 		break;
15647 	case DL_PHYS_ADDR_ACK:
15648 		reqprim = DL_PHYS_ADDR_REQ;
15649 		break;
15650 	case DL_NOTIFY_ACK:
15651 		reqprim = DL_NOTIFY_REQ;
15652 		break;
15653 	case DL_CONTROL_ACK:
15654 		reqprim = DL_CONTROL_REQ;
15655 		break;
15656 	case DL_CAPABILITY_ACK:
15657 		reqprim = DL_CAPABILITY_REQ;
15658 		break;
15659 	}
15660 
15661 	if (prim != DL_NOTIFY_IND) {
15662 		if (reqprim == DL_PRIM_INVAL ||
15663 		    !ill_dlpi_pending(ill, reqprim)) {
15664 			/* Not a DLPI message we support or expected */
15665 			freemsg(mp);
15666 			return;
15667 		}
15668 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15669 		    dl_primstr(reqprim)));
15670 	}
15671 
15672 	switch (reqprim) {
15673 	case DL_UNBIND_REQ:
15674 		/*
15675 		 * NOTE: we mark the unbind as complete even if we got a
15676 		 * DL_ERROR_ACK, since there's not much else we can do.
15677 		 */
15678 		mutex_enter(&ill->ill_lock);
15679 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15680 		cv_signal(&ill->ill_cv);
15681 		mutex_exit(&ill->ill_lock);
15682 		break;
15683 
15684 	case DL_ENABMULTI_REQ:
15685 		if (prim == DL_OK_ACK) {
15686 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15687 				ill->ill_dlpi_multicast_state = IDS_OK;
15688 		}
15689 		break;
15690 	}
15691 
15692 	/*
15693 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15694 	 * need to become writer to continue to process it.  Because an
15695 	 * exclusive operation doesn't complete until replies to all queued
15696 	 * DLPI messages have been received, we know we're in the middle of an
15697 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15698 	 *
15699 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15700 	 * Since this is on the ill stream we unconditionally bump up the
15701 	 * refcount without doing ILL_CAN_LOOKUP().
15702 	 */
15703 	ill_refhold(ill);
15704 	if (prim == DL_NOTIFY_IND)
15705 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15706 	else
15707 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15708 }
15709 
15710 /*
15711  * Handling of DLPI messages that require exclusive access to the ipsq.
15712  *
15713  * Need to do ill_pending_mp_release on ioctl completion, which could
15714  * happen here. (along with mi_copy_done)
15715  */
15716 /* ARGSUSED */
15717 static void
15718 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15719 {
15720 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15721 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15722 	int		err = 0;
15723 	ill_t		*ill;
15724 	ipif_t		*ipif = NULL;
15725 	mblk_t		*mp1 = NULL;
15726 	conn_t		*connp = NULL;
15727 	t_uscalar_t	paddrreq;
15728 	mblk_t		*mp_hw;
15729 	boolean_t	success;
15730 	boolean_t	ioctl_aborted = B_FALSE;
15731 	boolean_t	log = B_TRUE;
15732 	ip_stack_t		*ipst;
15733 
15734 	ip1dbg(("ip_rput_dlpi_writer .."));
15735 	ill = (ill_t *)q->q_ptr;
15736 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15737 	ASSERT(IAM_WRITER_ILL(ill));
15738 
15739 	ipst = ill->ill_ipst;
15740 
15741 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15742 	/*
15743 	 * The current ioctl could have been aborted by the user and a new
15744 	 * ioctl to bring up another ill could have started. We could still
15745 	 * get a response from the driver later.
15746 	 */
15747 	if (ipif != NULL && ipif->ipif_ill != ill)
15748 		ioctl_aborted = B_TRUE;
15749 
15750 	switch (dloa->dl_primitive) {
15751 	case DL_ERROR_ACK:
15752 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15753 		    dl_primstr(dlea->dl_error_primitive)));
15754 
15755 		switch (dlea->dl_error_primitive) {
15756 		case DL_DISABMULTI_REQ:
15757 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15758 			break;
15759 		case DL_PROMISCON_REQ:
15760 		case DL_PROMISCOFF_REQ:
15761 		case DL_UNBIND_REQ:
15762 		case DL_ATTACH_REQ:
15763 		case DL_INFO_REQ:
15764 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15765 			break;
15766 		case DL_NOTIFY_REQ:
15767 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15768 			log = B_FALSE;
15769 			break;
15770 		case DL_PHYS_ADDR_REQ:
15771 			/*
15772 			 * For IPv6 only, there are two additional
15773 			 * phys_addr_req's sent to the driver to get the
15774 			 * IPv6 token and lla. This allows IP to acquire
15775 			 * the hardware address format for a given interface
15776 			 * without having built in knowledge of the hardware
15777 			 * address. ill_phys_addr_pend keeps track of the last
15778 			 * DL_PAR sent so we know which response we are
15779 			 * dealing with. ill_dlpi_done will update
15780 			 * ill_phys_addr_pend when it sends the next req.
15781 			 * We don't complete the IOCTL until all three DL_PARs
15782 			 * have been attempted, so set *_len to 0 and break.
15783 			 */
15784 			paddrreq = ill->ill_phys_addr_pend;
15785 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15786 			if (paddrreq == DL_IPV6_TOKEN) {
15787 				ill->ill_token_length = 0;
15788 				log = B_FALSE;
15789 				break;
15790 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15791 				ill->ill_nd_lla_len = 0;
15792 				log = B_FALSE;
15793 				break;
15794 			}
15795 			/*
15796 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15797 			 * We presumably have an IOCTL hanging out waiting
15798 			 * for completion. Find it and complete the IOCTL
15799 			 * with the error noted.
15800 			 * However, ill_dl_phys was called on an ill queue
15801 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15802 			 * set. But the ioctl is known to be pending on ill_wq.
15803 			 */
15804 			if (!ill->ill_ifname_pending)
15805 				break;
15806 			ill->ill_ifname_pending = 0;
15807 			if (!ioctl_aborted)
15808 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15809 			if (mp1 != NULL) {
15810 				/*
15811 				 * This operation (SIOCSLIFNAME) must have
15812 				 * happened on the ill. Assert there is no conn
15813 				 */
15814 				ASSERT(connp == NULL);
15815 				q = ill->ill_wq;
15816 			}
15817 			break;
15818 		case DL_BIND_REQ:
15819 			ill_dlpi_done(ill, DL_BIND_REQ);
15820 			if (ill->ill_ifname_pending)
15821 				break;
15822 			/*
15823 			 * Something went wrong with the bind.  We presumably
15824 			 * have an IOCTL hanging out waiting for completion.
15825 			 * Find it, take down the interface that was coming
15826 			 * up, and complete the IOCTL with the error noted.
15827 			 */
15828 			if (!ioctl_aborted)
15829 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15830 			if (mp1 != NULL) {
15831 				/*
15832 				 * This might be a result of a DL_NOTE_REPLUMB
15833 				 * notification. In that case, connp is NULL.
15834 				 */
15835 				if (connp != NULL)
15836 					q = CONNP_TO_WQ(connp);
15837 
15838 				(void) ipif_down(ipif, NULL, NULL);
15839 				/* error is set below the switch */
15840 			}
15841 			break;
15842 		case DL_ENABMULTI_REQ:
15843 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15844 
15845 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15846 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15847 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15848 				ipif_t *ipif;
15849 
15850 				printf("ip: joining multicasts failed (%d)"
15851 				    " on %s - will use link layer "
15852 				    "broadcasts for multicast\n",
15853 				    dlea->dl_errno, ill->ill_name);
15854 
15855 				/*
15856 				 * Set up the multicast mapping alone.
15857 				 * writer, so ok to access ill->ill_ipif
15858 				 * without any lock.
15859 				 */
15860 				ipif = ill->ill_ipif;
15861 				mutex_enter(&ill->ill_phyint->phyint_lock);
15862 				ill->ill_phyint->phyint_flags |=
15863 				    PHYI_MULTI_BCAST;
15864 				mutex_exit(&ill->ill_phyint->phyint_lock);
15865 
15866 				if (!ill->ill_isv6) {
15867 					(void) ipif_arp_setup_multicast(ipif,
15868 					    NULL);
15869 				} else {
15870 					(void) ipif_ndp_setup_multicast(ipif,
15871 					    NULL);
15872 				}
15873 			}
15874 			freemsg(mp);	/* Don't want to pass this up */
15875 			return;
15876 		case DL_CONTROL_REQ:
15877 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15878 			    "DL_CONTROL_REQ\n"));
15879 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15880 			freemsg(mp);
15881 			return;
15882 		case DL_CAPABILITY_REQ:
15883 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15884 			    "DL_CAPABILITY REQ\n"));
15885 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15886 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15887 			ill_capability_done(ill);
15888 			freemsg(mp);
15889 			return;
15890 		}
15891 		/*
15892 		 * Note the error for IOCTL completion (mp1 is set when
15893 		 * ready to complete ioctl). If ill_ifname_pending_err is
15894 		 * set, an error occured during plumbing (ill_ifname_pending),
15895 		 * so we want to report that error.
15896 		 *
15897 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15898 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15899 		 * expected to get errack'd if the driver doesn't support
15900 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15901 		 * if these error conditions are encountered.
15902 		 */
15903 		if (mp1 != NULL) {
15904 			if (ill->ill_ifname_pending_err != 0)  {
15905 				err = ill->ill_ifname_pending_err;
15906 				ill->ill_ifname_pending_err = 0;
15907 			} else {
15908 				err = dlea->dl_unix_errno ?
15909 				    dlea->dl_unix_errno : ENXIO;
15910 			}
15911 		/*
15912 		 * If we're plumbing an interface and an error hasn't already
15913 		 * been saved, set ill_ifname_pending_err to the error passed
15914 		 * up. Ignore the error if log is B_FALSE (see comment above).
15915 		 */
15916 		} else if (log && ill->ill_ifname_pending &&
15917 		    ill->ill_ifname_pending_err == 0) {
15918 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15919 			    dlea->dl_unix_errno : ENXIO;
15920 		}
15921 
15922 		if (log)
15923 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15924 			    dlea->dl_errno, dlea->dl_unix_errno);
15925 		break;
15926 	case DL_CAPABILITY_ACK:
15927 		ill_capability_ack(ill, mp);
15928 		/*
15929 		 * The message has been handed off to ill_capability_ack
15930 		 * and must not be freed below
15931 		 */
15932 		mp = NULL;
15933 		break;
15934 
15935 	case DL_CONTROL_ACK:
15936 		/* We treat all of these as "fire and forget" */
15937 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15938 		break;
15939 	case DL_INFO_ACK:
15940 		/* Call a routine to handle this one. */
15941 		ill_dlpi_done(ill, DL_INFO_REQ);
15942 		ip_ll_subnet_defaults(ill, mp);
15943 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15944 		return;
15945 	case DL_BIND_ACK:
15946 		/*
15947 		 * We should have an IOCTL waiting on this unless
15948 		 * sent by ill_dl_phys, in which case just return
15949 		 */
15950 		ill_dlpi_done(ill, DL_BIND_REQ);
15951 		if (ill->ill_ifname_pending)
15952 			break;
15953 
15954 		if (!ioctl_aborted)
15955 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15956 		if (mp1 == NULL)
15957 			break;
15958 		/*
15959 		 * mp1 was added by ill_dl_up(). if that is a result of
15960 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
15961 		 */
15962 		if (connp != NULL)
15963 			q = CONNP_TO_WQ(connp);
15964 
15965 		/*
15966 		 * We are exclusive. So nothing can change even after
15967 		 * we get the pending mp. If need be we can put it back
15968 		 * and restart, as in calling ipif_arp_up()  below.
15969 		 */
15970 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15971 
15972 		mutex_enter(&ill->ill_lock);
15973 		ill->ill_dl_up = 1;
15974 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15975 		mutex_exit(&ill->ill_lock);
15976 
15977 		/*
15978 		 * Now bring up the resolver; when that is complete, we'll
15979 		 * create IREs.  Note that we intentionally mirror what
15980 		 * ipif_up() would have done, because we got here by way of
15981 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15982 		 */
15983 		if (ill->ill_isv6) {
15984 			if (ill->ill_flags & ILLF_XRESOLV) {
15985 				if (connp != NULL)
15986 					mutex_enter(&connp->conn_lock);
15987 				mutex_enter(&ill->ill_lock);
15988 				success = ipsq_pending_mp_add(connp, ipif, q,
15989 				    mp1, 0);
15990 				mutex_exit(&ill->ill_lock);
15991 				if (connp != NULL)
15992 					mutex_exit(&connp->conn_lock);
15993 				if (success) {
15994 					err = ipif_resolver_up(ipif,
15995 					    Res_act_initial);
15996 					if (err == EINPROGRESS) {
15997 						freemsg(mp);
15998 						return;
15999 					}
16000 					ASSERT(err != 0);
16001 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16002 					ASSERT(mp1 != NULL);
16003 				} else {
16004 					/* conn has started closing */
16005 					err = EINTR;
16006 				}
16007 			} else { /* Non XRESOLV interface */
16008 				(void) ipif_resolver_up(ipif, Res_act_initial);
16009 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16010 					err = ipif_up_done_v6(ipif);
16011 			}
16012 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16013 			/*
16014 			 * ARP and other v4 external resolvers.
16015 			 * Leave the pending mblk intact so that
16016 			 * the ioctl completes in ip_rput().
16017 			 */
16018 			if (connp != NULL)
16019 				mutex_enter(&connp->conn_lock);
16020 			mutex_enter(&ill->ill_lock);
16021 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16022 			mutex_exit(&ill->ill_lock);
16023 			if (connp != NULL)
16024 				mutex_exit(&connp->conn_lock);
16025 			if (success) {
16026 				err = ipif_resolver_up(ipif, Res_act_initial);
16027 				if (err == EINPROGRESS) {
16028 					freemsg(mp);
16029 					return;
16030 				}
16031 				ASSERT(err != 0);
16032 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16033 			} else {
16034 				/* The conn has started closing */
16035 				err = EINTR;
16036 			}
16037 		} else {
16038 			/*
16039 			 * This one is complete. Reply to pending ioctl.
16040 			 */
16041 			(void) ipif_resolver_up(ipif, Res_act_initial);
16042 			err = ipif_up_done(ipif);
16043 		}
16044 
16045 		if ((err == 0) && (ill->ill_up_ipifs)) {
16046 			err = ill_up_ipifs(ill, q, mp1);
16047 			if (err == EINPROGRESS) {
16048 				freemsg(mp);
16049 				return;
16050 			}
16051 		}
16052 
16053 		/*
16054 		 * If we have a moved ipif to bring up, and everything has
16055 		 * succeeded to this point, bring it up on the IPMP ill.
16056 		 * Otherwise, leave it down -- the admin can try to bring it
16057 		 * up by hand if need be.
16058 		 */
16059 		if (ill->ill_move_ipif != NULL) {
16060 			if (err != 0) {
16061 				ill->ill_move_ipif = NULL;
16062 			} else {
16063 				ipif = ill->ill_move_ipif;
16064 				ill->ill_move_ipif = NULL;
16065 				err = ipif_up(ipif, q, mp1);
16066 				if (err == EINPROGRESS) {
16067 					freemsg(mp);
16068 					return;
16069 				}
16070 			}
16071 		}
16072 		break;
16073 
16074 	case DL_NOTIFY_IND: {
16075 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16076 		ire_t *ire;
16077 		uint_t orig_mtu;
16078 		boolean_t need_ire_walk_v4 = B_FALSE;
16079 		boolean_t need_ire_walk_v6 = B_FALSE;
16080 
16081 		switch (notify->dl_notification) {
16082 		case DL_NOTE_PHYS_ADDR:
16083 			err = ill_set_phys_addr(ill, mp);
16084 			break;
16085 
16086 		case DL_NOTE_REPLUMB:
16087 			/*
16088 			 * Directly return after calling ill_replumb().
16089 			 * Note that we should not free mp as it is reused
16090 			 * in the ill_replumb() function.
16091 			 */
16092 			err = ill_replumb(ill, mp);
16093 			return;
16094 
16095 		case DL_NOTE_FASTPATH_FLUSH:
16096 			ill_fastpath_flush(ill);
16097 			break;
16098 
16099 		case DL_NOTE_SDU_SIZE:
16100 			/*
16101 			 * Change the MTU size of the interface, of all
16102 			 * attached ipif's, and of all relevant ire's.  The
16103 			 * new value's a uint32_t at notify->dl_data.
16104 			 * Mtu change Vs. new ire creation - protocol below.
16105 			 *
16106 			 * a Mark the ipif as IPIF_CHANGING.
16107 			 * b Set the new mtu in the ipif.
16108 			 * c Change the ire_max_frag on all affected ires
16109 			 * d Unmark the IPIF_CHANGING
16110 			 *
16111 			 * To see how the protocol works, assume an interface
16112 			 * route is also being added simultaneously by
16113 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16114 			 * the ire. If the ire is created before step a,
16115 			 * it will be cleaned up by step c. If the ire is
16116 			 * created after step d, it will see the new value of
16117 			 * ipif_mtu. Any attempt to create the ire between
16118 			 * steps a to d will fail because of the IPIF_CHANGING
16119 			 * flag. Note that ire_create() is passed a pointer to
16120 			 * the ipif_mtu, and not the value. During ire_add
16121 			 * under the bucket lock, the ire_max_frag of the
16122 			 * new ire being created is set from the ipif/ire from
16123 			 * which it is being derived.
16124 			 */
16125 			mutex_enter(&ill->ill_lock);
16126 
16127 			orig_mtu = ill->ill_max_mtu;
16128 			ill->ill_max_frag = (uint_t)notify->dl_data;
16129 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16130 
16131 			/*
16132 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16133 			 * clamp ill_max_mtu at it.
16134 			 */
16135 			if (ill->ill_user_mtu != 0 &&
16136 			    ill->ill_user_mtu < ill->ill_max_mtu)
16137 				ill->ill_max_mtu = ill->ill_user_mtu;
16138 
16139 			/*
16140 			 * If the MTU is unchanged, we're done.
16141 			 */
16142 			if (orig_mtu == ill->ill_max_mtu) {
16143 				mutex_exit(&ill->ill_lock);
16144 				break;
16145 			}
16146 
16147 			if (ill->ill_isv6) {
16148 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16149 					ill->ill_max_mtu = IPV6_MIN_MTU;
16150 			} else {
16151 				if (ill->ill_max_mtu < IP_MIN_MTU)
16152 					ill->ill_max_mtu = IP_MIN_MTU;
16153 			}
16154 			for (ipif = ill->ill_ipif; ipif != NULL;
16155 			    ipif = ipif->ipif_next) {
16156 				/*
16157 				 * Don't override the mtu if the user
16158 				 * has explicitly set it.
16159 				 */
16160 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16161 					continue;
16162 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16163 				if (ipif->ipif_isv6)
16164 					ire = ipif_to_ire_v6(ipif);
16165 				else
16166 					ire = ipif_to_ire(ipif);
16167 				if (ire != NULL) {
16168 					ire->ire_max_frag = ipif->ipif_mtu;
16169 					ire_refrele(ire);
16170 				}
16171 				if (ipif->ipif_flags & IPIF_UP) {
16172 					if (ill->ill_isv6)
16173 						need_ire_walk_v6 = B_TRUE;
16174 					else
16175 						need_ire_walk_v4 = B_TRUE;
16176 				}
16177 			}
16178 			mutex_exit(&ill->ill_lock);
16179 			if (need_ire_walk_v4)
16180 				ire_walk_v4(ill_mtu_change, (char *)ill,
16181 				    ALL_ZONES, ipst);
16182 			if (need_ire_walk_v6)
16183 				ire_walk_v6(ill_mtu_change, (char *)ill,
16184 				    ALL_ZONES, ipst);
16185 
16186 			/*
16187 			 * Refresh IPMP meta-interface MTU if necessary.
16188 			 */
16189 			if (IS_UNDER_IPMP(ill))
16190 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16191 			break;
16192 
16193 		case DL_NOTE_LINK_UP:
16194 		case DL_NOTE_LINK_DOWN: {
16195 			/*
16196 			 * We are writer. ill / phyint / ipsq assocs stable.
16197 			 * The RUNNING flag reflects the state of the link.
16198 			 */
16199 			phyint_t *phyint = ill->ill_phyint;
16200 			uint64_t new_phyint_flags;
16201 			boolean_t changed = B_FALSE;
16202 			boolean_t went_up;
16203 
16204 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16205 			mutex_enter(&phyint->phyint_lock);
16206 
16207 			new_phyint_flags = went_up ?
16208 			    phyint->phyint_flags | PHYI_RUNNING :
16209 			    phyint->phyint_flags & ~PHYI_RUNNING;
16210 
16211 			if (IS_IPMP(ill)) {
16212 				new_phyint_flags = went_up ?
16213 				    new_phyint_flags & ~PHYI_FAILED :
16214 				    new_phyint_flags | PHYI_FAILED;
16215 			}
16216 
16217 			if (new_phyint_flags != phyint->phyint_flags) {
16218 				phyint->phyint_flags = new_phyint_flags;
16219 				changed = B_TRUE;
16220 			}
16221 			mutex_exit(&phyint->phyint_lock);
16222 			/*
16223 			 * ill_restart_dad handles the DAD restart and routing
16224 			 * socket notification logic.
16225 			 */
16226 			if (changed) {
16227 				ill_restart_dad(phyint->phyint_illv4, went_up);
16228 				ill_restart_dad(phyint->phyint_illv6, went_up);
16229 			}
16230 			break;
16231 		}
16232 		case DL_NOTE_PROMISC_ON_PHYS: {
16233 			phyint_t *phyint = ill->ill_phyint;
16234 
16235 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16236 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16237 			mutex_enter(&phyint->phyint_lock);
16238 			phyint->phyint_flags |= PHYI_PROMISC;
16239 			mutex_exit(&phyint->phyint_lock);
16240 			break;
16241 		}
16242 		case DL_NOTE_PROMISC_OFF_PHYS: {
16243 			phyint_t *phyint = ill->ill_phyint;
16244 
16245 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16246 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16247 			mutex_enter(&phyint->phyint_lock);
16248 			phyint->phyint_flags &= ~PHYI_PROMISC;
16249 			mutex_exit(&phyint->phyint_lock);
16250 			break;
16251 		}
16252 		case DL_NOTE_CAPAB_RENEG:
16253 			/*
16254 			 * Something changed on the driver side.
16255 			 * It wants us to renegotiate the capabilities
16256 			 * on this ill. One possible cause is the aggregation
16257 			 * interface under us where a port got added or
16258 			 * went away.
16259 			 *
16260 			 * If the capability negotiation is already done
16261 			 * or is in progress, reset the capabilities and
16262 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16263 			 * so that when the ack comes back, we can start
16264 			 * the renegotiation process.
16265 			 *
16266 			 * Note that if ill_capab_reneg is already B_TRUE
16267 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16268 			 * the capability resetting request has been sent
16269 			 * and the renegotiation has not been started yet;
16270 			 * nothing needs to be done in this case.
16271 			 */
16272 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16273 			ill_capability_reset(ill, B_TRUE);
16274 			ipsq_current_finish(ipsq);
16275 			break;
16276 		default:
16277 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16278 			    "type 0x%x for DL_NOTIFY_IND\n",
16279 			    notify->dl_notification));
16280 			break;
16281 		}
16282 
16283 		/*
16284 		 * As this is an asynchronous operation, we
16285 		 * should not call ill_dlpi_done
16286 		 */
16287 		break;
16288 	}
16289 	case DL_NOTIFY_ACK: {
16290 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16291 
16292 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16293 			ill->ill_note_link = 1;
16294 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16295 		break;
16296 	}
16297 	case DL_PHYS_ADDR_ACK: {
16298 		/*
16299 		 * As part of plumbing the interface via SIOCSLIFNAME,
16300 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16301 		 * whose answers we receive here.  As each answer is received,
16302 		 * we call ill_dlpi_done() to dispatch the next request as
16303 		 * we're processing the current one.  Once all answers have
16304 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16305 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16306 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16307 		 * available, but we know the ioctl is pending on ill_wq.)
16308 		 */
16309 		uint_t	paddrlen, paddroff;
16310 		uint8_t	*addr;
16311 
16312 		paddrreq = ill->ill_phys_addr_pend;
16313 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16314 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16315 		addr = mp->b_rptr + paddroff;
16316 
16317 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16318 		if (paddrreq == DL_IPV6_TOKEN) {
16319 			/*
16320 			 * bcopy to low-order bits of ill_token
16321 			 *
16322 			 * XXX Temporary hack - currently, all known tokens
16323 			 * are 64 bits, so I'll cheat for the moment.
16324 			 */
16325 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
16326 			ill->ill_token_length = paddrlen;
16327 			break;
16328 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16329 			ASSERT(ill->ill_nd_lla_mp == NULL);
16330 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16331 			mp = NULL;
16332 			break;
16333 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
16334 			ASSERT(ill->ill_dest_addr_mp == NULL);
16335 			ill->ill_dest_addr_mp = mp;
16336 			ill->ill_dest_addr = addr;
16337 			mp = NULL;
16338 			if (ill->ill_isv6) {
16339 				ill_setdesttoken(ill);
16340 				ipif_setdestlinklocal(ill->ill_ipif);
16341 			}
16342 			break;
16343 		}
16344 
16345 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16346 		ASSERT(ill->ill_phys_addr_mp == NULL);
16347 		if (!ill->ill_ifname_pending)
16348 			break;
16349 		ill->ill_ifname_pending = 0;
16350 		if (!ioctl_aborted)
16351 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16352 		if (mp1 != NULL) {
16353 			ASSERT(connp == NULL);
16354 			q = ill->ill_wq;
16355 		}
16356 		/*
16357 		 * If any error acks received during the plumbing sequence,
16358 		 * ill_ifname_pending_err will be set. Break out and send up
16359 		 * the error to the pending ioctl.
16360 		 */
16361 		if (ill->ill_ifname_pending_err != 0) {
16362 			err = ill->ill_ifname_pending_err;
16363 			ill->ill_ifname_pending_err = 0;
16364 			break;
16365 		}
16366 
16367 		ill->ill_phys_addr_mp = mp;
16368 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
16369 		mp = NULL;
16370 
16371 		/*
16372 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
16373 		 * provider doesn't support physical addresses.  We check both
16374 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
16375 		 * not have physical addresses, but historically adversises a
16376 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
16377 		 * its DL_PHYS_ADDR_ACK.
16378 		 */
16379 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
16380 			ill->ill_phys_addr = NULL;
16381 		} else if (paddrlen != ill->ill_phys_addr_length) {
16382 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16383 			    paddrlen, ill->ill_phys_addr_length));
16384 			err = EINVAL;
16385 			break;
16386 		}
16387 
16388 		if (ill->ill_nd_lla_mp == NULL) {
16389 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16390 				err = ENOMEM;
16391 				break;
16392 			}
16393 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16394 		}
16395 
16396 		if (ill->ill_isv6) {
16397 			ill_setdefaulttoken(ill);
16398 			ipif_setlinklocal(ill->ill_ipif);
16399 		}
16400 		break;
16401 	}
16402 	case DL_OK_ACK:
16403 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16404 		    dl_primstr((int)dloa->dl_correct_primitive),
16405 		    dloa->dl_correct_primitive));
16406 		switch (dloa->dl_correct_primitive) {
16407 		case DL_ENABMULTI_REQ:
16408 		case DL_DISABMULTI_REQ:
16409 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16410 			break;
16411 		case DL_PROMISCON_REQ:
16412 		case DL_PROMISCOFF_REQ:
16413 		case DL_UNBIND_REQ:
16414 		case DL_ATTACH_REQ:
16415 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16416 			break;
16417 		}
16418 		break;
16419 	default:
16420 		break;
16421 	}
16422 
16423 	freemsg(mp);
16424 	if (mp1 == NULL)
16425 		return;
16426 
16427 	/*
16428 	 * The operation must complete without EINPROGRESS since
16429 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16430 	 * the operation will be stuck forever inside the IPSQ.
16431 	 */
16432 	ASSERT(err != EINPROGRESS);
16433 
16434 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16435 	case 0:
16436 		ipsq_current_finish(ipsq);
16437 		break;
16438 
16439 	case SIOCSLIFNAME:
16440 	case IF_UNITSEL: {
16441 		ill_t *ill_other = ILL_OTHER(ill);
16442 
16443 		/*
16444 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16445 		 * ill has a peer which is in an IPMP group, then place ill
16446 		 * into the same group.  One catch: although ifconfig plumbs
16447 		 * the appropriate IPMP meta-interface prior to plumbing this
16448 		 * ill, it is possible for multiple ifconfig applications to
16449 		 * race (or for another application to adjust plumbing), in
16450 		 * which case the IPMP meta-interface we need will be missing.
16451 		 * If so, kick the phyint out of the group.
16452 		 */
16453 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16454 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16455 			ipmp_illgrp_t	*illg;
16456 
16457 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16458 			if (illg == NULL)
16459 				ipmp_phyint_leave_grp(ill->ill_phyint);
16460 			else
16461 				ipmp_ill_join_illgrp(ill, illg);
16462 		}
16463 
16464 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16465 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16466 		else
16467 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16468 		break;
16469 	}
16470 	case SIOCLIFADDIF:
16471 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16472 		break;
16473 
16474 	default:
16475 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16476 		break;
16477 	}
16478 }
16479 
16480 /*
16481  * ip_rput_other is called by ip_rput to handle messages modifying the global
16482  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
16483  */
16484 /* ARGSUSED */
16485 void
16486 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16487 {
16488 	ill_t		*ill = q->q_ptr;
16489 	struct iocblk	*iocp;
16490 
16491 	ip1dbg(("ip_rput_other "));
16492 	if (ipsq != NULL) {
16493 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16494 		ASSERT(ipsq->ipsq_xop ==
16495 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16496 	}
16497 
16498 	switch (mp->b_datap->db_type) {
16499 	case M_ERROR:
16500 	case M_HANGUP:
16501 		/*
16502 		 * The device has a problem.  We force the ILL down.  It can
16503 		 * be brought up again manually using SIOCSIFFLAGS (via
16504 		 * ifconfig or equivalent).
16505 		 */
16506 		ASSERT(ipsq != NULL);
16507 		if (mp->b_rptr < mp->b_wptr)
16508 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16509 		if (ill->ill_error == 0)
16510 			ill->ill_error = ENXIO;
16511 		if (!ill_down_start(q, mp))
16512 			return;
16513 		ipif_all_down_tail(ipsq, q, mp, NULL);
16514 		break;
16515 	case M_IOCNAK: {
16516 		iocp = (struct iocblk *)mp->b_rptr;
16517 
16518 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
16519 		/*
16520 		 * If this was the first attempt, turn off the fastpath
16521 		 * probing.
16522 		 */
16523 		mutex_enter(&ill->ill_lock);
16524 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16525 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
16526 			mutex_exit(&ill->ill_lock);
16527 			ill_fastpath_nack(ill);
16528 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
16529 			    ill->ill_name));
16530 		} else {
16531 			mutex_exit(&ill->ill_lock);
16532 		}
16533 		freemsg(mp);
16534 		break;
16535 	}
16536 	default:
16537 		ASSERT(0);
16538 		break;
16539 	}
16540 }
16541 
16542 /*
16543  * NOTE : This function does not ire_refrele the ire argument passed in.
16544  *
16545  * IPQoS notes
16546  * IP policy is invoked twice for a forwarded packet, once on the read side
16547  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16548  * enabled. An additional parameter, in_ill, has been added for this purpose.
16549  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16550  * because ip_mroute drops this information.
16551  *
16552  */
16553 void
16554 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16555 {
16556 	uint32_t	old_pkt_len;
16557 	uint32_t	pkt_len;
16558 	queue_t	*q;
16559 	uint32_t	sum;
16560 #define	rptr	((uchar_t *)ipha)
16561 	uint32_t	max_frag;
16562 	uint32_t	ill_index;
16563 	ill_t		*out_ill;
16564 	mib2_ipIfStatsEntry_t *mibptr;
16565 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16566 
16567 	/* Get the ill_index of the incoming ILL */
16568 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16569 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16570 
16571 	/* Initiate Read side IPPF processing */
16572 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16573 		ip_process(IPP_FWD_IN, &mp, ill_index);
16574 		if (mp == NULL) {
16575 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16576 			    "during IPPF processing\n"));
16577 			return;
16578 		}
16579 	}
16580 
16581 	/* Adjust the checksum to reflect the ttl decrement. */
16582 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16583 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16584 
16585 	if (ipha->ipha_ttl-- <= 1) {
16586 		if (ip_csum_hdr(ipha)) {
16587 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16588 			goto drop_pkt;
16589 		}
16590 		/*
16591 		 * Note: ire_stq this will be NULL for multicast
16592 		 * datagrams using the long path through arp (the IRE
16593 		 * is not an IRE_CACHE). This should not cause
16594 		 * problems since we don't generate ICMP errors for
16595 		 * multicast packets.
16596 		 */
16597 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16598 		q = ire->ire_stq;
16599 		if (q != NULL) {
16600 			/* Sent by forwarding path, and router is global zone */
16601 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16602 			    GLOBAL_ZONEID, ipst);
16603 		} else
16604 			freemsg(mp);
16605 		return;
16606 	}
16607 
16608 	/*
16609 	 * Don't forward if the interface is down
16610 	 */
16611 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16612 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16613 		ip2dbg(("ip_rput_forward:interface is down\n"));
16614 		goto drop_pkt;
16615 	}
16616 
16617 	/* Get the ill_index of the outgoing ILL */
16618 	out_ill = ire_to_ill(ire);
16619 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16620 
16621 	DTRACE_PROBE4(ip4__forwarding__start,
16622 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16623 
16624 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16625 	    ipst->ips_ipv4firewall_forwarding,
16626 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16627 
16628 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16629 
16630 	if (mp == NULL)
16631 		return;
16632 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16633 
16634 	if (is_system_labeled()) {
16635 		mblk_t *mp1;
16636 
16637 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16638 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16639 			goto drop_pkt;
16640 		}
16641 		/* Size may have changed */
16642 		mp = mp1;
16643 		ipha = (ipha_t *)mp->b_rptr;
16644 		pkt_len = ntohs(ipha->ipha_length);
16645 	}
16646 
16647 	/* Check if there are options to update */
16648 	if (!IS_SIMPLE_IPH(ipha)) {
16649 		if (ip_csum_hdr(ipha)) {
16650 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16651 			goto drop_pkt;
16652 		}
16653 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16654 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16655 			return;
16656 		}
16657 
16658 		ipha->ipha_hdr_checksum = 0;
16659 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16660 	}
16661 	max_frag = ire->ire_max_frag;
16662 	if (pkt_len > max_frag) {
16663 		/*
16664 		 * It needs fragging on its way out.  We haven't
16665 		 * verified the header checksum yet.  Since we
16666 		 * are going to put a surely good checksum in the
16667 		 * outgoing header, we have to make sure that it
16668 		 * was good coming in.
16669 		 */
16670 		if (ip_csum_hdr(ipha)) {
16671 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16672 			goto drop_pkt;
16673 		}
16674 		/* Initiate Write side IPPF processing */
16675 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16676 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16677 			if (mp == NULL) {
16678 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16679 				    " during IPPF processing\n"));
16680 				return;
16681 			}
16682 		}
16683 		/*
16684 		 * Handle labeled packet resizing.
16685 		 *
16686 		 * If we have added a label, inform ip_wput_frag() of its
16687 		 * effect on the MTU for ICMP messages.
16688 		 */
16689 		if (pkt_len > old_pkt_len) {
16690 			uint32_t secopt_size;
16691 
16692 			secopt_size = pkt_len - old_pkt_len;
16693 			if (secopt_size < max_frag)
16694 				max_frag -= secopt_size;
16695 		}
16696 
16697 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16698 		    GLOBAL_ZONEID, ipst, NULL);
16699 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16700 		return;
16701 	}
16702 
16703 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16704 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16705 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16706 	    ipst->ips_ipv4firewall_physical_out,
16707 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16708 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16709 	if (mp == NULL)
16710 		return;
16711 
16712 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16713 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16714 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16715 	/* ip_xmit_v4 always consumes the packet */
16716 	return;
16717 
16718 drop_pkt:;
16719 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16720 	freemsg(mp);
16721 #undef	rptr
16722 }
16723 
16724 void
16725 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16726 {
16727 	ire_t	*ire;
16728 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16729 
16730 	ASSERT(!ipif->ipif_isv6);
16731 	/*
16732 	 * Find an IRE which matches the destination and the outgoing
16733 	 * queue in the cache table. All we need is an IRE_CACHE which
16734 	 * is pointing at ipif->ipif_ill.
16735 	 */
16736 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16737 		dst = ipif->ipif_pp_dst_addr;
16738 
16739 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16740 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16741 	if (ire == NULL) {
16742 		/*
16743 		 * Mark this packet to make it be delivered to
16744 		 * ip_rput_forward after the new ire has been
16745 		 * created.
16746 		 */
16747 		mp->b_prev = NULL;
16748 		mp->b_next = mp;
16749 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16750 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16751 	} else {
16752 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16753 		IRE_REFRELE(ire);
16754 	}
16755 }
16756 
16757 /* Update any source route, record route or timestamp options */
16758 static int
16759 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16760 {
16761 	ipoptp_t	opts;
16762 	uchar_t		*opt;
16763 	uint8_t		optval;
16764 	uint8_t		optlen;
16765 	ipaddr_t	dst;
16766 	uint32_t	ts;
16767 	ire_t		*dst_ire = NULL;
16768 	ire_t		*tmp_ire = NULL;
16769 	timestruc_t	now;
16770 
16771 	ip2dbg(("ip_rput_forward_options\n"));
16772 	dst = ipha->ipha_dst;
16773 	for (optval = ipoptp_first(&opts, ipha);
16774 	    optval != IPOPT_EOL;
16775 	    optval = ipoptp_next(&opts)) {
16776 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16777 		opt = opts.ipoptp_cur;
16778 		optlen = opts.ipoptp_len;
16779 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16780 		    optval, opts.ipoptp_len));
16781 		switch (optval) {
16782 			uint32_t off;
16783 		case IPOPT_SSRR:
16784 		case IPOPT_LSRR:
16785 			/* Check if adminstratively disabled */
16786 			if (!ipst->ips_ip_forward_src_routed) {
16787 				if (ire->ire_stq != NULL) {
16788 					/*
16789 					 * Sent by forwarding path, and router
16790 					 * is global zone
16791 					 */
16792 					icmp_unreachable(ire->ire_stq, mp,
16793 					    ICMP_SOURCE_ROUTE_FAILED,
16794 					    GLOBAL_ZONEID, ipst);
16795 				} else {
16796 					ip0dbg(("ip_rput_forward_options: "
16797 					    "unable to send unreach\n"));
16798 					freemsg(mp);
16799 				}
16800 				return (-1);
16801 			}
16802 
16803 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16804 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16805 			if (dst_ire == NULL) {
16806 				/*
16807 				 * Must be partial since ip_rput_options
16808 				 * checked for strict.
16809 				 */
16810 				break;
16811 			}
16812 			off = opt[IPOPT_OFFSET];
16813 			off--;
16814 		redo_srr:
16815 			if (optlen < IP_ADDR_LEN ||
16816 			    off > optlen - IP_ADDR_LEN) {
16817 				/* End of source route */
16818 				ip1dbg((
16819 				    "ip_rput_forward_options: end of SR\n"));
16820 				ire_refrele(dst_ire);
16821 				break;
16822 			}
16823 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16824 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16825 			    IP_ADDR_LEN);
16826 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16827 			    ntohl(dst)));
16828 
16829 			/*
16830 			 * Check if our address is present more than
16831 			 * once as consecutive hops in source route.
16832 			 */
16833 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16834 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16835 			if (tmp_ire != NULL) {
16836 				ire_refrele(tmp_ire);
16837 				off += IP_ADDR_LEN;
16838 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16839 				goto redo_srr;
16840 			}
16841 			ipha->ipha_dst = dst;
16842 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16843 			ire_refrele(dst_ire);
16844 			break;
16845 		case IPOPT_RR:
16846 			off = opt[IPOPT_OFFSET];
16847 			off--;
16848 			if (optlen < IP_ADDR_LEN ||
16849 			    off > optlen - IP_ADDR_LEN) {
16850 				/* No more room - ignore */
16851 				ip1dbg((
16852 				    "ip_rput_forward_options: end of RR\n"));
16853 				break;
16854 			}
16855 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16856 			    IP_ADDR_LEN);
16857 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16858 			break;
16859 		case IPOPT_TS:
16860 			/* Insert timestamp if there is room */
16861 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16862 			case IPOPT_TS_TSONLY:
16863 				off = IPOPT_TS_TIMELEN;
16864 				break;
16865 			case IPOPT_TS_PRESPEC:
16866 			case IPOPT_TS_PRESPEC_RFC791:
16867 				/* Verify that the address matched */
16868 				off = opt[IPOPT_OFFSET] - 1;
16869 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16870 				dst_ire = ire_ctable_lookup(dst, 0,
16871 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16872 				    MATCH_IRE_TYPE, ipst);
16873 				if (dst_ire == NULL) {
16874 					/* Not for us */
16875 					break;
16876 				}
16877 				ire_refrele(dst_ire);
16878 				/* FALLTHRU */
16879 			case IPOPT_TS_TSANDADDR:
16880 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16881 				break;
16882 			default:
16883 				/*
16884 				 * ip_*put_options should have already
16885 				 * dropped this packet.
16886 				 */
16887 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16888 				    "unknown IT - bug in ip_rput_options?\n");
16889 				return (0);	/* Keep "lint" happy */
16890 			}
16891 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16892 				/* Increase overflow counter */
16893 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16894 				opt[IPOPT_POS_OV_FLG] =
16895 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16896 				    (off << 4));
16897 				break;
16898 			}
16899 			off = opt[IPOPT_OFFSET] - 1;
16900 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16901 			case IPOPT_TS_PRESPEC:
16902 			case IPOPT_TS_PRESPEC_RFC791:
16903 			case IPOPT_TS_TSANDADDR:
16904 				bcopy(&ire->ire_src_addr,
16905 				    (char *)opt + off, IP_ADDR_LEN);
16906 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16907 				/* FALLTHRU */
16908 			case IPOPT_TS_TSONLY:
16909 				off = opt[IPOPT_OFFSET] - 1;
16910 				/* Compute # of milliseconds since midnight */
16911 				gethrestime(&now);
16912 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16913 				    now.tv_nsec / (NANOSEC / MILLISEC);
16914 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16915 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16916 				break;
16917 			}
16918 			break;
16919 		}
16920 	}
16921 	return (0);
16922 }
16923 
16924 /*
16925  * This is called after processing at least one of AH/ESP headers.
16926  *
16927  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16928  * the actual, physical interface on which the packet was received,
16929  * but, when ip_strict_dst_multihoming is set to 1, could be the
16930  * interface which had the ipha_dst configured when the packet went
16931  * through ip_rput. The ill_index corresponding to the recv_ill
16932  * is saved in ipsec_in_rill_index
16933  *
16934  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16935  * cannot assume "ire" points to valid data for any IPv6 cases.
16936  */
16937 void
16938 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16939 {
16940 	mblk_t *mp;
16941 	ipaddr_t dst;
16942 	in6_addr_t *v6dstp;
16943 	ipha_t *ipha;
16944 	ip6_t *ip6h;
16945 	ipsec_in_t *ii;
16946 	boolean_t ill_need_rele = B_FALSE;
16947 	boolean_t rill_need_rele = B_FALSE;
16948 	boolean_t ire_need_rele = B_FALSE;
16949 	netstack_t	*ns;
16950 	ip_stack_t	*ipst;
16951 
16952 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16953 	ASSERT(ii->ipsec_in_ill_index != 0);
16954 	ns = ii->ipsec_in_ns;
16955 	ASSERT(ii->ipsec_in_ns != NULL);
16956 	ipst = ns->netstack_ip;
16957 
16958 	mp = ipsec_mp->b_cont;
16959 	ASSERT(mp != NULL);
16960 
16961 	if (ill == NULL) {
16962 		ASSERT(recv_ill == NULL);
16963 		/*
16964 		 * We need to get the original queue on which ip_rput_local
16965 		 * or ip_rput_data_v6 was called.
16966 		 */
16967 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16968 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16969 		ill_need_rele = B_TRUE;
16970 
16971 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16972 			recv_ill = ill_lookup_on_ifindex(
16973 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16974 			    NULL, NULL, NULL, NULL, ipst);
16975 			rill_need_rele = B_TRUE;
16976 		} else {
16977 			recv_ill = ill;
16978 		}
16979 
16980 		if ((ill == NULL) || (recv_ill == NULL)) {
16981 			ip0dbg(("ip_fanout_proto_again: interface "
16982 			    "disappeared\n"));
16983 			if (ill != NULL)
16984 				ill_refrele(ill);
16985 			if (recv_ill != NULL)
16986 				ill_refrele(recv_ill);
16987 			freemsg(ipsec_mp);
16988 			return;
16989 		}
16990 	}
16991 
16992 	ASSERT(ill != NULL && recv_ill != NULL);
16993 
16994 	if (mp->b_datap->db_type == M_CTL) {
16995 		/*
16996 		 * AH/ESP is returning the ICMP message after
16997 		 * removing their headers. Fanout again till
16998 		 * it gets to the right protocol.
16999 		 */
17000 		if (ii->ipsec_in_v4) {
17001 			icmph_t *icmph;
17002 			int iph_hdr_length;
17003 			int hdr_length;
17004 
17005 			ipha = (ipha_t *)mp->b_rptr;
17006 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17007 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17008 			ipha = (ipha_t *)&icmph[1];
17009 			hdr_length = IPH_HDR_LENGTH(ipha);
17010 			/*
17011 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17012 			 * Reset the type to M_DATA.
17013 			 */
17014 			mp->b_datap->db_type = M_DATA;
17015 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17016 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17017 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17018 		} else {
17019 			icmp6_t *icmp6;
17020 			int hdr_length;
17021 
17022 			ip6h = (ip6_t *)mp->b_rptr;
17023 			/* Don't call hdr_length_v6() unless you have to. */
17024 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17025 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17026 			else
17027 				hdr_length = IPV6_HDR_LEN;
17028 
17029 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17030 			/*
17031 			 * icmp_inbound_error_fanout_v6 may need to do
17032 			 * pullupmsg.  Reset the type to M_DATA.
17033 			 */
17034 			mp->b_datap->db_type = M_DATA;
17035 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17036 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17037 			    ii->ipsec_in_zoneid);
17038 		}
17039 		if (ill_need_rele)
17040 			ill_refrele(ill);
17041 		if (rill_need_rele)
17042 			ill_refrele(recv_ill);
17043 		return;
17044 	}
17045 
17046 	if (ii->ipsec_in_v4) {
17047 		ipha = (ipha_t *)mp->b_rptr;
17048 		dst = ipha->ipha_dst;
17049 		if (CLASSD(dst)) {
17050 			/*
17051 			 * Multicast has to be delivered to all streams.
17052 			 */
17053 			dst = INADDR_BROADCAST;
17054 		}
17055 
17056 		if (ire == NULL) {
17057 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17058 			    msg_getlabel(mp), ipst);
17059 			if (ire == NULL) {
17060 				if (ill_need_rele)
17061 					ill_refrele(ill);
17062 				if (rill_need_rele)
17063 					ill_refrele(recv_ill);
17064 				ip1dbg(("ip_fanout_proto_again: "
17065 				    "IRE not found"));
17066 				freemsg(ipsec_mp);
17067 				return;
17068 			}
17069 			ire_need_rele = B_TRUE;
17070 		}
17071 
17072 		switch (ipha->ipha_protocol) {
17073 		case IPPROTO_UDP:
17074 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17075 			    recv_ill);
17076 			if (ire_need_rele)
17077 				ire_refrele(ire);
17078 			break;
17079 		case IPPROTO_TCP:
17080 			if (!ire_need_rele)
17081 				IRE_REFHOLD(ire);
17082 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17083 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17084 			IRE_REFRELE(ire);
17085 			if (mp != NULL) {
17086 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17087 				    mp, 1, SQ_PROCESS,
17088 				    SQTAG_IP_PROTO_AGAIN);
17089 			}
17090 			break;
17091 		case IPPROTO_SCTP:
17092 			if (!ire_need_rele)
17093 				IRE_REFHOLD(ire);
17094 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17095 			    ipsec_mp, 0, ill->ill_rq, dst);
17096 			break;
17097 		case IPPROTO_ENCAP:
17098 		case IPPROTO_IPV6:
17099 			if (ip_iptun_input(ipsec_mp, mp, ipha, ill, ire,
17100 			    ill->ill_ipst)) {
17101 				/*
17102 				 * If we made it here, we don't need to worry
17103 				 * about the raw-socket/protocol fanout.
17104 				 */
17105 				if (ire_need_rele)
17106 					ire_refrele(ire);
17107 				break;
17108 			}
17109 			/* else FALLTHRU */
17110 		default:
17111 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17112 			    recv_ill, 0);
17113 			if (ire_need_rele)
17114 				ire_refrele(ire);
17115 			break;
17116 		}
17117 	} else {
17118 		uint32_t rput_flags = 0;
17119 
17120 		ip6h = (ip6_t *)mp->b_rptr;
17121 		v6dstp = &ip6h->ip6_dst;
17122 		/*
17123 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17124 		 * address.
17125 		 *
17126 		 * Currently, we don't store that state in the IPSEC_IN
17127 		 * message, and we may need to.
17128 		 */
17129 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17130 		    IP6_IN_LLMCAST : 0);
17131 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17132 		    NULL, NULL);
17133 	}
17134 	if (ill_need_rele)
17135 		ill_refrele(ill);
17136 	if (rill_need_rele)
17137 		ill_refrele(recv_ill);
17138 }
17139 
17140 /*
17141  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17142  * returns 'true' if there are still fragments left on the queue, in
17143  * which case we restart the timer.
17144  */
17145 void
17146 ill_frag_timer(void *arg)
17147 {
17148 	ill_t	*ill = (ill_t *)arg;
17149 	boolean_t frag_pending;
17150 	ip_stack_t	*ipst = ill->ill_ipst;
17151 	time_t	timeout;
17152 
17153 	mutex_enter(&ill->ill_lock);
17154 	ASSERT(!ill->ill_fragtimer_executing);
17155 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17156 		ill->ill_frag_timer_id = 0;
17157 		mutex_exit(&ill->ill_lock);
17158 		return;
17159 	}
17160 	ill->ill_fragtimer_executing = 1;
17161 	mutex_exit(&ill->ill_lock);
17162 
17163 	if (ill->ill_isv6)
17164 		timeout = ipst->ips_ipv6_frag_timeout;
17165 	else
17166 		timeout = ipst->ips_ip_g_frag_timeout;
17167 
17168 	frag_pending = ill_frag_timeout(ill, timeout);
17169 
17170 	/*
17171 	 * Restart the timer, if we have fragments pending or if someone
17172 	 * wanted us to be scheduled again.
17173 	 */
17174 	mutex_enter(&ill->ill_lock);
17175 	ill->ill_fragtimer_executing = 0;
17176 	ill->ill_frag_timer_id = 0;
17177 	if (frag_pending || ill->ill_fragtimer_needrestart)
17178 		ill_frag_timer_start(ill);
17179 	mutex_exit(&ill->ill_lock);
17180 }
17181 
17182 void
17183 ill_frag_timer_start(ill_t *ill)
17184 {
17185 	ip_stack_t	*ipst = ill->ill_ipst;
17186 	clock_t	timeo_ms;
17187 
17188 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17189 
17190 	/* If the ill is closing or opening don't proceed */
17191 	if (ill->ill_state_flags & ILL_CONDEMNED)
17192 		return;
17193 
17194 	if (ill->ill_fragtimer_executing) {
17195 		/*
17196 		 * ill_frag_timer is currently executing. Just record the
17197 		 * the fact that we want the timer to be restarted.
17198 		 * ill_frag_timer will post a timeout before it returns,
17199 		 * ensuring it will be called again.
17200 		 */
17201 		ill->ill_fragtimer_needrestart = 1;
17202 		return;
17203 	}
17204 
17205 	if (ill->ill_frag_timer_id == 0) {
17206 		if (ill->ill_isv6)
17207 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17208 		else
17209 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17210 		/*
17211 		 * The timer is neither running nor is the timeout handler
17212 		 * executing. Post a timeout so that ill_frag_timer will be
17213 		 * called
17214 		 */
17215 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17216 		    MSEC_TO_TICK(timeo_ms >> 1));
17217 		ill->ill_fragtimer_needrestart = 0;
17218 	}
17219 }
17220 
17221 /*
17222  * This routine is needed for loopback when forwarding multicasts.
17223  *
17224  * IPQoS Notes:
17225  * IPPF processing is done in fanout routines.
17226  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17227  * processing for IPsec packets is done when it comes back in clear.
17228  * NOTE : The callers of this function need to do the ire_refrele for the
17229  *	  ire that is being passed in.
17230  */
17231 void
17232 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17233     ill_t *recv_ill, uint32_t esp_udp_ports)
17234 {
17235 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17236 	ill_t	*ill = (ill_t *)q->q_ptr;
17237 	uint32_t	sum;
17238 	uint32_t	u1;
17239 	uint32_t	u2;
17240 	int		hdr_length;
17241 	boolean_t	mctl_present;
17242 	mblk_t		*first_mp = mp;
17243 	mblk_t		*hada_mp = NULL;
17244 	ipha_t		*inner_ipha;
17245 	ip_stack_t	*ipst;
17246 
17247 	ASSERT(recv_ill != NULL);
17248 	ipst = recv_ill->ill_ipst;
17249 
17250 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17251 	    "ip_rput_locl_start: q %p", q);
17252 
17253 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17254 	ASSERT(ill != NULL);
17255 
17256 #define	rptr	((uchar_t *)ipha)
17257 #define	iphs	((uint16_t *)ipha)
17258 
17259 	/*
17260 	 * no UDP or TCP packet should come here anymore.
17261 	 */
17262 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17263 	    ipha->ipha_protocol != IPPROTO_UDP);
17264 
17265 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17266 	if (mctl_present &&
17267 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17268 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17269 
17270 		/*
17271 		 * It's an IPsec accelerated packet.
17272 		 * Keep a pointer to the data attributes around until
17273 		 * we allocate the ipsec_info_t.
17274 		 */
17275 		IPSECHW_DEBUG(IPSECHW_PKT,
17276 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17277 		hada_mp = first_mp;
17278 		hada_mp->b_cont = NULL;
17279 		/*
17280 		 * Since it is accelerated, it comes directly from
17281 		 * the ill and the data attributes is followed by
17282 		 * the packet data.
17283 		 */
17284 		ASSERT(mp->b_datap->db_type != M_CTL);
17285 		first_mp = mp;
17286 		mctl_present = B_FALSE;
17287 	}
17288 
17289 	/*
17290 	 * IF M_CTL is not present, then ipsec_in_is_secure
17291 	 * should return B_TRUE. There is a case where loopback
17292 	 * packets has an M_CTL in the front with all the
17293 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17294 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17295 	 * packets never comes here, it is safe to ASSERT the
17296 	 * following.
17297 	 */
17298 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17299 
17300 	/*
17301 	 * Also, we should never have an mctl_present if this is an
17302 	 * ESP-in-UDP packet.
17303 	 */
17304 	ASSERT(!mctl_present || !esp_in_udp_packet);
17305 
17306 	/* u1 is # words of IP options */
17307 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17308 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17309 
17310 	/*
17311 	 * Don't verify header checksum if we just removed UDP header or
17312 	 * packet is coming back from AH/ESP.
17313 	 */
17314 	if (!esp_in_udp_packet && !mctl_present) {
17315 		if (u1) {
17316 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17317 				if (hada_mp != NULL)
17318 					freemsg(hada_mp);
17319 				return;
17320 			}
17321 		} else {
17322 			/* Check the IP header checksum.  */
17323 #define	uph	((uint16_t *)ipha)
17324 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17325 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17326 #undef  uph
17327 			/* finish doing IP checksum */
17328 			sum = (sum & 0xFFFF) + (sum >> 16);
17329 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17330 			if (sum && sum != 0xFFFF) {
17331 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17332 				goto drop_pkt;
17333 			}
17334 		}
17335 	}
17336 
17337 	/*
17338 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17339 	 * might be called more than once for secure packets, count only
17340 	 * the first time.
17341 	 */
17342 	if (!mctl_present) {
17343 		UPDATE_IB_PKT_COUNT(ire);
17344 		ire->ire_last_used_time = lbolt;
17345 	}
17346 
17347 	/* Check for fragmentation offset. */
17348 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17349 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17350 	if (u1) {
17351 		/*
17352 		 * We re-assemble fragments before we do the AH/ESP
17353 		 * processing. Thus, M_CTL should not be present
17354 		 * while we are re-assembling.
17355 		 */
17356 		ASSERT(!mctl_present);
17357 		ASSERT(first_mp == mp);
17358 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17359 			return;
17360 
17361 		/*
17362 		 * Make sure that first_mp points back to mp as
17363 		 * the mp we came in with could have changed in
17364 		 * ip_rput_fragment().
17365 		 */
17366 		ipha = (ipha_t *)mp->b_rptr;
17367 		first_mp = mp;
17368 	}
17369 
17370 	/*
17371 	 * Clear hardware checksumming flag as it is currently only
17372 	 * used by TCP and UDP.
17373 	 */
17374 	DB_CKSUMFLAGS(mp) = 0;
17375 
17376 	/* Now we have a complete datagram, destined for this machine. */
17377 	u1 = IPH_HDR_LENGTH(ipha);
17378 	switch (ipha->ipha_protocol) {
17379 	case IPPROTO_ICMP: {
17380 		ire_t		*ire_zone;
17381 		ilm_t		*ilm;
17382 		mblk_t		*mp1;
17383 		zoneid_t	last_zoneid;
17384 		ilm_walker_t	ilw;
17385 
17386 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17387 			ASSERT(ire->ire_type == IRE_BROADCAST);
17388 
17389 			/*
17390 			 * In the multicast case, applications may have joined
17391 			 * the group from different zones, so we need to deliver
17392 			 * the packet to each of them. Loop through the
17393 			 * multicast memberships structures (ilm) on the receive
17394 			 * ill and send a copy of the packet up each matching
17395 			 * one. However, we don't do this for multicasts sent on
17396 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17397 			 * they must stay in the sender's zone.
17398 			 *
17399 			 * ilm_add_v6() ensures that ilms in the same zone are
17400 			 * contiguous in the ill_ilm list. We use this property
17401 			 * to avoid sending duplicates needed when two
17402 			 * applications in the same zone join the same group on
17403 			 * different logical interfaces: we ignore the ilm if
17404 			 * its zoneid is the same as the last matching one.
17405 			 * In addition, the sending of the packet for
17406 			 * ire_zoneid is delayed until all of the other ilms
17407 			 * have been exhausted.
17408 			 */
17409 			last_zoneid = -1;
17410 			ilm = ilm_walker_start(&ilw, recv_ill);
17411 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17412 				if (ipha->ipha_dst != ilm->ilm_addr ||
17413 				    ilm->ilm_zoneid == last_zoneid ||
17414 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17415 				    ilm->ilm_zoneid == ALL_ZONES ||
17416 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17417 					continue;
17418 				mp1 = ip_copymsg(first_mp);
17419 				if (mp1 == NULL)
17420 					continue;
17421 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17422 				    0, sum, mctl_present, B_TRUE,
17423 				    recv_ill, ilm->ilm_zoneid);
17424 				last_zoneid = ilm->ilm_zoneid;
17425 			}
17426 			ilm_walker_finish(&ilw);
17427 		} else if (ire->ire_type == IRE_BROADCAST) {
17428 			/*
17429 			 * In the broadcast case, there may be many zones
17430 			 * which need a copy of the packet delivered to them.
17431 			 * There is one IRE_BROADCAST per broadcast address
17432 			 * and per zone; we walk those using a helper function.
17433 			 * In addition, the sending of the packet for ire is
17434 			 * delayed until all of the other ires have been
17435 			 * processed.
17436 			 */
17437 			IRB_REFHOLD(ire->ire_bucket);
17438 			ire_zone = NULL;
17439 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17440 			    ire)) != NULL) {
17441 				mp1 = ip_copymsg(first_mp);
17442 				if (mp1 == NULL)
17443 					continue;
17444 
17445 				UPDATE_IB_PKT_COUNT(ire_zone);
17446 				ire_zone->ire_last_used_time = lbolt;
17447 				icmp_inbound(q, mp1, B_TRUE, ill,
17448 				    0, sum, mctl_present, B_TRUE,
17449 				    recv_ill, ire_zone->ire_zoneid);
17450 			}
17451 			IRB_REFRELE(ire->ire_bucket);
17452 		}
17453 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17454 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17455 		    ire->ire_zoneid);
17456 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17457 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17458 		return;
17459 	}
17460 	case IPPROTO_IGMP:
17461 		/*
17462 		 * If we are not willing to accept IGMP packets in clear,
17463 		 * then check with global policy.
17464 		 */
17465 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17466 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17467 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17468 			if (first_mp == NULL)
17469 				return;
17470 		}
17471 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17472 			freemsg(first_mp);
17473 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17474 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17475 			return;
17476 		}
17477 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17478 			/* Bad packet - discarded by igmp_input */
17479 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17480 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17481 			if (mctl_present)
17482 				freeb(first_mp);
17483 			return;
17484 		}
17485 		/*
17486 		 * igmp_input() may have returned the pulled up message.
17487 		 * So first_mp and ipha need to be reinitialized.
17488 		 */
17489 		ipha = (ipha_t *)mp->b_rptr;
17490 		if (mctl_present)
17491 			first_mp->b_cont = mp;
17492 		else
17493 			first_mp = mp;
17494 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17495 		    connf_head != NULL) {
17496 			/* No user-level listener for IGMP packets */
17497 			goto drop_pkt;
17498 		}
17499 		/* deliver to local raw users */
17500 		break;
17501 	case IPPROTO_PIM:
17502 		/*
17503 		 * If we are not willing to accept PIM packets in clear,
17504 		 * then check with global policy.
17505 		 */
17506 		if (ipst->ips_pim_accept_clear_messages == 0) {
17507 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17508 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17509 			if (first_mp == NULL)
17510 				return;
17511 		}
17512 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17513 			freemsg(first_mp);
17514 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17515 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17516 			return;
17517 		}
17518 		if (pim_input(q, mp, ill) != 0) {
17519 			/* Bad packet - discarded by pim_input */
17520 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17521 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17522 			if (mctl_present)
17523 				freeb(first_mp);
17524 			return;
17525 		}
17526 
17527 		/*
17528 		 * pim_input() may have pulled up the message so ipha needs to
17529 		 * be reinitialized.
17530 		 */
17531 		ipha = (ipha_t *)mp->b_rptr;
17532 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17533 		    connf_head != NULL) {
17534 			/* No user-level listener for PIM packets */
17535 			goto drop_pkt;
17536 		}
17537 		/* deliver to local raw users */
17538 		break;
17539 	case IPPROTO_ENCAP:
17540 		/*
17541 		 * Handle self-encapsulated packets (IP-in-IP where
17542 		 * the inner addresses == the outer addresses).
17543 		 */
17544 		hdr_length = IPH_HDR_LENGTH(ipha);
17545 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17546 		    mp->b_wptr) {
17547 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17548 			    sizeof (ipha_t) - mp->b_rptr)) {
17549 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17550 				freemsg(first_mp);
17551 				return;
17552 			}
17553 			ipha = (ipha_t *)mp->b_rptr;
17554 		}
17555 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17556 		/*
17557 		 * Check the sanity of the inner IP header.
17558 		 */
17559 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17560 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17561 			freemsg(first_mp);
17562 			return;
17563 		}
17564 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17565 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17566 			freemsg(first_mp);
17567 			return;
17568 		}
17569 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17570 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17571 			ipsec_in_t *ii;
17572 
17573 			/*
17574 			 * Self-encapsulated tunnel packet. Remove
17575 			 * the outer IP header and fanout again.
17576 			 * We also need to make sure that the inner
17577 			 * header is pulled up until options.
17578 			 */
17579 			mp->b_rptr = (uchar_t *)inner_ipha;
17580 			ipha = inner_ipha;
17581 			hdr_length = IPH_HDR_LENGTH(ipha);
17582 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17583 				if (!pullupmsg(mp, (uchar_t *)ipha +
17584 				    + hdr_length - mp->b_rptr)) {
17585 					freemsg(first_mp);
17586 					return;
17587 				}
17588 				ipha = (ipha_t *)mp->b_rptr;
17589 			}
17590 			if (hdr_length > sizeof (ipha_t)) {
17591 				/* We got options on the inner packet. */
17592 				ipaddr_t dst = ipha->ipha_dst;
17593 
17594 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17595 				    -1) {
17596 					/* Bad options! */
17597 					return;
17598 				}
17599 				if (dst != ipha->ipha_dst) {
17600 					/*
17601 					 * Someone put a source-route in
17602 					 * the inside header of a self-
17603 					 * encapsulated packet.  Drop it
17604 					 * with extreme prejudice and let
17605 					 * the sender know.
17606 					 */
17607 					icmp_unreachable(q, first_mp,
17608 					    ICMP_SOURCE_ROUTE_FAILED,
17609 					    recv_ill->ill_zoneid, ipst);
17610 					return;
17611 				}
17612 			}
17613 			if (!mctl_present) {
17614 				ASSERT(first_mp == mp);
17615 				/*
17616 				 * This means that somebody is sending
17617 				 * Self-encapsualted packets without AH/ESP.
17618 				 * If AH/ESP was present, we would have already
17619 				 * allocated the first_mp.
17620 				 *
17621 				 * Send this packet to find a tunnel endpoint.
17622 				 * if I can't find one, an ICMP
17623 				 * PROTOCOL_UNREACHABLE will get sent.
17624 				 */
17625 				goto fanout;
17626 			}
17627 			/*
17628 			 * We generally store the ill_index if we need to
17629 			 * do IPsec processing as we lose the ill queue when
17630 			 * we come back. But in this case, we never should
17631 			 * have to store the ill_index here as it should have
17632 			 * been stored previously when we processed the
17633 			 * AH/ESP header in this routine or for non-ipsec
17634 			 * cases, we still have the queue. But for some bad
17635 			 * packets from the wire, we can get to IPsec after
17636 			 * this and we better store the index for that case.
17637 			 */
17638 			ill = (ill_t *)q->q_ptr;
17639 			ii = (ipsec_in_t *)first_mp->b_rptr;
17640 			ii->ipsec_in_ill_index =
17641 			    ill->ill_phyint->phyint_ifindex;
17642 			ii->ipsec_in_rill_index =
17643 			    recv_ill->ill_phyint->phyint_ifindex;
17644 			if (ii->ipsec_in_decaps) {
17645 				/*
17646 				 * This packet is self-encapsulated multiple
17647 				 * times. We don't want to recurse infinitely.
17648 				 * To keep it simple, drop the packet.
17649 				 */
17650 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17651 				freemsg(first_mp);
17652 				return;
17653 			}
17654 			ii->ipsec_in_decaps = B_TRUE;
17655 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17656 			    ire);
17657 			return;
17658 		}
17659 		break;
17660 	case IPPROTO_AH:
17661 	case IPPROTO_ESP: {
17662 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17663 
17664 		/*
17665 		 * Fast path for AH/ESP. If this is the first time
17666 		 * we are sending a datagram to AH/ESP, allocate
17667 		 * a IPSEC_IN message and prepend it. Otherwise,
17668 		 * just fanout.
17669 		 */
17670 
17671 		int ipsec_rc;
17672 		ipsec_in_t *ii;
17673 		netstack_t *ns = ipst->ips_netstack;
17674 
17675 		IP_STAT(ipst, ipsec_proto_ahesp);
17676 		if (!mctl_present) {
17677 			ASSERT(first_mp == mp);
17678 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17679 			if (first_mp == NULL) {
17680 				ip1dbg(("ip_proto_input: IPSEC_IN "
17681 				    "allocation failure.\n"));
17682 				freemsg(hada_mp); /* okay ifnull */
17683 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17684 				freemsg(mp);
17685 				return;
17686 			}
17687 			/*
17688 			 * Store the ill_index so that when we come back
17689 			 * from IPsec we ride on the same queue.
17690 			 */
17691 			ill = (ill_t *)q->q_ptr;
17692 			ii = (ipsec_in_t *)first_mp->b_rptr;
17693 			ii->ipsec_in_ill_index =
17694 			    ill->ill_phyint->phyint_ifindex;
17695 			ii->ipsec_in_rill_index =
17696 			    recv_ill->ill_phyint->phyint_ifindex;
17697 			first_mp->b_cont = mp;
17698 			/*
17699 			 * Cache hardware acceleration info.
17700 			 */
17701 			if (hada_mp != NULL) {
17702 				IPSECHW_DEBUG(IPSECHW_PKT,
17703 				    ("ip_rput_local: caching data attr.\n"));
17704 				ii->ipsec_in_accelerated = B_TRUE;
17705 				ii->ipsec_in_da = hada_mp;
17706 				hada_mp = NULL;
17707 			}
17708 		} else {
17709 			ii = (ipsec_in_t *)first_mp->b_rptr;
17710 		}
17711 
17712 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17713 
17714 		if (!ipsec_loaded(ipss)) {
17715 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17716 			    ire->ire_zoneid, ipst);
17717 			return;
17718 		}
17719 
17720 		ns = ipst->ips_netstack;
17721 		/* select inbound SA and have IPsec process the pkt */
17722 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17723 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17724 			boolean_t esp_in_udp_sa;
17725 			if (esph == NULL)
17726 				return;
17727 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17728 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17729 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17730 			    IPSA_F_NATT) != 0);
17731 			/*
17732 			 * The following is a fancy, but quick, way of saying:
17733 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17734 			 *    OR
17735 			 * ESP SA and ESP-in-UDP packet --> drop
17736 			 */
17737 			if (esp_in_udp_sa != esp_in_udp_packet) {
17738 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17739 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17740 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17741 				    &ns->netstack_ipsec->ipsec_dropper);
17742 				return;
17743 			}
17744 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17745 			    first_mp, esph);
17746 		} else {
17747 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17748 			if (ah == NULL)
17749 				return;
17750 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17751 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17752 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17753 			    first_mp, ah);
17754 		}
17755 
17756 		switch (ipsec_rc) {
17757 		case IPSEC_STATUS_SUCCESS:
17758 			break;
17759 		case IPSEC_STATUS_FAILED:
17760 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17761 			/* FALLTHRU */
17762 		case IPSEC_STATUS_PENDING:
17763 			return;
17764 		}
17765 		/* we're done with IPsec processing, send it up */
17766 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17767 		return;
17768 	}
17769 	default:
17770 		break;
17771 	}
17772 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17773 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17774 		    ire->ire_zoneid));
17775 		goto drop_pkt;
17776 	}
17777 	/*
17778 	 * Handle protocols with which IP is less intimate.  There
17779 	 * can be more than one stream bound to a particular
17780 	 * protocol.  When this is the case, each one gets a copy
17781 	 * of any incoming packets.
17782 	 */
17783 fanout:
17784 	ip_fanout_proto(q, first_mp, ill, ipha,
17785 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17786 	    B_TRUE, recv_ill, ire->ire_zoneid);
17787 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17788 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17789 	return;
17790 
17791 drop_pkt:
17792 	freemsg(first_mp);
17793 	if (hada_mp != NULL)
17794 		freeb(hada_mp);
17795 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17796 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17797 #undef	rptr
17798 #undef  iphs
17799 
17800 }
17801 
17802 /*
17803  * Update any source route, record route or timestamp options.
17804  * Check that we are at end of strict source route.
17805  * The options have already been checked for sanity in ip_rput_options().
17806  */
17807 static boolean_t
17808 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17809     ip_stack_t *ipst)
17810 {
17811 	ipoptp_t	opts;
17812 	uchar_t		*opt;
17813 	uint8_t		optval;
17814 	uint8_t		optlen;
17815 	ipaddr_t	dst;
17816 	uint32_t	ts;
17817 	ire_t		*dst_ire;
17818 	timestruc_t	now;
17819 	zoneid_t	zoneid;
17820 	ill_t		*ill;
17821 
17822 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17823 
17824 	ip2dbg(("ip_rput_local_options\n"));
17825 
17826 	for (optval = ipoptp_first(&opts, ipha);
17827 	    optval != IPOPT_EOL;
17828 	    optval = ipoptp_next(&opts)) {
17829 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17830 		opt = opts.ipoptp_cur;
17831 		optlen = opts.ipoptp_len;
17832 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17833 		    optval, optlen));
17834 		switch (optval) {
17835 			uint32_t off;
17836 		case IPOPT_SSRR:
17837 		case IPOPT_LSRR:
17838 			off = opt[IPOPT_OFFSET];
17839 			off--;
17840 			if (optlen < IP_ADDR_LEN ||
17841 			    off > optlen - IP_ADDR_LEN) {
17842 				/* End of source route */
17843 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17844 				break;
17845 			}
17846 			/*
17847 			 * This will only happen if two consecutive entries
17848 			 * in the source route contains our address or if
17849 			 * it is a packet with a loose source route which
17850 			 * reaches us before consuming the whole source route
17851 			 */
17852 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17853 			if (optval == IPOPT_SSRR) {
17854 				goto bad_src_route;
17855 			}
17856 			/*
17857 			 * Hack: instead of dropping the packet truncate the
17858 			 * source route to what has been used by filling the
17859 			 * rest with IPOPT_NOP.
17860 			 */
17861 			opt[IPOPT_OLEN] = (uint8_t)off;
17862 			while (off < optlen) {
17863 				opt[off++] = IPOPT_NOP;
17864 			}
17865 			break;
17866 		case IPOPT_RR:
17867 			off = opt[IPOPT_OFFSET];
17868 			off--;
17869 			if (optlen < IP_ADDR_LEN ||
17870 			    off > optlen - IP_ADDR_LEN) {
17871 				/* No more room - ignore */
17872 				ip1dbg((
17873 				    "ip_rput_local_options: end of RR\n"));
17874 				break;
17875 			}
17876 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17877 			    IP_ADDR_LEN);
17878 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17879 			break;
17880 		case IPOPT_TS:
17881 			/* Insert timestamp if there is romm */
17882 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17883 			case IPOPT_TS_TSONLY:
17884 				off = IPOPT_TS_TIMELEN;
17885 				break;
17886 			case IPOPT_TS_PRESPEC:
17887 			case IPOPT_TS_PRESPEC_RFC791:
17888 				/* Verify that the address matched */
17889 				off = opt[IPOPT_OFFSET] - 1;
17890 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17891 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17892 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17893 				    ipst);
17894 				if (dst_ire == NULL) {
17895 					/* Not for us */
17896 					break;
17897 				}
17898 				ire_refrele(dst_ire);
17899 				/* FALLTHRU */
17900 			case IPOPT_TS_TSANDADDR:
17901 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17902 				break;
17903 			default:
17904 				/*
17905 				 * ip_*put_options should have already
17906 				 * dropped this packet.
17907 				 */
17908 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17909 				    "unknown IT - bug in ip_rput_options?\n");
17910 				return (B_TRUE);	/* Keep "lint" happy */
17911 			}
17912 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17913 				/* Increase overflow counter */
17914 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17915 				opt[IPOPT_POS_OV_FLG] =
17916 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17917 				    (off << 4));
17918 				break;
17919 			}
17920 			off = opt[IPOPT_OFFSET] - 1;
17921 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17922 			case IPOPT_TS_PRESPEC:
17923 			case IPOPT_TS_PRESPEC_RFC791:
17924 			case IPOPT_TS_TSANDADDR:
17925 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17926 				    IP_ADDR_LEN);
17927 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17928 				/* FALLTHRU */
17929 			case IPOPT_TS_TSONLY:
17930 				off = opt[IPOPT_OFFSET] - 1;
17931 				/* Compute # of milliseconds since midnight */
17932 				gethrestime(&now);
17933 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17934 				    now.tv_nsec / (NANOSEC / MILLISEC);
17935 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17936 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17937 				break;
17938 			}
17939 			break;
17940 		}
17941 	}
17942 	return (B_TRUE);
17943 
17944 bad_src_route:
17945 	q = WR(q);
17946 	if (q->q_next != NULL)
17947 		ill = q->q_ptr;
17948 	else
17949 		ill = NULL;
17950 
17951 	/* make sure we clear any indication of a hardware checksum */
17952 	DB_CKSUMFLAGS(mp) = 0;
17953 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17954 	if (zoneid == ALL_ZONES)
17955 		freemsg(mp);
17956 	else
17957 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17958 	return (B_FALSE);
17959 
17960 }
17961 
17962 /*
17963  * Process IP options in an inbound packet.  If an option affects the
17964  * effective destination address, return the next hop address via dstp.
17965  * Returns -1 if something fails in which case an ICMP error has been sent
17966  * and mp freed.
17967  */
17968 static int
17969 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17970     ip_stack_t *ipst)
17971 {
17972 	ipoptp_t	opts;
17973 	uchar_t		*opt;
17974 	uint8_t		optval;
17975 	uint8_t		optlen;
17976 	ipaddr_t	dst;
17977 	intptr_t	code = 0;
17978 	ire_t		*ire = NULL;
17979 	zoneid_t	zoneid;
17980 	ill_t		*ill;
17981 
17982 	ip2dbg(("ip_rput_options\n"));
17983 	dst = ipha->ipha_dst;
17984 	for (optval = ipoptp_first(&opts, ipha);
17985 	    optval != IPOPT_EOL;
17986 	    optval = ipoptp_next(&opts)) {
17987 		opt = opts.ipoptp_cur;
17988 		optlen = opts.ipoptp_len;
17989 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17990 		    optval, optlen));
17991 		/*
17992 		 * Note: we need to verify the checksum before we
17993 		 * modify anything thus this routine only extracts the next
17994 		 * hop dst from any source route.
17995 		 */
17996 		switch (optval) {
17997 			uint32_t off;
17998 		case IPOPT_SSRR:
17999 		case IPOPT_LSRR:
18000 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18001 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18002 			if (ire == NULL) {
18003 				if (optval == IPOPT_SSRR) {
18004 					ip1dbg(("ip_rput_options: not next"
18005 					    " strict source route 0x%x\n",
18006 					    ntohl(dst)));
18007 					code = (char *)&ipha->ipha_dst -
18008 					    (char *)ipha;
18009 					goto param_prob; /* RouterReq's */
18010 				}
18011 				ip2dbg(("ip_rput_options: "
18012 				    "not next source route 0x%x\n",
18013 				    ntohl(dst)));
18014 				break;
18015 			}
18016 			ire_refrele(ire);
18017 
18018 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18019 				ip1dbg((
18020 				    "ip_rput_options: bad option offset\n"));
18021 				code = (char *)&opt[IPOPT_OLEN] -
18022 				    (char *)ipha;
18023 				goto param_prob;
18024 			}
18025 			off = opt[IPOPT_OFFSET];
18026 			off--;
18027 		redo_srr:
18028 			if (optlen < IP_ADDR_LEN ||
18029 			    off > optlen - IP_ADDR_LEN) {
18030 				/* End of source route */
18031 				ip1dbg(("ip_rput_options: end of SR\n"));
18032 				break;
18033 			}
18034 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18035 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18036 			    ntohl(dst)));
18037 
18038 			/*
18039 			 * Check if our address is present more than
18040 			 * once as consecutive hops in source route.
18041 			 * XXX verify per-interface ip_forwarding
18042 			 * for source route?
18043 			 */
18044 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18045 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18046 
18047 			if (ire != NULL) {
18048 				ire_refrele(ire);
18049 				off += IP_ADDR_LEN;
18050 				goto redo_srr;
18051 			}
18052 
18053 			if (dst == htonl(INADDR_LOOPBACK)) {
18054 				ip1dbg(("ip_rput_options: loopback addr in "
18055 				    "source route!\n"));
18056 				goto bad_src_route;
18057 			}
18058 			/*
18059 			 * For strict: verify that dst is directly
18060 			 * reachable.
18061 			 */
18062 			if (optval == IPOPT_SSRR) {
18063 				ire = ire_ftable_lookup(dst, 0, 0,
18064 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18065 				    msg_getlabel(mp),
18066 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18067 				if (ire == NULL) {
18068 					ip1dbg(("ip_rput_options: SSRR not "
18069 					    "directly reachable: 0x%x\n",
18070 					    ntohl(dst)));
18071 					goto bad_src_route;
18072 				}
18073 				ire_refrele(ire);
18074 			}
18075 			/*
18076 			 * Defer update of the offset and the record route
18077 			 * until the packet is forwarded.
18078 			 */
18079 			break;
18080 		case IPOPT_RR:
18081 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18082 				ip1dbg((
18083 				    "ip_rput_options: bad option offset\n"));
18084 				code = (char *)&opt[IPOPT_OLEN] -
18085 				    (char *)ipha;
18086 				goto param_prob;
18087 			}
18088 			break;
18089 		case IPOPT_TS:
18090 			/*
18091 			 * Verify that length >= 5 and that there is either
18092 			 * room for another timestamp or that the overflow
18093 			 * counter is not maxed out.
18094 			 */
18095 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18096 			if (optlen < IPOPT_MINLEN_IT) {
18097 				goto param_prob;
18098 			}
18099 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18100 				ip1dbg((
18101 				    "ip_rput_options: bad option offset\n"));
18102 				code = (char *)&opt[IPOPT_OFFSET] -
18103 				    (char *)ipha;
18104 				goto param_prob;
18105 			}
18106 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18107 			case IPOPT_TS_TSONLY:
18108 				off = IPOPT_TS_TIMELEN;
18109 				break;
18110 			case IPOPT_TS_TSANDADDR:
18111 			case IPOPT_TS_PRESPEC:
18112 			case IPOPT_TS_PRESPEC_RFC791:
18113 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18114 				break;
18115 			default:
18116 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18117 				    (char *)ipha;
18118 				goto param_prob;
18119 			}
18120 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18121 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18122 				/*
18123 				 * No room and the overflow counter is 15
18124 				 * already.
18125 				 */
18126 				goto param_prob;
18127 			}
18128 			break;
18129 		}
18130 	}
18131 
18132 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18133 		*dstp = dst;
18134 		return (0);
18135 	}
18136 
18137 	ip1dbg(("ip_rput_options: error processing IP options."));
18138 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18139 
18140 param_prob:
18141 	q = WR(q);
18142 	if (q->q_next != NULL)
18143 		ill = q->q_ptr;
18144 	else
18145 		ill = NULL;
18146 
18147 	/* make sure we clear any indication of a hardware checksum */
18148 	DB_CKSUMFLAGS(mp) = 0;
18149 	/* Don't know whether this is for non-global or global/forwarding */
18150 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18151 	if (zoneid == ALL_ZONES)
18152 		freemsg(mp);
18153 	else
18154 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18155 	return (-1);
18156 
18157 bad_src_route:
18158 	q = WR(q);
18159 	if (q->q_next != NULL)
18160 		ill = q->q_ptr;
18161 	else
18162 		ill = NULL;
18163 
18164 	/* make sure we clear any indication of a hardware checksum */
18165 	DB_CKSUMFLAGS(mp) = 0;
18166 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18167 	if (zoneid == ALL_ZONES)
18168 		freemsg(mp);
18169 	else
18170 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18171 	return (-1);
18172 }
18173 
18174 /*
18175  * IP & ICMP info in >=14 msg's ...
18176  *  - ip fixed part (mib2_ip_t)
18177  *  - icmp fixed part (mib2_icmp_t)
18178  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18179  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18180  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18181  *  - ipRouteAttributeTable (ip 102)	labeled routes
18182  *  - ip multicast membership (ip_member_t)
18183  *  - ip multicast source filtering (ip_grpsrc_t)
18184  *  - igmp fixed part (struct igmpstat)
18185  *  - multicast routing stats (struct mrtstat)
18186  *  - multicast routing vifs (array of struct vifctl)
18187  *  - multicast routing routes (array of struct mfcctl)
18188  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18189  *					One per ill plus one generic
18190  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18191  *					One per ill plus one generic
18192  *  - ipv6RouteEntry			all IPv6 IREs
18193  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18194  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18195  *  - ipv6AddrEntry			all IPv6 ipifs
18196  *  - ipv6 multicast membership (ipv6_member_t)
18197  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18198  *
18199  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18200  *
18201  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18202  * already filled in by the caller.
18203  * Return value of 0 indicates that no messages were sent and caller
18204  * should free mpctl.
18205  */
18206 int
18207 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18208 {
18209 	ip_stack_t *ipst;
18210 	sctp_stack_t *sctps;
18211 
18212 	if (q->q_next != NULL) {
18213 		ipst = ILLQ_TO_IPST(q);
18214 	} else {
18215 		ipst = CONNQ_TO_IPST(q);
18216 	}
18217 	ASSERT(ipst != NULL);
18218 	sctps = ipst->ips_netstack->netstack_sctp;
18219 
18220 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18221 		return (0);
18222 	}
18223 
18224 	/*
18225 	 * For the purposes of the (broken) packet shell use
18226 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18227 	 * to make TCP and UDP appear first in the list of mib items.
18228 	 * TBD: We could expand this and use it in netstat so that
18229 	 * the kernel doesn't have to produce large tables (connections,
18230 	 * routes, etc) when netstat only wants the statistics or a particular
18231 	 * table.
18232 	 */
18233 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18234 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18235 			return (1);
18236 		}
18237 	}
18238 
18239 	if (level != MIB2_TCP) {
18240 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18241 			return (1);
18242 		}
18243 	}
18244 
18245 	if (level != MIB2_UDP) {
18246 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18247 			return (1);
18248 		}
18249 	}
18250 
18251 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18252 	    ipst)) == NULL) {
18253 		return (1);
18254 	}
18255 
18256 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18257 		return (1);
18258 	}
18259 
18260 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18261 		return (1);
18262 	}
18263 
18264 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18265 		return (1);
18266 	}
18267 
18268 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18269 		return (1);
18270 	}
18271 
18272 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18273 		return (1);
18274 	}
18275 
18276 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18277 		return (1);
18278 	}
18279 
18280 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18281 		return (1);
18282 	}
18283 
18284 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18285 		return (1);
18286 	}
18287 
18288 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18289 		return (1);
18290 	}
18291 
18292 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18293 		return (1);
18294 	}
18295 
18296 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18297 		return (1);
18298 	}
18299 
18300 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18301 		return (1);
18302 	}
18303 
18304 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18305 		return (1);
18306 	}
18307 
18308 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18309 	if (mpctl == NULL)
18310 		return (1);
18311 
18312 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18313 	if (mpctl == NULL)
18314 		return (1);
18315 
18316 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18317 		return (1);
18318 	}
18319 	freemsg(mpctl);
18320 	return (1);
18321 }
18322 
18323 /* Get global (legacy) IPv4 statistics */
18324 static mblk_t *
18325 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18326     ip_stack_t *ipst)
18327 {
18328 	mib2_ip_t		old_ip_mib;
18329 	struct opthdr		*optp;
18330 	mblk_t			*mp2ctl;
18331 
18332 	/*
18333 	 * make a copy of the original message
18334 	 */
18335 	mp2ctl = copymsg(mpctl);
18336 
18337 	/* fixed length IP structure... */
18338 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18339 	optp->level = MIB2_IP;
18340 	optp->name = 0;
18341 	SET_MIB(old_ip_mib.ipForwarding,
18342 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18343 	SET_MIB(old_ip_mib.ipDefaultTTL,
18344 	    (uint32_t)ipst->ips_ip_def_ttl);
18345 	SET_MIB(old_ip_mib.ipReasmTimeout,
18346 	    ipst->ips_ip_g_frag_timeout);
18347 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18348 	    sizeof (mib2_ipAddrEntry_t));
18349 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18350 	    sizeof (mib2_ipRouteEntry_t));
18351 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18352 	    sizeof (mib2_ipNetToMediaEntry_t));
18353 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18354 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18355 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18356 	    sizeof (mib2_ipAttributeEntry_t));
18357 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18358 
18359 	/*
18360 	 * Grab the statistics from the new IP MIB
18361 	 */
18362 	SET_MIB(old_ip_mib.ipInReceives,
18363 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18364 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18365 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18366 	SET_MIB(old_ip_mib.ipForwDatagrams,
18367 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18368 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18369 	    ipmib->ipIfStatsInUnknownProtos);
18370 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18371 	SET_MIB(old_ip_mib.ipInDelivers,
18372 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18373 	SET_MIB(old_ip_mib.ipOutRequests,
18374 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18375 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18376 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18377 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18378 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18379 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18380 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18381 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18382 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18383 
18384 	/* ipRoutingDiscards is not being used */
18385 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18386 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18387 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18388 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18389 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18390 	    ipmib->ipIfStatsReasmDuplicates);
18391 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18392 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18393 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18394 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18395 	SET_MIB(old_ip_mib.rawipInOverflows,
18396 	    ipmib->rawipIfStatsInOverflows);
18397 
18398 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18399 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18400 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18401 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18402 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18403 	    ipmib->ipIfStatsOutSwitchIPVersion);
18404 
18405 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18406 	    (int)sizeof (old_ip_mib))) {
18407 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18408 		    (uint_t)sizeof (old_ip_mib)));
18409 	}
18410 
18411 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18412 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18413 	    (int)optp->level, (int)optp->name, (int)optp->len));
18414 	qreply(q, mpctl);
18415 	return (mp2ctl);
18416 }
18417 
18418 /* Per interface IPv4 statistics */
18419 static mblk_t *
18420 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18421 {
18422 	struct opthdr		*optp;
18423 	mblk_t			*mp2ctl;
18424 	ill_t			*ill;
18425 	ill_walk_context_t	ctx;
18426 	mblk_t			*mp_tail = NULL;
18427 	mib2_ipIfStatsEntry_t	global_ip_mib;
18428 
18429 	/*
18430 	 * Make a copy of the original message
18431 	 */
18432 	mp2ctl = copymsg(mpctl);
18433 
18434 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18435 	optp->level = MIB2_IP;
18436 	optp->name = MIB2_IP_TRAFFIC_STATS;
18437 	/* Include "unknown interface" ip_mib */
18438 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18439 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18440 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18441 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18442 	    (ipst->ips_ip_g_forward ? 1 : 2));
18443 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18444 	    (uint32_t)ipst->ips_ip_def_ttl);
18445 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18446 	    sizeof (mib2_ipIfStatsEntry_t));
18447 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18448 	    sizeof (mib2_ipAddrEntry_t));
18449 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18450 	    sizeof (mib2_ipRouteEntry_t));
18451 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18452 	    sizeof (mib2_ipNetToMediaEntry_t));
18453 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18454 	    sizeof (ip_member_t));
18455 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18456 	    sizeof (ip_grpsrc_t));
18457 
18458 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18459 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18460 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18461 		    "failed to allocate %u bytes\n",
18462 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18463 	}
18464 
18465 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18466 
18467 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18468 	ill = ILL_START_WALK_V4(&ctx, ipst);
18469 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18470 		ill->ill_ip_mib->ipIfStatsIfIndex =
18471 		    ill->ill_phyint->phyint_ifindex;
18472 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18473 		    (ipst->ips_ip_g_forward ? 1 : 2));
18474 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18475 		    (uint32_t)ipst->ips_ip_def_ttl);
18476 
18477 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18478 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18479 		    (char *)ill->ill_ip_mib,
18480 		    (int)sizeof (*ill->ill_ip_mib))) {
18481 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18482 			    "failed to allocate %u bytes\n",
18483 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18484 		}
18485 	}
18486 	rw_exit(&ipst->ips_ill_g_lock);
18487 
18488 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18489 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18490 	    "level %d, name %d, len %d\n",
18491 	    (int)optp->level, (int)optp->name, (int)optp->len));
18492 	qreply(q, mpctl);
18493 
18494 	if (mp2ctl == NULL)
18495 		return (NULL);
18496 
18497 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18498 }
18499 
18500 /* Global IPv4 ICMP statistics */
18501 static mblk_t *
18502 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18503 {
18504 	struct opthdr		*optp;
18505 	mblk_t			*mp2ctl;
18506 
18507 	/*
18508 	 * Make a copy of the original message
18509 	 */
18510 	mp2ctl = copymsg(mpctl);
18511 
18512 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18513 	optp->level = MIB2_ICMP;
18514 	optp->name = 0;
18515 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18516 	    (int)sizeof (ipst->ips_icmp_mib))) {
18517 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18518 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18519 	}
18520 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18521 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18522 	    (int)optp->level, (int)optp->name, (int)optp->len));
18523 	qreply(q, mpctl);
18524 	return (mp2ctl);
18525 }
18526 
18527 /* Global IPv4 IGMP statistics */
18528 static mblk_t *
18529 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18530 {
18531 	struct opthdr		*optp;
18532 	mblk_t			*mp2ctl;
18533 
18534 	/*
18535 	 * make a copy of the original message
18536 	 */
18537 	mp2ctl = copymsg(mpctl);
18538 
18539 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18540 	optp->level = EXPER_IGMP;
18541 	optp->name = 0;
18542 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18543 	    (int)sizeof (ipst->ips_igmpstat))) {
18544 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18545 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18546 	}
18547 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18548 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18549 	    (int)optp->level, (int)optp->name, (int)optp->len));
18550 	qreply(q, mpctl);
18551 	return (mp2ctl);
18552 }
18553 
18554 /* Global IPv4 Multicast Routing statistics */
18555 static mblk_t *
18556 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18557 {
18558 	struct opthdr		*optp;
18559 	mblk_t			*mp2ctl;
18560 
18561 	/*
18562 	 * make a copy of the original message
18563 	 */
18564 	mp2ctl = copymsg(mpctl);
18565 
18566 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18567 	optp->level = EXPER_DVMRP;
18568 	optp->name = 0;
18569 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18570 		ip0dbg(("ip_mroute_stats: failed\n"));
18571 	}
18572 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18573 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18574 	    (int)optp->level, (int)optp->name, (int)optp->len));
18575 	qreply(q, mpctl);
18576 	return (mp2ctl);
18577 }
18578 
18579 /* IPv4 address information */
18580 static mblk_t *
18581 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18582 {
18583 	struct opthdr		*optp;
18584 	mblk_t			*mp2ctl;
18585 	mblk_t			*mp_tail = NULL;
18586 	ill_t			*ill;
18587 	ipif_t			*ipif;
18588 	uint_t			bitval;
18589 	mib2_ipAddrEntry_t	mae;
18590 	zoneid_t		zoneid;
18591 	ill_walk_context_t ctx;
18592 
18593 	/*
18594 	 * make a copy of the original message
18595 	 */
18596 	mp2ctl = copymsg(mpctl);
18597 
18598 	/* ipAddrEntryTable */
18599 
18600 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18601 	optp->level = MIB2_IP;
18602 	optp->name = MIB2_IP_ADDR;
18603 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18604 
18605 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18606 	ill = ILL_START_WALK_V4(&ctx, ipst);
18607 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18608 		for (ipif = ill->ill_ipif; ipif != NULL;
18609 		    ipif = ipif->ipif_next) {
18610 			if (ipif->ipif_zoneid != zoneid &&
18611 			    ipif->ipif_zoneid != ALL_ZONES)
18612 				continue;
18613 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18614 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18615 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18616 
18617 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18618 			    OCTET_LENGTH);
18619 			mae.ipAdEntIfIndex.o_length =
18620 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18621 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18622 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18623 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18624 			mae.ipAdEntInfo.ae_subnet_len =
18625 			    ip_mask_to_plen(ipif->ipif_net_mask);
18626 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18627 			for (bitval = 1;
18628 			    bitval &&
18629 			    !(bitval & ipif->ipif_brd_addr);
18630 			    bitval <<= 1)
18631 				noop;
18632 			mae.ipAdEntBcastAddr = bitval;
18633 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18634 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18635 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18636 			mae.ipAdEntInfo.ae_broadcast_addr =
18637 			    ipif->ipif_brd_addr;
18638 			mae.ipAdEntInfo.ae_pp_dst_addr =
18639 			    ipif->ipif_pp_dst_addr;
18640 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18641 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18642 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18643 
18644 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18645 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18646 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18647 				    "allocate %u bytes\n",
18648 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18649 			}
18650 		}
18651 	}
18652 	rw_exit(&ipst->ips_ill_g_lock);
18653 
18654 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18655 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18656 	    (int)optp->level, (int)optp->name, (int)optp->len));
18657 	qreply(q, mpctl);
18658 	return (mp2ctl);
18659 }
18660 
18661 /* IPv6 address information */
18662 static mblk_t *
18663 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18664 {
18665 	struct opthdr		*optp;
18666 	mblk_t			*mp2ctl;
18667 	mblk_t			*mp_tail = NULL;
18668 	ill_t			*ill;
18669 	ipif_t			*ipif;
18670 	mib2_ipv6AddrEntry_t	mae6;
18671 	zoneid_t		zoneid;
18672 	ill_walk_context_t	ctx;
18673 
18674 	/*
18675 	 * make a copy of the original message
18676 	 */
18677 	mp2ctl = copymsg(mpctl);
18678 
18679 	/* ipv6AddrEntryTable */
18680 
18681 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18682 	optp->level = MIB2_IP6;
18683 	optp->name = MIB2_IP6_ADDR;
18684 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18685 
18686 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18687 	ill = ILL_START_WALK_V6(&ctx, ipst);
18688 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18689 		for (ipif = ill->ill_ipif; ipif != NULL;
18690 		    ipif = ipif->ipif_next) {
18691 			if (ipif->ipif_zoneid != zoneid &&
18692 			    ipif->ipif_zoneid != ALL_ZONES)
18693 				continue;
18694 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18695 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18696 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18697 
18698 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18699 			    OCTET_LENGTH);
18700 			mae6.ipv6AddrIfIndex.o_length =
18701 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18702 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18703 			mae6.ipv6AddrPfxLength =
18704 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18705 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18706 			mae6.ipv6AddrInfo.ae_subnet_len =
18707 			    mae6.ipv6AddrPfxLength;
18708 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18709 
18710 			/* Type: stateless(1), stateful(2), unknown(3) */
18711 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18712 				mae6.ipv6AddrType = 1;
18713 			else
18714 				mae6.ipv6AddrType = 2;
18715 			/* Anycast: true(1), false(2) */
18716 			if (ipif->ipif_flags & IPIF_ANYCAST)
18717 				mae6.ipv6AddrAnycastFlag = 1;
18718 			else
18719 				mae6.ipv6AddrAnycastFlag = 2;
18720 
18721 			/*
18722 			 * Address status: preferred(1), deprecated(2),
18723 			 * invalid(3), inaccessible(4), unknown(5)
18724 			 */
18725 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18726 				mae6.ipv6AddrStatus = 3;
18727 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18728 				mae6.ipv6AddrStatus = 2;
18729 			else
18730 				mae6.ipv6AddrStatus = 1;
18731 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18732 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18733 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18734 			    ipif->ipif_v6pp_dst_addr;
18735 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18736 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18737 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18738 			mae6.ipv6AddrIdentifier = ill->ill_token;
18739 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18740 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18741 			mae6.ipv6AddrRetransmitTime =
18742 			    ill->ill_reachable_retrans_time;
18743 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18744 			    (char *)&mae6,
18745 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18746 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18747 				    "allocate %u bytes\n",
18748 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18749 			}
18750 		}
18751 	}
18752 	rw_exit(&ipst->ips_ill_g_lock);
18753 
18754 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18755 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18756 	    (int)optp->level, (int)optp->name, (int)optp->len));
18757 	qreply(q, mpctl);
18758 	return (mp2ctl);
18759 }
18760 
18761 /* IPv4 multicast group membership. */
18762 static mblk_t *
18763 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18764 {
18765 	struct opthdr		*optp;
18766 	mblk_t			*mp2ctl;
18767 	ill_t			*ill;
18768 	ipif_t			*ipif;
18769 	ilm_t			*ilm;
18770 	ip_member_t		ipm;
18771 	mblk_t			*mp_tail = NULL;
18772 	ill_walk_context_t	ctx;
18773 	zoneid_t		zoneid;
18774 	ilm_walker_t		ilw;
18775 
18776 	/*
18777 	 * make a copy of the original message
18778 	 */
18779 	mp2ctl = copymsg(mpctl);
18780 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18781 
18782 	/* ipGroupMember table */
18783 	optp = (struct opthdr *)&mpctl->b_rptr[
18784 	    sizeof (struct T_optmgmt_ack)];
18785 	optp->level = MIB2_IP;
18786 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18787 
18788 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18789 	ill = ILL_START_WALK_V4(&ctx, ipst);
18790 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18791 		if (IS_UNDER_IPMP(ill))
18792 			continue;
18793 
18794 		ilm = ilm_walker_start(&ilw, ill);
18795 		for (ipif = ill->ill_ipif; ipif != NULL;
18796 		    ipif = ipif->ipif_next) {
18797 			if (ipif->ipif_zoneid != zoneid &&
18798 			    ipif->ipif_zoneid != ALL_ZONES)
18799 				continue;	/* not this zone */
18800 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18801 			    OCTET_LENGTH);
18802 			ipm.ipGroupMemberIfIndex.o_length =
18803 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18804 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18805 				ASSERT(ilm->ilm_ipif != NULL);
18806 				ASSERT(ilm->ilm_ill == NULL);
18807 				if (ilm->ilm_ipif != ipif)
18808 					continue;
18809 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18810 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18811 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18812 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18813 				    (char *)&ipm, (int)sizeof (ipm))) {
18814 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18815 					    "failed to allocate %u bytes\n",
18816 					    (uint_t)sizeof (ipm)));
18817 				}
18818 			}
18819 		}
18820 		ilm_walker_finish(&ilw);
18821 	}
18822 	rw_exit(&ipst->ips_ill_g_lock);
18823 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18824 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18825 	    (int)optp->level, (int)optp->name, (int)optp->len));
18826 	qreply(q, mpctl);
18827 	return (mp2ctl);
18828 }
18829 
18830 /* IPv6 multicast group membership. */
18831 static mblk_t *
18832 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18833 {
18834 	struct opthdr		*optp;
18835 	mblk_t			*mp2ctl;
18836 	ill_t			*ill;
18837 	ilm_t			*ilm;
18838 	ipv6_member_t		ipm6;
18839 	mblk_t			*mp_tail = NULL;
18840 	ill_walk_context_t	ctx;
18841 	zoneid_t		zoneid;
18842 	ilm_walker_t		ilw;
18843 
18844 	/*
18845 	 * make a copy of the original message
18846 	 */
18847 	mp2ctl = copymsg(mpctl);
18848 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18849 
18850 	/* ip6GroupMember table */
18851 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18852 	optp->level = MIB2_IP6;
18853 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18854 
18855 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18856 	ill = ILL_START_WALK_V6(&ctx, ipst);
18857 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18858 		if (IS_UNDER_IPMP(ill))
18859 			continue;
18860 
18861 		ilm = ilm_walker_start(&ilw, ill);
18862 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18863 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18864 			ASSERT(ilm->ilm_ipif == NULL);
18865 			ASSERT(ilm->ilm_ill != NULL);
18866 			if (ilm->ilm_zoneid != zoneid)
18867 				continue;	/* not this zone */
18868 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18869 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18870 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18871 			if (!snmp_append_data2(mpctl->b_cont,
18872 			    &mp_tail,
18873 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18874 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18875 				    "failed to allocate %u bytes\n",
18876 				    (uint_t)sizeof (ipm6)));
18877 			}
18878 		}
18879 		ilm_walker_finish(&ilw);
18880 	}
18881 	rw_exit(&ipst->ips_ill_g_lock);
18882 
18883 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18884 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18885 	    (int)optp->level, (int)optp->name, (int)optp->len));
18886 	qreply(q, mpctl);
18887 	return (mp2ctl);
18888 }
18889 
18890 /* IP multicast filtered sources */
18891 static mblk_t *
18892 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18893 {
18894 	struct opthdr		*optp;
18895 	mblk_t			*mp2ctl;
18896 	ill_t			*ill;
18897 	ipif_t			*ipif;
18898 	ilm_t			*ilm;
18899 	ip_grpsrc_t		ips;
18900 	mblk_t			*mp_tail = NULL;
18901 	ill_walk_context_t	ctx;
18902 	zoneid_t		zoneid;
18903 	int			i;
18904 	slist_t			*sl;
18905 	ilm_walker_t		ilw;
18906 
18907 	/*
18908 	 * make a copy of the original message
18909 	 */
18910 	mp2ctl = copymsg(mpctl);
18911 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18912 
18913 	/* ipGroupSource table */
18914 	optp = (struct opthdr *)&mpctl->b_rptr[
18915 	    sizeof (struct T_optmgmt_ack)];
18916 	optp->level = MIB2_IP;
18917 	optp->name = EXPER_IP_GROUP_SOURCES;
18918 
18919 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18920 	ill = ILL_START_WALK_V4(&ctx, ipst);
18921 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18922 		if (IS_UNDER_IPMP(ill))
18923 			continue;
18924 
18925 		ilm = ilm_walker_start(&ilw, ill);
18926 		for (ipif = ill->ill_ipif; ipif != NULL;
18927 		    ipif = ipif->ipif_next) {
18928 			if (ipif->ipif_zoneid != zoneid)
18929 				continue;	/* not this zone */
18930 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18931 			    OCTET_LENGTH);
18932 			ips.ipGroupSourceIfIndex.o_length =
18933 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18934 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18935 				ASSERT(ilm->ilm_ipif != NULL);
18936 				ASSERT(ilm->ilm_ill == NULL);
18937 				sl = ilm->ilm_filter;
18938 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18939 					continue;
18940 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18941 				for (i = 0; i < sl->sl_numsrc; i++) {
18942 					if (!IN6_IS_ADDR_V4MAPPED(
18943 					    &sl->sl_addr[i]))
18944 						continue;
18945 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18946 					    ips.ipGroupSourceAddress);
18947 					if (snmp_append_data2(mpctl->b_cont,
18948 					    &mp_tail, (char *)&ips,
18949 					    (int)sizeof (ips)) == 0) {
18950 						ip1dbg(("ip_snmp_get_mib2_"
18951 						    "ip_group_src: failed to "
18952 						    "allocate %u bytes\n",
18953 						    (uint_t)sizeof (ips)));
18954 					}
18955 				}
18956 			}
18957 		}
18958 		ilm_walker_finish(&ilw);
18959 	}
18960 	rw_exit(&ipst->ips_ill_g_lock);
18961 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18962 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18963 	    (int)optp->level, (int)optp->name, (int)optp->len));
18964 	qreply(q, mpctl);
18965 	return (mp2ctl);
18966 }
18967 
18968 /* IPv6 multicast filtered sources. */
18969 static mblk_t *
18970 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18971 {
18972 	struct opthdr		*optp;
18973 	mblk_t			*mp2ctl;
18974 	ill_t			*ill;
18975 	ilm_t			*ilm;
18976 	ipv6_grpsrc_t		ips6;
18977 	mblk_t			*mp_tail = NULL;
18978 	ill_walk_context_t	ctx;
18979 	zoneid_t		zoneid;
18980 	int			i;
18981 	slist_t			*sl;
18982 	ilm_walker_t		ilw;
18983 
18984 	/*
18985 	 * make a copy of the original message
18986 	 */
18987 	mp2ctl = copymsg(mpctl);
18988 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18989 
18990 	/* ip6GroupMember table */
18991 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18992 	optp->level = MIB2_IP6;
18993 	optp->name = EXPER_IP6_GROUP_SOURCES;
18994 
18995 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18996 	ill = ILL_START_WALK_V6(&ctx, ipst);
18997 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18998 		if (IS_UNDER_IPMP(ill))
18999 			continue;
19000 
19001 		ilm = ilm_walker_start(&ilw, ill);
19002 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19003 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19004 			ASSERT(ilm->ilm_ipif == NULL);
19005 			ASSERT(ilm->ilm_ill != NULL);
19006 			sl = ilm->ilm_filter;
19007 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19008 				continue;
19009 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19010 			for (i = 0; i < sl->sl_numsrc; i++) {
19011 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19012 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19013 				    (char *)&ips6, (int)sizeof (ips6))) {
19014 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19015 					    "group_src: failed to allocate "
19016 					    "%u bytes\n",
19017 					    (uint_t)sizeof (ips6)));
19018 				}
19019 			}
19020 		}
19021 		ilm_walker_finish(&ilw);
19022 	}
19023 	rw_exit(&ipst->ips_ill_g_lock);
19024 
19025 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19026 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19027 	    (int)optp->level, (int)optp->name, (int)optp->len));
19028 	qreply(q, mpctl);
19029 	return (mp2ctl);
19030 }
19031 
19032 /* Multicast routing virtual interface table. */
19033 static mblk_t *
19034 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19035 {
19036 	struct opthdr		*optp;
19037 	mblk_t			*mp2ctl;
19038 
19039 	/*
19040 	 * make a copy of the original message
19041 	 */
19042 	mp2ctl = copymsg(mpctl);
19043 
19044 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19045 	optp->level = EXPER_DVMRP;
19046 	optp->name = EXPER_DVMRP_VIF;
19047 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19048 		ip0dbg(("ip_mroute_vif: failed\n"));
19049 	}
19050 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19051 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19052 	    (int)optp->level, (int)optp->name, (int)optp->len));
19053 	qreply(q, mpctl);
19054 	return (mp2ctl);
19055 }
19056 
19057 /* Multicast routing table. */
19058 static mblk_t *
19059 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19060 {
19061 	struct opthdr		*optp;
19062 	mblk_t			*mp2ctl;
19063 
19064 	/*
19065 	 * make a copy of the original message
19066 	 */
19067 	mp2ctl = copymsg(mpctl);
19068 
19069 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19070 	optp->level = EXPER_DVMRP;
19071 	optp->name = EXPER_DVMRP_MRT;
19072 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19073 		ip0dbg(("ip_mroute_mrt: failed\n"));
19074 	}
19075 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19076 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19077 	    (int)optp->level, (int)optp->name, (int)optp->len));
19078 	qreply(q, mpctl);
19079 	return (mp2ctl);
19080 }
19081 
19082 /*
19083  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19084  * in one IRE walk.
19085  */
19086 static mblk_t *
19087 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19088     ip_stack_t *ipst)
19089 {
19090 	struct opthdr	*optp;
19091 	mblk_t		*mp2ctl;	/* Returned */
19092 	mblk_t		*mp3ctl;	/* nettomedia */
19093 	mblk_t		*mp4ctl;	/* routeattrs */
19094 	iproutedata_t	ird;
19095 	zoneid_t	zoneid;
19096 
19097 	/*
19098 	 * make copies of the original message
19099 	 *	- mp2ctl is returned unchanged to the caller for his use
19100 	 *	- mpctl is sent upstream as ipRouteEntryTable
19101 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19102 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19103 	 */
19104 	mp2ctl = copymsg(mpctl);
19105 	mp3ctl = copymsg(mpctl);
19106 	mp4ctl = copymsg(mpctl);
19107 	if (mp3ctl == NULL || mp4ctl == NULL) {
19108 		freemsg(mp4ctl);
19109 		freemsg(mp3ctl);
19110 		freemsg(mp2ctl);
19111 		freemsg(mpctl);
19112 		return (NULL);
19113 	}
19114 
19115 	bzero(&ird, sizeof (ird));
19116 
19117 	ird.ird_route.lp_head = mpctl->b_cont;
19118 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19119 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19120 	/*
19121 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19122 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19123 	 * intended a temporary solution until a proper MIB API is provided
19124 	 * that provides complete filtering/caller-opt-in.
19125 	 */
19126 	if (level == EXPER_IP_AND_TESTHIDDEN)
19127 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19128 
19129 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19130 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19131 
19132 	/* ipRouteEntryTable in mpctl */
19133 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19134 	optp->level = MIB2_IP;
19135 	optp->name = MIB2_IP_ROUTE;
19136 	optp->len = msgdsize(ird.ird_route.lp_head);
19137 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19138 	    (int)optp->level, (int)optp->name, (int)optp->len));
19139 	qreply(q, mpctl);
19140 
19141 	/* ipNetToMediaEntryTable in mp3ctl */
19142 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19143 	optp->level = MIB2_IP;
19144 	optp->name = MIB2_IP_MEDIA;
19145 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19146 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19147 	    (int)optp->level, (int)optp->name, (int)optp->len));
19148 	qreply(q, mp3ctl);
19149 
19150 	/* ipRouteAttributeTable in mp4ctl */
19151 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19152 	optp->level = MIB2_IP;
19153 	optp->name = EXPER_IP_RTATTR;
19154 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19155 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19156 	    (int)optp->level, (int)optp->name, (int)optp->len));
19157 	if (optp->len == 0)
19158 		freemsg(mp4ctl);
19159 	else
19160 		qreply(q, mp4ctl);
19161 
19162 	return (mp2ctl);
19163 }
19164 
19165 /*
19166  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19167  * ipv6NetToMediaEntryTable in an NDP walk.
19168  */
19169 static mblk_t *
19170 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19171     ip_stack_t *ipst)
19172 {
19173 	struct opthdr	*optp;
19174 	mblk_t		*mp2ctl;	/* Returned */
19175 	mblk_t		*mp3ctl;	/* nettomedia */
19176 	mblk_t		*mp4ctl;	/* routeattrs */
19177 	iproutedata_t	ird;
19178 	zoneid_t	zoneid;
19179 
19180 	/*
19181 	 * make copies of the original message
19182 	 *	- mp2ctl is returned unchanged to the caller for his use
19183 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19184 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19185 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19186 	 */
19187 	mp2ctl = copymsg(mpctl);
19188 	mp3ctl = copymsg(mpctl);
19189 	mp4ctl = copymsg(mpctl);
19190 	if (mp3ctl == NULL || mp4ctl == NULL) {
19191 		freemsg(mp4ctl);
19192 		freemsg(mp3ctl);
19193 		freemsg(mp2ctl);
19194 		freemsg(mpctl);
19195 		return (NULL);
19196 	}
19197 
19198 	bzero(&ird, sizeof (ird));
19199 
19200 	ird.ird_route.lp_head = mpctl->b_cont;
19201 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19202 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19203 	/*
19204 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19205 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19206 	 * intended a temporary solution until a proper MIB API is provided
19207 	 * that provides complete filtering/caller-opt-in.
19208 	 */
19209 	if (level == EXPER_IP_AND_TESTHIDDEN)
19210 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19211 
19212 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19213 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19214 
19215 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19216 	optp->level = MIB2_IP6;
19217 	optp->name = MIB2_IP6_ROUTE;
19218 	optp->len = msgdsize(ird.ird_route.lp_head);
19219 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19220 	    (int)optp->level, (int)optp->name, (int)optp->len));
19221 	qreply(q, mpctl);
19222 
19223 	/* ipv6NetToMediaEntryTable in mp3ctl */
19224 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19225 
19226 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19227 	optp->level = MIB2_IP6;
19228 	optp->name = MIB2_IP6_MEDIA;
19229 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19230 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19231 	    (int)optp->level, (int)optp->name, (int)optp->len));
19232 	qreply(q, mp3ctl);
19233 
19234 	/* ipv6RouteAttributeTable in mp4ctl */
19235 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19236 	optp->level = MIB2_IP6;
19237 	optp->name = EXPER_IP_RTATTR;
19238 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19239 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19240 	    (int)optp->level, (int)optp->name, (int)optp->len));
19241 	if (optp->len == 0)
19242 		freemsg(mp4ctl);
19243 	else
19244 		qreply(q, mp4ctl);
19245 
19246 	return (mp2ctl);
19247 }
19248 
19249 /*
19250  * IPv6 mib: One per ill
19251  */
19252 static mblk_t *
19253 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19254 {
19255 	struct opthdr		*optp;
19256 	mblk_t			*mp2ctl;
19257 	ill_t			*ill;
19258 	ill_walk_context_t	ctx;
19259 	mblk_t			*mp_tail = NULL;
19260 
19261 	/*
19262 	 * Make a copy of the original message
19263 	 */
19264 	mp2ctl = copymsg(mpctl);
19265 
19266 	/* fixed length IPv6 structure ... */
19267 
19268 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19269 	optp->level = MIB2_IP6;
19270 	optp->name = 0;
19271 	/* Include "unknown interface" ip6_mib */
19272 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19273 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19274 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19275 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19276 	    ipst->ips_ipv6_forward ? 1 : 2);
19277 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19278 	    ipst->ips_ipv6_def_hops);
19279 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19280 	    sizeof (mib2_ipIfStatsEntry_t));
19281 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19282 	    sizeof (mib2_ipv6AddrEntry_t));
19283 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19284 	    sizeof (mib2_ipv6RouteEntry_t));
19285 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19286 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19287 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19288 	    sizeof (ipv6_member_t));
19289 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19290 	    sizeof (ipv6_grpsrc_t));
19291 
19292 	/*
19293 	 * Synchronize 64- and 32-bit counters
19294 	 */
19295 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19296 	    ipIfStatsHCInReceives);
19297 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19298 	    ipIfStatsHCInDelivers);
19299 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19300 	    ipIfStatsHCOutRequests);
19301 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19302 	    ipIfStatsHCOutForwDatagrams);
19303 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19304 	    ipIfStatsHCOutMcastPkts);
19305 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19306 	    ipIfStatsHCInMcastPkts);
19307 
19308 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19309 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19310 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19311 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19312 	}
19313 
19314 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19315 	ill = ILL_START_WALK_V6(&ctx, ipst);
19316 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19317 		ill->ill_ip_mib->ipIfStatsIfIndex =
19318 		    ill->ill_phyint->phyint_ifindex;
19319 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19320 		    ipst->ips_ipv6_forward ? 1 : 2);
19321 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19322 		    ill->ill_max_hops);
19323 
19324 		/*
19325 		 * Synchronize 64- and 32-bit counters
19326 		 */
19327 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19328 		    ipIfStatsHCInReceives);
19329 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19330 		    ipIfStatsHCInDelivers);
19331 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19332 		    ipIfStatsHCOutRequests);
19333 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19334 		    ipIfStatsHCOutForwDatagrams);
19335 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19336 		    ipIfStatsHCOutMcastPkts);
19337 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19338 		    ipIfStatsHCInMcastPkts);
19339 
19340 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19341 		    (char *)ill->ill_ip_mib,
19342 		    (int)sizeof (*ill->ill_ip_mib))) {
19343 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19344 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19345 		}
19346 	}
19347 	rw_exit(&ipst->ips_ill_g_lock);
19348 
19349 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19350 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19351 	    (int)optp->level, (int)optp->name, (int)optp->len));
19352 	qreply(q, mpctl);
19353 	return (mp2ctl);
19354 }
19355 
19356 /*
19357  * ICMPv6 mib: One per ill
19358  */
19359 static mblk_t *
19360 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19361 {
19362 	struct opthdr		*optp;
19363 	mblk_t			*mp2ctl;
19364 	ill_t			*ill;
19365 	ill_walk_context_t	ctx;
19366 	mblk_t			*mp_tail = NULL;
19367 	/*
19368 	 * Make a copy of the original message
19369 	 */
19370 	mp2ctl = copymsg(mpctl);
19371 
19372 	/* fixed length ICMPv6 structure ... */
19373 
19374 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19375 	optp->level = MIB2_ICMP6;
19376 	optp->name = 0;
19377 	/* Include "unknown interface" icmp6_mib */
19378 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19379 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19380 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19381 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19382 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19383 	    (char *)&ipst->ips_icmp6_mib,
19384 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19385 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19386 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19387 	}
19388 
19389 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19390 	ill = ILL_START_WALK_V6(&ctx, ipst);
19391 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19392 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19393 		    ill->ill_phyint->phyint_ifindex;
19394 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19395 		    (char *)ill->ill_icmp6_mib,
19396 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19397 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19398 			    "%u bytes\n",
19399 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19400 		}
19401 	}
19402 	rw_exit(&ipst->ips_ill_g_lock);
19403 
19404 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19405 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19406 	    (int)optp->level, (int)optp->name, (int)optp->len));
19407 	qreply(q, mpctl);
19408 	return (mp2ctl);
19409 }
19410 
19411 /*
19412  * ire_walk routine to create both ipRouteEntryTable and
19413  * ipRouteAttributeTable in one IRE walk
19414  */
19415 static void
19416 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19417 {
19418 	ill_t				*ill;
19419 	ipif_t				*ipif;
19420 	mib2_ipRouteEntry_t		*re;
19421 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19422 	ipaddr_t			gw_addr;
19423 	tsol_ire_gw_secattr_t		*attrp;
19424 	tsol_gc_t			*gc = NULL;
19425 	tsol_gcgrp_t			*gcgrp = NULL;
19426 	uint_t				sacnt = 0;
19427 	int				i;
19428 
19429 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19430 
19431 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19432 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19433 		return;
19434 	}
19435 
19436 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19437 		return;
19438 
19439 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19440 		mutex_enter(&attrp->igsa_lock);
19441 		if ((gc = attrp->igsa_gc) != NULL) {
19442 			gcgrp = gc->gc_grp;
19443 			ASSERT(gcgrp != NULL);
19444 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19445 			sacnt = 1;
19446 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19447 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19448 			gc = gcgrp->gcgrp_head;
19449 			sacnt = gcgrp->gcgrp_count;
19450 		}
19451 		mutex_exit(&attrp->igsa_lock);
19452 
19453 		/* do nothing if there's no gc to report */
19454 		if (gc == NULL) {
19455 			ASSERT(sacnt == 0);
19456 			if (gcgrp != NULL) {
19457 				/* we might as well drop the lock now */
19458 				rw_exit(&gcgrp->gcgrp_rwlock);
19459 				gcgrp = NULL;
19460 			}
19461 			attrp = NULL;
19462 		}
19463 
19464 		ASSERT(gc == NULL || (gcgrp != NULL &&
19465 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19466 	}
19467 	ASSERT(sacnt == 0 || gc != NULL);
19468 
19469 	if (sacnt != 0 &&
19470 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19471 		kmem_free(re, sizeof (*re));
19472 		rw_exit(&gcgrp->gcgrp_rwlock);
19473 		return;
19474 	}
19475 
19476 	/*
19477 	 * Return all IRE types for route table... let caller pick and choose
19478 	 */
19479 	re->ipRouteDest = ire->ire_addr;
19480 	ipif = ire->ire_ipif;
19481 	re->ipRouteIfIndex.o_length = 0;
19482 	if (ire->ire_type == IRE_CACHE) {
19483 		ill = (ill_t *)ire->ire_stq->q_ptr;
19484 		re->ipRouteIfIndex.o_length =
19485 		    ill->ill_name_length == 0 ? 0 :
19486 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19487 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19488 		    re->ipRouteIfIndex.o_length);
19489 	} else if (ipif != NULL) {
19490 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19491 		re->ipRouteIfIndex.o_length =
19492 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19493 	}
19494 	re->ipRouteMetric1 = -1;
19495 	re->ipRouteMetric2 = -1;
19496 	re->ipRouteMetric3 = -1;
19497 	re->ipRouteMetric4 = -1;
19498 
19499 	gw_addr = ire->ire_gateway_addr;
19500 
19501 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19502 		re->ipRouteNextHop = ire->ire_src_addr;
19503 	else
19504 		re->ipRouteNextHop = gw_addr;
19505 	/* indirect(4), direct(3), or invalid(2) */
19506 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19507 		re->ipRouteType = 2;
19508 	else
19509 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19510 	re->ipRouteProto = -1;
19511 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19512 	re->ipRouteMask = ire->ire_mask;
19513 	re->ipRouteMetric5 = -1;
19514 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19515 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19516 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19517 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19518 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19519 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19520 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19521 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19522 
19523 	if (ire->ire_flags & RTF_DYNAMIC) {
19524 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19525 	} else {
19526 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19527 	}
19528 
19529 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19530 	    (char *)re, (int)sizeof (*re))) {
19531 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19532 		    (uint_t)sizeof (*re)));
19533 	}
19534 
19535 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19536 		iaeptr->iae_routeidx = ird->ird_idx;
19537 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19538 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19539 	}
19540 
19541 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19542 	    (char *)iae, sacnt * sizeof (*iae))) {
19543 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19544 		    (unsigned)(sacnt * sizeof (*iae))));
19545 	}
19546 
19547 	/* bump route index for next pass */
19548 	ird->ird_idx++;
19549 
19550 	kmem_free(re, sizeof (*re));
19551 	if (sacnt != 0)
19552 		kmem_free(iae, sacnt * sizeof (*iae));
19553 
19554 	if (gcgrp != NULL)
19555 		rw_exit(&gcgrp->gcgrp_rwlock);
19556 }
19557 
19558 /*
19559  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19560  */
19561 static void
19562 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19563 {
19564 	ill_t				*ill;
19565 	ipif_t				*ipif;
19566 	mib2_ipv6RouteEntry_t		*re;
19567 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19568 	in6_addr_t			gw_addr_v6;
19569 	tsol_ire_gw_secattr_t		*attrp;
19570 	tsol_gc_t			*gc = NULL;
19571 	tsol_gcgrp_t			*gcgrp = NULL;
19572 	uint_t				sacnt = 0;
19573 	int				i;
19574 
19575 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19576 
19577 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19578 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19579 		return;
19580 	}
19581 
19582 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19583 		return;
19584 
19585 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19586 		mutex_enter(&attrp->igsa_lock);
19587 		if ((gc = attrp->igsa_gc) != NULL) {
19588 			gcgrp = gc->gc_grp;
19589 			ASSERT(gcgrp != NULL);
19590 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19591 			sacnt = 1;
19592 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19593 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19594 			gc = gcgrp->gcgrp_head;
19595 			sacnt = gcgrp->gcgrp_count;
19596 		}
19597 		mutex_exit(&attrp->igsa_lock);
19598 
19599 		/* do nothing if there's no gc to report */
19600 		if (gc == NULL) {
19601 			ASSERT(sacnt == 0);
19602 			if (gcgrp != NULL) {
19603 				/* we might as well drop the lock now */
19604 				rw_exit(&gcgrp->gcgrp_rwlock);
19605 				gcgrp = NULL;
19606 			}
19607 			attrp = NULL;
19608 		}
19609 
19610 		ASSERT(gc == NULL || (gcgrp != NULL &&
19611 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19612 	}
19613 	ASSERT(sacnt == 0 || gc != NULL);
19614 
19615 	if (sacnt != 0 &&
19616 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19617 		kmem_free(re, sizeof (*re));
19618 		rw_exit(&gcgrp->gcgrp_rwlock);
19619 		return;
19620 	}
19621 
19622 	/*
19623 	 * Return all IRE types for route table... let caller pick and choose
19624 	 */
19625 	re->ipv6RouteDest = ire->ire_addr_v6;
19626 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19627 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19628 	re->ipv6RouteIfIndex.o_length = 0;
19629 	ipif = ire->ire_ipif;
19630 	if (ire->ire_type == IRE_CACHE) {
19631 		ill = (ill_t *)ire->ire_stq->q_ptr;
19632 		re->ipv6RouteIfIndex.o_length =
19633 		    ill->ill_name_length == 0 ? 0 :
19634 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19635 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19636 		    re->ipv6RouteIfIndex.o_length);
19637 	} else if (ipif != NULL) {
19638 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19639 		re->ipv6RouteIfIndex.o_length =
19640 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19641 	}
19642 
19643 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19644 
19645 	mutex_enter(&ire->ire_lock);
19646 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19647 	mutex_exit(&ire->ire_lock);
19648 
19649 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19650 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19651 	else
19652 		re->ipv6RouteNextHop = gw_addr_v6;
19653 
19654 	/* remote(4), local(3), or discard(2) */
19655 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19656 		re->ipv6RouteType = 2;
19657 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19658 		re->ipv6RouteType = 3;
19659 	else
19660 		re->ipv6RouteType = 4;
19661 
19662 	re->ipv6RouteProtocol	= -1;
19663 	re->ipv6RoutePolicy	= 0;
19664 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19665 	re->ipv6RouteNextHopRDI	= 0;
19666 	re->ipv6RouteWeight	= 0;
19667 	re->ipv6RouteMetric	= 0;
19668 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19669 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19670 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19671 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19672 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19673 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19674 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19675 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19676 
19677 	if (ire->ire_flags & RTF_DYNAMIC) {
19678 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19679 	} else {
19680 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19681 	}
19682 
19683 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19684 	    (char *)re, (int)sizeof (*re))) {
19685 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19686 		    (uint_t)sizeof (*re)));
19687 	}
19688 
19689 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19690 		iaeptr->iae_routeidx = ird->ird_idx;
19691 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19692 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19693 	}
19694 
19695 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19696 	    (char *)iae, sacnt * sizeof (*iae))) {
19697 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19698 		    (unsigned)(sacnt * sizeof (*iae))));
19699 	}
19700 
19701 	/* bump route index for next pass */
19702 	ird->ird_idx++;
19703 
19704 	kmem_free(re, sizeof (*re));
19705 	if (sacnt != 0)
19706 		kmem_free(iae, sacnt * sizeof (*iae));
19707 
19708 	if (gcgrp != NULL)
19709 		rw_exit(&gcgrp->gcgrp_rwlock);
19710 }
19711 
19712 /*
19713  * ndp_walk routine to create ipv6NetToMediaEntryTable
19714  */
19715 static int
19716 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19717 {
19718 	ill_t				*ill;
19719 	mib2_ipv6NetToMediaEntry_t	ntme;
19720 	dl_unitdata_req_t		*dl;
19721 
19722 	ill = nce->nce_ill;
19723 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19724 		return (0);
19725 
19726 	/*
19727 	 * Neighbor cache entry attached to IRE with on-link
19728 	 * destination.
19729 	 */
19730 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19731 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19732 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19733 	    (nce->nce_res_mp != NULL)) {
19734 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19735 		ntme.ipv6NetToMediaPhysAddress.o_length =
19736 		    dl->dl_dest_addr_length;
19737 	} else {
19738 		ntme.ipv6NetToMediaPhysAddress.o_length =
19739 		    ill->ill_phys_addr_length;
19740 	}
19741 	if (nce->nce_res_mp != NULL) {
19742 		bcopy((char *)nce->nce_res_mp->b_rptr +
19743 		    NCE_LL_ADDR_OFFSET(ill),
19744 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19745 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19746 	} else {
19747 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19748 		    ill->ill_phys_addr_length);
19749 	}
19750 	/*
19751 	 * Note: Returns ND_* states. Should be:
19752 	 * reachable(1), stale(2), delay(3), probe(4),
19753 	 * invalid(5), unknown(6)
19754 	 */
19755 	ntme.ipv6NetToMediaState = nce->nce_state;
19756 	ntme.ipv6NetToMediaLastUpdated = 0;
19757 
19758 	/* other(1), dynamic(2), static(3), local(4) */
19759 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19760 		ntme.ipv6NetToMediaType = 4;
19761 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19762 		ntme.ipv6NetToMediaType = 1;
19763 	} else {
19764 		ntme.ipv6NetToMediaType = 2;
19765 	}
19766 
19767 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19768 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19769 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19770 		    (uint_t)sizeof (ntme)));
19771 	}
19772 	return (0);
19773 }
19774 
19775 /*
19776  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19777  */
19778 /* ARGSUSED */
19779 int
19780 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19781 {
19782 	switch (level) {
19783 	case MIB2_IP:
19784 	case MIB2_ICMP:
19785 		switch (name) {
19786 		default:
19787 			break;
19788 		}
19789 		return (1);
19790 	default:
19791 		return (1);
19792 	}
19793 }
19794 
19795 /*
19796  * When there exists both a 64- and 32-bit counter of a particular type
19797  * (i.e., InReceives), only the 64-bit counters are added.
19798  */
19799 void
19800 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19801 {
19802 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19803 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19804 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19805 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19806 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19807 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19808 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19809 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19810 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19811 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19812 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19813 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19814 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19815 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19816 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19817 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19818 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19819 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19820 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19821 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19822 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19823 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19824 	    o2->ipIfStatsInWrongIPVersion);
19825 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19826 	    o2->ipIfStatsInWrongIPVersion);
19827 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19828 	    o2->ipIfStatsOutSwitchIPVersion);
19829 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19830 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19831 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19832 	    o2->ipIfStatsHCInForwDatagrams);
19833 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19834 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19835 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19836 	    o2->ipIfStatsHCOutForwDatagrams);
19837 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19838 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19839 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19840 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19841 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19842 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19843 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19844 	    o2->ipIfStatsHCOutMcastOctets);
19845 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19846 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19847 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19848 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19849 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19850 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19851 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19852 }
19853 
19854 void
19855 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19856 {
19857 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19859 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19861 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19862 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19863 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19864 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19866 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19867 	    o2->ipv6IfIcmpInRouterSolicits);
19868 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19869 	    o2->ipv6IfIcmpInRouterAdvertisements);
19870 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19871 	    o2->ipv6IfIcmpInNeighborSolicits);
19872 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19873 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19874 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19875 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19876 	    o2->ipv6IfIcmpInGroupMembQueries);
19877 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19878 	    o2->ipv6IfIcmpInGroupMembResponses);
19879 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19880 	    o2->ipv6IfIcmpInGroupMembReductions);
19881 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19882 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19883 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19884 	    o2->ipv6IfIcmpOutDestUnreachs);
19885 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19886 	    o2->ipv6IfIcmpOutAdminProhibs);
19887 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19888 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19889 	    o2->ipv6IfIcmpOutParmProblems);
19890 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19891 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19892 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19893 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19894 	    o2->ipv6IfIcmpOutRouterSolicits);
19895 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19896 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19897 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19898 	    o2->ipv6IfIcmpOutNeighborSolicits);
19899 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19900 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19901 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19902 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19903 	    o2->ipv6IfIcmpOutGroupMembQueries);
19904 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19905 	    o2->ipv6IfIcmpOutGroupMembResponses);
19906 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19907 	    o2->ipv6IfIcmpOutGroupMembReductions);
19908 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19909 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19910 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19911 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19912 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19913 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19914 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19915 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19916 	    o2->ipv6IfIcmpInGroupMembTotal);
19917 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19918 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19919 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19920 	    o2->ipv6IfIcmpInGroupMembBadReports);
19921 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19922 	    o2->ipv6IfIcmpInGroupMembOurReports);
19923 }
19924 
19925 /*
19926  * Called before the options are updated to check if this packet will
19927  * be source routed from here.
19928  * This routine assumes that the options are well formed i.e. that they
19929  * have already been checked.
19930  */
19931 static boolean_t
19932 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19933 {
19934 	ipoptp_t	opts;
19935 	uchar_t		*opt;
19936 	uint8_t		optval;
19937 	uint8_t		optlen;
19938 	ipaddr_t	dst;
19939 	ire_t		*ire;
19940 
19941 	if (IS_SIMPLE_IPH(ipha)) {
19942 		ip2dbg(("not source routed\n"));
19943 		return (B_FALSE);
19944 	}
19945 	dst = ipha->ipha_dst;
19946 	for (optval = ipoptp_first(&opts, ipha);
19947 	    optval != IPOPT_EOL;
19948 	    optval = ipoptp_next(&opts)) {
19949 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19950 		opt = opts.ipoptp_cur;
19951 		optlen = opts.ipoptp_len;
19952 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19953 		    optval, optlen));
19954 		switch (optval) {
19955 			uint32_t off;
19956 		case IPOPT_SSRR:
19957 		case IPOPT_LSRR:
19958 			/*
19959 			 * If dst is one of our addresses and there are some
19960 			 * entries left in the source route return (true).
19961 			 */
19962 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19963 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19964 			if (ire == NULL) {
19965 				ip2dbg(("ip_source_routed: not next"
19966 				    " source route 0x%x\n",
19967 				    ntohl(dst)));
19968 				return (B_FALSE);
19969 			}
19970 			ire_refrele(ire);
19971 			off = opt[IPOPT_OFFSET];
19972 			off--;
19973 			if (optlen < IP_ADDR_LEN ||
19974 			    off > optlen - IP_ADDR_LEN) {
19975 				/* End of source route */
19976 				ip1dbg(("ip_source_routed: end of SR\n"));
19977 				return (B_FALSE);
19978 			}
19979 			return (B_TRUE);
19980 		}
19981 	}
19982 	ip2dbg(("not source routed\n"));
19983 	return (B_FALSE);
19984 }
19985 
19986 /*
19987  * Check if the packet contains any source route.
19988  */
19989 static boolean_t
19990 ip_source_route_included(ipha_t *ipha)
19991 {
19992 	ipoptp_t	opts;
19993 	uint8_t		optval;
19994 
19995 	if (IS_SIMPLE_IPH(ipha))
19996 		return (B_FALSE);
19997 	for (optval = ipoptp_first(&opts, ipha);
19998 	    optval != IPOPT_EOL;
19999 	    optval = ipoptp_next(&opts)) {
20000 		switch (optval) {
20001 		case IPOPT_SSRR:
20002 		case IPOPT_LSRR:
20003 			return (B_TRUE);
20004 		}
20005 	}
20006 	return (B_FALSE);
20007 }
20008 
20009 /*
20010  * Called when the IRE expiration timer fires.
20011  */
20012 void
20013 ip_trash_timer_expire(void *args)
20014 {
20015 	int			flush_flag = 0;
20016 	ire_expire_arg_t	iea;
20017 	ip_stack_t		*ipst = (ip_stack_t *)args;
20018 
20019 	iea.iea_ipst = ipst;	/* No netstack_hold */
20020 
20021 	/*
20022 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20023 	 * This lock makes sure that a new invocation of this function
20024 	 * that occurs due to an almost immediate timer firing will not
20025 	 * progress beyond this point until the current invocation is done
20026 	 */
20027 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20028 	ipst->ips_ip_ire_expire_id = 0;
20029 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20030 
20031 	/* Periodic timer */
20032 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20033 	    ipst->ips_ip_ire_arp_interval) {
20034 		/*
20035 		 * Remove all IRE_CACHE entries since they might
20036 		 * contain arp information.
20037 		 */
20038 		flush_flag |= FLUSH_ARP_TIME;
20039 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20040 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20041 	}
20042 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20043 	    ipst->ips_ip_ire_redir_interval) {
20044 		/* Remove all redirects */
20045 		flush_flag |= FLUSH_REDIRECT_TIME;
20046 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20047 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20048 	}
20049 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20050 	    ipst->ips_ip_ire_pathmtu_interval) {
20051 		/* Increase path mtu */
20052 		flush_flag |= FLUSH_MTU_TIME;
20053 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20054 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20055 	}
20056 
20057 	/*
20058 	 * Optimize for the case when there are no redirects in the
20059 	 * ftable, that is, no need to walk the ftable in that case.
20060 	 */
20061 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20062 		iea.iea_flush_flag = flush_flag;
20063 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20064 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20065 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20066 		    NULL, ALL_ZONES, ipst);
20067 	}
20068 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20069 	    ipst->ips_ip_redirect_cnt > 0) {
20070 		iea.iea_flush_flag = flush_flag;
20071 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20072 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20073 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20074 	}
20075 	if (flush_flag & FLUSH_MTU_TIME) {
20076 		/*
20077 		 * Walk all IPv6 IRE's and update them
20078 		 * Note that ARP and redirect timers are not
20079 		 * needed since NUD handles stale entries.
20080 		 */
20081 		flush_flag = FLUSH_MTU_TIME;
20082 		iea.iea_flush_flag = flush_flag;
20083 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20084 		    ALL_ZONES, ipst);
20085 	}
20086 
20087 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20088 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20089 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20090 
20091 	/*
20092 	 * Hold the lock to serialize timeout calls and prevent
20093 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20094 	 * for the timer to fire and a new invocation of this function
20095 	 * to start before the return value of timeout has been stored
20096 	 * in ip_ire_expire_id by the current invocation.
20097 	 */
20098 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20099 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20100 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20101 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20102 }
20103 
20104 /*
20105  * Called by the memory allocator subsystem directly, when the system
20106  * is running low on memory.
20107  */
20108 /* ARGSUSED */
20109 void
20110 ip_trash_ire_reclaim(void *args)
20111 {
20112 	netstack_handle_t nh;
20113 	netstack_t *ns;
20114 
20115 	netstack_next_init(&nh);
20116 	while ((ns = netstack_next(&nh)) != NULL) {
20117 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20118 		netstack_rele(ns);
20119 	}
20120 	netstack_next_fini(&nh);
20121 }
20122 
20123 static void
20124 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20125 {
20126 	ire_cache_count_t icc;
20127 	ire_cache_reclaim_t icr;
20128 	ncc_cache_count_t ncc;
20129 	nce_cache_reclaim_t ncr;
20130 	uint_t delete_cnt;
20131 	/*
20132 	 * Memory reclaim call back.
20133 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20134 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20135 	 * entries, determine what fraction to free for
20136 	 * each category of IRE_CACHE entries giving absolute priority
20137 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20138 	 * entry will be freed unless all offlink entries are freed).
20139 	 */
20140 	icc.icc_total = 0;
20141 	icc.icc_unused = 0;
20142 	icc.icc_offlink = 0;
20143 	icc.icc_pmtu = 0;
20144 	icc.icc_onlink = 0;
20145 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20146 
20147 	/*
20148 	 * Free NCEs for IPv6 like the onlink ires.
20149 	 */
20150 	ncc.ncc_total = 0;
20151 	ncc.ncc_host = 0;
20152 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20153 
20154 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20155 	    icc.icc_pmtu + icc.icc_onlink);
20156 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20157 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20158 	if (delete_cnt == 0)
20159 		return;
20160 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20161 	/* Always delete all unused offlink entries */
20162 	icr.icr_ipst = ipst;
20163 	icr.icr_unused = 1;
20164 	if (delete_cnt <= icc.icc_unused) {
20165 		/*
20166 		 * Only need to free unused entries.  In other words,
20167 		 * there are enough unused entries to free to meet our
20168 		 * target number of freed ire cache entries.
20169 		 */
20170 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20171 		ncr.ncr_host = 0;
20172 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20173 		/*
20174 		 * Only need to free unused entries, plus a fraction of offlink
20175 		 * entries.  It follows from the first if statement that
20176 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20177 		 */
20178 		delete_cnt -= icc.icc_unused;
20179 		/* Round up # deleted by truncating fraction */
20180 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20181 		icr.icr_pmtu = icr.icr_onlink = 0;
20182 		ncr.ncr_host = 0;
20183 	} else if (delete_cnt <=
20184 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20185 		/*
20186 		 * Free all unused and offlink entries, plus a fraction of
20187 		 * pmtu entries.  It follows from the previous if statement
20188 		 * that icc_pmtu is non-zero, and that
20189 		 * delete_cnt != icc_unused + icc_offlink.
20190 		 */
20191 		icr.icr_offlink = 1;
20192 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20193 		/* Round up # deleted by truncating fraction */
20194 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20195 		icr.icr_onlink = 0;
20196 		ncr.ncr_host = 0;
20197 	} else {
20198 		/*
20199 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20200 		 * of onlink entries.  If we're here, then we know that
20201 		 * icc_onlink is non-zero, and that
20202 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20203 		 */
20204 		icr.icr_offlink = icr.icr_pmtu = 1;
20205 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20206 		    icc.icc_pmtu;
20207 		/* Round up # deleted by truncating fraction */
20208 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20209 		/* Using the same delete fraction as for onlink IREs */
20210 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20211 	}
20212 #ifdef DEBUG
20213 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20214 	    "fractions %d/%d/%d/%d\n",
20215 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20216 	    icc.icc_unused, icc.icc_offlink,
20217 	    icc.icc_pmtu, icc.icc_onlink,
20218 	    icr.icr_unused, icr.icr_offlink,
20219 	    icr.icr_pmtu, icr.icr_onlink));
20220 #endif
20221 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20222 	if (ncr.ncr_host != 0)
20223 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20224 		    (uchar_t *)&ncr, ipst);
20225 #ifdef DEBUG
20226 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20227 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20228 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20229 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20230 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20231 	    icc.icc_pmtu, icc.icc_onlink));
20232 #endif
20233 }
20234 
20235 /*
20236  * ip_unbind is called when a copy of an unbind request is received from the
20237  * upper level protocol.  We remove this conn from any fanout hash list it is
20238  * on, and zero out the bind information.  No reply is expected up above.
20239  */
20240 void
20241 ip_unbind(conn_t *connp)
20242 {
20243 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20244 
20245 	if (is_system_labeled() && connp->conn_anon_port) {
20246 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20247 		    connp->conn_mlp_type, connp->conn_ulp,
20248 		    ntohs(connp->conn_lport), B_FALSE);
20249 		connp->conn_anon_port = 0;
20250 	}
20251 	connp->conn_mlp_type = mlptSingle;
20252 
20253 	ipcl_hash_remove(connp);
20254 }
20255 
20256 /*
20257  * Write side put procedure.  Outbound data, IOCTLs, responses from
20258  * resolvers, etc, come down through here.
20259  *
20260  * arg2 is always a queue_t *.
20261  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20262  * the zoneid.
20263  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20264  */
20265 void
20266 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20267 {
20268 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20269 }
20270 
20271 void
20272 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20273     ip_opt_info_t *infop)
20274 {
20275 	conn_t		*connp = NULL;
20276 	queue_t		*q = (queue_t *)arg2;
20277 	ipha_t		*ipha;
20278 #define	rptr	((uchar_t *)ipha)
20279 	ire_t		*ire = NULL;
20280 	ire_t		*sctp_ire = NULL;
20281 	uint32_t	v_hlen_tos_len;
20282 	ipaddr_t	dst;
20283 	mblk_t		*first_mp = NULL;
20284 	boolean_t	mctl_present;
20285 	ipsec_out_t	*io;
20286 	int		match_flags;
20287 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20288 	ipif_t		*dst_ipif;
20289 	boolean_t	multirt_need_resolve = B_FALSE;
20290 	mblk_t		*copy_mp = NULL;
20291 	int		err = 0;
20292 	zoneid_t	zoneid;
20293 	boolean_t	need_decref = B_FALSE;
20294 	boolean_t	ignore_dontroute = B_FALSE;
20295 	boolean_t	ignore_nexthop = B_FALSE;
20296 	boolean_t	ip_nexthop = B_FALSE;
20297 	ipaddr_t	nexthop_addr;
20298 	ip_stack_t	*ipst;
20299 
20300 #ifdef	_BIG_ENDIAN
20301 #define	V_HLEN	(v_hlen_tos_len >> 24)
20302 #else
20303 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20304 #endif
20305 
20306 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20307 	    "ip_wput_start: q %p", q);
20308 
20309 	/*
20310 	 * ip_wput fast path
20311 	 */
20312 
20313 	/* is packet from ARP ? */
20314 	if (q->q_next != NULL) {
20315 		zoneid = (zoneid_t)(uintptr_t)arg;
20316 		goto qnext;
20317 	}
20318 
20319 	connp = (conn_t *)arg;
20320 	ASSERT(connp != NULL);
20321 	zoneid = connp->conn_zoneid;
20322 	ipst = connp->conn_netstack->netstack_ip;
20323 	ASSERT(ipst != NULL);
20324 
20325 	/* is queue flow controlled? */
20326 	if ((q->q_first != NULL || connp->conn_draining) &&
20327 	    (caller == IP_WPUT)) {
20328 		ASSERT(!need_decref);
20329 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20330 		(void) putq(q, mp);
20331 		return;
20332 	}
20333 
20334 	/* Multidata transmit? */
20335 	if (DB_TYPE(mp) == M_MULTIDATA) {
20336 		/*
20337 		 * We should never get here, since all Multidata messages
20338 		 * originating from tcp should have been directed over to
20339 		 * tcp_multisend() in the first place.
20340 		 */
20341 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20342 		freemsg(mp);
20343 		return;
20344 	} else if (DB_TYPE(mp) != M_DATA)
20345 		goto notdata;
20346 
20347 	if (mp->b_flag & MSGHASREF) {
20348 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20349 		mp->b_flag &= ~MSGHASREF;
20350 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20351 		need_decref = B_TRUE;
20352 	}
20353 	ipha = (ipha_t *)mp->b_rptr;
20354 
20355 	/* is IP header non-aligned or mblk smaller than basic IP header */
20356 #ifndef SAFETY_BEFORE_SPEED
20357 	if (!OK_32PTR(rptr) ||
20358 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20359 		goto hdrtoosmall;
20360 #endif
20361 
20362 	ASSERT(OK_32PTR(ipha));
20363 
20364 	/*
20365 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20366 	 * wrong version, we'll catch it again in ip_output_v6.
20367 	 *
20368 	 * Note that this is *only* locally-generated output here, and never
20369 	 * forwarded data, and that we need to deal only with transports that
20370 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20371 	 * label.)
20372 	 */
20373 	if (is_system_labeled() &&
20374 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20375 	    !connp->conn_ulp_labeled) {
20376 		cred_t	*credp;
20377 		pid_t	pid;
20378 
20379 		credp = BEST_CRED(mp, connp, &pid);
20380 		err = tsol_check_label(credp, &mp,
20381 		    connp->conn_mac_exempt, ipst, pid);
20382 		ipha = (ipha_t *)mp->b_rptr;
20383 		if (err != 0) {
20384 			first_mp = mp;
20385 			if (err == EINVAL)
20386 				goto icmp_parameter_problem;
20387 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20388 			goto discard_pkt;
20389 		}
20390 	}
20391 
20392 	ASSERT(infop != NULL);
20393 
20394 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20395 		/*
20396 		 * IP_PKTINFO ancillary option is present.
20397 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20398 		 * allows using address of any zone as the source address.
20399 		 */
20400 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20401 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20402 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20403 		if (ire == NULL)
20404 			goto drop_pkt;
20405 		ire_refrele(ire);
20406 		ire = NULL;
20407 	}
20408 
20409 	/*
20410 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20411 	 */
20412 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20413 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20414 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20415 
20416 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20417 			goto drop_pkt;
20418 		/*
20419 		 * check that there is an ipif belonging
20420 		 * to our zone. IPCL_ZONEID is not used because
20421 		 * IP_ALLZONES option is valid only when the ill is
20422 		 * accessible from all zones i.e has a valid ipif in
20423 		 * all zones.
20424 		 */
20425 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20426 			goto drop_pkt;
20427 		}
20428 	}
20429 
20430 	/*
20431 	 * If there is a policy, try to attach an ipsec_out in
20432 	 * the front. At the end, first_mp either points to a
20433 	 * M_DATA message or IPSEC_OUT message linked to a
20434 	 * M_DATA message. We have to do it now as we might
20435 	 * lose the "conn" if we go through ip_newroute.
20436 	 */
20437 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20438 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20439 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20440 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20441 			if (need_decref)
20442 				CONN_DEC_REF(connp);
20443 			return;
20444 		} else {
20445 			ASSERT(mp->b_datap->db_type == M_CTL);
20446 			first_mp = mp;
20447 			mp = mp->b_cont;
20448 			mctl_present = B_TRUE;
20449 		}
20450 	} else {
20451 		first_mp = mp;
20452 		mctl_present = B_FALSE;
20453 	}
20454 
20455 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20456 
20457 	/* is wrong version or IP options present */
20458 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20459 		goto version_hdrlen_check;
20460 	dst = ipha->ipha_dst;
20461 
20462 	/* If IP_BOUND_IF has been set, use that ill. */
20463 	if (connp->conn_outgoing_ill != NULL) {
20464 		xmit_ill = conn_get_held_ill(connp,
20465 		    &connp->conn_outgoing_ill, &err);
20466 		if (err == ILL_LOOKUP_FAILED)
20467 			goto drop_pkt;
20468 
20469 		goto send_from_ill;
20470 	}
20471 
20472 	/* is packet multicast? */
20473 	if (CLASSD(dst))
20474 		goto multicast;
20475 
20476 	/*
20477 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20478 	 * takes precedence over conn_dontroute and conn_nexthop_set
20479 	 */
20480 	if (xmit_ill != NULL)
20481 		goto send_from_ill;
20482 
20483 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20484 		/*
20485 		 * If the destination is a broadcast, local, or loopback
20486 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20487 		 * standard path.
20488 		 */
20489 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20490 		if ((ire == NULL) || (ire->ire_type &
20491 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20492 			if (ire != NULL) {
20493 				ire_refrele(ire);
20494 				/* No more access to ire */
20495 				ire = NULL;
20496 			}
20497 			/*
20498 			 * bypass routing checks and go directly to interface.
20499 			 */
20500 			if (connp->conn_dontroute)
20501 				goto dontroute;
20502 
20503 			ASSERT(connp->conn_nexthop_set);
20504 			ip_nexthop = B_TRUE;
20505 			nexthop_addr = connp->conn_nexthop_v4;
20506 			goto send_from_ill;
20507 		}
20508 
20509 		/* Must be a broadcast, a loopback or a local ire */
20510 		ire_refrele(ire);
20511 		/* No more access to ire */
20512 		ire = NULL;
20513 	}
20514 
20515 	/*
20516 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20517 	 * this for the tcp global queue and listen end point
20518 	 * as it does not really have a real destination to
20519 	 * talk to.  This is also true for SCTP.
20520 	 */
20521 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20522 	    !connp->conn_fully_bound) {
20523 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20524 		if (ire == NULL)
20525 			goto noirefound;
20526 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20527 		    "ip_wput_end: q %p (%S)", q, "end");
20528 
20529 		/*
20530 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20531 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20532 		 */
20533 		if (ire->ire_flags & RTF_MULTIRT) {
20534 
20535 			/*
20536 			 * Force the TTL of multirouted packets if required.
20537 			 * The TTL of such packets is bounded by the
20538 			 * ip_multirt_ttl ndd variable.
20539 			 */
20540 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20541 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20542 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20543 				    "(was %d), dst 0x%08x\n",
20544 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20545 				    ntohl(ire->ire_addr)));
20546 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20547 			}
20548 			/*
20549 			 * We look at this point if there are pending
20550 			 * unresolved routes. ire_multirt_resolvable()
20551 			 * checks in O(n) that all IRE_OFFSUBNET ire
20552 			 * entries for the packet's destination and
20553 			 * flagged RTF_MULTIRT are currently resolved.
20554 			 * If some remain unresolved, we make a copy
20555 			 * of the current message. It will be used
20556 			 * to initiate additional route resolutions.
20557 			 */
20558 			multirt_need_resolve =
20559 			    ire_multirt_need_resolve(ire->ire_addr,
20560 			    msg_getlabel(first_mp), ipst);
20561 			ip2dbg(("ip_wput[TCP]: ire %p, "
20562 			    "multirt_need_resolve %d, first_mp %p\n",
20563 			    (void *)ire, multirt_need_resolve,
20564 			    (void *)first_mp));
20565 			if (multirt_need_resolve) {
20566 				copy_mp = copymsg(first_mp);
20567 				if (copy_mp != NULL) {
20568 					MULTIRT_DEBUG_TAG(copy_mp);
20569 				}
20570 			}
20571 		}
20572 
20573 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20574 
20575 		/*
20576 		 * Try to resolve another multiroute if
20577 		 * ire_multirt_need_resolve() deemed it necessary.
20578 		 */
20579 		if (copy_mp != NULL)
20580 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20581 		if (need_decref)
20582 			CONN_DEC_REF(connp);
20583 		return;
20584 	}
20585 
20586 	/*
20587 	 * Access to conn_ire_cache. (protected by conn_lock)
20588 	 *
20589 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20590 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20591 	 * send a packet or two with the IRE_CACHE that is going away.
20592 	 * Access to the ire requires an ire refhold on the ire prior to
20593 	 * its use since an interface unplumb thread may delete the cached
20594 	 * ire and release the refhold at any time.
20595 	 *
20596 	 * Caching an ire in the conn_ire_cache
20597 	 *
20598 	 * o Caching an ire pointer in the conn requires a strict check for
20599 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20600 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20601 	 * in the conn is done after making sure under the bucket lock that the
20602 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20603 	 * caching an ire after the unplumb thread has cleaned up the conn.
20604 	 * If the conn does not send a packet subsequently the unplumb thread
20605 	 * will be hanging waiting for the ire count to drop to zero.
20606 	 *
20607 	 * o We also need to atomically test for a null conn_ire_cache and
20608 	 * set the conn_ire_cache under the the protection of the conn_lock
20609 	 * to avoid races among concurrent threads trying to simultaneously
20610 	 * cache an ire in the conn_ire_cache.
20611 	 */
20612 	mutex_enter(&connp->conn_lock);
20613 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20614 
20615 	if (ire != NULL && ire->ire_addr == dst &&
20616 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20617 
20618 		IRE_REFHOLD(ire);
20619 		mutex_exit(&connp->conn_lock);
20620 
20621 	} else {
20622 		boolean_t cached = B_FALSE;
20623 		connp->conn_ire_cache = NULL;
20624 		mutex_exit(&connp->conn_lock);
20625 		/* Release the old ire */
20626 		if (ire != NULL && sctp_ire == NULL)
20627 			IRE_REFRELE_NOTR(ire);
20628 
20629 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20630 		if (ire == NULL)
20631 			goto noirefound;
20632 		IRE_REFHOLD_NOTR(ire);
20633 
20634 		mutex_enter(&connp->conn_lock);
20635 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20636 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20637 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20638 				if (connp->conn_ulp == IPPROTO_TCP)
20639 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20640 				connp->conn_ire_cache = ire;
20641 				cached = B_TRUE;
20642 			}
20643 			rw_exit(&ire->ire_bucket->irb_lock);
20644 		}
20645 		mutex_exit(&connp->conn_lock);
20646 
20647 		/*
20648 		 * We can continue to use the ire but since it was
20649 		 * not cached, we should drop the extra reference.
20650 		 */
20651 		if (!cached)
20652 			IRE_REFRELE_NOTR(ire);
20653 	}
20654 
20655 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20656 	    "ip_wput_end: q %p (%S)", q, "end");
20657 
20658 	/*
20659 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20660 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20661 	 */
20662 	if (ire->ire_flags & RTF_MULTIRT) {
20663 		/*
20664 		 * Force the TTL of multirouted packets if required.
20665 		 * The TTL of such packets is bounded by the
20666 		 * ip_multirt_ttl ndd variable.
20667 		 */
20668 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20669 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20670 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20671 			    "(was %d), dst 0x%08x\n",
20672 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20673 			    ntohl(ire->ire_addr)));
20674 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20675 		}
20676 
20677 		/*
20678 		 * At this point, we check to see if there are any pending
20679 		 * unresolved routes. ire_multirt_resolvable()
20680 		 * checks in O(n) that all IRE_OFFSUBNET ire
20681 		 * entries for the packet's destination and
20682 		 * flagged RTF_MULTIRT are currently resolved.
20683 		 * If some remain unresolved, we make a copy
20684 		 * of the current message. It will be used
20685 		 * to initiate additional route resolutions.
20686 		 */
20687 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20688 		    msg_getlabel(first_mp), ipst);
20689 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20690 		    "multirt_need_resolve %d, first_mp %p\n",
20691 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20692 		if (multirt_need_resolve) {
20693 			copy_mp = copymsg(first_mp);
20694 			if (copy_mp != NULL) {
20695 				MULTIRT_DEBUG_TAG(copy_mp);
20696 			}
20697 		}
20698 	}
20699 
20700 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20701 
20702 	/*
20703 	 * Try to resolve another multiroute if
20704 	 * ire_multirt_resolvable() deemed it necessary
20705 	 */
20706 	if (copy_mp != NULL)
20707 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20708 	if (need_decref)
20709 		CONN_DEC_REF(connp);
20710 	return;
20711 
20712 qnext:
20713 	/*
20714 	 * Upper Level Protocols pass down complete IP datagrams
20715 	 * as M_DATA messages.	Everything else is a sideshow.
20716 	 *
20717 	 * 1) We could be re-entering ip_wput because of ip_neworute
20718 	 *    in which case we could have a IPSEC_OUT message. We
20719 	 *    need to pass through ip_wput like other datagrams and
20720 	 *    hence cannot branch to ip_wput_nondata.
20721 	 *
20722 	 * 2) ARP, AH, ESP, and other clients who are on the module
20723 	 *    instance of IP stream, give us something to deal with.
20724 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20725 	 *
20726 	 * 3) ICMP replies also could come here.
20727 	 */
20728 	ipst = ILLQ_TO_IPST(q);
20729 
20730 	if (DB_TYPE(mp) != M_DATA) {
20731 notdata:
20732 		if (DB_TYPE(mp) == M_CTL) {
20733 			/*
20734 			 * M_CTL messages are used by ARP, AH and ESP to
20735 			 * communicate with IP. We deal with IPSEC_IN and
20736 			 * IPSEC_OUT here. ip_wput_nondata handles other
20737 			 * cases.
20738 			 */
20739 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20740 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20741 				first_mp = mp->b_cont;
20742 				first_mp->b_flag &= ~MSGHASREF;
20743 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20744 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20745 				CONN_DEC_REF(connp);
20746 				connp = NULL;
20747 			}
20748 			if (ii->ipsec_info_type == IPSEC_IN) {
20749 				/*
20750 				 * Either this message goes back to
20751 				 * IPsec for further processing or to
20752 				 * ULP after policy checks.
20753 				 */
20754 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20755 				return;
20756 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20757 				io = (ipsec_out_t *)ii;
20758 				if (io->ipsec_out_proc_begin) {
20759 					/*
20760 					 * IPsec processing has already started.
20761 					 * Complete it.
20762 					 * IPQoS notes: We don't care what is
20763 					 * in ipsec_out_ill_index since this
20764 					 * won't be processed for IPQoS policies
20765 					 * in ipsec_out_process.
20766 					 */
20767 					ipsec_out_process(q, mp, NULL,
20768 					    io->ipsec_out_ill_index);
20769 					return;
20770 				} else {
20771 					connp = (q->q_next != NULL) ?
20772 					    NULL : Q_TO_CONN(q);
20773 					first_mp = mp;
20774 					mp = mp->b_cont;
20775 					mctl_present = B_TRUE;
20776 				}
20777 				zoneid = io->ipsec_out_zoneid;
20778 				ASSERT(zoneid != ALL_ZONES);
20779 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20780 				/*
20781 				 * It's an IPsec control message requesting
20782 				 * an SADB update to be sent to the IPsec
20783 				 * hardware acceleration capable ills.
20784 				 */
20785 				ipsec_ctl_t *ipsec_ctl =
20786 				    (ipsec_ctl_t *)mp->b_rptr;
20787 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20788 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20789 				mblk_t *cmp = mp->b_cont;
20790 
20791 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20792 				ASSERT(cmp != NULL);
20793 
20794 				freeb(mp);
20795 				ill_ipsec_capab_send_all(satype, cmp, sa,
20796 				    ipst->ips_netstack);
20797 				return;
20798 			} else {
20799 				/*
20800 				 * This must be ARP or special TSOL signaling.
20801 				 */
20802 				ip_wput_nondata(NULL, q, mp, NULL);
20803 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20804 				    "ip_wput_end: q %p (%S)", q, "nondata");
20805 				return;
20806 			}
20807 		} else {
20808 			/*
20809 			 * This must be non-(ARP/AH/ESP) messages.
20810 			 */
20811 			ASSERT(!need_decref);
20812 			ip_wput_nondata(NULL, q, mp, NULL);
20813 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20814 			    "ip_wput_end: q %p (%S)", q, "nondata");
20815 			return;
20816 		}
20817 	} else {
20818 		first_mp = mp;
20819 		mctl_present = B_FALSE;
20820 	}
20821 
20822 	ASSERT(first_mp != NULL);
20823 
20824 	if (mctl_present) {
20825 		io = (ipsec_out_t *)first_mp->b_rptr;
20826 		if (io->ipsec_out_ip_nexthop) {
20827 			/*
20828 			 * We may have lost the conn context if we are
20829 			 * coming here from ip_newroute(). Copy the
20830 			 * nexthop information.
20831 			 */
20832 			ip_nexthop = B_TRUE;
20833 			nexthop_addr = io->ipsec_out_nexthop_addr;
20834 
20835 			ipha = (ipha_t *)mp->b_rptr;
20836 			dst = ipha->ipha_dst;
20837 			goto send_from_ill;
20838 		}
20839 	}
20840 
20841 	ASSERT(xmit_ill == NULL);
20842 
20843 	/* We have a complete IP datagram heading outbound. */
20844 	ipha = (ipha_t *)mp->b_rptr;
20845 
20846 #ifndef SPEED_BEFORE_SAFETY
20847 	/*
20848 	 * Make sure we have a full-word aligned message and that at least
20849 	 * a simple IP header is accessible in the first message.  If not,
20850 	 * try a pullup.  For labeled systems we need to always take this
20851 	 * path as M_CTLs are "notdata" but have trailing data to process.
20852 	 */
20853 	if (!OK_32PTR(rptr) ||
20854 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20855 hdrtoosmall:
20856 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20857 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20858 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20859 			if (first_mp == NULL)
20860 				first_mp = mp;
20861 			goto discard_pkt;
20862 		}
20863 
20864 		/* This function assumes that mp points to an IPv4 packet. */
20865 		if (is_system_labeled() &&
20866 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20867 		    (connp == NULL || !connp->conn_ulp_labeled)) {
20868 			cred_t	*credp;
20869 			pid_t	pid;
20870 
20871 			if (connp != NULL) {
20872 				credp = BEST_CRED(mp, connp, &pid);
20873 				err = tsol_check_label(credp, &mp,
20874 				    connp->conn_mac_exempt, ipst, pid);
20875 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
20876 				err = tsol_check_label(credp, &mp,
20877 				    B_FALSE, ipst, pid);
20878 			}
20879 			ipha = (ipha_t *)mp->b_rptr;
20880 			if (mctl_present)
20881 				first_mp->b_cont = mp;
20882 			else
20883 				first_mp = mp;
20884 			if (err != 0) {
20885 				if (err == EINVAL)
20886 					goto icmp_parameter_problem;
20887 				ip2dbg(("ip_wput: label check failed (%d)\n",
20888 				    err));
20889 				goto discard_pkt;
20890 			}
20891 		}
20892 
20893 		ipha = (ipha_t *)mp->b_rptr;
20894 		if (first_mp == NULL) {
20895 			ASSERT(xmit_ill == NULL);
20896 			/*
20897 			 * If we got here because of "goto hdrtoosmall"
20898 			 * We need to attach a IPSEC_OUT.
20899 			 */
20900 			if (connp->conn_out_enforce_policy) {
20901 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20902 				    NULL, ipha->ipha_protocol,
20903 				    ipst->ips_netstack)) == NULL)) {
20904 					BUMP_MIB(&ipst->ips_ip_mib,
20905 					    ipIfStatsOutDiscards);
20906 					if (need_decref)
20907 						CONN_DEC_REF(connp);
20908 					return;
20909 				} else {
20910 					ASSERT(mp->b_datap->db_type == M_CTL);
20911 					first_mp = mp;
20912 					mp = mp->b_cont;
20913 					mctl_present = B_TRUE;
20914 				}
20915 			} else {
20916 				first_mp = mp;
20917 				mctl_present = B_FALSE;
20918 			}
20919 		}
20920 	}
20921 #endif
20922 
20923 	/* Most of the code below is written for speed, not readability */
20924 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20925 
20926 	/*
20927 	 * If ip_newroute() fails, we're going to need a full
20928 	 * header for the icmp wraparound.
20929 	 */
20930 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20931 		uint_t	v_hlen;
20932 version_hdrlen_check:
20933 		ASSERT(first_mp != NULL);
20934 		v_hlen = V_HLEN;
20935 		/*
20936 		 * siphon off IPv6 packets coming down from transport
20937 		 * layer modules here.
20938 		 * Note: high-order bit carries NUD reachability confirmation
20939 		 */
20940 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20941 			/*
20942 			 * FIXME: assume that callers of ip_output* call
20943 			 * the right version?
20944 			 */
20945 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20946 			ASSERT(xmit_ill == NULL);
20947 			if (need_decref)
20948 				mp->b_flag |= MSGHASREF;
20949 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20950 			return;
20951 		}
20952 
20953 		if ((v_hlen >> 4) != IP_VERSION) {
20954 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20955 			    "ip_wput_end: q %p (%S)", q, "badvers");
20956 			goto discard_pkt;
20957 		}
20958 		/*
20959 		 * Is the header length at least 20 bytes?
20960 		 *
20961 		 * Are there enough bytes accessible in the header?  If
20962 		 * not, try a pullup.
20963 		 */
20964 		v_hlen &= 0xF;
20965 		v_hlen <<= 2;
20966 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20967 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20968 			    "ip_wput_end: q %p (%S)", q, "badlen");
20969 			goto discard_pkt;
20970 		}
20971 		if (v_hlen > (mp->b_wptr - rptr)) {
20972 			if (!pullupmsg(mp, v_hlen)) {
20973 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20974 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20975 				goto discard_pkt;
20976 			}
20977 			ipha = (ipha_t *)mp->b_rptr;
20978 		}
20979 		/*
20980 		 * Move first entry from any source route into ipha_dst and
20981 		 * verify the options
20982 		 */
20983 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20984 		    zoneid, ipst)) {
20985 			ASSERT(xmit_ill == NULL);
20986 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20987 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20988 			    "ip_wput_end: q %p (%S)", q, "badopts");
20989 			if (need_decref)
20990 				CONN_DEC_REF(connp);
20991 			return;
20992 		}
20993 	}
20994 	dst = ipha->ipha_dst;
20995 
20996 	/*
20997 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20998 	 * we have to run the packet through ip_newroute which will take
20999 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21000 	 * a resolver, or assigning a default gateway, etc.
21001 	 */
21002 	if (CLASSD(dst)) {
21003 		ipif_t	*ipif;
21004 		uint32_t setsrc = 0;
21005 
21006 multicast:
21007 		ASSERT(first_mp != NULL);
21008 		ip2dbg(("ip_wput: CLASSD\n"));
21009 		if (connp == NULL) {
21010 			/*
21011 			 * Use the first good ipif on the ill.
21012 			 * XXX Should this ever happen? (Appears
21013 			 * to show up with just ppp and no ethernet due
21014 			 * to in.rdisc.)
21015 			 * However, ire_send should be able to
21016 			 * call ip_wput_ire directly.
21017 			 *
21018 			 * XXX Also, this can happen for ICMP and other packets
21019 			 * with multicast source addresses.  Perhaps we should
21020 			 * fix things so that we drop the packet in question,
21021 			 * but for now, just run with it.
21022 			 */
21023 			ill_t *ill = (ill_t *)q->q_ptr;
21024 
21025 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21026 			if (ipif == NULL) {
21027 				if (need_decref)
21028 					CONN_DEC_REF(connp);
21029 				freemsg(first_mp);
21030 				return;
21031 			}
21032 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21033 			    ntohl(dst), ill->ill_name));
21034 		} else {
21035 			/*
21036 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21037 			 * and IP_MULTICAST_IF.  The block comment above this
21038 			 * function explains the locking mechanism used here.
21039 			 */
21040 			if (xmit_ill == NULL) {
21041 				xmit_ill = conn_get_held_ill(connp,
21042 				    &connp->conn_outgoing_ill, &err);
21043 				if (err == ILL_LOOKUP_FAILED) {
21044 					ip1dbg(("ip_wput: No ill for "
21045 					    "IP_BOUND_IF\n"));
21046 					BUMP_MIB(&ipst->ips_ip_mib,
21047 					    ipIfStatsOutNoRoutes);
21048 					goto drop_pkt;
21049 				}
21050 			}
21051 
21052 			if (xmit_ill == NULL) {
21053 				ipif = conn_get_held_ipif(connp,
21054 				    &connp->conn_multicast_ipif, &err);
21055 				if (err == IPIF_LOOKUP_FAILED) {
21056 					ip1dbg(("ip_wput: No ipif for "
21057 					    "multicast\n"));
21058 					BUMP_MIB(&ipst->ips_ip_mib,
21059 					    ipIfStatsOutNoRoutes);
21060 					goto drop_pkt;
21061 				}
21062 			}
21063 			if (xmit_ill != NULL) {
21064 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21065 				if (ipif == NULL) {
21066 					ip1dbg(("ip_wput: No ipif for "
21067 					    "xmit_ill\n"));
21068 					BUMP_MIB(&ipst->ips_ip_mib,
21069 					    ipIfStatsOutNoRoutes);
21070 					goto drop_pkt;
21071 				}
21072 			} else if (ipif == NULL || ipif->ipif_isv6) {
21073 				/*
21074 				 * We must do this ipif determination here
21075 				 * else we could pass through ip_newroute
21076 				 * and come back here without the conn context.
21077 				 *
21078 				 * Note: we do late binding i.e. we bind to
21079 				 * the interface when the first packet is sent.
21080 				 * For performance reasons we do not rebind on
21081 				 * each packet but keep the binding until the
21082 				 * next IP_MULTICAST_IF option.
21083 				 *
21084 				 * conn_multicast_{ipif,ill} are shared between
21085 				 * IPv4 and IPv6 and AF_INET6 sockets can
21086 				 * send both IPv4 and IPv6 packets. Hence
21087 				 * we have to check that "isv6" matches above.
21088 				 */
21089 				if (ipif != NULL)
21090 					ipif_refrele(ipif);
21091 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21092 				if (ipif == NULL) {
21093 					ip1dbg(("ip_wput: No ipif for "
21094 					    "multicast\n"));
21095 					BUMP_MIB(&ipst->ips_ip_mib,
21096 					    ipIfStatsOutNoRoutes);
21097 					goto drop_pkt;
21098 				}
21099 				err = conn_set_held_ipif(connp,
21100 				    &connp->conn_multicast_ipif, ipif);
21101 				if (err == IPIF_LOOKUP_FAILED) {
21102 					ipif_refrele(ipif);
21103 					ip1dbg(("ip_wput: No ipif for "
21104 					    "multicast\n"));
21105 					BUMP_MIB(&ipst->ips_ip_mib,
21106 					    ipIfStatsOutNoRoutes);
21107 					goto drop_pkt;
21108 				}
21109 			}
21110 		}
21111 		ASSERT(!ipif->ipif_isv6);
21112 		/*
21113 		 * As we may lose the conn by the time we reach ip_wput_ire,
21114 		 * we copy conn_multicast_loop and conn_dontroute on to an
21115 		 * ipsec_out. In case if this datagram goes out secure,
21116 		 * we need the ill_index also. Copy that also into the
21117 		 * ipsec_out.
21118 		 */
21119 		if (mctl_present) {
21120 			io = (ipsec_out_t *)first_mp->b_rptr;
21121 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21122 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21123 		} else {
21124 			ASSERT(mp == first_mp);
21125 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21126 			    BPRI_HI)) == NULL) {
21127 				ipif_refrele(ipif);
21128 				first_mp = mp;
21129 				goto discard_pkt;
21130 			}
21131 			first_mp->b_datap->db_type = M_CTL;
21132 			first_mp->b_wptr += sizeof (ipsec_info_t);
21133 			/* ipsec_out_secure is B_FALSE now */
21134 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21135 			io = (ipsec_out_t *)first_mp->b_rptr;
21136 			io->ipsec_out_type = IPSEC_OUT;
21137 			io->ipsec_out_len = sizeof (ipsec_out_t);
21138 			io->ipsec_out_use_global_policy = B_TRUE;
21139 			io->ipsec_out_ns = ipst->ips_netstack;
21140 			first_mp->b_cont = mp;
21141 			mctl_present = B_TRUE;
21142 		}
21143 
21144 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21145 		io->ipsec_out_ill_index =
21146 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21147 
21148 		if (connp != NULL) {
21149 			io->ipsec_out_multicast_loop =
21150 			    connp->conn_multicast_loop;
21151 			io->ipsec_out_dontroute = connp->conn_dontroute;
21152 			io->ipsec_out_zoneid = connp->conn_zoneid;
21153 		}
21154 		/*
21155 		 * If the application uses IP_MULTICAST_IF with
21156 		 * different logical addresses of the same ILL, we
21157 		 * need to make sure that the soruce address of
21158 		 * the packet matches the logical IP address used
21159 		 * in the option. We do it by initializing ipha_src
21160 		 * here. This should keep IPsec also happy as
21161 		 * when we return from IPsec processing, we don't
21162 		 * have to worry about getting the right address on
21163 		 * the packet. Thus it is sufficient to look for
21164 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21165 		 * MATCH_IRE_IPIF.
21166 		 *
21167 		 * NOTE : We need to do it for non-secure case also as
21168 		 * this might go out secure if there is a global policy
21169 		 * match in ip_wput_ire.
21170 		 *
21171 		 * As we do not have the ire yet, it is possible that
21172 		 * we set the source address here and then later discover
21173 		 * that the ire implies the source address to be assigned
21174 		 * through the RTF_SETSRC flag.
21175 		 * In that case, the setsrc variable will remind us
21176 		 * that overwritting the source address by the one
21177 		 * of the RTF_SETSRC-flagged ire is allowed.
21178 		 */
21179 		if (ipha->ipha_src == INADDR_ANY &&
21180 		    (connp == NULL || !connp->conn_unspec_src)) {
21181 			ipha->ipha_src = ipif->ipif_src_addr;
21182 			setsrc = RTF_SETSRC;
21183 		}
21184 		/*
21185 		 * Find an IRE which matches the destination and the outgoing
21186 		 * queue (i.e. the outgoing interface.)
21187 		 * For loopback use a unicast IP address for
21188 		 * the ire lookup.
21189 		 */
21190 		if (IS_LOOPBACK(ipif->ipif_ill))
21191 			dst = ipif->ipif_lcl_addr;
21192 
21193 		/*
21194 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21195 		 * We don't need to lookup ire in ctable as the packet
21196 		 * needs to be sent to the destination through the specified
21197 		 * ill irrespective of ires in the cache table.
21198 		 */
21199 		ire = NULL;
21200 		if (xmit_ill == NULL) {
21201 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21202 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21203 		}
21204 
21205 		if (ire == NULL) {
21206 			/*
21207 			 * Multicast loopback and multicast forwarding is
21208 			 * done in ip_wput_ire.
21209 			 *
21210 			 * Mark this packet to make it be delivered to
21211 			 * ip_wput_ire after the new ire has been
21212 			 * created.
21213 			 *
21214 			 * The call to ip_newroute_ipif takes into account
21215 			 * the setsrc reminder. In any case, we take care
21216 			 * of the RTF_MULTIRT flag.
21217 			 */
21218 			mp->b_prev = mp->b_next = NULL;
21219 			if (xmit_ill == NULL ||
21220 			    xmit_ill->ill_ipif_up_count > 0) {
21221 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21222 				    setsrc | RTF_MULTIRT, zoneid, infop);
21223 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21224 				    "ip_wput_end: q %p (%S)", q, "noire");
21225 			} else {
21226 				freemsg(first_mp);
21227 			}
21228 			ipif_refrele(ipif);
21229 			if (xmit_ill != NULL)
21230 				ill_refrele(xmit_ill);
21231 			if (need_decref)
21232 				CONN_DEC_REF(connp);
21233 			return;
21234 		}
21235 
21236 		ipif_refrele(ipif);
21237 		ipif = NULL;
21238 		ASSERT(xmit_ill == NULL);
21239 
21240 		/*
21241 		 * Honor the RTF_SETSRC flag for multicast packets,
21242 		 * if allowed by the setsrc reminder.
21243 		 */
21244 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21245 			ipha->ipha_src = ire->ire_src_addr;
21246 		}
21247 
21248 		/*
21249 		 * Unconditionally force the TTL to 1 for
21250 		 * multirouted multicast packets:
21251 		 * multirouted multicast should not cross
21252 		 * multicast routers.
21253 		 */
21254 		if (ire->ire_flags & RTF_MULTIRT) {
21255 			if (ipha->ipha_ttl > 1) {
21256 				ip2dbg(("ip_wput: forcing multicast "
21257 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21258 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21259 				ipha->ipha_ttl = 1;
21260 			}
21261 		}
21262 	} else {
21263 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21264 		if ((ire != NULL) && (ire->ire_type &
21265 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21266 			ignore_dontroute = B_TRUE;
21267 			ignore_nexthop = B_TRUE;
21268 		}
21269 		if (ire != NULL) {
21270 			ire_refrele(ire);
21271 			ire = NULL;
21272 		}
21273 		/*
21274 		 * Guard against coming in from arp in which case conn is NULL.
21275 		 * Also guard against non M_DATA with dontroute set but
21276 		 * destined to local, loopback or broadcast addresses.
21277 		 */
21278 		if (connp != NULL && connp->conn_dontroute &&
21279 		    !ignore_dontroute) {
21280 dontroute:
21281 			/*
21282 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21283 			 * routing protocols from seeing false direct
21284 			 * connectivity.
21285 			 */
21286 			ipha->ipha_ttl = 1;
21287 			/* If suitable ipif not found, drop packet */
21288 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21289 			if (dst_ipif == NULL) {
21290 noroute:
21291 				ip1dbg(("ip_wput: no route for dst using"
21292 				    " SO_DONTROUTE\n"));
21293 				BUMP_MIB(&ipst->ips_ip_mib,
21294 				    ipIfStatsOutNoRoutes);
21295 				mp->b_prev = mp->b_next = NULL;
21296 				if (first_mp == NULL)
21297 					first_mp = mp;
21298 				goto drop_pkt;
21299 			} else {
21300 				/*
21301 				 * If suitable ipif has been found, set
21302 				 * xmit_ill to the corresponding
21303 				 * ipif_ill because we'll be using the
21304 				 * send_from_ill logic below.
21305 				 */
21306 				ASSERT(xmit_ill == NULL);
21307 				xmit_ill = dst_ipif->ipif_ill;
21308 				mutex_enter(&xmit_ill->ill_lock);
21309 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21310 					mutex_exit(&xmit_ill->ill_lock);
21311 					xmit_ill = NULL;
21312 					ipif_refrele(dst_ipif);
21313 					goto noroute;
21314 				}
21315 				ill_refhold_locked(xmit_ill);
21316 				mutex_exit(&xmit_ill->ill_lock);
21317 				ipif_refrele(dst_ipif);
21318 			}
21319 		}
21320 
21321 send_from_ill:
21322 		if (xmit_ill != NULL) {
21323 			ipif_t *ipif;
21324 
21325 			/*
21326 			 * Mark this packet as originated locally
21327 			 */
21328 			mp->b_prev = mp->b_next = NULL;
21329 
21330 			/*
21331 			 * Could be SO_DONTROUTE case also.
21332 			 * Verify that at least one ipif is up on the ill.
21333 			 */
21334 			if (xmit_ill->ill_ipif_up_count == 0) {
21335 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21336 				    xmit_ill->ill_name));
21337 				goto drop_pkt;
21338 			}
21339 
21340 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21341 			if (ipif == NULL) {
21342 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21343 				    xmit_ill->ill_name));
21344 				goto drop_pkt;
21345 			}
21346 
21347 			match_flags = 0;
21348 			if (IS_UNDER_IPMP(xmit_ill))
21349 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21350 
21351 			/*
21352 			 * Look for a ire that is part of the group,
21353 			 * if found use it else call ip_newroute_ipif.
21354 			 * IPCL_ZONEID is not used for matching because
21355 			 * IP_ALLZONES option is valid only when the
21356 			 * ill is accessible from all zones i.e has a
21357 			 * valid ipif in all zones.
21358 			 */
21359 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21360 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21361 			    msg_getlabel(mp), match_flags, ipst);
21362 			/*
21363 			 * If an ire exists use it or else create
21364 			 * an ire but don't add it to the cache.
21365 			 * Adding an ire may cause issues with
21366 			 * asymmetric routing.
21367 			 * In case of multiroute always act as if
21368 			 * ire does not exist.
21369 			 */
21370 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21371 				if (ire != NULL)
21372 					ire_refrele(ire);
21373 				ip_newroute_ipif(q, first_mp, ipif,
21374 				    dst, connp, 0, zoneid, infop);
21375 				ipif_refrele(ipif);
21376 				ip1dbg(("ip_output: xmit_ill via %s\n",
21377 				    xmit_ill->ill_name));
21378 				ill_refrele(xmit_ill);
21379 				if (need_decref)
21380 					CONN_DEC_REF(connp);
21381 				return;
21382 			}
21383 			ipif_refrele(ipif);
21384 		} else if (ip_nexthop || (connp != NULL &&
21385 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21386 			if (!ip_nexthop) {
21387 				ip_nexthop = B_TRUE;
21388 				nexthop_addr = connp->conn_nexthop_v4;
21389 			}
21390 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21391 			    MATCH_IRE_GW;
21392 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21393 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21394 		} else {
21395 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21396 			    ipst);
21397 		}
21398 		if (!ire) {
21399 			if (ip_nexthop && !ignore_nexthop) {
21400 				if (mctl_present) {
21401 					io = (ipsec_out_t *)first_mp->b_rptr;
21402 					ASSERT(first_mp->b_datap->db_type ==
21403 					    M_CTL);
21404 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21405 				} else {
21406 					ASSERT(mp == first_mp);
21407 					first_mp = allocb(
21408 					    sizeof (ipsec_info_t), BPRI_HI);
21409 					if (first_mp == NULL) {
21410 						first_mp = mp;
21411 						goto discard_pkt;
21412 					}
21413 					first_mp->b_datap->db_type = M_CTL;
21414 					first_mp->b_wptr +=
21415 					    sizeof (ipsec_info_t);
21416 					/* ipsec_out_secure is B_FALSE now */
21417 					bzero(first_mp->b_rptr,
21418 					    sizeof (ipsec_info_t));
21419 					io = (ipsec_out_t *)first_mp->b_rptr;
21420 					io->ipsec_out_type = IPSEC_OUT;
21421 					io->ipsec_out_len =
21422 					    sizeof (ipsec_out_t);
21423 					io->ipsec_out_use_global_policy =
21424 					    B_TRUE;
21425 					io->ipsec_out_ns = ipst->ips_netstack;
21426 					first_mp->b_cont = mp;
21427 					mctl_present = B_TRUE;
21428 				}
21429 				io->ipsec_out_ip_nexthop = ip_nexthop;
21430 				io->ipsec_out_nexthop_addr = nexthop_addr;
21431 			}
21432 noirefound:
21433 			/*
21434 			 * Mark this packet as having originated on
21435 			 * this machine.  This will be noted in
21436 			 * ire_add_then_send, which needs to know
21437 			 * whether to run it back through ip_wput or
21438 			 * ip_rput following successful resolution.
21439 			 */
21440 			mp->b_prev = NULL;
21441 			mp->b_next = NULL;
21442 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21443 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21444 			    "ip_wput_end: q %p (%S)", q, "newroute");
21445 			if (xmit_ill != NULL)
21446 				ill_refrele(xmit_ill);
21447 			if (need_decref)
21448 				CONN_DEC_REF(connp);
21449 			return;
21450 		}
21451 	}
21452 
21453 	/* We now know where we are going with it. */
21454 
21455 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21456 	    "ip_wput_end: q %p (%S)", q, "end");
21457 
21458 	/*
21459 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21460 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21461 	 */
21462 	if (ire->ire_flags & RTF_MULTIRT) {
21463 		/*
21464 		 * Force the TTL of multirouted packets if required.
21465 		 * The TTL of such packets is bounded by the
21466 		 * ip_multirt_ttl ndd variable.
21467 		 */
21468 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21469 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21470 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21471 			    "(was %d), dst 0x%08x\n",
21472 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21473 			    ntohl(ire->ire_addr)));
21474 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21475 		}
21476 		/*
21477 		 * At this point, we check to see if there are any pending
21478 		 * unresolved routes. ire_multirt_resolvable()
21479 		 * checks in O(n) that all IRE_OFFSUBNET ire
21480 		 * entries for the packet's destination and
21481 		 * flagged RTF_MULTIRT are currently resolved.
21482 		 * If some remain unresolved, we make a copy
21483 		 * of the current message. It will be used
21484 		 * to initiate additional route resolutions.
21485 		 */
21486 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21487 		    msg_getlabel(first_mp), ipst);
21488 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21489 		    "multirt_need_resolve %d, first_mp %p\n",
21490 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21491 		if (multirt_need_resolve) {
21492 			copy_mp = copymsg(first_mp);
21493 			if (copy_mp != NULL) {
21494 				MULTIRT_DEBUG_TAG(copy_mp);
21495 			}
21496 		}
21497 	}
21498 
21499 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21500 	/*
21501 	 * Try to resolve another multiroute if
21502 	 * ire_multirt_resolvable() deemed it necessary.
21503 	 * At this point, we need to distinguish
21504 	 * multicasts from other packets. For multicasts,
21505 	 * we call ip_newroute_ipif() and request that both
21506 	 * multirouting and setsrc flags are checked.
21507 	 */
21508 	if (copy_mp != NULL) {
21509 		if (CLASSD(dst)) {
21510 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21511 			if (ipif) {
21512 				ASSERT(infop->ip_opt_ill_index == 0);
21513 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21514 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21515 				ipif_refrele(ipif);
21516 			} else {
21517 				MULTIRT_DEBUG_UNTAG(copy_mp);
21518 				freemsg(copy_mp);
21519 				copy_mp = NULL;
21520 			}
21521 		} else {
21522 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21523 		}
21524 	}
21525 	if (xmit_ill != NULL)
21526 		ill_refrele(xmit_ill);
21527 	if (need_decref)
21528 		CONN_DEC_REF(connp);
21529 	return;
21530 
21531 icmp_parameter_problem:
21532 	/* could not have originated externally */
21533 	ASSERT(mp->b_prev == NULL);
21534 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21535 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21536 		/* it's the IP header length that's in trouble */
21537 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21538 		first_mp = NULL;
21539 	}
21540 
21541 discard_pkt:
21542 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21543 drop_pkt:
21544 	ip1dbg(("ip_wput: dropped packet\n"));
21545 	if (ire != NULL)
21546 		ire_refrele(ire);
21547 	if (need_decref)
21548 		CONN_DEC_REF(connp);
21549 	freemsg(first_mp);
21550 	if (xmit_ill != NULL)
21551 		ill_refrele(xmit_ill);
21552 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21553 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21554 }
21555 
21556 /*
21557  * If this is a conn_t queue, then we pass in the conn. This includes the
21558  * zoneid.
21559  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21560  * in which case we use the global zoneid since those are all part of
21561  * the global zone.
21562  */
21563 void
21564 ip_wput(queue_t *q, mblk_t *mp)
21565 {
21566 	if (CONN_Q(q))
21567 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21568 	else
21569 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21570 }
21571 
21572 /*
21573  *
21574  * The following rules must be observed when accessing any ipif or ill
21575  * that has been cached in the conn. Typically conn_outgoing_ill,
21576  * conn_multicast_ipif and conn_multicast_ill.
21577  *
21578  * Access: The ipif or ill pointed to from the conn can be accessed under
21579  * the protection of the conn_lock or after it has been refheld under the
21580  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21581  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21582  * The reason for this is that a concurrent unplumb could actually be
21583  * cleaning up these cached pointers by walking the conns and might have
21584  * finished cleaning up the conn in question. The macros check that an
21585  * unplumb has not yet started on the ipif or ill.
21586  *
21587  * Caching: An ipif or ill pointer may be cached in the conn only after
21588  * making sure that an unplumb has not started. So the caching is done
21589  * while holding both the conn_lock and the ill_lock and after using the
21590  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21591  * flag before starting the cleanup of conns.
21592  *
21593  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21594  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21595  * or a reference to the ipif or a reference to an ire that references the
21596  * ipif. An ipif only changes its ill when migrating from an underlying ill
21597  * to an IPMP ill in ipif_up().
21598  */
21599 ipif_t *
21600 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21601 {
21602 	ipif_t	*ipif;
21603 	ill_t	*ill;
21604 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21605 
21606 	*err = 0;
21607 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21608 	mutex_enter(&connp->conn_lock);
21609 	ipif = *ipifp;
21610 	if (ipif != NULL) {
21611 		ill = ipif->ipif_ill;
21612 		mutex_enter(&ill->ill_lock);
21613 		if (IPIF_CAN_LOOKUP(ipif)) {
21614 			ipif_refhold_locked(ipif);
21615 			mutex_exit(&ill->ill_lock);
21616 			mutex_exit(&connp->conn_lock);
21617 			rw_exit(&ipst->ips_ill_g_lock);
21618 			return (ipif);
21619 		} else {
21620 			*err = IPIF_LOOKUP_FAILED;
21621 		}
21622 		mutex_exit(&ill->ill_lock);
21623 	}
21624 	mutex_exit(&connp->conn_lock);
21625 	rw_exit(&ipst->ips_ill_g_lock);
21626 	return (NULL);
21627 }
21628 
21629 ill_t *
21630 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21631 {
21632 	ill_t	*ill;
21633 
21634 	*err = 0;
21635 	mutex_enter(&connp->conn_lock);
21636 	ill = *illp;
21637 	if (ill != NULL) {
21638 		mutex_enter(&ill->ill_lock);
21639 		if (ILL_CAN_LOOKUP(ill)) {
21640 			ill_refhold_locked(ill);
21641 			mutex_exit(&ill->ill_lock);
21642 			mutex_exit(&connp->conn_lock);
21643 			return (ill);
21644 		} else {
21645 			*err = ILL_LOOKUP_FAILED;
21646 		}
21647 		mutex_exit(&ill->ill_lock);
21648 	}
21649 	mutex_exit(&connp->conn_lock);
21650 	return (NULL);
21651 }
21652 
21653 static int
21654 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21655 {
21656 	ill_t	*ill;
21657 
21658 	ill = ipif->ipif_ill;
21659 	mutex_enter(&connp->conn_lock);
21660 	mutex_enter(&ill->ill_lock);
21661 	if (IPIF_CAN_LOOKUP(ipif)) {
21662 		*ipifp = ipif;
21663 		mutex_exit(&ill->ill_lock);
21664 		mutex_exit(&connp->conn_lock);
21665 		return (0);
21666 	}
21667 	mutex_exit(&ill->ill_lock);
21668 	mutex_exit(&connp->conn_lock);
21669 	return (IPIF_LOOKUP_FAILED);
21670 }
21671 
21672 /*
21673  * This is called if the outbound datagram needs fragmentation.
21674  *
21675  * NOTE : This function does not ire_refrele the ire argument passed in.
21676  */
21677 static void
21678 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21679     ip_stack_t *ipst, conn_t *connp)
21680 {
21681 	ipha_t		*ipha;
21682 	mblk_t		*mp;
21683 	uint32_t	v_hlen_tos_len;
21684 	uint32_t	max_frag;
21685 	uint32_t	frag_flag;
21686 	boolean_t	dont_use;
21687 
21688 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21689 		mp = ipsec_mp->b_cont;
21690 	} else {
21691 		mp = ipsec_mp;
21692 	}
21693 
21694 	ipha = (ipha_t *)mp->b_rptr;
21695 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21696 
21697 #ifdef	_BIG_ENDIAN
21698 #define	V_HLEN	(v_hlen_tos_len >> 24)
21699 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21700 #else
21701 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21702 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21703 #endif
21704 
21705 #ifndef SPEED_BEFORE_SAFETY
21706 	/*
21707 	 * Check that ipha_length is consistent with
21708 	 * the mblk length
21709 	 */
21710 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21711 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21712 		    LENGTH, msgdsize(mp)));
21713 		freemsg(ipsec_mp);
21714 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21715 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21716 		    "packet length mismatch");
21717 		return;
21718 	}
21719 #endif
21720 	/*
21721 	 * Don't use frag_flag if pre-built packet or source
21722 	 * routed or if multicast (since multicast packets do not solicit
21723 	 * ICMP "packet too big" messages). Get the values of
21724 	 * max_frag and frag_flag atomically by acquiring the
21725 	 * ire_lock.
21726 	 */
21727 	mutex_enter(&ire->ire_lock);
21728 	max_frag = ire->ire_max_frag;
21729 	frag_flag = ire->ire_frag_flag;
21730 	mutex_exit(&ire->ire_lock);
21731 
21732 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21733 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21734 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21735 
21736 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21737 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21738 }
21739 
21740 /*
21741  * Used for deciding the MSS size for the upper layer. Thus
21742  * we need to check the outbound policy values in the conn.
21743  */
21744 int
21745 conn_ipsec_length(conn_t *connp)
21746 {
21747 	ipsec_latch_t *ipl;
21748 
21749 	ipl = connp->conn_latch;
21750 	if (ipl == NULL)
21751 		return (0);
21752 
21753 	if (ipl->ipl_out_policy == NULL)
21754 		return (0);
21755 
21756 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21757 }
21758 
21759 /*
21760  * Returns an estimate of the IPsec headers size. This is used if
21761  * we don't want to call into IPsec to get the exact size.
21762  */
21763 int
21764 ipsec_out_extra_length(mblk_t *ipsec_mp)
21765 {
21766 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21767 	ipsec_action_t *a;
21768 
21769 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21770 	if (!io->ipsec_out_secure)
21771 		return (0);
21772 
21773 	a = io->ipsec_out_act;
21774 
21775 	if (a == NULL) {
21776 		ASSERT(io->ipsec_out_policy != NULL);
21777 		a = io->ipsec_out_policy->ipsp_act;
21778 	}
21779 	ASSERT(a != NULL);
21780 
21781 	return (a->ipa_ovhd);
21782 }
21783 
21784 /*
21785  * Returns an estimate of the IPsec headers size. This is used if
21786  * we don't want to call into IPsec to get the exact size.
21787  */
21788 int
21789 ipsec_in_extra_length(mblk_t *ipsec_mp)
21790 {
21791 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21792 	ipsec_action_t *a;
21793 
21794 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21795 
21796 	a = ii->ipsec_in_action;
21797 	return (a == NULL ? 0 : a->ipa_ovhd);
21798 }
21799 
21800 /*
21801  * If there are any source route options, return the true final
21802  * destination. Otherwise, return the destination.
21803  */
21804 ipaddr_t
21805 ip_get_dst(ipha_t *ipha)
21806 {
21807 	ipoptp_t	opts;
21808 	uchar_t		*opt;
21809 	uint8_t		optval;
21810 	uint8_t		optlen;
21811 	ipaddr_t	dst;
21812 	uint32_t off;
21813 
21814 	dst = ipha->ipha_dst;
21815 
21816 	if (IS_SIMPLE_IPH(ipha))
21817 		return (dst);
21818 
21819 	for (optval = ipoptp_first(&opts, ipha);
21820 	    optval != IPOPT_EOL;
21821 	    optval = ipoptp_next(&opts)) {
21822 		opt = opts.ipoptp_cur;
21823 		optlen = opts.ipoptp_len;
21824 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21825 		switch (optval) {
21826 		case IPOPT_SSRR:
21827 		case IPOPT_LSRR:
21828 			off = opt[IPOPT_OFFSET];
21829 			/*
21830 			 * If one of the conditions is true, it means
21831 			 * end of options and dst already has the right
21832 			 * value.
21833 			 */
21834 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21835 				off = optlen - IP_ADDR_LEN;
21836 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21837 			}
21838 			return (dst);
21839 		default:
21840 			break;
21841 		}
21842 	}
21843 
21844 	return (dst);
21845 }
21846 
21847 mblk_t *
21848 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21849     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21850 {
21851 	ipsec_out_t	*io;
21852 	mblk_t		*first_mp;
21853 	boolean_t policy_present;
21854 	ip_stack_t	*ipst;
21855 	ipsec_stack_t	*ipss;
21856 
21857 	ASSERT(ire != NULL);
21858 	ipst = ire->ire_ipst;
21859 	ipss = ipst->ips_netstack->netstack_ipsec;
21860 
21861 	first_mp = mp;
21862 	if (mp->b_datap->db_type == M_CTL) {
21863 		io = (ipsec_out_t *)first_mp->b_rptr;
21864 		/*
21865 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21866 		 *
21867 		 * 1) There is per-socket policy (including cached global
21868 		 *    policy) or a policy on the IP-in-IP tunnel.
21869 		 * 2) There is no per-socket policy, but it is
21870 		 *    a multicast packet that needs to go out
21871 		 *    on a specific interface. This is the case
21872 		 *    where (ip_wput and ip_wput_multicast) attaches
21873 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21874 		 *
21875 		 * In case (2) we check with global policy to
21876 		 * see if there is a match and set the ill_index
21877 		 * appropriately so that we can lookup the ire
21878 		 * properly in ip_wput_ipsec_out.
21879 		 */
21880 
21881 		/*
21882 		 * ipsec_out_use_global_policy is set to B_FALSE
21883 		 * in ipsec_in_to_out(). Refer to that function for
21884 		 * details.
21885 		 */
21886 		if ((io->ipsec_out_latch == NULL) &&
21887 		    (io->ipsec_out_use_global_policy)) {
21888 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21889 			    ire, connp, unspec_src, zoneid));
21890 		}
21891 		if (!io->ipsec_out_secure) {
21892 			/*
21893 			 * If this is not a secure packet, drop
21894 			 * the IPSEC_OUT mp and treat it as a clear
21895 			 * packet. This happens when we are sending
21896 			 * a ICMP reply back to a clear packet. See
21897 			 * ipsec_in_to_out() for details.
21898 			 */
21899 			mp = first_mp->b_cont;
21900 			freeb(first_mp);
21901 		}
21902 		return (mp);
21903 	}
21904 	/*
21905 	 * See whether we need to attach a global policy here. We
21906 	 * don't depend on the conn (as it could be null) for deciding
21907 	 * what policy this datagram should go through because it
21908 	 * should have happened in ip_wput if there was some
21909 	 * policy. This normally happens for connections which are not
21910 	 * fully bound preventing us from caching policies in
21911 	 * ip_bind. Packets coming from the TCP listener/global queue
21912 	 * - which are non-hard_bound - could also be affected by
21913 	 * applying policy here.
21914 	 *
21915 	 * If this packet is coming from tcp global queue or listener,
21916 	 * we will be applying policy here.  This may not be *right*
21917 	 * if these packets are coming from the detached connection as
21918 	 * it could have gone in clear before. This happens only if a
21919 	 * TCP connection started when there is no policy and somebody
21920 	 * added policy before it became detached. Thus packets of the
21921 	 * detached connection could go out secure and the other end
21922 	 * would drop it because it will be expecting in clear. The
21923 	 * converse is not true i.e if somebody starts a TCP
21924 	 * connection and deletes the policy, all the packets will
21925 	 * still go out with the policy that existed before deleting
21926 	 * because ip_unbind sends up policy information which is used
21927 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21928 	 * TCP to attach a dummy IPSEC_OUT and set
21929 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21930 	 * affect performance for normal cases, we are not doing it.
21931 	 * Thus, set policy before starting any TCP connections.
21932 	 *
21933 	 * NOTE - We might apply policy even for a hard bound connection
21934 	 * - for which we cached policy in ip_bind - if somebody added
21935 	 * global policy after we inherited the policy in ip_bind.
21936 	 * This means that the packets that were going out in clear
21937 	 * previously would start going secure and hence get dropped
21938 	 * on the other side. To fix this, TCP attaches a dummy
21939 	 * ipsec_out and make sure that we don't apply global policy.
21940 	 */
21941 	if (ipha != NULL)
21942 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21943 	else
21944 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21945 	if (!policy_present)
21946 		return (mp);
21947 
21948 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21949 	    zoneid));
21950 }
21951 
21952 /*
21953  * This function does the ire_refrele of the ire passed in as the
21954  * argument. As this function looks up more ires i.e broadcast ires,
21955  * it needs to REFRELE them. Currently, for simplicity we don't
21956  * differentiate the one passed in and looked up here. We always
21957  * REFRELE.
21958  * IPQoS Notes:
21959  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21960  * IPsec packets are done in ipsec_out_process.
21961  */
21962 void
21963 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21964     zoneid_t zoneid)
21965 {
21966 	ipha_t		*ipha;
21967 #define	rptr	((uchar_t *)ipha)
21968 	queue_t		*stq;
21969 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21970 	uint32_t	v_hlen_tos_len;
21971 	uint32_t	ttl_protocol;
21972 	ipaddr_t	src;
21973 	ipaddr_t	dst;
21974 	uint32_t	cksum;
21975 	ipaddr_t	orig_src;
21976 	ire_t		*ire1;
21977 	mblk_t		*next_mp;
21978 	uint_t		hlen;
21979 	uint16_t	*up;
21980 	uint32_t	max_frag = ire->ire_max_frag;
21981 	ill_t		*ill = ire_to_ill(ire);
21982 	int		clusterwide;
21983 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21984 	int		ipsec_len;
21985 	mblk_t		*first_mp;
21986 	ipsec_out_t	*io;
21987 	boolean_t	conn_dontroute;		/* conn value for multicast */
21988 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21989 	boolean_t	multicast_forward;	/* Should we forward ? */
21990 	boolean_t	unspec_src;
21991 	ill_t		*conn_outgoing_ill = NULL;
21992 	ill_t		*ire_ill;
21993 	ill_t		*ire1_ill;
21994 	ill_t		*out_ill;
21995 	uint32_t 	ill_index = 0;
21996 	boolean_t	multirt_send = B_FALSE;
21997 	int		err;
21998 	ipxmit_state_t	pktxmit_state;
21999 	ip_stack_t	*ipst = ire->ire_ipst;
22000 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22001 
22002 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22003 	    "ip_wput_ire_start: q %p", q);
22004 
22005 	multicast_forward = B_FALSE;
22006 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22007 
22008 	if (ire->ire_flags & RTF_MULTIRT) {
22009 		/*
22010 		 * Multirouting case. The bucket where ire is stored
22011 		 * probably holds other RTF_MULTIRT flagged ire
22012 		 * to the destination. In this call to ip_wput_ire,
22013 		 * we attempt to send the packet through all
22014 		 * those ires. Thus, we first ensure that ire is the
22015 		 * first RTF_MULTIRT ire in the bucket,
22016 		 * before walking the ire list.
22017 		 */
22018 		ire_t *first_ire;
22019 		irb_t *irb = ire->ire_bucket;
22020 		ASSERT(irb != NULL);
22021 
22022 		/* Make sure we do not omit any multiroute ire. */
22023 		IRB_REFHOLD(irb);
22024 		for (first_ire = irb->irb_ire;
22025 		    first_ire != NULL;
22026 		    first_ire = first_ire->ire_next) {
22027 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22028 			    (first_ire->ire_addr == ire->ire_addr) &&
22029 			    !(first_ire->ire_marks &
22030 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22031 				break;
22032 		}
22033 
22034 		if ((first_ire != NULL) && (first_ire != ire)) {
22035 			IRE_REFHOLD(first_ire);
22036 			ire_refrele(ire);
22037 			ire = first_ire;
22038 			ill = ire_to_ill(ire);
22039 		}
22040 		IRB_REFRELE(irb);
22041 	}
22042 
22043 	/*
22044 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22045 	 * for performance we don't grab the mutexs in the fastpath
22046 	 */
22047 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22048 	    connp->conn_outgoing_ill != NULL) {
22049 		conn_outgoing_ill = conn_get_held_ill(connp,
22050 		    &connp->conn_outgoing_ill, &err);
22051 		if (err == ILL_LOOKUP_FAILED) {
22052 			ire_refrele(ire);
22053 			freemsg(mp);
22054 			return;
22055 		}
22056 	}
22057 
22058 	if (mp->b_datap->db_type != M_CTL) {
22059 		ipha = (ipha_t *)mp->b_rptr;
22060 	} else {
22061 		io = (ipsec_out_t *)mp->b_rptr;
22062 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22063 		ASSERT(zoneid == io->ipsec_out_zoneid);
22064 		ASSERT(zoneid != ALL_ZONES);
22065 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22066 		dst = ipha->ipha_dst;
22067 		/*
22068 		 * For the multicast case, ipsec_out carries conn_dontroute and
22069 		 * conn_multicast_loop as conn may not be available here. We
22070 		 * need this for multicast loopback and forwarding which is done
22071 		 * later in the code.
22072 		 */
22073 		if (CLASSD(dst)) {
22074 			conn_dontroute = io->ipsec_out_dontroute;
22075 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22076 			/*
22077 			 * If conn_dontroute is not set or conn_multicast_loop
22078 			 * is set, we need to do forwarding/loopback. For
22079 			 * datagrams from ip_wput_multicast, conn_dontroute is
22080 			 * set to B_TRUE and conn_multicast_loop is set to
22081 			 * B_FALSE so that we neither do forwarding nor
22082 			 * loopback.
22083 			 */
22084 			if (!conn_dontroute || conn_multicast_loop)
22085 				multicast_forward = B_TRUE;
22086 		}
22087 	}
22088 
22089 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22090 	    ire->ire_zoneid != ALL_ZONES) {
22091 		/*
22092 		 * When a zone sends a packet to another zone, we try to deliver
22093 		 * the packet under the same conditions as if the destination
22094 		 * was a real node on the network. To do so, we look for a
22095 		 * matching route in the forwarding table.
22096 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22097 		 * ip_newroute() does.
22098 		 * Note that IRE_LOCAL are special, since they are used
22099 		 * when the zoneid doesn't match in some cases. This means that
22100 		 * we need to handle ipha_src differently since ire_src_addr
22101 		 * belongs to the receiving zone instead of the sending zone.
22102 		 * When ip_restrict_interzone_loopback is set, then
22103 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22104 		 * for loopback between zones when the logical "Ethernet" would
22105 		 * have looped them back.
22106 		 */
22107 		ire_t *src_ire;
22108 
22109 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22110 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22111 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22112 		if (src_ire != NULL &&
22113 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22114 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22115 		    ire_local_same_lan(ire, src_ire))) {
22116 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22117 				ipha->ipha_src = src_ire->ire_src_addr;
22118 			ire_refrele(src_ire);
22119 		} else {
22120 			ire_refrele(ire);
22121 			if (conn_outgoing_ill != NULL)
22122 				ill_refrele(conn_outgoing_ill);
22123 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22124 			if (src_ire != NULL) {
22125 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22126 					ire_refrele(src_ire);
22127 					freemsg(mp);
22128 					return;
22129 				}
22130 				ire_refrele(src_ire);
22131 			}
22132 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22133 				/* Failed */
22134 				freemsg(mp);
22135 				return;
22136 			}
22137 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22138 			    ipst);
22139 			return;
22140 		}
22141 	}
22142 
22143 	if (mp->b_datap->db_type == M_CTL ||
22144 	    ipss->ipsec_outbound_v4_policy_present) {
22145 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22146 		    unspec_src, zoneid);
22147 		if (mp == NULL) {
22148 			ire_refrele(ire);
22149 			if (conn_outgoing_ill != NULL)
22150 				ill_refrele(conn_outgoing_ill);
22151 			return;
22152 		}
22153 		/*
22154 		 * Trusted Extensions supports all-zones interfaces, so
22155 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22156 		 * the global zone.
22157 		 */
22158 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22159 			io = (ipsec_out_t *)mp->b_rptr;
22160 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22161 			zoneid = io->ipsec_out_zoneid;
22162 		}
22163 	}
22164 
22165 	first_mp = mp;
22166 	ipsec_len = 0;
22167 
22168 	if (first_mp->b_datap->db_type == M_CTL) {
22169 		io = (ipsec_out_t *)first_mp->b_rptr;
22170 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22171 		mp = first_mp->b_cont;
22172 		ipsec_len = ipsec_out_extra_length(first_mp);
22173 		ASSERT(ipsec_len >= 0);
22174 		/* We already picked up the zoneid from the M_CTL above */
22175 		ASSERT(zoneid == io->ipsec_out_zoneid);
22176 		ASSERT(zoneid != ALL_ZONES);
22177 
22178 		/*
22179 		 * Drop M_CTL here if IPsec processing is not needed.
22180 		 * (Non-IPsec use of M_CTL extracted any information it
22181 		 * needed above).
22182 		 */
22183 		if (ipsec_len == 0) {
22184 			freeb(first_mp);
22185 			first_mp = mp;
22186 		}
22187 	}
22188 
22189 	/*
22190 	 * Fast path for ip_wput_ire
22191 	 */
22192 
22193 	ipha = (ipha_t *)mp->b_rptr;
22194 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22195 	dst = ipha->ipha_dst;
22196 
22197 	/*
22198 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22199 	 * if the socket is a SOCK_RAW type. The transport checksum should
22200 	 * be provided in the pre-built packet, so we don't need to compute it.
22201 	 * Also, other application set flags, like DF, should not be altered.
22202 	 * Other transport MUST pass down zero.
22203 	 */
22204 	ip_hdr_included = ipha->ipha_ident;
22205 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22206 
22207 	if (CLASSD(dst)) {
22208 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22209 		    ntohl(dst),
22210 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22211 		    ntohl(ire->ire_addr)));
22212 	}
22213 
22214 /* Macros to extract header fields from data already in registers */
22215 #ifdef	_BIG_ENDIAN
22216 #define	V_HLEN	(v_hlen_tos_len >> 24)
22217 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22218 #define	PROTO	(ttl_protocol & 0xFF)
22219 #else
22220 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22221 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22222 #define	PROTO	(ttl_protocol >> 8)
22223 #endif
22224 
22225 	orig_src = src = ipha->ipha_src;
22226 	/* (The loop back to "another" is explained down below.) */
22227 another:;
22228 	/*
22229 	 * Assign an ident value for this packet.  We assign idents on
22230 	 * a per destination basis out of the IRE.  There could be
22231 	 * other threads targeting the same destination, so we have to
22232 	 * arrange for a atomic increment.  Note that we use a 32-bit
22233 	 * atomic add because it has better performance than its
22234 	 * 16-bit sibling.
22235 	 *
22236 	 * If running in cluster mode and if the source address
22237 	 * belongs to a replicated service then vector through
22238 	 * cl_inet_ipident vector to allocate ip identifier
22239 	 * NOTE: This is a contract private interface with the
22240 	 * clustering group.
22241 	 */
22242 	clusterwide = 0;
22243 	if (cl_inet_ipident) {
22244 		ASSERT(cl_inet_isclusterwide);
22245 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22246 
22247 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22248 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22249 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22250 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22251 			    (uint8_t *)(uintptr_t)dst, NULL);
22252 			clusterwide = 1;
22253 		}
22254 	}
22255 	if (!clusterwide) {
22256 		ipha->ipha_ident =
22257 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22258 	}
22259 
22260 #ifndef _BIG_ENDIAN
22261 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22262 #endif
22263 
22264 	/*
22265 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22266 	 * This is needed to obey conn_unspec_src when packets go through
22267 	 * ip_newroute + arp.
22268 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22269 	 */
22270 	if (src == INADDR_ANY && !unspec_src) {
22271 		/*
22272 		 * Assign the appropriate source address from the IRE if none
22273 		 * was specified.
22274 		 */
22275 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22276 
22277 		src = ire->ire_src_addr;
22278 		if (connp == NULL) {
22279 			ip1dbg(("ip_wput_ire: no connp and no src "
22280 			    "address for dst 0x%x, using src 0x%x\n",
22281 			    ntohl(dst),
22282 			    ntohl(src)));
22283 		}
22284 		ipha->ipha_src = src;
22285 	}
22286 	stq = ire->ire_stq;
22287 
22288 	/*
22289 	 * We only allow ire chains for broadcasts since there will
22290 	 * be multiple IRE_CACHE entries for the same multicast
22291 	 * address (one per ipif).
22292 	 */
22293 	next_mp = NULL;
22294 
22295 	/* broadcast packet */
22296 	if (ire->ire_type == IRE_BROADCAST)
22297 		goto broadcast;
22298 
22299 	/* loopback ? */
22300 	if (stq == NULL)
22301 		goto nullstq;
22302 
22303 	/* The ill_index for outbound ILL */
22304 	ill_index = Q_TO_INDEX(stq);
22305 
22306 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22307 	ttl_protocol = ((uint16_t *)ipha)[4];
22308 
22309 	/* pseudo checksum (do it in parts for IP header checksum) */
22310 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22311 
22312 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22313 		queue_t *dev_q = stq->q_next;
22314 
22315 		/*
22316 		 * For DIRECT_CAPABLE, we do flow control at
22317 		 * the time of sending the packet. See
22318 		 * ILL_SEND_TX().
22319 		 */
22320 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22321 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22322 			goto blocked;
22323 
22324 		if ((PROTO == IPPROTO_UDP) &&
22325 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22326 			hlen = (V_HLEN & 0xF) << 2;
22327 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22328 			if (*up != 0) {
22329 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22330 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22331 				/* Software checksum? */
22332 				if (DB_CKSUMFLAGS(mp) == 0) {
22333 					IP_STAT(ipst, ip_out_sw_cksum);
22334 					IP_STAT_UPDATE(ipst,
22335 					    ip_udp_out_sw_cksum_bytes,
22336 					    LENGTH - hlen);
22337 				}
22338 			}
22339 		}
22340 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22341 		hlen = (V_HLEN & 0xF) << 2;
22342 		if (PROTO == IPPROTO_TCP) {
22343 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22344 			/*
22345 			 * The packet header is processed once and for all, even
22346 			 * in the multirouting case. We disable hardware
22347 			 * checksum if the packet is multirouted, as it will be
22348 			 * replicated via several interfaces, and not all of
22349 			 * them may have this capability.
22350 			 */
22351 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22352 			    LENGTH, max_frag, ipsec_len, cksum);
22353 			/* Software checksum? */
22354 			if (DB_CKSUMFLAGS(mp) == 0) {
22355 				IP_STAT(ipst, ip_out_sw_cksum);
22356 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22357 				    LENGTH - hlen);
22358 			}
22359 		} else {
22360 			sctp_hdr_t	*sctph;
22361 
22362 			ASSERT(PROTO == IPPROTO_SCTP);
22363 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22364 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22365 			/*
22366 			 * Zero out the checksum field to ensure proper
22367 			 * checksum calculation.
22368 			 */
22369 			sctph->sh_chksum = 0;
22370 #ifdef	DEBUG
22371 			if (!skip_sctp_cksum)
22372 #endif
22373 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22374 		}
22375 	}
22376 
22377 	/*
22378 	 * If this is a multicast packet and originated from ip_wput
22379 	 * we need to do loopback and forwarding checks. If it comes
22380 	 * from ip_wput_multicast, we SHOULD not do this.
22381 	 */
22382 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22383 
22384 	/* checksum */
22385 	cksum += ttl_protocol;
22386 
22387 	/* fragment the packet */
22388 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22389 		goto fragmentit;
22390 	/*
22391 	 * Don't use frag_flag if packet is pre-built or source
22392 	 * routed or if multicast (since multicast packets do
22393 	 * not solicit ICMP "packet too big" messages).
22394 	 */
22395 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22396 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22397 	    !ip_source_route_included(ipha)) &&
22398 	    !CLASSD(ipha->ipha_dst))
22399 		ipha->ipha_fragment_offset_and_flags |=
22400 		    htons(ire->ire_frag_flag);
22401 
22402 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22403 		/* calculate IP header checksum */
22404 		cksum += ipha->ipha_ident;
22405 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22406 		cksum += ipha->ipha_fragment_offset_and_flags;
22407 
22408 		/* IP options present */
22409 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22410 		if (hlen)
22411 			goto checksumoptions;
22412 
22413 		/* calculate hdr checksum */
22414 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22415 		cksum = ~(cksum + (cksum >> 16));
22416 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22417 	}
22418 	if (ipsec_len != 0) {
22419 		/*
22420 		 * We will do the rest of the processing after
22421 		 * we come back from IPsec in ip_wput_ipsec_out().
22422 		 */
22423 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22424 
22425 		io = (ipsec_out_t *)first_mp->b_rptr;
22426 		io->ipsec_out_ill_index =
22427 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22428 		ipsec_out_process(q, first_mp, ire, 0);
22429 		ire_refrele(ire);
22430 		if (conn_outgoing_ill != NULL)
22431 			ill_refrele(conn_outgoing_ill);
22432 		return;
22433 	}
22434 
22435 	/*
22436 	 * In most cases, the emission loop below is entered only
22437 	 * once. Only in the case where the ire holds the
22438 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22439 	 * flagged ires in the bucket, and send the packet
22440 	 * through all crossed RTF_MULTIRT routes.
22441 	 */
22442 	if (ire->ire_flags & RTF_MULTIRT) {
22443 		multirt_send = B_TRUE;
22444 	}
22445 	do {
22446 		if (multirt_send) {
22447 			irb_t *irb;
22448 			/*
22449 			 * We are in a multiple send case, need to get
22450 			 * the next ire and make a duplicate of the packet.
22451 			 * ire1 holds here the next ire to process in the
22452 			 * bucket. If multirouting is expected,
22453 			 * any non-RTF_MULTIRT ire that has the
22454 			 * right destination address is ignored.
22455 			 */
22456 			irb = ire->ire_bucket;
22457 			ASSERT(irb != NULL);
22458 
22459 			IRB_REFHOLD(irb);
22460 			for (ire1 = ire->ire_next;
22461 			    ire1 != NULL;
22462 			    ire1 = ire1->ire_next) {
22463 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22464 					continue;
22465 				if (ire1->ire_addr != ire->ire_addr)
22466 					continue;
22467 				if (ire1->ire_marks &
22468 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22469 					continue;
22470 
22471 				/* Got one */
22472 				IRE_REFHOLD(ire1);
22473 				break;
22474 			}
22475 			IRB_REFRELE(irb);
22476 
22477 			if (ire1 != NULL) {
22478 				next_mp = copyb(mp);
22479 				if ((next_mp == NULL) ||
22480 				    ((mp->b_cont != NULL) &&
22481 				    ((next_mp->b_cont =
22482 				    dupmsg(mp->b_cont)) == NULL))) {
22483 					freemsg(next_mp);
22484 					next_mp = NULL;
22485 					ire_refrele(ire1);
22486 					ire1 = NULL;
22487 				}
22488 			}
22489 
22490 			/* Last multiroute ire; don't loop anymore. */
22491 			if (ire1 == NULL) {
22492 				multirt_send = B_FALSE;
22493 			}
22494 		}
22495 
22496 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22497 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22498 		    mblk_t *, mp);
22499 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22500 		    ipst->ips_ipv4firewall_physical_out,
22501 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22502 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22503 
22504 		if (mp == NULL)
22505 			goto release_ire_and_ill;
22506 
22507 		if (ipst->ips_ip4_observe.he_interested) {
22508 			zoneid_t szone;
22509 
22510 			/*
22511 			 * On the outbound path the destination zone will be
22512 			 * unknown as we're sending this packet out on the
22513 			 * wire.
22514 			 */
22515 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22516 			    ALL_ZONES);
22517 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22518 			    ire->ire_ipif->ipif_ill, ipst);
22519 		}
22520 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22521 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22522 
22523 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22524 
22525 		if ((pktxmit_state == SEND_FAILED) ||
22526 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22527 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22528 			    "- packet dropped\n"));
22529 release_ire_and_ill:
22530 			ire_refrele(ire);
22531 			if (next_mp != NULL) {
22532 				freemsg(next_mp);
22533 				ire_refrele(ire1);
22534 			}
22535 			if (conn_outgoing_ill != NULL)
22536 				ill_refrele(conn_outgoing_ill);
22537 			return;
22538 		}
22539 
22540 		if (CLASSD(dst)) {
22541 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22542 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22543 			    LENGTH);
22544 		}
22545 
22546 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22547 		    "ip_wput_ire_end: q %p (%S)",
22548 		    q, "last copy out");
22549 		IRE_REFRELE(ire);
22550 
22551 		if (multirt_send) {
22552 			ASSERT(ire1);
22553 			/*
22554 			 * Proceed with the next RTF_MULTIRT ire,
22555 			 * Also set up the send-to queue accordingly.
22556 			 */
22557 			ire = ire1;
22558 			ire1 = NULL;
22559 			stq = ire->ire_stq;
22560 			mp = next_mp;
22561 			next_mp = NULL;
22562 			ipha = (ipha_t *)mp->b_rptr;
22563 			ill_index = Q_TO_INDEX(stq);
22564 			ill = (ill_t *)stq->q_ptr;
22565 		}
22566 	} while (multirt_send);
22567 	if (conn_outgoing_ill != NULL)
22568 		ill_refrele(conn_outgoing_ill);
22569 	return;
22570 
22571 	/*
22572 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22573 	 */
22574 broadcast:
22575 	{
22576 		/*
22577 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22578 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22579 		 * can be overridden stack-wide through the ip_broadcast_ttl
22580 		 * ndd tunable, or on a per-connection basis through the
22581 		 * IP_BROADCAST_TTL socket option.
22582 		 *
22583 		 * In the event that we are replying to incoming ICMP packets,
22584 		 * connp could be NULL.
22585 		 */
22586 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22587 		if (connp != NULL) {
22588 			if (connp->conn_dontroute)
22589 				ipha->ipha_ttl = 1;
22590 			else if (connp->conn_broadcast_ttl != 0)
22591 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22592 		}
22593 
22594 		/*
22595 		 * Note that we are not doing a IRB_REFHOLD here.
22596 		 * Actually we don't care if the list changes i.e
22597 		 * if somebody deletes an IRE from the list while
22598 		 * we drop the lock, the next time we come around
22599 		 * ire_next will be NULL and hence we won't send
22600 		 * out multiple copies which is fine.
22601 		 */
22602 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22603 		ire1 = ire->ire_next;
22604 		if (conn_outgoing_ill != NULL) {
22605 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22606 				ASSERT(ire1 == ire->ire_next);
22607 				if (ire1 != NULL && ire1->ire_addr == dst) {
22608 					ire_refrele(ire);
22609 					ire = ire1;
22610 					IRE_REFHOLD(ire);
22611 					ire1 = ire->ire_next;
22612 					continue;
22613 				}
22614 				rw_exit(&ire->ire_bucket->irb_lock);
22615 				/* Did not find a matching ill */
22616 				ip1dbg(("ip_wput_ire: broadcast with no "
22617 				    "matching IP_BOUND_IF ill %s dst %x\n",
22618 				    conn_outgoing_ill->ill_name, dst));
22619 				freemsg(first_mp);
22620 				if (ire != NULL)
22621 					ire_refrele(ire);
22622 				ill_refrele(conn_outgoing_ill);
22623 				return;
22624 			}
22625 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22626 			/*
22627 			 * If the next IRE has the same address and is not one
22628 			 * of the two copies that we need to send, try to see
22629 			 * whether this copy should be sent at all. This
22630 			 * assumes that we insert loopbacks first and then
22631 			 * non-loopbacks. This is acheived by inserting the
22632 			 * loopback always before non-loopback.
22633 			 * This is used to send a single copy of a broadcast
22634 			 * packet out all physical interfaces that have an
22635 			 * matching IRE_BROADCAST while also looping
22636 			 * back one copy (to ip_wput_local) for each
22637 			 * matching physical interface. However, we avoid
22638 			 * sending packets out different logical that match by
22639 			 * having ipif_up/ipif_down supress duplicate
22640 			 * IRE_BROADCASTS.
22641 			 *
22642 			 * This feature is currently used to get broadcasts
22643 			 * sent to multiple interfaces, when the broadcast
22644 			 * address being used applies to multiple interfaces.
22645 			 * For example, a whole net broadcast will be
22646 			 * replicated on every connected subnet of
22647 			 * the target net.
22648 			 *
22649 			 * Each zone has its own set of IRE_BROADCASTs, so that
22650 			 * we're able to distribute inbound packets to multiple
22651 			 * zones who share a broadcast address. We avoid looping
22652 			 * back outbound packets in different zones but on the
22653 			 * same ill, as the application would see duplicates.
22654 			 *
22655 			 * This logic assumes that ire_add_v4() groups the
22656 			 * IRE_BROADCAST entries so that those with the same
22657 			 * ire_addr are kept together.
22658 			 */
22659 			ire_ill = ire->ire_ipif->ipif_ill;
22660 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22661 				while (ire1 != NULL && ire1->ire_addr == dst) {
22662 					ire1_ill = ire1->ire_ipif->ipif_ill;
22663 					if (ire1_ill != ire_ill)
22664 						break;
22665 					ire1 = ire1->ire_next;
22666 				}
22667 			}
22668 		}
22669 		ASSERT(multirt_send == B_FALSE);
22670 		if (ire1 != NULL && ire1->ire_addr == dst) {
22671 			if ((ire->ire_flags & RTF_MULTIRT) &&
22672 			    (ire1->ire_flags & RTF_MULTIRT)) {
22673 				/*
22674 				 * We are in the multirouting case.
22675 				 * The message must be sent at least
22676 				 * on both ires. These ires have been
22677 				 * inserted AFTER the standard ones
22678 				 * in ip_rt_add(). There are thus no
22679 				 * other ire entries for the destination
22680 				 * address in the rest of the bucket
22681 				 * that do not have the RTF_MULTIRT
22682 				 * flag. We don't process a copy
22683 				 * of the message here. This will be
22684 				 * done in the final sending loop.
22685 				 */
22686 				multirt_send = B_TRUE;
22687 			} else {
22688 				next_mp = ip_copymsg(first_mp);
22689 				if (next_mp != NULL)
22690 					IRE_REFHOLD(ire1);
22691 			}
22692 		}
22693 		rw_exit(&ire->ire_bucket->irb_lock);
22694 	}
22695 
22696 	if (stq) {
22697 		/*
22698 		 * A non-NULL send-to queue means this packet is going
22699 		 * out of this machine.
22700 		 */
22701 		out_ill = (ill_t *)stq->q_ptr;
22702 
22703 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22704 		ttl_protocol = ((uint16_t *)ipha)[4];
22705 		/*
22706 		 * We accumulate the pseudo header checksum in cksum.
22707 		 * This is pretty hairy code, so watch close.  One
22708 		 * thing to keep in mind is that UDP and TCP have
22709 		 * stored their respective datagram lengths in their
22710 		 * checksum fields.  This lines things up real nice.
22711 		 */
22712 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22713 		    (src >> 16) + (src & 0xFFFF);
22714 		/*
22715 		 * We assume the udp checksum field contains the
22716 		 * length, so to compute the pseudo header checksum,
22717 		 * all we need is the protocol number and src/dst.
22718 		 */
22719 		/* Provide the checksums for UDP and TCP. */
22720 		if ((PROTO == IPPROTO_TCP) &&
22721 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22722 			/* hlen gets the number of uchar_ts in the IP header */
22723 			hlen = (V_HLEN & 0xF) << 2;
22724 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22725 			IP_STAT(ipst, ip_out_sw_cksum);
22726 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22727 			    LENGTH - hlen);
22728 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22729 		} else if (PROTO == IPPROTO_SCTP &&
22730 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22731 			sctp_hdr_t	*sctph;
22732 
22733 			hlen = (V_HLEN & 0xF) << 2;
22734 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22735 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22736 			sctph->sh_chksum = 0;
22737 #ifdef	DEBUG
22738 			if (!skip_sctp_cksum)
22739 #endif
22740 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22741 		} else {
22742 			queue_t	*dev_q = stq->q_next;
22743 
22744 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22745 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22746 blocked:
22747 				ipha->ipha_ident = ip_hdr_included;
22748 				/*
22749 				 * If we don't have a conn to apply
22750 				 * backpressure, free the message.
22751 				 * In the ire_send path, we don't know
22752 				 * the position to requeue the packet. Rather
22753 				 * than reorder packets, we just drop this
22754 				 * packet.
22755 				 */
22756 				if (ipst->ips_ip_output_queue &&
22757 				    connp != NULL &&
22758 				    caller != IRE_SEND) {
22759 					if (caller == IP_WSRV) {
22760 						idl_tx_list_t *idl_txl;
22761 
22762 						idl_txl =
22763 						    &ipst->ips_idl_tx_list[0];
22764 						connp->conn_did_putbq = 1;
22765 						(void) putbq(connp->conn_wq,
22766 						    first_mp);
22767 						conn_drain_insert(connp,
22768 						    idl_txl);
22769 						/*
22770 						 * This is the service thread,
22771 						 * and the queue is already
22772 						 * noenabled. The check for
22773 						 * canput and the putbq is not
22774 						 * atomic. So we need to check
22775 						 * again.
22776 						 */
22777 						if (canput(stq->q_next))
22778 							connp->conn_did_putbq
22779 							    = 0;
22780 						IP_STAT(ipst, ip_conn_flputbq);
22781 					} else {
22782 						/*
22783 						 * We are not the service proc.
22784 						 * ip_wsrv will be scheduled or
22785 						 * is already running.
22786 						 */
22787 
22788 						(void) putq(connp->conn_wq,
22789 						    first_mp);
22790 					}
22791 				} else {
22792 					out_ill = (ill_t *)stq->q_ptr;
22793 					BUMP_MIB(out_ill->ill_ip_mib,
22794 					    ipIfStatsOutDiscards);
22795 					freemsg(first_mp);
22796 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22797 					    "ip_wput_ire_end: q %p (%S)",
22798 					    q, "discard");
22799 				}
22800 				ire_refrele(ire);
22801 				if (next_mp) {
22802 					ire_refrele(ire1);
22803 					freemsg(next_mp);
22804 				}
22805 				if (conn_outgoing_ill != NULL)
22806 					ill_refrele(conn_outgoing_ill);
22807 				return;
22808 			}
22809 			if ((PROTO == IPPROTO_UDP) &&
22810 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22811 				/*
22812 				 * hlen gets the number of uchar_ts in the
22813 				 * IP header
22814 				 */
22815 				hlen = (V_HLEN & 0xF) << 2;
22816 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22817 				max_frag = ire->ire_max_frag;
22818 				if (*up != 0) {
22819 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22820 					    up, PROTO, hlen, LENGTH, max_frag,
22821 					    ipsec_len, cksum);
22822 					/* Software checksum? */
22823 					if (DB_CKSUMFLAGS(mp) == 0) {
22824 						IP_STAT(ipst, ip_out_sw_cksum);
22825 						IP_STAT_UPDATE(ipst,
22826 						    ip_udp_out_sw_cksum_bytes,
22827 						    LENGTH - hlen);
22828 					}
22829 				}
22830 			}
22831 		}
22832 		/*
22833 		 * Need to do this even when fragmenting. The local
22834 		 * loopback can be done without computing checksums
22835 		 * but forwarding out other interface must be done
22836 		 * after the IP checksum (and ULP checksums) have been
22837 		 * computed.
22838 		 *
22839 		 * NOTE : multicast_forward is set only if this packet
22840 		 * originated from ip_wput. For packets originating from
22841 		 * ip_wput_multicast, it is not set.
22842 		 */
22843 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22844 multi_loopback:
22845 			ip2dbg(("ip_wput: multicast, loop %d\n",
22846 			    conn_multicast_loop));
22847 
22848 			/*  Forget header checksum offload */
22849 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22850 
22851 			/*
22852 			 * Local loopback of multicasts?  Check the
22853 			 * ill.
22854 			 *
22855 			 * Note that the loopback function will not come
22856 			 * in through ip_rput - it will only do the
22857 			 * client fanout thus we need to do an mforward
22858 			 * as well.  The is different from the BSD
22859 			 * logic.
22860 			 */
22861 			if (ill != NULL) {
22862 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22863 				    ALL_ZONES) != NULL) {
22864 					/*
22865 					 * Pass along the virtual output q.
22866 					 * ip_wput_local() will distribute the
22867 					 * packet to all the matching zones,
22868 					 * except the sending zone when
22869 					 * IP_MULTICAST_LOOP is false.
22870 					 */
22871 					ip_multicast_loopback(q, ill, first_mp,
22872 					    conn_multicast_loop ? 0 :
22873 					    IP_FF_NO_MCAST_LOOP, zoneid);
22874 				}
22875 			}
22876 			if (ipha->ipha_ttl == 0) {
22877 				/*
22878 				 * 0 => only to this host i.e. we are
22879 				 * done. We are also done if this was the
22880 				 * loopback interface since it is sufficient
22881 				 * to loopback one copy of a multicast packet.
22882 				 */
22883 				freemsg(first_mp);
22884 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22885 				    "ip_wput_ire_end: q %p (%S)",
22886 				    q, "loopback");
22887 				ire_refrele(ire);
22888 				if (conn_outgoing_ill != NULL)
22889 					ill_refrele(conn_outgoing_ill);
22890 				return;
22891 			}
22892 			/*
22893 			 * ILLF_MULTICAST is checked in ip_newroute
22894 			 * i.e. we don't need to check it here since
22895 			 * all IRE_CACHEs come from ip_newroute.
22896 			 * For multicast traffic, SO_DONTROUTE is interpreted
22897 			 * to mean only send the packet out the interface
22898 			 * (optionally specified with IP_MULTICAST_IF)
22899 			 * and do not forward it out additional interfaces.
22900 			 * RSVP and the rsvp daemon is an example of a
22901 			 * protocol and user level process that
22902 			 * handles it's own routing. Hence, it uses the
22903 			 * SO_DONTROUTE option to accomplish this.
22904 			 */
22905 
22906 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22907 			    ill != NULL) {
22908 				/* Unconditionally redo the checksum */
22909 				ipha->ipha_hdr_checksum = 0;
22910 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22911 
22912 				/*
22913 				 * If this needs to go out secure, we need
22914 				 * to wait till we finish the IPsec
22915 				 * processing.
22916 				 */
22917 				if (ipsec_len == 0 &&
22918 				    ip_mforward(ill, ipha, mp)) {
22919 					freemsg(first_mp);
22920 					ip1dbg(("ip_wput: mforward failed\n"));
22921 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22922 					    "ip_wput_ire_end: q %p (%S)",
22923 					    q, "mforward failed");
22924 					ire_refrele(ire);
22925 					if (conn_outgoing_ill != NULL)
22926 						ill_refrele(conn_outgoing_ill);
22927 					return;
22928 				}
22929 			}
22930 		}
22931 		max_frag = ire->ire_max_frag;
22932 		cksum += ttl_protocol;
22933 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22934 			/* No fragmentation required for this one. */
22935 			/*
22936 			 * Don't use frag_flag if packet is pre-built or source
22937 			 * routed or if multicast (since multicast packets do
22938 			 * not solicit ICMP "packet too big" messages).
22939 			 */
22940 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22941 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22942 			    !ip_source_route_included(ipha)) &&
22943 			    !CLASSD(ipha->ipha_dst))
22944 				ipha->ipha_fragment_offset_and_flags |=
22945 				    htons(ire->ire_frag_flag);
22946 
22947 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22948 				/* Complete the IP header checksum. */
22949 				cksum += ipha->ipha_ident;
22950 				cksum += (v_hlen_tos_len >> 16)+
22951 				    (v_hlen_tos_len & 0xFFFF);
22952 				cksum += ipha->ipha_fragment_offset_and_flags;
22953 				hlen = (V_HLEN & 0xF) -
22954 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22955 				if (hlen) {
22956 checksumoptions:
22957 					/*
22958 					 * Account for the IP Options in the IP
22959 					 * header checksum.
22960 					 */
22961 					up = (uint16_t *)(rptr+
22962 					    IP_SIMPLE_HDR_LENGTH);
22963 					do {
22964 						cksum += up[0];
22965 						cksum += up[1];
22966 						up += 2;
22967 					} while (--hlen);
22968 				}
22969 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22970 				cksum = ~(cksum + (cksum >> 16));
22971 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22972 			}
22973 			if (ipsec_len != 0) {
22974 				ipsec_out_process(q, first_mp, ire, ill_index);
22975 				if (!next_mp) {
22976 					ire_refrele(ire);
22977 					if (conn_outgoing_ill != NULL)
22978 						ill_refrele(conn_outgoing_ill);
22979 					return;
22980 				}
22981 				goto next;
22982 			}
22983 
22984 			/*
22985 			 * multirt_send has already been handled
22986 			 * for broadcast, but not yet for multicast
22987 			 * or IP options.
22988 			 */
22989 			if (next_mp == NULL) {
22990 				if (ire->ire_flags & RTF_MULTIRT) {
22991 					multirt_send = B_TRUE;
22992 				}
22993 			}
22994 
22995 			/*
22996 			 * In most cases, the emission loop below is
22997 			 * entered only once. Only in the case where
22998 			 * the ire holds the RTF_MULTIRT flag, do we loop
22999 			 * to process all RTF_MULTIRT ires in the bucket,
23000 			 * and send the packet through all crossed
23001 			 * RTF_MULTIRT routes.
23002 			 */
23003 			do {
23004 				if (multirt_send) {
23005 					irb_t *irb;
23006 
23007 					irb = ire->ire_bucket;
23008 					ASSERT(irb != NULL);
23009 					/*
23010 					 * We are in a multiple send case,
23011 					 * need to get the next IRE and make
23012 					 * a duplicate of the packet.
23013 					 */
23014 					IRB_REFHOLD(irb);
23015 					for (ire1 = ire->ire_next;
23016 					    ire1 != NULL;
23017 					    ire1 = ire1->ire_next) {
23018 						if (!(ire1->ire_flags &
23019 						    RTF_MULTIRT))
23020 							continue;
23021 
23022 						if (ire1->ire_addr !=
23023 						    ire->ire_addr)
23024 							continue;
23025 
23026 						if (ire1->ire_marks &
23027 						    (IRE_MARK_CONDEMNED |
23028 						    IRE_MARK_TESTHIDDEN))
23029 							continue;
23030 
23031 						/* Got one */
23032 						IRE_REFHOLD(ire1);
23033 						break;
23034 					}
23035 					IRB_REFRELE(irb);
23036 
23037 					if (ire1 != NULL) {
23038 						next_mp = copyb(mp);
23039 						if ((next_mp == NULL) ||
23040 						    ((mp->b_cont != NULL) &&
23041 						    ((next_mp->b_cont =
23042 						    dupmsg(mp->b_cont))
23043 						    == NULL))) {
23044 							freemsg(next_mp);
23045 							next_mp = NULL;
23046 							ire_refrele(ire1);
23047 							ire1 = NULL;
23048 						}
23049 					}
23050 
23051 					/*
23052 					 * Last multiroute ire; don't loop
23053 					 * anymore. The emission is over
23054 					 * and next_mp is NULL.
23055 					 */
23056 					if (ire1 == NULL) {
23057 						multirt_send = B_FALSE;
23058 					}
23059 				}
23060 
23061 				out_ill = ire_to_ill(ire);
23062 				DTRACE_PROBE4(ip4__physical__out__start,
23063 				    ill_t *, NULL,
23064 				    ill_t *, out_ill,
23065 				    ipha_t *, ipha, mblk_t *, mp);
23066 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23067 				    ipst->ips_ipv4firewall_physical_out,
23068 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23069 				DTRACE_PROBE1(ip4__physical__out__end,
23070 				    mblk_t *, mp);
23071 				if (mp == NULL)
23072 					goto release_ire_and_ill_2;
23073 
23074 				ASSERT(ipsec_len == 0);
23075 				mp->b_prev =
23076 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23077 				DTRACE_PROBE2(ip__xmit__2,
23078 				    mblk_t *, mp, ire_t *, ire);
23079 				pktxmit_state = ip_xmit_v4(mp, ire,
23080 				    NULL, B_TRUE, connp);
23081 				if ((pktxmit_state == SEND_FAILED) ||
23082 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23083 release_ire_and_ill_2:
23084 					if (next_mp) {
23085 						freemsg(next_mp);
23086 						ire_refrele(ire1);
23087 					}
23088 					ire_refrele(ire);
23089 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23090 					    "ip_wput_ire_end: q %p (%S)",
23091 					    q, "discard MDATA");
23092 					if (conn_outgoing_ill != NULL)
23093 						ill_refrele(conn_outgoing_ill);
23094 					return;
23095 				}
23096 
23097 				if (CLASSD(dst)) {
23098 					BUMP_MIB(out_ill->ill_ip_mib,
23099 					    ipIfStatsHCOutMcastPkts);
23100 					UPDATE_MIB(out_ill->ill_ip_mib,
23101 					    ipIfStatsHCOutMcastOctets,
23102 					    LENGTH);
23103 				} else if (ire->ire_type == IRE_BROADCAST) {
23104 					BUMP_MIB(out_ill->ill_ip_mib,
23105 					    ipIfStatsHCOutBcastPkts);
23106 				}
23107 
23108 				if (multirt_send) {
23109 					/*
23110 					 * We are in a multiple send case,
23111 					 * need to re-enter the sending loop
23112 					 * using the next ire.
23113 					 */
23114 					ire_refrele(ire);
23115 					ire = ire1;
23116 					stq = ire->ire_stq;
23117 					mp = next_mp;
23118 					next_mp = NULL;
23119 					ipha = (ipha_t *)mp->b_rptr;
23120 					ill_index = Q_TO_INDEX(stq);
23121 				}
23122 			} while (multirt_send);
23123 
23124 			if (!next_mp) {
23125 				/*
23126 				 * Last copy going out (the ultra-common
23127 				 * case).  Note that we intentionally replicate
23128 				 * the putnext rather than calling it before
23129 				 * the next_mp check in hopes of a little
23130 				 * tail-call action out of the compiler.
23131 				 */
23132 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23133 				    "ip_wput_ire_end: q %p (%S)",
23134 				    q, "last copy out(1)");
23135 				ire_refrele(ire);
23136 				if (conn_outgoing_ill != NULL)
23137 					ill_refrele(conn_outgoing_ill);
23138 				return;
23139 			}
23140 			/* More copies going out below. */
23141 		} else {
23142 			int offset;
23143 fragmentit:
23144 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23145 			/*
23146 			 * If this would generate a icmp_frag_needed message,
23147 			 * we need to handle it before we do the IPsec
23148 			 * processing. Otherwise, we need to strip the IPsec
23149 			 * headers before we send up the message to the ULPs
23150 			 * which becomes messy and difficult.
23151 			 */
23152 			if (ipsec_len != 0) {
23153 				if ((max_frag < (unsigned int)(LENGTH +
23154 				    ipsec_len)) && (offset & IPH_DF)) {
23155 					out_ill = (ill_t *)stq->q_ptr;
23156 					BUMP_MIB(out_ill->ill_ip_mib,
23157 					    ipIfStatsOutFragFails);
23158 					BUMP_MIB(out_ill->ill_ip_mib,
23159 					    ipIfStatsOutFragReqds);
23160 					ipha->ipha_hdr_checksum = 0;
23161 					ipha->ipha_hdr_checksum =
23162 					    (uint16_t)ip_csum_hdr(ipha);
23163 					icmp_frag_needed(ire->ire_stq, first_mp,
23164 					    max_frag, zoneid, ipst);
23165 					if (!next_mp) {
23166 						ire_refrele(ire);
23167 						if (conn_outgoing_ill != NULL) {
23168 							ill_refrele(
23169 							    conn_outgoing_ill);
23170 						}
23171 						return;
23172 					}
23173 				} else {
23174 					/*
23175 					 * This won't cause a icmp_frag_needed
23176 					 * message. to be generated. Send it on
23177 					 * the wire. Note that this could still
23178 					 * cause fragmentation and all we
23179 					 * do is the generation of the message
23180 					 * to the ULP if needed before IPsec.
23181 					 */
23182 					if (!next_mp) {
23183 						ipsec_out_process(q, first_mp,
23184 						    ire, ill_index);
23185 						TRACE_2(TR_FAC_IP,
23186 						    TR_IP_WPUT_IRE_END,
23187 						    "ip_wput_ire_end: q %p "
23188 						    "(%S)", q,
23189 						    "last ipsec_out_process");
23190 						ire_refrele(ire);
23191 						if (conn_outgoing_ill != NULL) {
23192 							ill_refrele(
23193 							    conn_outgoing_ill);
23194 						}
23195 						return;
23196 					}
23197 					ipsec_out_process(q, first_mp,
23198 					    ire, ill_index);
23199 				}
23200 			} else {
23201 				/*
23202 				 * Initiate IPPF processing. For
23203 				 * fragmentable packets we finish
23204 				 * all QOS packet processing before
23205 				 * calling:
23206 				 * ip_wput_ire_fragmentit->ip_wput_frag
23207 				 */
23208 
23209 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23210 					ip_process(IPP_LOCAL_OUT, &mp,
23211 					    ill_index);
23212 					if (mp == NULL) {
23213 						out_ill = (ill_t *)stq->q_ptr;
23214 						BUMP_MIB(out_ill->ill_ip_mib,
23215 						    ipIfStatsOutDiscards);
23216 						if (next_mp != NULL) {
23217 							freemsg(next_mp);
23218 							ire_refrele(ire1);
23219 						}
23220 						ire_refrele(ire);
23221 						TRACE_2(TR_FAC_IP,
23222 						    TR_IP_WPUT_IRE_END,
23223 						    "ip_wput_ire: q %p (%S)",
23224 						    q, "discard MDATA");
23225 						if (conn_outgoing_ill != NULL) {
23226 							ill_refrele(
23227 							    conn_outgoing_ill);
23228 						}
23229 						return;
23230 					}
23231 				}
23232 				if (!next_mp) {
23233 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23234 					    "ip_wput_ire_end: q %p (%S)",
23235 					    q, "last fragmentation");
23236 					ip_wput_ire_fragmentit(mp, ire,
23237 					    zoneid, ipst, connp);
23238 					ire_refrele(ire);
23239 					if (conn_outgoing_ill != NULL)
23240 						ill_refrele(conn_outgoing_ill);
23241 					return;
23242 				}
23243 				ip_wput_ire_fragmentit(mp, ire,
23244 				    zoneid, ipst, connp);
23245 			}
23246 		}
23247 	} else {
23248 nullstq:
23249 		/* A NULL stq means the destination address is local. */
23250 		UPDATE_OB_PKT_COUNT(ire);
23251 		ire->ire_last_used_time = lbolt;
23252 		ASSERT(ire->ire_ipif != NULL);
23253 		if (!next_mp) {
23254 			/*
23255 			 * Is there an "in" and "out" for traffic local
23256 			 * to a host (loopback)?  The code in Solaris doesn't
23257 			 * explicitly draw a line in its code for in vs out,
23258 			 * so we've had to draw a line in the sand: ip_wput_ire
23259 			 * is considered to be the "output" side and
23260 			 * ip_wput_local to be the "input" side.
23261 			 */
23262 			out_ill = ire_to_ill(ire);
23263 
23264 			/*
23265 			 * DTrace this as ip:::send.  A blocked packet will
23266 			 * fire the send probe, but not the receive probe.
23267 			 */
23268 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23269 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23270 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23271 
23272 			DTRACE_PROBE4(ip4__loopback__out__start,
23273 			    ill_t *, NULL, ill_t *, out_ill,
23274 			    ipha_t *, ipha, mblk_t *, first_mp);
23275 
23276 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23277 			    ipst->ips_ipv4firewall_loopback_out,
23278 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23279 
23280 			DTRACE_PROBE1(ip4__loopback__out_end,
23281 			    mblk_t *, first_mp);
23282 
23283 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23284 			    "ip_wput_ire_end: q %p (%S)",
23285 			    q, "local address");
23286 
23287 			if (first_mp != NULL)
23288 				ip_wput_local(q, out_ill, ipha,
23289 				    first_mp, ire, 0, ire->ire_zoneid);
23290 			ire_refrele(ire);
23291 			if (conn_outgoing_ill != NULL)
23292 				ill_refrele(conn_outgoing_ill);
23293 			return;
23294 		}
23295 
23296 		out_ill = ire_to_ill(ire);
23297 
23298 		/*
23299 		 * DTrace this as ip:::send.  A blocked packet will fire the
23300 		 * send probe, but not the receive probe.
23301 		 */
23302 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23303 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23304 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23305 
23306 		DTRACE_PROBE4(ip4__loopback__out__start,
23307 		    ill_t *, NULL, ill_t *, out_ill,
23308 		    ipha_t *, ipha, mblk_t *, first_mp);
23309 
23310 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23311 		    ipst->ips_ipv4firewall_loopback_out,
23312 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23313 
23314 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23315 
23316 		if (first_mp != NULL)
23317 			ip_wput_local(q, out_ill, ipha,
23318 			    first_mp, ire, 0, ire->ire_zoneid);
23319 	}
23320 next:
23321 	/*
23322 	 * More copies going out to additional interfaces.
23323 	 * ire1 has already been held. We don't need the
23324 	 * "ire" anymore.
23325 	 */
23326 	ire_refrele(ire);
23327 	ire = ire1;
23328 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23329 	mp = next_mp;
23330 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23331 	ill = ire_to_ill(ire);
23332 	first_mp = mp;
23333 	if (ipsec_len != 0) {
23334 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23335 		mp = mp->b_cont;
23336 	}
23337 	dst = ire->ire_addr;
23338 	ipha = (ipha_t *)mp->b_rptr;
23339 	/*
23340 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23341 	 * Restore ipha_ident "no checksum" flag.
23342 	 */
23343 	src = orig_src;
23344 	ipha->ipha_ident = ip_hdr_included;
23345 	goto another;
23346 
23347 #undef	rptr
23348 #undef	Q_TO_INDEX
23349 }
23350 
23351 /*
23352  * Routine to allocate a message that is used to notify the ULP about MDT.
23353  * The caller may provide a pointer to the link-layer MDT capabilities,
23354  * or NULL if MDT is to be disabled on the stream.
23355  */
23356 mblk_t *
23357 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23358 {
23359 	mblk_t *mp;
23360 	ip_mdt_info_t *mdti;
23361 	ill_mdt_capab_t *idst;
23362 
23363 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23364 		DB_TYPE(mp) = M_CTL;
23365 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23366 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23367 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23368 		idst = &(mdti->mdt_capab);
23369 
23370 		/*
23371 		 * If the caller provides us with the capability, copy
23372 		 * it over into our notification message; otherwise
23373 		 * we zero out the capability portion.
23374 		 */
23375 		if (isrc != NULL)
23376 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23377 		else
23378 			bzero((caddr_t)idst, sizeof (*idst));
23379 	}
23380 	return (mp);
23381 }
23382 
23383 /*
23384  * Routine which determines whether MDT can be enabled on the destination
23385  * IRE and IPC combination, and if so, allocates and returns the MDT
23386  * notification mblk that may be used by ULP.  We also check if we need to
23387  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23388  * MDT usage in the past have been lifted.  This gets called during IP
23389  * and ULP binding.
23390  */
23391 mblk_t *
23392 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23393     ill_mdt_capab_t *mdt_cap)
23394 {
23395 	mblk_t *mp;
23396 	boolean_t rc = B_FALSE;
23397 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23398 
23399 	ASSERT(dst_ire != NULL);
23400 	ASSERT(connp != NULL);
23401 	ASSERT(mdt_cap != NULL);
23402 
23403 	/*
23404 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23405 	 * Multidata, which is handled in tcp_multisend().  This
23406 	 * is the reason why we do all these checks here, to ensure
23407 	 * that we don't enable Multidata for the cases which we
23408 	 * can't handle at the moment.
23409 	 */
23410 	do {
23411 		/* Only do TCP at the moment */
23412 		if (connp->conn_ulp != IPPROTO_TCP)
23413 			break;
23414 
23415 		/*
23416 		 * IPsec outbound policy present?  Note that we get here
23417 		 * after calling ipsec_conn_cache_policy() where the global
23418 		 * policy checking is performed.  conn_latch will be
23419 		 * non-NULL as long as there's a policy defined,
23420 		 * i.e. conn_out_enforce_policy may be NULL in such case
23421 		 * when the connection is non-secure, and hence we check
23422 		 * further if the latch refers to an outbound policy.
23423 		 */
23424 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23425 			break;
23426 
23427 		/* CGTP (multiroute) is enabled? */
23428 		if (dst_ire->ire_flags & RTF_MULTIRT)
23429 			break;
23430 
23431 		/* Outbound IPQoS enabled? */
23432 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23433 			/*
23434 			 * In this case, we disable MDT for this and all
23435 			 * future connections going over the interface.
23436 			 */
23437 			mdt_cap->ill_mdt_on = 0;
23438 			break;
23439 		}
23440 
23441 		/* socket option(s) present? */
23442 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23443 			break;
23444 
23445 		rc = B_TRUE;
23446 	/* CONSTCOND */
23447 	} while (0);
23448 
23449 	/* Remember the result */
23450 	connp->conn_mdt_ok = rc;
23451 
23452 	if (!rc)
23453 		return (NULL);
23454 	else if (!mdt_cap->ill_mdt_on) {
23455 		/*
23456 		 * If MDT has been previously turned off in the past, and we
23457 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23458 		 * then enable it for this interface.
23459 		 */
23460 		mdt_cap->ill_mdt_on = 1;
23461 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23462 		    "interface %s\n", ill_name));
23463 	}
23464 
23465 	/* Allocate the MDT info mblk */
23466 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23467 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23468 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23469 		return (NULL);
23470 	}
23471 	return (mp);
23472 }
23473 
23474 /*
23475  * Routine to allocate a message that is used to notify the ULP about LSO.
23476  * The caller may provide a pointer to the link-layer LSO capabilities,
23477  * or NULL if LSO is to be disabled on the stream.
23478  */
23479 mblk_t *
23480 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23481 {
23482 	mblk_t *mp;
23483 	ip_lso_info_t *lsoi;
23484 	ill_lso_capab_t *idst;
23485 
23486 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23487 		DB_TYPE(mp) = M_CTL;
23488 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23489 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23490 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23491 		idst = &(lsoi->lso_capab);
23492 
23493 		/*
23494 		 * If the caller provides us with the capability, copy
23495 		 * it over into our notification message; otherwise
23496 		 * we zero out the capability portion.
23497 		 */
23498 		if (isrc != NULL)
23499 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23500 		else
23501 			bzero((caddr_t)idst, sizeof (*idst));
23502 	}
23503 	return (mp);
23504 }
23505 
23506 /*
23507  * Routine which determines whether LSO can be enabled on the destination
23508  * IRE and IPC combination, and if so, allocates and returns the LSO
23509  * notification mblk that may be used by ULP.  We also check if we need to
23510  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23511  * LSO usage in the past have been lifted.  This gets called during IP
23512  * and ULP binding.
23513  */
23514 mblk_t *
23515 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23516     ill_lso_capab_t *lso_cap)
23517 {
23518 	mblk_t *mp;
23519 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23520 
23521 	ASSERT(dst_ire != NULL);
23522 	ASSERT(connp != NULL);
23523 	ASSERT(lso_cap != NULL);
23524 
23525 	connp->conn_lso_ok = B_TRUE;
23526 
23527 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23528 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23529 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23530 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23531 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23532 		connp->conn_lso_ok = B_FALSE;
23533 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23534 			/*
23535 			 * Disable LSO for this and all future connections going
23536 			 * over the interface.
23537 			 */
23538 			lso_cap->ill_lso_on = 0;
23539 		}
23540 	}
23541 
23542 	if (!connp->conn_lso_ok)
23543 		return (NULL);
23544 	else if (!lso_cap->ill_lso_on) {
23545 		/*
23546 		 * If LSO has been previously turned off in the past, and we
23547 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23548 		 * then enable it for this interface.
23549 		 */
23550 		lso_cap->ill_lso_on = 1;
23551 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23552 		    ill_name));
23553 	}
23554 
23555 	/* Allocate the LSO info mblk */
23556 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23557 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23558 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23559 
23560 	return (mp);
23561 }
23562 
23563 /*
23564  * Create destination address attribute, and fill it with the physical
23565  * destination address and SAP taken from the template DL_UNITDATA_REQ
23566  * message block.
23567  */
23568 boolean_t
23569 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23570 {
23571 	dl_unitdata_req_t *dlurp;
23572 	pattr_t *pa;
23573 	pattrinfo_t pa_info;
23574 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23575 	uint_t das_len, das_off;
23576 
23577 	ASSERT(dlmp != NULL);
23578 
23579 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23580 	das_len = dlurp->dl_dest_addr_length;
23581 	das_off = dlurp->dl_dest_addr_offset;
23582 
23583 	pa_info.type = PATTR_DSTADDRSAP;
23584 	pa_info.len = sizeof (**das) + das_len - 1;
23585 
23586 	/* create and associate the attribute */
23587 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23588 	if (pa != NULL) {
23589 		ASSERT(*das != NULL);
23590 		(*das)->addr_is_group = 0;
23591 		(*das)->addr_len = (uint8_t)das_len;
23592 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23593 	}
23594 
23595 	return (pa != NULL);
23596 }
23597 
23598 /*
23599  * Create hardware checksum attribute and fill it with the values passed.
23600  */
23601 boolean_t
23602 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23603     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23604 {
23605 	pattr_t *pa;
23606 	pattrinfo_t pa_info;
23607 
23608 	ASSERT(mmd != NULL);
23609 
23610 	pa_info.type = PATTR_HCKSUM;
23611 	pa_info.len = sizeof (pattr_hcksum_t);
23612 
23613 	/* create and associate the attribute */
23614 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23615 	if (pa != NULL) {
23616 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23617 
23618 		hck->hcksum_start_offset = start_offset;
23619 		hck->hcksum_stuff_offset = stuff_offset;
23620 		hck->hcksum_end_offset = end_offset;
23621 		hck->hcksum_flags = flags;
23622 	}
23623 	return (pa != NULL);
23624 }
23625 
23626 /*
23627  * Create zerocopy attribute and fill it with the specified flags
23628  */
23629 boolean_t
23630 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23631 {
23632 	pattr_t *pa;
23633 	pattrinfo_t pa_info;
23634 
23635 	ASSERT(mmd != NULL);
23636 	pa_info.type = PATTR_ZCOPY;
23637 	pa_info.len = sizeof (pattr_zcopy_t);
23638 
23639 	/* create and associate the attribute */
23640 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23641 	if (pa != NULL) {
23642 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23643 
23644 		zcopy->zcopy_flags = flags;
23645 	}
23646 	return (pa != NULL);
23647 }
23648 
23649 /*
23650  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23651  * block chain. We could rewrite to handle arbitrary message block chains but
23652  * that would make the code complicated and slow. Right now there three
23653  * restrictions:
23654  *
23655  *   1. The first message block must contain the complete IP header and
23656  *	at least 1 byte of payload data.
23657  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23658  *	so that we can use a single Multidata message.
23659  *   3. No frag must be distributed over two or more message blocks so
23660  *	that we don't need more than two packet descriptors per frag.
23661  *
23662  * The above restrictions allow us to support userland applications (which
23663  * will send down a single message block) and NFS over UDP (which will
23664  * send down a chain of at most three message blocks).
23665  *
23666  * We also don't use MDT for payloads with less than or equal to
23667  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23668  */
23669 boolean_t
23670 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23671 {
23672 	int	blocks;
23673 	ssize_t	total, missing, size;
23674 
23675 	ASSERT(mp != NULL);
23676 	ASSERT(hdr_len > 0);
23677 
23678 	size = MBLKL(mp) - hdr_len;
23679 	if (size <= 0)
23680 		return (B_FALSE);
23681 
23682 	/* The first mblk contains the header and some payload. */
23683 	blocks = 1;
23684 	total = size;
23685 	size %= len;
23686 	missing = (size == 0) ? 0 : (len - size);
23687 	mp = mp->b_cont;
23688 
23689 	while (mp != NULL) {
23690 		/*
23691 		 * Give up if we encounter a zero length message block.
23692 		 * In practice, this should rarely happen and therefore
23693 		 * not worth the trouble of freeing and re-linking the
23694 		 * mblk from the chain to handle such case.
23695 		 */
23696 		if ((size = MBLKL(mp)) == 0)
23697 			return (B_FALSE);
23698 
23699 		/* Too many payload buffers for a single Multidata message? */
23700 		if (++blocks > MULTIDATA_MAX_PBUFS)
23701 			return (B_FALSE);
23702 
23703 		total += size;
23704 		/* Is a frag distributed over two or more message blocks? */
23705 		if (missing > size)
23706 			return (B_FALSE);
23707 		size -= missing;
23708 
23709 		size %= len;
23710 		missing = (size == 0) ? 0 : (len - size);
23711 
23712 		mp = mp->b_cont;
23713 	}
23714 
23715 	return (total > ip_wput_frag_mdt_min);
23716 }
23717 
23718 /*
23719  * Outbound IPv4 fragmentation routine using MDT.
23720  */
23721 static void
23722 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23723     uint32_t frag_flag, int offset)
23724 {
23725 	ipha_t		*ipha_orig;
23726 	int		i1, ip_data_end;
23727 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23728 	mblk_t		*hdr_mp, *md_mp = NULL;
23729 	unsigned char	*hdr_ptr, *pld_ptr;
23730 	multidata_t	*mmd;
23731 	ip_pdescinfo_t	pdi;
23732 	ill_t		*ill;
23733 	ip_stack_t	*ipst = ire->ire_ipst;
23734 
23735 	ASSERT(DB_TYPE(mp) == M_DATA);
23736 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23737 
23738 	ill = ire_to_ill(ire);
23739 	ASSERT(ill != NULL);
23740 
23741 	ipha_orig = (ipha_t *)mp->b_rptr;
23742 	mp->b_rptr += sizeof (ipha_t);
23743 
23744 	/* Calculate how many packets we will send out */
23745 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23746 	pkts = (i1 + len - 1) / len;
23747 	ASSERT(pkts > 1);
23748 
23749 	/* Allocate a message block which will hold all the IP Headers. */
23750 	wroff = ipst->ips_ip_wroff_extra;
23751 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23752 
23753 	i1 = pkts * hdr_chunk_len;
23754 	/*
23755 	 * Create the header buffer, Multidata and destination address
23756 	 * and SAP attribute that should be associated with it.
23757 	 */
23758 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23759 	    ((hdr_mp->b_wptr += i1),
23760 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23761 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23762 		freemsg(mp);
23763 		if (md_mp == NULL) {
23764 			freemsg(hdr_mp);
23765 		} else {
23766 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23767 			freemsg(md_mp);
23768 		}
23769 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23770 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23771 		return;
23772 	}
23773 	IP_STAT(ipst, ip_frag_mdt_allocd);
23774 
23775 	/*
23776 	 * Add a payload buffer to the Multidata; this operation must not
23777 	 * fail, or otherwise our logic in this routine is broken.  There
23778 	 * is no memory allocation done by the routine, so any returned
23779 	 * failure simply tells us that we've done something wrong.
23780 	 *
23781 	 * A failure tells us that either we're adding the same payload
23782 	 * buffer more than once, or we're trying to add more buffers than
23783 	 * allowed.  None of the above cases should happen, and we panic
23784 	 * because either there's horrible heap corruption, and/or
23785 	 * programming mistake.
23786 	 */
23787 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23788 		goto pbuf_panic;
23789 
23790 	hdr_ptr = hdr_mp->b_rptr;
23791 	pld_ptr = mp->b_rptr;
23792 
23793 	/* Establish the ending byte offset, based on the starting offset. */
23794 	offset <<= 3;
23795 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23796 	    IP_SIMPLE_HDR_LENGTH;
23797 
23798 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23799 
23800 	while (pld_ptr < mp->b_wptr) {
23801 		ipha_t		*ipha;
23802 		uint16_t	offset_and_flags;
23803 		uint16_t	ip_len;
23804 		int		error;
23805 
23806 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23807 		ipha = (ipha_t *)(hdr_ptr + wroff);
23808 		ASSERT(OK_32PTR(ipha));
23809 		*ipha = *ipha_orig;
23810 
23811 		if (ip_data_end - offset > len) {
23812 			offset_and_flags = IPH_MF;
23813 		} else {
23814 			/*
23815 			 * Last frag. Set len to the length of this last piece.
23816 			 */
23817 			len = ip_data_end - offset;
23818 			/* A frag of a frag might have IPH_MF non-zero */
23819 			offset_and_flags =
23820 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23821 			    IPH_MF;
23822 		}
23823 		offset_and_flags |= (uint16_t)(offset >> 3);
23824 		offset_and_flags |= (uint16_t)frag_flag;
23825 		/* Store the offset and flags in the IP header. */
23826 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23827 
23828 		/* Store the length in the IP header. */
23829 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23830 		ipha->ipha_length = htons(ip_len);
23831 
23832 		/*
23833 		 * Set the IP header checksum.  Note that mp is just
23834 		 * the header, so this is easy to pass to ip_csum.
23835 		 */
23836 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23837 
23838 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23839 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23840 		    NULL, int, 0);
23841 
23842 		/*
23843 		 * Record offset and size of header and data of the next packet
23844 		 * in the multidata message.
23845 		 */
23846 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23847 		PDESC_PLD_INIT(&pdi);
23848 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23849 		ASSERT(i1 > 0);
23850 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23851 		if (i1 == len) {
23852 			pld_ptr += len;
23853 		} else {
23854 			i1 = len - i1;
23855 			mp = mp->b_cont;
23856 			ASSERT(mp != NULL);
23857 			ASSERT(MBLKL(mp) >= i1);
23858 			/*
23859 			 * Attach the next payload message block to the
23860 			 * multidata message.
23861 			 */
23862 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23863 				goto pbuf_panic;
23864 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23865 			pld_ptr = mp->b_rptr + i1;
23866 		}
23867 
23868 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23869 		    KM_NOSLEEP)) == NULL) {
23870 			/*
23871 			 * Any failure other than ENOMEM indicates that we
23872 			 * have passed in invalid pdesc info or parameters
23873 			 * to mmd_addpdesc, which must not happen.
23874 			 *
23875 			 * EINVAL is a result of failure on boundary checks
23876 			 * against the pdesc info contents.  It should not
23877 			 * happen, and we panic because either there's
23878 			 * horrible heap corruption, and/or programming
23879 			 * mistake.
23880 			 */
23881 			if (error != ENOMEM) {
23882 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23883 				    "pdesc logic error detected for "
23884 				    "mmd %p pinfo %p (%d)\n",
23885 				    (void *)mmd, (void *)&pdi, error);
23886 				/* NOTREACHED */
23887 			}
23888 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23889 			/* Free unattached payload message blocks as well */
23890 			md_mp->b_cont = mp->b_cont;
23891 			goto free_mmd;
23892 		}
23893 
23894 		/* Advance fragment offset. */
23895 		offset += len;
23896 
23897 		/* Advance to location for next header in the buffer. */
23898 		hdr_ptr += hdr_chunk_len;
23899 
23900 		/* Did we reach the next payload message block? */
23901 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23902 			mp = mp->b_cont;
23903 			/*
23904 			 * Attach the next message block with payload
23905 			 * data to the multidata message.
23906 			 */
23907 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23908 				goto pbuf_panic;
23909 			pld_ptr = mp->b_rptr;
23910 		}
23911 	}
23912 
23913 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23914 	ASSERT(mp->b_wptr == pld_ptr);
23915 
23916 	/* Update IP statistics */
23917 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23918 
23919 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23920 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23921 
23922 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23923 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23924 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23925 
23926 	if (pkt_type == OB_PKT) {
23927 		ire->ire_ob_pkt_count += pkts;
23928 		if (ire->ire_ipif != NULL)
23929 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23930 	} else {
23931 		/* The type is IB_PKT in the forwarding path. */
23932 		ire->ire_ib_pkt_count += pkts;
23933 		ASSERT(!IRE_IS_LOCAL(ire));
23934 		if (ire->ire_type & IRE_BROADCAST) {
23935 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23936 		} else {
23937 			UPDATE_MIB(ill->ill_ip_mib,
23938 			    ipIfStatsHCOutForwDatagrams, pkts);
23939 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23940 		}
23941 	}
23942 	ire->ire_last_used_time = lbolt;
23943 	/* Send it down */
23944 	putnext(ire->ire_stq, md_mp);
23945 	return;
23946 
23947 pbuf_panic:
23948 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23949 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23950 	    pbuf_idx);
23951 	/* NOTREACHED */
23952 }
23953 
23954 /*
23955  * Outbound IP fragmentation routine.
23956  *
23957  * NOTE : This routine does not ire_refrele the ire that is passed in
23958  * as the argument.
23959  */
23960 static void
23961 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23962     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
23963 {
23964 	int		i1;
23965 	mblk_t		*ll_hdr_mp;
23966 	int 		ll_hdr_len;
23967 	int		hdr_len;
23968 	mblk_t		*hdr_mp;
23969 	ipha_t		*ipha;
23970 	int		ip_data_end;
23971 	int		len;
23972 	mblk_t		*mp = mp_orig, *mp1;
23973 	int		offset;
23974 	queue_t		*q;
23975 	uint32_t	v_hlen_tos_len;
23976 	mblk_t		*first_mp;
23977 	boolean_t	mctl_present;
23978 	ill_t		*ill;
23979 	ill_t		*out_ill;
23980 	mblk_t		*xmit_mp;
23981 	mblk_t		*carve_mp;
23982 	ire_t		*ire1 = NULL;
23983 	ire_t		*save_ire = NULL;
23984 	mblk_t  	*next_mp = NULL;
23985 	boolean_t	last_frag = B_FALSE;
23986 	boolean_t	multirt_send = B_FALSE;
23987 	ire_t		*first_ire = NULL;
23988 	irb_t		*irb = NULL;
23989 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23990 
23991 	ill = ire_to_ill(ire);
23992 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23993 
23994 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23995 
23996 	if (max_frag == 0) {
23997 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23998 		    " -  dropping packet\n"));
23999 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24000 		freemsg(mp);
24001 		return;
24002 	}
24003 
24004 	/*
24005 	 * IPsec does not allow hw accelerated packets to be fragmented
24006 	 * This check is made in ip_wput_ipsec_out prior to coming here
24007 	 * via ip_wput_ire_fragmentit.
24008 	 *
24009 	 * If at this point we have an ire whose ARP request has not
24010 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24011 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24012 	 * This packet and all fragmentable packets for this ire will
24013 	 * continue to get dropped while ire_nce->nce_state remains in
24014 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24015 	 * ND_REACHABLE, all subsquent large packets for this ire will
24016 	 * get fragemented and sent out by this function.
24017 	 */
24018 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24019 		/* If nce_state is ND_INITIAL, trigger ARP query */
24020 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24021 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24022 		    " -  dropping packet\n"));
24023 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24024 		freemsg(mp);
24025 		return;
24026 	}
24027 
24028 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24029 	    "ip_wput_frag_start:");
24030 
24031 	if (mp->b_datap->db_type == M_CTL) {
24032 		first_mp = mp;
24033 		mp_orig = mp = mp->b_cont;
24034 		mctl_present = B_TRUE;
24035 	} else {
24036 		first_mp = mp;
24037 		mctl_present = B_FALSE;
24038 	}
24039 
24040 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24041 	ipha = (ipha_t *)mp->b_rptr;
24042 
24043 	/*
24044 	 * If the Don't Fragment flag is on, generate an ICMP destination
24045 	 * unreachable, fragmentation needed.
24046 	 */
24047 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24048 	if (offset & IPH_DF) {
24049 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24050 		if (is_system_labeled()) {
24051 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24052 			    ire->ire_max_frag - max_frag, AF_INET);
24053 		}
24054 		/*
24055 		 * Need to compute hdr checksum if called from ip_wput_ire.
24056 		 * Note that ip_rput_forward verifies the checksum before
24057 		 * calling this routine so in that case this is a noop.
24058 		 */
24059 		ipha->ipha_hdr_checksum = 0;
24060 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24061 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24062 		    ipst);
24063 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24064 		    "ip_wput_frag_end:(%S)",
24065 		    "don't fragment");
24066 		return;
24067 	}
24068 	/*
24069 	 * Labeled systems adjust max_frag if they add a label
24070 	 * to send the correct path mtu.  We need the real mtu since we
24071 	 * are fragmenting the packet after label adjustment.
24072 	 */
24073 	if (is_system_labeled())
24074 		max_frag = ire->ire_max_frag;
24075 	if (mctl_present)
24076 		freeb(first_mp);
24077 	/*
24078 	 * Establish the starting offset.  May not be zero if we are fragging
24079 	 * a fragment that is being forwarded.
24080 	 */
24081 	offset = offset & IPH_OFFSET;
24082 
24083 	/* TODO why is this test needed? */
24084 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24085 	if (((max_frag - LENGTH) & ~7) < 8) {
24086 		/* TODO: notify ulp somehow */
24087 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24088 		freemsg(mp);
24089 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24090 		    "ip_wput_frag_end:(%S)",
24091 		    "len < 8");
24092 		return;
24093 	}
24094 
24095 	hdr_len = (V_HLEN & 0xF) << 2;
24096 
24097 	ipha->ipha_hdr_checksum = 0;
24098 
24099 	/*
24100 	 * Establish the number of bytes maximum per frag, after putting
24101 	 * in the header.
24102 	 */
24103 	len = (max_frag - hdr_len) & ~7;
24104 
24105 	/* Check if we can use MDT to send out the frags. */
24106 	ASSERT(!IRE_IS_LOCAL(ire));
24107 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24108 	    ipst->ips_ip_multidata_outbound &&
24109 	    !(ire->ire_flags & RTF_MULTIRT) &&
24110 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24111 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24112 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24113 		ASSERT(ill->ill_mdt_capab != NULL);
24114 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24115 			/*
24116 			 * If MDT has been previously turned off in the past,
24117 			 * and we currently can do MDT (due to IPQoS policy
24118 			 * removal, etc.) then enable it for this interface.
24119 			 */
24120 			ill->ill_mdt_capab->ill_mdt_on = 1;
24121 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24122 			    ill->ill_name));
24123 		}
24124 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24125 		    offset);
24126 		return;
24127 	}
24128 
24129 	/* Get a copy of the header for the trailing frags */
24130 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24131 	    mp);
24132 	if (!hdr_mp) {
24133 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24134 		freemsg(mp);
24135 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24136 		    "ip_wput_frag_end:(%S)",
24137 		    "couldn't copy hdr");
24138 		return;
24139 	}
24140 
24141 	/* Store the starting offset, with the MoreFrags flag. */
24142 	i1 = offset | IPH_MF | frag_flag;
24143 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24144 
24145 	/* Establish the ending byte offset, based on the starting offset. */
24146 	offset <<= 3;
24147 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24148 
24149 	/* Store the length of the first fragment in the IP header. */
24150 	i1 = len + hdr_len;
24151 	ASSERT(i1 <= IP_MAXPACKET);
24152 	ipha->ipha_length = htons((uint16_t)i1);
24153 
24154 	/*
24155 	 * Compute the IP header checksum for the first frag.  We have to
24156 	 * watch out that we stop at the end of the header.
24157 	 */
24158 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24159 
24160 	/*
24161 	 * Now carve off the first frag.  Note that this will include the
24162 	 * original IP header.
24163 	 */
24164 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24165 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24166 		freeb(hdr_mp);
24167 		freemsg(mp_orig);
24168 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24169 		    "ip_wput_frag_end:(%S)",
24170 		    "couldn't carve first");
24171 		return;
24172 	}
24173 
24174 	/*
24175 	 * Multirouting case. Each fragment is replicated
24176 	 * via all non-condemned RTF_MULTIRT routes
24177 	 * currently resolved.
24178 	 * We ensure that first_ire is the first RTF_MULTIRT
24179 	 * ire in the bucket.
24180 	 */
24181 	if (ire->ire_flags & RTF_MULTIRT) {
24182 		irb = ire->ire_bucket;
24183 		ASSERT(irb != NULL);
24184 
24185 		multirt_send = B_TRUE;
24186 
24187 		/* Make sure we do not omit any multiroute ire. */
24188 		IRB_REFHOLD(irb);
24189 		for (first_ire = irb->irb_ire;
24190 		    first_ire != NULL;
24191 		    first_ire = first_ire->ire_next) {
24192 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24193 			    (first_ire->ire_addr == ire->ire_addr) &&
24194 			    !(first_ire->ire_marks &
24195 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24196 				break;
24197 		}
24198 
24199 		if (first_ire != NULL) {
24200 			if (first_ire != ire) {
24201 				IRE_REFHOLD(first_ire);
24202 				/*
24203 				 * Do not release the ire passed in
24204 				 * as the argument.
24205 				 */
24206 				ire = first_ire;
24207 			} else {
24208 				first_ire = NULL;
24209 			}
24210 		}
24211 		IRB_REFRELE(irb);
24212 
24213 		/*
24214 		 * Save the first ire; we will need to restore it
24215 		 * for the trailing frags.
24216 		 * We REFHOLD save_ire, as each iterated ire will be
24217 		 * REFRELEd.
24218 		 */
24219 		save_ire = ire;
24220 		IRE_REFHOLD(save_ire);
24221 	}
24222 
24223 	/*
24224 	 * First fragment emission loop.
24225 	 * In most cases, the emission loop below is entered only
24226 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24227 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24228 	 * bucket, and send the fragment through all crossed
24229 	 * RTF_MULTIRT routes.
24230 	 */
24231 	do {
24232 		if (ire->ire_flags & RTF_MULTIRT) {
24233 			/*
24234 			 * We are in a multiple send case, need to get
24235 			 * the next ire and make a copy of the packet.
24236 			 * ire1 holds here the next ire to process in the
24237 			 * bucket. If multirouting is expected,
24238 			 * any non-RTF_MULTIRT ire that has the
24239 			 * right destination address is ignored.
24240 			 *
24241 			 * We have to take into account the MTU of
24242 			 * each walked ire. max_frag is set by the
24243 			 * the caller and generally refers to
24244 			 * the primary ire entry. Here we ensure that
24245 			 * no route with a lower MTU will be used, as
24246 			 * fragments are carved once for all ires,
24247 			 * then replicated.
24248 			 */
24249 			ASSERT(irb != NULL);
24250 			IRB_REFHOLD(irb);
24251 			for (ire1 = ire->ire_next;
24252 			    ire1 != NULL;
24253 			    ire1 = ire1->ire_next) {
24254 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24255 					continue;
24256 				if (ire1->ire_addr != ire->ire_addr)
24257 					continue;
24258 				if (ire1->ire_marks &
24259 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24260 					continue;
24261 				/*
24262 				 * Ensure we do not exceed the MTU
24263 				 * of the next route.
24264 				 */
24265 				if (ire1->ire_max_frag < max_frag) {
24266 					ip_multirt_bad_mtu(ire1, max_frag);
24267 					continue;
24268 				}
24269 
24270 				/* Got one. */
24271 				IRE_REFHOLD(ire1);
24272 				break;
24273 			}
24274 			IRB_REFRELE(irb);
24275 
24276 			if (ire1 != NULL) {
24277 				next_mp = copyb(mp);
24278 				if ((next_mp == NULL) ||
24279 				    ((mp->b_cont != NULL) &&
24280 				    ((next_mp->b_cont =
24281 				    dupmsg(mp->b_cont)) == NULL))) {
24282 					freemsg(next_mp);
24283 					next_mp = NULL;
24284 					ire_refrele(ire1);
24285 					ire1 = NULL;
24286 				}
24287 			}
24288 
24289 			/* Last multiroute ire; don't loop anymore. */
24290 			if (ire1 == NULL) {
24291 				multirt_send = B_FALSE;
24292 			}
24293 		}
24294 
24295 		ll_hdr_len = 0;
24296 		LOCK_IRE_FP_MP(ire);
24297 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24298 		if (ll_hdr_mp != NULL) {
24299 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24300 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24301 		} else {
24302 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24303 		}
24304 
24305 		/* If there is a transmit header, get a copy for this frag. */
24306 		/*
24307 		 * TODO: should check db_ref before calling ip_carve_mp since
24308 		 * it might give us a dup.
24309 		 */
24310 		if (!ll_hdr_mp) {
24311 			/* No xmit header. */
24312 			xmit_mp = mp;
24313 
24314 		/* We have a link-layer header that can fit in our mblk. */
24315 		} else if (mp->b_datap->db_ref == 1 &&
24316 		    ll_hdr_len != 0 &&
24317 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24318 			/* M_DATA fastpath */
24319 			mp->b_rptr -= ll_hdr_len;
24320 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24321 			xmit_mp = mp;
24322 
24323 		/* Corner case if copyb has failed */
24324 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24325 			UNLOCK_IRE_FP_MP(ire);
24326 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24327 			freeb(hdr_mp);
24328 			freemsg(mp);
24329 			freemsg(mp_orig);
24330 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24331 			    "ip_wput_frag_end:(%S)",
24332 			    "discard");
24333 
24334 			if (multirt_send) {
24335 				ASSERT(ire1);
24336 				ASSERT(next_mp);
24337 
24338 				freemsg(next_mp);
24339 				ire_refrele(ire1);
24340 			}
24341 			if (save_ire != NULL)
24342 				IRE_REFRELE(save_ire);
24343 
24344 			if (first_ire != NULL)
24345 				ire_refrele(first_ire);
24346 			return;
24347 
24348 		/*
24349 		 * Case of res_mp OR the fastpath mp can't fit
24350 		 * in the mblk
24351 		 */
24352 		} else {
24353 			xmit_mp->b_cont = mp;
24354 
24355 			/*
24356 			 * Get priority marking, if any.
24357 			 * We propagate the CoS marking from the
24358 			 * original packet that went to QoS processing
24359 			 * in ip_wput_ire to the newly carved mp.
24360 			 */
24361 			if (DB_TYPE(xmit_mp) == M_DATA)
24362 				xmit_mp->b_band = mp->b_band;
24363 		}
24364 		UNLOCK_IRE_FP_MP(ire);
24365 
24366 		q = ire->ire_stq;
24367 		out_ill = (ill_t *)q->q_ptr;
24368 
24369 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24370 
24371 		DTRACE_PROBE4(ip4__physical__out__start,
24372 		    ill_t *, NULL, ill_t *, out_ill,
24373 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24374 
24375 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24376 		    ipst->ips_ipv4firewall_physical_out,
24377 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24378 
24379 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24380 
24381 		if (xmit_mp != NULL) {
24382 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24383 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24384 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24385 
24386 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24387 
24388 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24389 			UPDATE_MIB(out_ill->ill_ip_mib,
24390 			    ipIfStatsHCOutOctets, i1);
24391 
24392 			if (pkt_type != OB_PKT) {
24393 				/*
24394 				 * Update the packet count and MIB stats
24395 				 * of trailing RTF_MULTIRT ires.
24396 				 */
24397 				UPDATE_OB_PKT_COUNT(ire);
24398 				BUMP_MIB(out_ill->ill_ip_mib,
24399 				    ipIfStatsOutFragReqds);
24400 			}
24401 		}
24402 
24403 		if (multirt_send) {
24404 			/*
24405 			 * We are in a multiple send case; look for
24406 			 * the next ire and re-enter the loop.
24407 			 */
24408 			ASSERT(ire1);
24409 			ASSERT(next_mp);
24410 			/* REFRELE the current ire before looping */
24411 			ire_refrele(ire);
24412 			ire = ire1;
24413 			ire1 = NULL;
24414 			mp = next_mp;
24415 			next_mp = NULL;
24416 		}
24417 	} while (multirt_send);
24418 
24419 	ASSERT(ire1 == NULL);
24420 
24421 	/* Restore the original ire; we need it for the trailing frags */
24422 	if (save_ire != NULL) {
24423 		/* REFRELE the last iterated ire */
24424 		ire_refrele(ire);
24425 		/* save_ire has been REFHOLDed */
24426 		ire = save_ire;
24427 		save_ire = NULL;
24428 		q = ire->ire_stq;
24429 	}
24430 
24431 	if (pkt_type == OB_PKT) {
24432 		UPDATE_OB_PKT_COUNT(ire);
24433 	} else {
24434 		out_ill = (ill_t *)q->q_ptr;
24435 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24436 		UPDATE_IB_PKT_COUNT(ire);
24437 	}
24438 
24439 	/* Advance the offset to the second frag starting point. */
24440 	offset += len;
24441 	/*
24442 	 * Update hdr_len from the copied header - there might be less options
24443 	 * in the later fragments.
24444 	 */
24445 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24446 	/* Loop until done. */
24447 	for (;;) {
24448 		uint16_t	offset_and_flags;
24449 		uint16_t	ip_len;
24450 
24451 		if (ip_data_end - offset > len) {
24452 			/*
24453 			 * Carve off the appropriate amount from the original
24454 			 * datagram.
24455 			 */
24456 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24457 				mp = NULL;
24458 				break;
24459 			}
24460 			/*
24461 			 * More frags after this one.  Get another copy
24462 			 * of the header.
24463 			 */
24464 			if (carve_mp->b_datap->db_ref == 1 &&
24465 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24466 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24467 				/* Inline IP header */
24468 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24469 				    hdr_mp->b_rptr;
24470 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24471 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24472 				mp = carve_mp;
24473 			} else {
24474 				if (!(mp = copyb(hdr_mp))) {
24475 					freemsg(carve_mp);
24476 					break;
24477 				}
24478 				/* Get priority marking, if any. */
24479 				mp->b_band = carve_mp->b_band;
24480 				mp->b_cont = carve_mp;
24481 			}
24482 			ipha = (ipha_t *)mp->b_rptr;
24483 			offset_and_flags = IPH_MF;
24484 		} else {
24485 			/*
24486 			 * Last frag.  Consume the header. Set len to
24487 			 * the length of this last piece.
24488 			 */
24489 			len = ip_data_end - offset;
24490 
24491 			/*
24492 			 * Carve off the appropriate amount from the original
24493 			 * datagram.
24494 			 */
24495 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24496 				mp = NULL;
24497 				break;
24498 			}
24499 			if (carve_mp->b_datap->db_ref == 1 &&
24500 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24501 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24502 				/* Inline IP header */
24503 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24504 				    hdr_mp->b_rptr;
24505 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24506 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24507 				mp = carve_mp;
24508 				freeb(hdr_mp);
24509 				hdr_mp = mp;
24510 			} else {
24511 				mp = hdr_mp;
24512 				/* Get priority marking, if any. */
24513 				mp->b_band = carve_mp->b_band;
24514 				mp->b_cont = carve_mp;
24515 			}
24516 			ipha = (ipha_t *)mp->b_rptr;
24517 			/* A frag of a frag might have IPH_MF non-zero */
24518 			offset_and_flags =
24519 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24520 			    IPH_MF;
24521 		}
24522 		offset_and_flags |= (uint16_t)(offset >> 3);
24523 		offset_and_flags |= (uint16_t)frag_flag;
24524 		/* Store the offset and flags in the IP header. */
24525 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24526 
24527 		/* Store the length in the IP header. */
24528 		ip_len = (uint16_t)(len + hdr_len);
24529 		ipha->ipha_length = htons(ip_len);
24530 
24531 		/*
24532 		 * Set the IP header checksum.	Note that mp is just
24533 		 * the header, so this is easy to pass to ip_csum.
24534 		 */
24535 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24536 
24537 		/* Attach a transmit header, if any, and ship it. */
24538 		if (pkt_type == OB_PKT) {
24539 			UPDATE_OB_PKT_COUNT(ire);
24540 		} else {
24541 			out_ill = (ill_t *)q->q_ptr;
24542 			BUMP_MIB(out_ill->ill_ip_mib,
24543 			    ipIfStatsHCOutForwDatagrams);
24544 			UPDATE_IB_PKT_COUNT(ire);
24545 		}
24546 
24547 		if (ire->ire_flags & RTF_MULTIRT) {
24548 			irb = ire->ire_bucket;
24549 			ASSERT(irb != NULL);
24550 
24551 			multirt_send = B_TRUE;
24552 
24553 			/*
24554 			 * Save the original ire; we will need to restore it
24555 			 * for the tailing frags.
24556 			 */
24557 			save_ire = ire;
24558 			IRE_REFHOLD(save_ire);
24559 		}
24560 		/*
24561 		 * Emission loop for this fragment, similar
24562 		 * to what is done for the first fragment.
24563 		 */
24564 		do {
24565 			if (multirt_send) {
24566 				/*
24567 				 * We are in a multiple send case, need to get
24568 				 * the next ire and make a copy of the packet.
24569 				 */
24570 				ASSERT(irb != NULL);
24571 				IRB_REFHOLD(irb);
24572 				for (ire1 = ire->ire_next;
24573 				    ire1 != NULL;
24574 				    ire1 = ire1->ire_next) {
24575 					if (!(ire1->ire_flags & RTF_MULTIRT))
24576 						continue;
24577 					if (ire1->ire_addr != ire->ire_addr)
24578 						continue;
24579 					if (ire1->ire_marks &
24580 					    (IRE_MARK_CONDEMNED |
24581 					    IRE_MARK_TESTHIDDEN))
24582 						continue;
24583 					/*
24584 					 * Ensure we do not exceed the MTU
24585 					 * of the next route.
24586 					 */
24587 					if (ire1->ire_max_frag < max_frag) {
24588 						ip_multirt_bad_mtu(ire1,
24589 						    max_frag);
24590 						continue;
24591 					}
24592 
24593 					/* Got one. */
24594 					IRE_REFHOLD(ire1);
24595 					break;
24596 				}
24597 				IRB_REFRELE(irb);
24598 
24599 				if (ire1 != NULL) {
24600 					next_mp = copyb(mp);
24601 					if ((next_mp == NULL) ||
24602 					    ((mp->b_cont != NULL) &&
24603 					    ((next_mp->b_cont =
24604 					    dupmsg(mp->b_cont)) == NULL))) {
24605 						freemsg(next_mp);
24606 						next_mp = NULL;
24607 						ire_refrele(ire1);
24608 						ire1 = NULL;
24609 					}
24610 				}
24611 
24612 				/* Last multiroute ire; don't loop anymore. */
24613 				if (ire1 == NULL) {
24614 					multirt_send = B_FALSE;
24615 				}
24616 			}
24617 
24618 			/* Update transmit header */
24619 			ll_hdr_len = 0;
24620 			LOCK_IRE_FP_MP(ire);
24621 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24622 			if (ll_hdr_mp != NULL) {
24623 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24624 				ll_hdr_len = MBLKL(ll_hdr_mp);
24625 			} else {
24626 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24627 			}
24628 
24629 			if (!ll_hdr_mp) {
24630 				xmit_mp = mp;
24631 
24632 			/*
24633 			 * We have link-layer header that can fit in
24634 			 * our mblk.
24635 			 */
24636 			} else if (mp->b_datap->db_ref == 1 &&
24637 			    ll_hdr_len != 0 &&
24638 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24639 				/* M_DATA fastpath */
24640 				mp->b_rptr -= ll_hdr_len;
24641 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24642 				    ll_hdr_len);
24643 				xmit_mp = mp;
24644 
24645 			/*
24646 			 * Case of res_mp OR the fastpath mp can't fit
24647 			 * in the mblk
24648 			 */
24649 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24650 				xmit_mp->b_cont = mp;
24651 				/* Get priority marking, if any. */
24652 				if (DB_TYPE(xmit_mp) == M_DATA)
24653 					xmit_mp->b_band = mp->b_band;
24654 
24655 			/* Corner case if copyb failed */
24656 			} else {
24657 				/*
24658 				 * Exit both the replication and
24659 				 * fragmentation loops.
24660 				 */
24661 				UNLOCK_IRE_FP_MP(ire);
24662 				goto drop_pkt;
24663 			}
24664 			UNLOCK_IRE_FP_MP(ire);
24665 
24666 			mp1 = mp;
24667 			out_ill = (ill_t *)q->q_ptr;
24668 
24669 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24670 
24671 			DTRACE_PROBE4(ip4__physical__out__start,
24672 			    ill_t *, NULL, ill_t *, out_ill,
24673 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24674 
24675 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24676 			    ipst->ips_ipv4firewall_physical_out,
24677 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24678 
24679 			DTRACE_PROBE1(ip4__physical__out__end,
24680 			    mblk_t *, xmit_mp);
24681 
24682 			if (mp != mp1 && hdr_mp == mp1)
24683 				hdr_mp = mp;
24684 			if (mp != mp1 && mp_orig == mp1)
24685 				mp_orig = mp;
24686 
24687 			if (xmit_mp != NULL) {
24688 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24689 				    NULL, void_ip_t *, ipha,
24690 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24691 				    ipha, ip6_t *, NULL, int, 0);
24692 
24693 				ILL_SEND_TX(out_ill, ire, connp,
24694 				    xmit_mp, 0, connp);
24695 
24696 				BUMP_MIB(out_ill->ill_ip_mib,
24697 				    ipIfStatsHCOutTransmits);
24698 				UPDATE_MIB(out_ill->ill_ip_mib,
24699 				    ipIfStatsHCOutOctets, ip_len);
24700 
24701 				if (pkt_type != OB_PKT) {
24702 					/*
24703 					 * Update the packet count of trailing
24704 					 * RTF_MULTIRT ires.
24705 					 */
24706 					UPDATE_OB_PKT_COUNT(ire);
24707 				}
24708 			}
24709 
24710 			/* All done if we just consumed the hdr_mp. */
24711 			if (mp == hdr_mp) {
24712 				last_frag = B_TRUE;
24713 				BUMP_MIB(out_ill->ill_ip_mib,
24714 				    ipIfStatsOutFragOKs);
24715 			}
24716 
24717 			if (multirt_send) {
24718 				/*
24719 				 * We are in a multiple send case; look for
24720 				 * the next ire and re-enter the loop.
24721 				 */
24722 				ASSERT(ire1);
24723 				ASSERT(next_mp);
24724 				/* REFRELE the current ire before looping */
24725 				ire_refrele(ire);
24726 				ire = ire1;
24727 				ire1 = NULL;
24728 				q = ire->ire_stq;
24729 				mp = next_mp;
24730 				next_mp = NULL;
24731 			}
24732 		} while (multirt_send);
24733 		/*
24734 		 * Restore the original ire; we need it for the
24735 		 * trailing frags
24736 		 */
24737 		if (save_ire != NULL) {
24738 			ASSERT(ire1 == NULL);
24739 			/* REFRELE the last iterated ire */
24740 			ire_refrele(ire);
24741 			/* save_ire has been REFHOLDed */
24742 			ire = save_ire;
24743 			q = ire->ire_stq;
24744 			save_ire = NULL;
24745 		}
24746 
24747 		if (last_frag) {
24748 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24749 			    "ip_wput_frag_end:(%S)",
24750 			    "consumed hdr_mp");
24751 
24752 			if (first_ire != NULL)
24753 				ire_refrele(first_ire);
24754 			return;
24755 		}
24756 		/* Otherwise, advance and loop. */
24757 		offset += len;
24758 	}
24759 
24760 drop_pkt:
24761 	/* Clean up following allocation failure. */
24762 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24763 	freemsg(mp);
24764 	if (mp != hdr_mp)
24765 		freeb(hdr_mp);
24766 	if (mp != mp_orig)
24767 		freemsg(mp_orig);
24768 
24769 	if (save_ire != NULL)
24770 		IRE_REFRELE(save_ire);
24771 	if (first_ire != NULL)
24772 		ire_refrele(first_ire);
24773 
24774 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24775 	    "ip_wput_frag_end:(%S)",
24776 	    "end--alloc failure");
24777 }
24778 
24779 /*
24780  * Copy the header plus those options which have the copy bit set
24781  * src is the template to make sure we preserve the cred for TX purposes.
24782  */
24783 static mblk_t *
24784 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24785     mblk_t *src)
24786 {
24787 	mblk_t	*mp;
24788 	uchar_t	*up;
24789 
24790 	/*
24791 	 * Quick check if we need to look for options without the copy bit
24792 	 * set
24793 	 */
24794 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24795 	if (!mp)
24796 		return (mp);
24797 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24798 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24799 		bcopy(rptr, mp->b_rptr, hdr_len);
24800 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24801 		return (mp);
24802 	}
24803 	up  = mp->b_rptr;
24804 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24805 	up += IP_SIMPLE_HDR_LENGTH;
24806 	rptr += IP_SIMPLE_HDR_LENGTH;
24807 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24808 	while (hdr_len > 0) {
24809 		uint32_t optval;
24810 		uint32_t optlen;
24811 
24812 		optval = *rptr;
24813 		if (optval == IPOPT_EOL)
24814 			break;
24815 		if (optval == IPOPT_NOP)
24816 			optlen = 1;
24817 		else
24818 			optlen = rptr[1];
24819 		if (optval & IPOPT_COPY) {
24820 			bcopy(rptr, up, optlen);
24821 			up += optlen;
24822 		}
24823 		rptr += optlen;
24824 		hdr_len -= optlen;
24825 	}
24826 	/*
24827 	 * Make sure that we drop an even number of words by filling
24828 	 * with EOL to the next word boundary.
24829 	 */
24830 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24831 	    hdr_len & 0x3; hdr_len++)
24832 		*up++ = IPOPT_EOL;
24833 	mp->b_wptr = up;
24834 	/* Update header length */
24835 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24836 	return (mp);
24837 }
24838 
24839 /*
24840  * Delivery to local recipients including fanout to multiple recipients.
24841  * Does not do checksumming of UDP/TCP.
24842  * Note: q should be the read side queue for either the ill or conn.
24843  * Note: rq should be the read side q for the lower (ill) stream.
24844  * We don't send packets to IPPF processing, thus the last argument
24845  * to all the fanout calls are B_FALSE.
24846  */
24847 void
24848 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24849     int fanout_flags, zoneid_t zoneid)
24850 {
24851 	uint32_t	protocol;
24852 	mblk_t		*first_mp;
24853 	boolean_t	mctl_present;
24854 	int		ire_type;
24855 #define	rptr	((uchar_t *)ipha)
24856 	ip_stack_t	*ipst = ill->ill_ipst;
24857 
24858 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24859 	    "ip_wput_local_start: q %p", q);
24860 
24861 	if (ire != NULL) {
24862 		ire_type = ire->ire_type;
24863 	} else {
24864 		/*
24865 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24866 		 * packet is not multicast, we can't tell the ire type.
24867 		 */
24868 		ASSERT(CLASSD(ipha->ipha_dst));
24869 		ire_type = IRE_BROADCAST;
24870 	}
24871 
24872 	first_mp = mp;
24873 	if (first_mp->b_datap->db_type == M_CTL) {
24874 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24875 		if (!io->ipsec_out_secure) {
24876 			/*
24877 			 * This ipsec_out_t was allocated in ip_wput
24878 			 * for multicast packets to store the ill_index.
24879 			 * As this is being delivered locally, we don't
24880 			 * need this anymore.
24881 			 */
24882 			mp = first_mp->b_cont;
24883 			freeb(first_mp);
24884 			first_mp = mp;
24885 			mctl_present = B_FALSE;
24886 		} else {
24887 			/*
24888 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24889 			 * security properties for the looped-back packet.
24890 			 */
24891 			mctl_present = B_TRUE;
24892 			mp = first_mp->b_cont;
24893 			ASSERT(mp != NULL);
24894 			ipsec_out_to_in(first_mp);
24895 		}
24896 	} else {
24897 		mctl_present = B_FALSE;
24898 	}
24899 
24900 	DTRACE_PROBE4(ip4__loopback__in__start,
24901 	    ill_t *, ill, ill_t *, NULL,
24902 	    ipha_t *, ipha, mblk_t *, first_mp);
24903 
24904 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24905 	    ipst->ips_ipv4firewall_loopback_in,
24906 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24907 
24908 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24909 
24910 	if (first_mp == NULL)
24911 		return;
24912 
24913 	if (ipst->ips_ip4_observe.he_interested) {
24914 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
24915 		zoneid_t stackzoneid = netstackid_to_zoneid(
24916 		    ipst->ips_netstack->netstack_stackid);
24917 
24918 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
24919 		/*
24920 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
24921 		 * address.  Restrict the lookup below to the destination zone.
24922 		 */
24923 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
24924 			lookup_zoneid = zoneid;
24925 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
24926 		    lookup_zoneid);
24927 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill, ipst);
24928 	}
24929 
24930 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
24931 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
24932 	    int, 1);
24933 
24934 	ipst->ips_loopback_packets++;
24935 
24936 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24937 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24938 	if (!IS_SIMPLE_IPH(ipha)) {
24939 		ip_wput_local_options(ipha, ipst);
24940 	}
24941 
24942 	protocol = ipha->ipha_protocol;
24943 	switch (protocol) {
24944 	case IPPROTO_ICMP: {
24945 		ire_t		*ire_zone;
24946 		ilm_t		*ilm;
24947 		mblk_t		*mp1;
24948 		zoneid_t	last_zoneid;
24949 		ilm_walker_t	ilw;
24950 
24951 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24952 			ASSERT(ire_type == IRE_BROADCAST);
24953 			/*
24954 			 * In the multicast case, applications may have joined
24955 			 * the group from different zones, so we need to deliver
24956 			 * the packet to each of them. Loop through the
24957 			 * multicast memberships structures (ilm) on the receive
24958 			 * ill and send a copy of the packet up each matching
24959 			 * one. However, we don't do this for multicasts sent on
24960 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24961 			 * they must stay in the sender's zone.
24962 			 *
24963 			 * ilm_add_v6() ensures that ilms in the same zone are
24964 			 * contiguous in the ill_ilm list. We use this property
24965 			 * to avoid sending duplicates needed when two
24966 			 * applications in the same zone join the same group on
24967 			 * different logical interfaces: we ignore the ilm if
24968 			 * it's zoneid is the same as the last matching one.
24969 			 * In addition, the sending of the packet for
24970 			 * ire_zoneid is delayed until all of the other ilms
24971 			 * have been exhausted.
24972 			 */
24973 			last_zoneid = -1;
24974 			ilm = ilm_walker_start(&ilw, ill);
24975 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
24976 				if (ipha->ipha_dst != ilm->ilm_addr ||
24977 				    ilm->ilm_zoneid == last_zoneid ||
24978 				    ilm->ilm_zoneid == zoneid ||
24979 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24980 					continue;
24981 				mp1 = ip_copymsg(first_mp);
24982 				if (mp1 == NULL)
24983 					continue;
24984 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
24985 				    0, 0, mctl_present, B_FALSE, ill,
24986 				    ilm->ilm_zoneid);
24987 				last_zoneid = ilm->ilm_zoneid;
24988 			}
24989 			ilm_walker_finish(&ilw);
24990 			/*
24991 			 * Loopback case: the sending endpoint has
24992 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24993 			 * dispatch the multicast packet to the sending zone.
24994 			 */
24995 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24996 				freemsg(first_mp);
24997 				return;
24998 			}
24999 		} else if (ire_type == IRE_BROADCAST) {
25000 			/*
25001 			 * In the broadcast case, there may be many zones
25002 			 * which need a copy of the packet delivered to them.
25003 			 * There is one IRE_BROADCAST per broadcast address
25004 			 * and per zone; we walk those using a helper function.
25005 			 * In addition, the sending of the packet for zoneid is
25006 			 * delayed until all of the other ires have been
25007 			 * processed.
25008 			 */
25009 			IRB_REFHOLD(ire->ire_bucket);
25010 			ire_zone = NULL;
25011 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25012 			    ire)) != NULL) {
25013 				mp1 = ip_copymsg(first_mp);
25014 				if (mp1 == NULL)
25015 					continue;
25016 
25017 				UPDATE_IB_PKT_COUNT(ire_zone);
25018 				ire_zone->ire_last_used_time = lbolt;
25019 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25020 				    mctl_present, B_FALSE, ill,
25021 				    ire_zone->ire_zoneid);
25022 			}
25023 			IRB_REFRELE(ire->ire_bucket);
25024 		}
25025 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25026 		    0, mctl_present, B_FALSE, ill, zoneid);
25027 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25028 		    "ip_wput_local_end: q %p (%S)",
25029 		    q, "icmp");
25030 		return;
25031 	}
25032 	case IPPROTO_IGMP:
25033 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25034 			/* Bad packet - discarded by igmp_input */
25035 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25036 			    "ip_wput_local_end: q %p (%S)",
25037 			    q, "igmp_input--bad packet");
25038 			if (mctl_present)
25039 				freeb(first_mp);
25040 			return;
25041 		}
25042 		/*
25043 		 * igmp_input() may have returned the pulled up message.
25044 		 * So first_mp and ipha need to be reinitialized.
25045 		 */
25046 		ipha = (ipha_t *)mp->b_rptr;
25047 		if (mctl_present)
25048 			first_mp->b_cont = mp;
25049 		else
25050 			first_mp = mp;
25051 		/* deliver to local raw users */
25052 		break;
25053 	case IPPROTO_ENCAP:
25054 		/*
25055 		 * This case is covered by either ip_fanout_proto, or by
25056 		 * the above security processing for self-tunneled packets.
25057 		 */
25058 		break;
25059 	case IPPROTO_UDP: {
25060 		uint16_t	*up;
25061 		uint32_t	ports;
25062 
25063 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25064 		    UDP_PORTS_OFFSET);
25065 		/* Force a 'valid' checksum. */
25066 		up[3] = 0;
25067 
25068 		ports = *(uint32_t *)up;
25069 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25070 		    (ire_type == IRE_BROADCAST),
25071 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25072 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25073 		    ill, zoneid);
25074 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25075 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25076 		return;
25077 	}
25078 	case IPPROTO_TCP: {
25079 
25080 		/*
25081 		 * For TCP, discard broadcast packets.
25082 		 */
25083 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25084 			freemsg(first_mp);
25085 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25086 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25087 			return;
25088 		}
25089 
25090 		if (mp->b_datap->db_type == M_DATA) {
25091 			/*
25092 			 * M_DATA mblk, so init mblk (chain) for no struio().
25093 			 */
25094 			mblk_t	*mp1 = mp;
25095 
25096 			do {
25097 				mp1->b_datap->db_struioflag = 0;
25098 			} while ((mp1 = mp1->b_cont) != NULL);
25099 		}
25100 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25101 		    <= mp->b_wptr);
25102 		ip_fanout_tcp(q, first_mp, ill, ipha,
25103 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25104 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25105 		    mctl_present, B_FALSE, zoneid);
25106 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25107 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25108 		return;
25109 	}
25110 	case IPPROTO_SCTP:
25111 	{
25112 		uint32_t	ports;
25113 
25114 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25115 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25116 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25117 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25118 		return;
25119 	}
25120 
25121 	default:
25122 		break;
25123 	}
25124 	/*
25125 	 * Find a client for some other protocol.  We give
25126 	 * copies to multiple clients, if more than one is
25127 	 * bound.
25128 	 */
25129 	ip_fanout_proto(q, first_mp, ill, ipha,
25130 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25131 	    mctl_present, B_FALSE, ill, zoneid);
25132 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25133 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25134 #undef	rptr
25135 }
25136 
25137 /*
25138  * Update any source route, record route, or timestamp options.
25139  * Check that we are at end of strict source route.
25140  * The options have been sanity checked by ip_wput_options().
25141  */
25142 static void
25143 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25144 {
25145 	ipoptp_t	opts;
25146 	uchar_t		*opt;
25147 	uint8_t		optval;
25148 	uint8_t		optlen;
25149 	ipaddr_t	dst;
25150 	uint32_t	ts;
25151 	ire_t		*ire;
25152 	timestruc_t	now;
25153 
25154 	ip2dbg(("ip_wput_local_options\n"));
25155 	for (optval = ipoptp_first(&opts, ipha);
25156 	    optval != IPOPT_EOL;
25157 	    optval = ipoptp_next(&opts)) {
25158 		opt = opts.ipoptp_cur;
25159 		optlen = opts.ipoptp_len;
25160 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25161 		switch (optval) {
25162 			uint32_t off;
25163 		case IPOPT_SSRR:
25164 		case IPOPT_LSRR:
25165 			off = opt[IPOPT_OFFSET];
25166 			off--;
25167 			if (optlen < IP_ADDR_LEN ||
25168 			    off > optlen - IP_ADDR_LEN) {
25169 				/* End of source route */
25170 				break;
25171 			}
25172 			/*
25173 			 * This will only happen if two consecutive entries
25174 			 * in the source route contains our address or if
25175 			 * it is a packet with a loose source route which
25176 			 * reaches us before consuming the whole source route
25177 			 */
25178 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25179 			if (optval == IPOPT_SSRR) {
25180 				return;
25181 			}
25182 			/*
25183 			 * Hack: instead of dropping the packet truncate the
25184 			 * source route to what has been used by filling the
25185 			 * rest with IPOPT_NOP.
25186 			 */
25187 			opt[IPOPT_OLEN] = (uint8_t)off;
25188 			while (off < optlen) {
25189 				opt[off++] = IPOPT_NOP;
25190 			}
25191 			break;
25192 		case IPOPT_RR:
25193 			off = opt[IPOPT_OFFSET];
25194 			off--;
25195 			if (optlen < IP_ADDR_LEN ||
25196 			    off > optlen - IP_ADDR_LEN) {
25197 				/* No more room - ignore */
25198 				ip1dbg((
25199 				    "ip_wput_forward_options: end of RR\n"));
25200 				break;
25201 			}
25202 			dst = htonl(INADDR_LOOPBACK);
25203 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25204 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25205 			break;
25206 		case IPOPT_TS:
25207 			/* Insert timestamp if there is romm */
25208 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25209 			case IPOPT_TS_TSONLY:
25210 				off = IPOPT_TS_TIMELEN;
25211 				break;
25212 			case IPOPT_TS_PRESPEC:
25213 			case IPOPT_TS_PRESPEC_RFC791:
25214 				/* Verify that the address matched */
25215 				off = opt[IPOPT_OFFSET] - 1;
25216 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25217 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25218 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25219 				    ipst);
25220 				if (ire == NULL) {
25221 					/* Not for us */
25222 					break;
25223 				}
25224 				ire_refrele(ire);
25225 				/* FALLTHRU */
25226 			case IPOPT_TS_TSANDADDR:
25227 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25228 				break;
25229 			default:
25230 				/*
25231 				 * ip_*put_options should have already
25232 				 * dropped this packet.
25233 				 */
25234 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25235 				    "unknown IT - bug in ip_wput_options?\n");
25236 				return;	/* Keep "lint" happy */
25237 			}
25238 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25239 				/* Increase overflow counter */
25240 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25241 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25242 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25243 				    (off << 4);
25244 				break;
25245 			}
25246 			off = opt[IPOPT_OFFSET] - 1;
25247 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25248 			case IPOPT_TS_PRESPEC:
25249 			case IPOPT_TS_PRESPEC_RFC791:
25250 			case IPOPT_TS_TSANDADDR:
25251 				dst = htonl(INADDR_LOOPBACK);
25252 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25253 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25254 				/* FALLTHRU */
25255 			case IPOPT_TS_TSONLY:
25256 				off = opt[IPOPT_OFFSET] - 1;
25257 				/* Compute # of milliseconds since midnight */
25258 				gethrestime(&now);
25259 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25260 				    now.tv_nsec / (NANOSEC / MILLISEC);
25261 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25262 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25263 				break;
25264 			}
25265 			break;
25266 		}
25267 	}
25268 }
25269 
25270 /*
25271  * Send out a multicast packet on interface ipif.
25272  * The sender does not have an conn.
25273  * Caller verifies that this isn't a PHYI_LOOPBACK.
25274  */
25275 void
25276 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25277 {
25278 	ipha_t	*ipha;
25279 	ire_t	*ire;
25280 	ipaddr_t	dst;
25281 	mblk_t		*first_mp;
25282 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25283 
25284 	/* igmp_sendpkt always allocates a ipsec_out_t */
25285 	ASSERT(mp->b_datap->db_type == M_CTL);
25286 	ASSERT(!ipif->ipif_isv6);
25287 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25288 
25289 	first_mp = mp;
25290 	mp = first_mp->b_cont;
25291 	ASSERT(mp->b_datap->db_type == M_DATA);
25292 	ipha = (ipha_t *)mp->b_rptr;
25293 
25294 	/*
25295 	 * Find an IRE which matches the destination and the outgoing
25296 	 * queue (i.e. the outgoing interface.)
25297 	 */
25298 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25299 		dst = ipif->ipif_pp_dst_addr;
25300 	else
25301 		dst = ipha->ipha_dst;
25302 	/*
25303 	 * The source address has already been initialized by the
25304 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25305 	 * be sufficient rather than MATCH_IRE_IPIF.
25306 	 *
25307 	 * This function is used for sending IGMP packets.  For IPMP,
25308 	 * we sidestep IGMP snooping issues by sending all multicast
25309 	 * traffic on a single interface in the IPMP group.
25310 	 */
25311 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25312 	    MATCH_IRE_ILL, ipst);
25313 	if (!ire) {
25314 		/*
25315 		 * Mark this packet to make it be delivered to
25316 		 * ip_wput_ire after the new ire has been
25317 		 * created.
25318 		 */
25319 		mp->b_prev = NULL;
25320 		mp->b_next = NULL;
25321 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25322 		    zoneid, &zero_info);
25323 		return;
25324 	}
25325 
25326 	/*
25327 	 * Honor the RTF_SETSRC flag; this is the only case
25328 	 * where we force this addr whatever the current src addr is,
25329 	 * because this address is set by igmp_sendpkt(), and
25330 	 * cannot be specified by any user.
25331 	 */
25332 	if (ire->ire_flags & RTF_SETSRC) {
25333 		ipha->ipha_src = ire->ire_src_addr;
25334 	}
25335 
25336 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25337 }
25338 
25339 /*
25340  * NOTE : This function does not ire_refrele the ire argument passed in.
25341  *
25342  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25343  * failure. The nce_fp_mp can vanish any time in the case of
25344  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25345  * the ire_lock to access the nce_fp_mp in this case.
25346  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25347  * prepending a fastpath message IPQoS processing must precede it, we also set
25348  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25349  * (IPQoS might have set the b_band for CoS marking).
25350  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25351  * must follow it so that IPQoS can mark the dl_priority field for CoS
25352  * marking, if needed.
25353  */
25354 static mblk_t *
25355 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25356     uint32_t ill_index, ipha_t **iphap)
25357 {
25358 	uint_t	hlen;
25359 	ipha_t *ipha;
25360 	mblk_t *mp1;
25361 	boolean_t qos_done = B_FALSE;
25362 	uchar_t	*ll_hdr;
25363 	ip_stack_t	*ipst = ire->ire_ipst;
25364 
25365 #define	rptr	((uchar_t *)ipha)
25366 
25367 	ipha = (ipha_t *)mp->b_rptr;
25368 	hlen = 0;
25369 	LOCK_IRE_FP_MP(ire);
25370 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25371 		ASSERT(DB_TYPE(mp1) == M_DATA);
25372 		/* Initiate IPPF processing */
25373 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25374 			UNLOCK_IRE_FP_MP(ire);
25375 			ip_process(proc, &mp, ill_index);
25376 			if (mp == NULL)
25377 				return (NULL);
25378 
25379 			ipha = (ipha_t *)mp->b_rptr;
25380 			LOCK_IRE_FP_MP(ire);
25381 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25382 				qos_done = B_TRUE;
25383 				goto no_fp_mp;
25384 			}
25385 			ASSERT(DB_TYPE(mp1) == M_DATA);
25386 		}
25387 		hlen = MBLKL(mp1);
25388 		/*
25389 		 * Check if we have enough room to prepend fastpath
25390 		 * header
25391 		 */
25392 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25393 			ll_hdr = rptr - hlen;
25394 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25395 			/*
25396 			 * Set the b_rptr to the start of the link layer
25397 			 * header
25398 			 */
25399 			mp->b_rptr = ll_hdr;
25400 			mp1 = mp;
25401 		} else {
25402 			mp1 = copyb(mp1);
25403 			if (mp1 == NULL)
25404 				goto unlock_err;
25405 			mp1->b_band = mp->b_band;
25406 			mp1->b_cont = mp;
25407 			/*
25408 			 * XXX disable ICK_VALID and compute checksum
25409 			 * here; can happen if nce_fp_mp changes and
25410 			 * it can't be copied now due to insufficient
25411 			 * space. (unlikely, fp mp can change, but it
25412 			 * does not increase in length)
25413 			 */
25414 		}
25415 		UNLOCK_IRE_FP_MP(ire);
25416 	} else {
25417 no_fp_mp:
25418 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25419 		if (mp1 == NULL) {
25420 unlock_err:
25421 			UNLOCK_IRE_FP_MP(ire);
25422 			freemsg(mp);
25423 			return (NULL);
25424 		}
25425 		UNLOCK_IRE_FP_MP(ire);
25426 		mp1->b_cont = mp;
25427 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25428 			ip_process(proc, &mp1, ill_index);
25429 			if (mp1 == NULL)
25430 				return (NULL);
25431 
25432 			if (mp1->b_cont == NULL)
25433 				ipha = NULL;
25434 			else
25435 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25436 		}
25437 	}
25438 
25439 	*iphap = ipha;
25440 	return (mp1);
25441 #undef rptr
25442 }
25443 
25444 /*
25445  * Finish the outbound IPsec processing for an IPv6 packet. This function
25446  * is called from ipsec_out_process() if the IPsec packet was processed
25447  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25448  * asynchronously.
25449  */
25450 void
25451 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25452     ire_t *ire_arg)
25453 {
25454 	in6_addr_t *v6dstp;
25455 	ire_t *ire;
25456 	mblk_t *mp;
25457 	ip6_t *ip6h1;
25458 	uint_t	ill_index;
25459 	ipsec_out_t *io;
25460 	boolean_t hwaccel;
25461 	uint32_t flags = IP6_NO_IPPOLICY;
25462 	int match_flags;
25463 	zoneid_t zoneid;
25464 	boolean_t ill_need_rele = B_FALSE;
25465 	boolean_t ire_need_rele = B_FALSE;
25466 	ip_stack_t	*ipst;
25467 
25468 	mp = ipsec_mp->b_cont;
25469 	ip6h1 = (ip6_t *)mp->b_rptr;
25470 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25471 	ASSERT(io->ipsec_out_ns != NULL);
25472 	ipst = io->ipsec_out_ns->netstack_ip;
25473 	ill_index = io->ipsec_out_ill_index;
25474 	if (io->ipsec_out_reachable) {
25475 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25476 	}
25477 	hwaccel = io->ipsec_out_accelerated;
25478 	zoneid = io->ipsec_out_zoneid;
25479 	ASSERT(zoneid != ALL_ZONES);
25480 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25481 	/* Multicast addresses should have non-zero ill_index. */
25482 	v6dstp = &ip6h->ip6_dst;
25483 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25484 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25485 
25486 	if (ill == NULL && ill_index != 0) {
25487 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25488 		/* Failure case frees things for us. */
25489 		if (ill == NULL)
25490 			return;
25491 
25492 		ill_need_rele = B_TRUE;
25493 	}
25494 	ASSERT(mp != NULL);
25495 
25496 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25497 		boolean_t unspec_src;
25498 		ipif_t	*ipif;
25499 
25500 		/*
25501 		 * Use the ill_index to get the right ill.
25502 		 */
25503 		unspec_src = io->ipsec_out_unspec_src;
25504 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25505 		if (ipif == NULL) {
25506 			if (ill_need_rele)
25507 				ill_refrele(ill);
25508 			freemsg(ipsec_mp);
25509 			return;
25510 		}
25511 
25512 		if (ire_arg != NULL) {
25513 			ire = ire_arg;
25514 		} else {
25515 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25516 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25517 			ire_need_rele = B_TRUE;
25518 		}
25519 		if (ire != NULL) {
25520 			ipif_refrele(ipif);
25521 			/*
25522 			 * XXX Do the multicast forwarding now, as the IPsec
25523 			 * processing has been done.
25524 			 */
25525 			goto send;
25526 		}
25527 
25528 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25529 		mp->b_prev = NULL;
25530 		mp->b_next = NULL;
25531 
25532 		/*
25533 		 * If the IPsec packet was processed asynchronously,
25534 		 * drop it now.
25535 		 */
25536 		if (q == NULL) {
25537 			if (ill_need_rele)
25538 				ill_refrele(ill);
25539 			freemsg(ipsec_mp);
25540 			return;
25541 		}
25542 
25543 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25544 		    unspec_src, zoneid);
25545 		ipif_refrele(ipif);
25546 	} else {
25547 		if (ire_arg != NULL) {
25548 			ire = ire_arg;
25549 		} else {
25550 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25551 			ire_need_rele = B_TRUE;
25552 		}
25553 		if (ire != NULL)
25554 			goto send;
25555 		/*
25556 		 * ire disappeared underneath.
25557 		 *
25558 		 * What we need to do here is the ip_newroute
25559 		 * logic to get the ire without doing the IPsec
25560 		 * processing. Follow the same old path. But this
25561 		 * time, ip_wput or ire_add_then_send will call us
25562 		 * directly as all the IPsec operations are done.
25563 		 */
25564 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25565 		mp->b_prev = NULL;
25566 		mp->b_next = NULL;
25567 
25568 		/*
25569 		 * If the IPsec packet was processed asynchronously,
25570 		 * drop it now.
25571 		 */
25572 		if (q == NULL) {
25573 			if (ill_need_rele)
25574 				ill_refrele(ill);
25575 			freemsg(ipsec_mp);
25576 			return;
25577 		}
25578 
25579 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25580 		    zoneid, ipst);
25581 	}
25582 	if (ill != NULL && ill_need_rele)
25583 		ill_refrele(ill);
25584 	return;
25585 send:
25586 	if (ill != NULL && ill_need_rele)
25587 		ill_refrele(ill);
25588 
25589 	/* Local delivery */
25590 	if (ire->ire_stq == NULL) {
25591 		ill_t	*out_ill;
25592 		ASSERT(q != NULL);
25593 
25594 		/* PFHooks: LOOPBACK_OUT */
25595 		out_ill = ire_to_ill(ire);
25596 
25597 		/*
25598 		 * DTrace this as ip:::send.  A blocked packet will fire the
25599 		 * send probe, but not the receive probe.
25600 		 */
25601 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25602 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25603 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25604 
25605 		DTRACE_PROBE4(ip6__loopback__out__start,
25606 		    ill_t *, NULL, ill_t *, out_ill,
25607 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25608 
25609 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25610 		    ipst->ips_ipv6firewall_loopback_out,
25611 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25612 
25613 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25614 
25615 		if (ipsec_mp != NULL) {
25616 			ip_wput_local_v6(RD(q), out_ill,
25617 			    ip6h, ipsec_mp, ire, 0, zoneid);
25618 		}
25619 		if (ire_need_rele)
25620 			ire_refrele(ire);
25621 		return;
25622 	}
25623 	/*
25624 	 * Everything is done. Send it out on the wire.
25625 	 * We force the insertion of a fragment header using the
25626 	 * IPH_FRAG_HDR flag in two cases:
25627 	 * - after reception of an ICMPv6 "packet too big" message
25628 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25629 	 * - for multirouted IPv6 packets, so that the receiver can
25630 	 *   discard duplicates according to their fragment identifier
25631 	 */
25632 	/* XXX fix flow control problems. */
25633 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25634 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25635 		if (hwaccel) {
25636 			/*
25637 			 * hardware acceleration does not handle these
25638 			 * "slow path" cases.
25639 			 */
25640 			/* IPsec KSTATS: should bump bean counter here. */
25641 			if (ire_need_rele)
25642 				ire_refrele(ire);
25643 			freemsg(ipsec_mp);
25644 			return;
25645 		}
25646 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25647 		    (mp->b_cont ? msgdsize(mp) :
25648 		    mp->b_wptr - (uchar_t *)ip6h)) {
25649 			/* IPsec KSTATS: should bump bean counter here. */
25650 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25651 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25652 			    msgdsize(mp)));
25653 			if (ire_need_rele)
25654 				ire_refrele(ire);
25655 			freemsg(ipsec_mp);
25656 			return;
25657 		}
25658 		ASSERT(mp->b_prev == NULL);
25659 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25660 		    ntohs(ip6h->ip6_plen) +
25661 		    IPV6_HDR_LEN, ire->ire_max_frag));
25662 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25663 		    ire->ire_max_frag);
25664 	} else {
25665 		UPDATE_OB_PKT_COUNT(ire);
25666 		ire->ire_last_used_time = lbolt;
25667 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25668 	}
25669 	if (ire_need_rele)
25670 		ire_refrele(ire);
25671 	freeb(ipsec_mp);
25672 }
25673 
25674 void
25675 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25676 {
25677 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25678 	da_ipsec_t *hada;	/* data attributes */
25679 	ill_t *ill = (ill_t *)q->q_ptr;
25680 
25681 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25682 
25683 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25684 		/* IPsec KSTATS: Bump lose counter here! */
25685 		freemsg(mp);
25686 		return;
25687 	}
25688 
25689 	/*
25690 	 * It's an IPsec packet that must be
25691 	 * accelerated by the Provider, and the
25692 	 * outbound ill is IPsec acceleration capable.
25693 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25694 	 * to the ill.
25695 	 * IPsec KSTATS: should bump packet counter here.
25696 	 */
25697 
25698 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25699 	if (hada_mp == NULL) {
25700 		/* IPsec KSTATS: should bump packet counter here. */
25701 		freemsg(mp);
25702 		return;
25703 	}
25704 
25705 	hada_mp->b_datap->db_type = M_CTL;
25706 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25707 	hada_mp->b_cont = mp;
25708 
25709 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25710 	bzero(hada, sizeof (da_ipsec_t));
25711 	hada->da_type = IPHADA_M_CTL;
25712 
25713 	putnext(q, hada_mp);
25714 }
25715 
25716 /*
25717  * Finish the outbound IPsec processing. This function is called from
25718  * ipsec_out_process() if the IPsec packet was processed
25719  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25720  * asynchronously.
25721  */
25722 void
25723 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25724     ire_t *ire_arg)
25725 {
25726 	uint32_t v_hlen_tos_len;
25727 	ipaddr_t	dst;
25728 	ipif_t	*ipif = NULL;
25729 	ire_t *ire;
25730 	ire_t *ire1 = NULL;
25731 	mblk_t *next_mp = NULL;
25732 	uint32_t max_frag;
25733 	boolean_t multirt_send = B_FALSE;
25734 	mblk_t *mp;
25735 	ipha_t *ipha1;
25736 	uint_t	ill_index;
25737 	ipsec_out_t *io;
25738 	int match_flags;
25739 	irb_t *irb = NULL;
25740 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25741 	zoneid_t zoneid;
25742 	ipxmit_state_t	pktxmit_state;
25743 	ip_stack_t	*ipst;
25744 
25745 #ifdef	_BIG_ENDIAN
25746 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25747 #else
25748 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25749 #endif
25750 
25751 	mp = ipsec_mp->b_cont;
25752 	ipha1 = (ipha_t *)mp->b_rptr;
25753 	ASSERT(mp != NULL);
25754 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25755 	dst = ipha->ipha_dst;
25756 
25757 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25758 	ill_index = io->ipsec_out_ill_index;
25759 	zoneid = io->ipsec_out_zoneid;
25760 	ASSERT(zoneid != ALL_ZONES);
25761 	ipst = io->ipsec_out_ns->netstack_ip;
25762 	ASSERT(io->ipsec_out_ns != NULL);
25763 
25764 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25765 	if (ill == NULL && ill_index != 0) {
25766 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25767 		/* Failure case frees things for us. */
25768 		if (ill == NULL)
25769 			return;
25770 
25771 		ill_need_rele = B_TRUE;
25772 	}
25773 
25774 	if (CLASSD(dst)) {
25775 		boolean_t conn_dontroute;
25776 		/*
25777 		 * Use the ill_index to get the right ipif.
25778 		 */
25779 		conn_dontroute = io->ipsec_out_dontroute;
25780 		if (ill_index == 0)
25781 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25782 		else
25783 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25784 		if (ipif == NULL) {
25785 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25786 			    " multicast\n"));
25787 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25788 			freemsg(ipsec_mp);
25789 			goto done;
25790 		}
25791 		/*
25792 		 * ipha_src has already been intialized with the
25793 		 * value of the ipif in ip_wput. All we need now is
25794 		 * an ire to send this downstream.
25795 		 */
25796 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25797 		    msg_getlabel(mp), match_flags, ipst);
25798 		if (ire != NULL) {
25799 			ill_t *ill1;
25800 			/*
25801 			 * Do the multicast forwarding now, as the IPsec
25802 			 * processing has been done.
25803 			 */
25804 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25805 			    (ill1 = ire_to_ill(ire))) {
25806 				if (ip_mforward(ill1, ipha, mp)) {
25807 					freemsg(ipsec_mp);
25808 					ip1dbg(("ip_wput_ipsec_out: mforward "
25809 					    "failed\n"));
25810 					ire_refrele(ire);
25811 					goto done;
25812 				}
25813 			}
25814 			goto send;
25815 		}
25816 
25817 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25818 		mp->b_prev = NULL;
25819 		mp->b_next = NULL;
25820 
25821 		/*
25822 		 * If the IPsec packet was processed asynchronously,
25823 		 * drop it now.
25824 		 */
25825 		if (q == NULL) {
25826 			freemsg(ipsec_mp);
25827 			goto done;
25828 		}
25829 
25830 		/*
25831 		 * We may be using a wrong ipif to create the ire.
25832 		 * But it is okay as the source address is assigned
25833 		 * for the packet already. Next outbound packet would
25834 		 * create the IRE with the right IPIF in ip_wput.
25835 		 *
25836 		 * Also handle RTF_MULTIRT routes.
25837 		 */
25838 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25839 		    zoneid, &zero_info);
25840 	} else {
25841 		if (ire_arg != NULL) {
25842 			ire = ire_arg;
25843 			ire_need_rele = B_FALSE;
25844 		} else {
25845 			ire = ire_cache_lookup(dst, zoneid,
25846 			    msg_getlabel(mp), ipst);
25847 		}
25848 		if (ire != NULL) {
25849 			goto send;
25850 		}
25851 
25852 		/*
25853 		 * ire disappeared underneath.
25854 		 *
25855 		 * What we need to do here is the ip_newroute
25856 		 * logic to get the ire without doing the IPsec
25857 		 * processing. Follow the same old path. But this
25858 		 * time, ip_wput or ire_add_then_put will call us
25859 		 * directly as all the IPsec operations are done.
25860 		 */
25861 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25862 		mp->b_prev = NULL;
25863 		mp->b_next = NULL;
25864 
25865 		/*
25866 		 * If the IPsec packet was processed asynchronously,
25867 		 * drop it now.
25868 		 */
25869 		if (q == NULL) {
25870 			freemsg(ipsec_mp);
25871 			goto done;
25872 		}
25873 
25874 		/*
25875 		 * Since we're going through ip_newroute() again, we
25876 		 * need to make sure we don't:
25877 		 *
25878 		 *	1.) Trigger the ASSERT() with the ipha_ident
25879 		 *	    overloading.
25880 		 *	2.) Redo transport-layer checksumming, since we've
25881 		 *	    already done all that to get this far.
25882 		 *
25883 		 * The easiest way not do either of the above is to set
25884 		 * the ipha_ident field to IP_HDR_INCLUDED.
25885 		 */
25886 		ipha->ipha_ident = IP_HDR_INCLUDED;
25887 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25888 		    zoneid, ipst);
25889 	}
25890 	goto done;
25891 send:
25892 	if (ire->ire_stq == NULL) {
25893 		ill_t	*out_ill;
25894 		/*
25895 		 * Loopbacks go through ip_wput_local except for one case.
25896 		 * We come here if we generate a icmp_frag_needed message
25897 		 * after IPsec processing is over. When this function calls
25898 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25899 		 * icmp_frag_needed. The message generated comes back here
25900 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25901 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25902 		 * source address as it is usually set in ip_wput_ire. As
25903 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25904 		 * and we end up here. We can't enter ip_wput_ire once the
25905 		 * IPsec processing is over and hence we need to do it here.
25906 		 */
25907 		ASSERT(q != NULL);
25908 		UPDATE_OB_PKT_COUNT(ire);
25909 		ire->ire_last_used_time = lbolt;
25910 		if (ipha->ipha_src == 0)
25911 			ipha->ipha_src = ire->ire_src_addr;
25912 
25913 		/* PFHooks: LOOPBACK_OUT */
25914 		out_ill = ire_to_ill(ire);
25915 
25916 		/*
25917 		 * DTrace this as ip:::send.  A blocked packet will fire the
25918 		 * send probe, but not the receive probe.
25919 		 */
25920 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25921 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
25922 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
25923 
25924 		DTRACE_PROBE4(ip4__loopback__out__start,
25925 		    ill_t *, NULL, ill_t *, out_ill,
25926 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25927 
25928 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25929 		    ipst->ips_ipv4firewall_loopback_out,
25930 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
25931 
25932 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25933 
25934 		if (ipsec_mp != NULL)
25935 			ip_wput_local(RD(q), out_ill,
25936 			    ipha, ipsec_mp, ire, 0, zoneid);
25937 		if (ire_need_rele)
25938 			ire_refrele(ire);
25939 		goto done;
25940 	}
25941 
25942 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25943 		/*
25944 		 * We are through with IPsec processing.
25945 		 * Fragment this and send it on the wire.
25946 		 */
25947 		if (io->ipsec_out_accelerated) {
25948 			/*
25949 			 * The packet has been accelerated but must
25950 			 * be fragmented. This should not happen
25951 			 * since AH and ESP must not accelerate
25952 			 * packets that need fragmentation, however
25953 			 * the configuration could have changed
25954 			 * since the AH or ESP processing.
25955 			 * Drop packet.
25956 			 * IPsec KSTATS: bump bean counter here.
25957 			 */
25958 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25959 			    "fragmented accelerated packet!\n"));
25960 			freemsg(ipsec_mp);
25961 		} else {
25962 			ip_wput_ire_fragmentit(ipsec_mp, ire,
25963 			    zoneid, ipst, NULL);
25964 		}
25965 		if (ire_need_rele)
25966 			ire_refrele(ire);
25967 		goto done;
25968 	}
25969 
25970 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25971 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25972 	    (void *)ire->ire_ipif, (void *)ipif));
25973 
25974 	/*
25975 	 * Multiroute the secured packet.
25976 	 */
25977 	if (ire->ire_flags & RTF_MULTIRT) {
25978 		ire_t *first_ire;
25979 		irb = ire->ire_bucket;
25980 		ASSERT(irb != NULL);
25981 		/*
25982 		 * This ire has been looked up as the one that
25983 		 * goes through the given ipif;
25984 		 * make sure we do not omit any other multiroute ire
25985 		 * that may be present in the bucket before this one.
25986 		 */
25987 		IRB_REFHOLD(irb);
25988 		for (first_ire = irb->irb_ire;
25989 		    first_ire != NULL;
25990 		    first_ire = first_ire->ire_next) {
25991 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25992 			    (first_ire->ire_addr == ire->ire_addr) &&
25993 			    !(first_ire->ire_marks &
25994 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
25995 				break;
25996 		}
25997 
25998 		if ((first_ire != NULL) && (first_ire != ire)) {
25999 			/*
26000 			 * Don't change the ire if the packet must
26001 			 * be fragmented if sent via this new one.
26002 			 */
26003 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26004 				IRE_REFHOLD(first_ire);
26005 				if (ire_need_rele)
26006 					ire_refrele(ire);
26007 				else
26008 					ire_need_rele = B_TRUE;
26009 				ire = first_ire;
26010 			}
26011 		}
26012 		IRB_REFRELE(irb);
26013 
26014 		multirt_send = B_TRUE;
26015 		max_frag = ire->ire_max_frag;
26016 	}
26017 
26018 	/*
26019 	 * In most cases, the emission loop below is entered only once.
26020 	 * Only in the case where the ire holds the RTF_MULTIRT
26021 	 * flag, we loop to process all RTF_MULTIRT ires in the
26022 	 * bucket, and send the packet through all crossed
26023 	 * RTF_MULTIRT routes.
26024 	 */
26025 	do {
26026 		if (multirt_send) {
26027 			/*
26028 			 * ire1 holds here the next ire to process in the
26029 			 * bucket. If multirouting is expected,
26030 			 * any non-RTF_MULTIRT ire that has the
26031 			 * right destination address is ignored.
26032 			 */
26033 			ASSERT(irb != NULL);
26034 			IRB_REFHOLD(irb);
26035 			for (ire1 = ire->ire_next;
26036 			    ire1 != NULL;
26037 			    ire1 = ire1->ire_next) {
26038 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26039 					continue;
26040 				if (ire1->ire_addr != ire->ire_addr)
26041 					continue;
26042 				if (ire1->ire_marks &
26043 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26044 					continue;
26045 				/* No loopback here */
26046 				if (ire1->ire_stq == NULL)
26047 					continue;
26048 				/*
26049 				 * Ensure we do not exceed the MTU
26050 				 * of the next route.
26051 				 */
26052 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26053 					ip_multirt_bad_mtu(ire1, max_frag);
26054 					continue;
26055 				}
26056 
26057 				IRE_REFHOLD(ire1);
26058 				break;
26059 			}
26060 			IRB_REFRELE(irb);
26061 			if (ire1 != NULL) {
26062 				/*
26063 				 * We are in a multiple send case, need to
26064 				 * make a copy of the packet.
26065 				 */
26066 				next_mp = copymsg(ipsec_mp);
26067 				if (next_mp == NULL) {
26068 					ire_refrele(ire1);
26069 					ire1 = NULL;
26070 				}
26071 			}
26072 		}
26073 		/*
26074 		 * Everything is done. Send it out on the wire
26075 		 *
26076 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26077 		 * either send it on the wire or, in the case of
26078 		 * HW acceleration, call ipsec_hw_putnext.
26079 		 */
26080 		if (ire->ire_nce &&
26081 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26082 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26083 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26084 			/*
26085 			 * If ire's link-layer is unresolved (this
26086 			 * would only happen if the incomplete ire
26087 			 * was added to cachetable via forwarding path)
26088 			 * don't bother going to ip_xmit_v4. Just drop the
26089 			 * packet.
26090 			 * There is a slight risk here, in that, if we
26091 			 * have the forwarding path create an incomplete
26092 			 * IRE, then until the IRE is completed, any
26093 			 * transmitted IPsec packets will be dropped
26094 			 * instead of being queued waiting for resolution.
26095 			 *
26096 			 * But the likelihood of a forwarding packet and a wput
26097 			 * packet sending to the same dst at the same time
26098 			 * and there not yet be an ARP entry for it is small.
26099 			 * Furthermore, if this actually happens, it might
26100 			 * be likely that wput would generate multiple
26101 			 * packets (and forwarding would also have a train
26102 			 * of packets) for that destination. If this is
26103 			 * the case, some of them would have been dropped
26104 			 * anyway, since ARP only queues a few packets while
26105 			 * waiting for resolution
26106 			 *
26107 			 * NOTE: We should really call ip_xmit_v4,
26108 			 * and let it queue the packet and send the
26109 			 * ARP query and have ARP come back thus:
26110 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26111 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26112 			 * hw accel work. But it's too complex to get
26113 			 * the IPsec hw  acceleration approach to fit
26114 			 * well with ip_xmit_v4 doing ARP without
26115 			 * doing IPsec simplification. For now, we just
26116 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26117 			 * that we can continue with the send on the next
26118 			 * attempt.
26119 			 *
26120 			 * XXX THis should be revisited, when
26121 			 * the IPsec/IP interaction is cleaned up
26122 			 */
26123 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26124 			    " - dropping packet\n"));
26125 			freemsg(ipsec_mp);
26126 			/*
26127 			 * Call ip_xmit_v4() to trigger ARP query
26128 			 * in case the nce_state is ND_INITIAL
26129 			 */
26130 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26131 			goto drop_pkt;
26132 		}
26133 
26134 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26135 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26136 		    mblk_t *, ipsec_mp);
26137 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26138 		    ipst->ips_ipv4firewall_physical_out, NULL,
26139 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26140 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26141 		if (ipsec_mp == NULL)
26142 			goto drop_pkt;
26143 
26144 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26145 		pktxmit_state = ip_xmit_v4(mp, ire,
26146 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26147 
26148 		if ((pktxmit_state ==  SEND_FAILED) ||
26149 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26150 
26151 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26152 drop_pkt:
26153 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26154 			    ipIfStatsOutDiscards);
26155 			if (ire_need_rele)
26156 				ire_refrele(ire);
26157 			if (ire1 != NULL) {
26158 				ire_refrele(ire1);
26159 				freemsg(next_mp);
26160 			}
26161 			goto done;
26162 		}
26163 
26164 		freeb(ipsec_mp);
26165 		if (ire_need_rele)
26166 			ire_refrele(ire);
26167 
26168 		if (ire1 != NULL) {
26169 			ire = ire1;
26170 			ire_need_rele = B_TRUE;
26171 			ASSERT(next_mp);
26172 			ipsec_mp = next_mp;
26173 			mp = ipsec_mp->b_cont;
26174 			ire1 = NULL;
26175 			next_mp = NULL;
26176 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26177 		} else {
26178 			multirt_send = B_FALSE;
26179 		}
26180 	} while (multirt_send);
26181 done:
26182 	if (ill != NULL && ill_need_rele)
26183 		ill_refrele(ill);
26184 	if (ipif != NULL)
26185 		ipif_refrele(ipif);
26186 }
26187 
26188 /*
26189  * Get the ill corresponding to the specified ire, and compare its
26190  * capabilities with the protocol and algorithms specified by the
26191  * the SA obtained from ipsec_out. If they match, annotate the
26192  * ipsec_out structure to indicate that the packet needs acceleration.
26193  *
26194  *
26195  * A packet is eligible for outbound hardware acceleration if the
26196  * following conditions are satisfied:
26197  *
26198  * 1. the packet will not be fragmented
26199  * 2. the provider supports the algorithm
26200  * 3. there is no pending control message being exchanged
26201  * 4. snoop is not attached
26202  * 5. the destination address is not a broadcast or multicast address.
26203  *
26204  * Rationale:
26205  *	- Hardware drivers do not support fragmentation with
26206  *	  the current interface.
26207  *	- snoop, multicast, and broadcast may result in exposure of
26208  *	  a cleartext datagram.
26209  * We check all five of these conditions here.
26210  *
26211  * XXX would like to nuke "ire_t *" parameter here; problem is that
26212  * IRE is only way to figure out if a v4 address is a broadcast and
26213  * thus ineligible for acceleration...
26214  */
26215 static void
26216 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26217 {
26218 	ipsec_out_t *io;
26219 	mblk_t *data_mp;
26220 	uint_t plen, overhead;
26221 	ip_stack_t	*ipst;
26222 	phyint_t	*phyint;
26223 
26224 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26225 		return;
26226 
26227 	if (ill == NULL)
26228 		return;
26229 	ipst = ill->ill_ipst;
26230 	phyint = ill->ill_phyint;
26231 
26232 	/*
26233 	 * Destination address is a broadcast or multicast.  Punt.
26234 	 */
26235 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26236 	    IRE_LOCAL)))
26237 		return;
26238 
26239 	data_mp = ipsec_mp->b_cont;
26240 
26241 	if (ill->ill_isv6) {
26242 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26243 
26244 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26245 			return;
26246 
26247 		plen = ip6h->ip6_plen;
26248 	} else {
26249 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26250 
26251 		if (CLASSD(ipha->ipha_dst))
26252 			return;
26253 
26254 		plen = ipha->ipha_length;
26255 	}
26256 	/*
26257 	 * Is there a pending DLPI control message being exchanged
26258 	 * between IP/IPsec and the DLS Provider? If there is, it
26259 	 * could be a SADB update, and the state of the DLS Provider
26260 	 * SADB might not be in sync with the SADB maintained by
26261 	 * IPsec. To avoid dropping packets or using the wrong keying
26262 	 * material, we do not accelerate this packet.
26263 	 */
26264 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26265 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26266 		    "ill_dlpi_pending! don't accelerate packet\n"));
26267 		return;
26268 	}
26269 
26270 	/*
26271 	 * Is the Provider in promiscous mode? If it does, we don't
26272 	 * accelerate the packet since it will bounce back up to the
26273 	 * listeners in the clear.
26274 	 */
26275 	if (phyint->phyint_flags & PHYI_PROMISC) {
26276 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26277 		    "ill in promiscous mode, don't accelerate packet\n"));
26278 		return;
26279 	}
26280 
26281 	/*
26282 	 * Will the packet require fragmentation?
26283 	 */
26284 
26285 	/*
26286 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26287 	 * as is used elsewhere.
26288 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26289 	 *	+ 2-byte trailer
26290 	 */
26291 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26292 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26293 
26294 	if ((plen + overhead) > ill->ill_max_mtu)
26295 		return;
26296 
26297 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26298 
26299 	/*
26300 	 * Can the ill accelerate this IPsec protocol and algorithm
26301 	 * specified by the SA?
26302 	 */
26303 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26304 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26305 		return;
26306 	}
26307 
26308 	/*
26309 	 * Tell AH or ESP that the outbound ill is capable of
26310 	 * accelerating this packet.
26311 	 */
26312 	io->ipsec_out_is_capab_ill = B_TRUE;
26313 }
26314 
26315 /*
26316  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26317  *
26318  * If this function returns B_TRUE, the requested SA's have been filled
26319  * into the ipsec_out_*_sa pointers.
26320  *
26321  * If the function returns B_FALSE, the packet has been "consumed", most
26322  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26323  *
26324  * The SA references created by the protocol-specific "select"
26325  * function will be released when the ipsec_mp is freed, thanks to the
26326  * ipsec_out_free destructor -- see spd.c.
26327  */
26328 static boolean_t
26329 ipsec_out_select_sa(mblk_t *ipsec_mp)
26330 {
26331 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26332 	ipsec_out_t *io;
26333 	ipsec_policy_t *pp;
26334 	ipsec_action_t *ap;
26335 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26336 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26337 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26338 
26339 	if (!io->ipsec_out_secure) {
26340 		/*
26341 		 * We came here by mistake.
26342 		 * Don't bother with ipsec processing
26343 		 * We should "discourage" this path in the future.
26344 		 */
26345 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26346 		return (B_FALSE);
26347 	}
26348 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26349 	ASSERT((io->ipsec_out_policy != NULL) ||
26350 	    (io->ipsec_out_act != NULL));
26351 
26352 	ASSERT(io->ipsec_out_failed == B_FALSE);
26353 
26354 	/*
26355 	 * IPsec processing has started.
26356 	 */
26357 	io->ipsec_out_proc_begin = B_TRUE;
26358 	ap = io->ipsec_out_act;
26359 	if (ap == NULL) {
26360 		pp = io->ipsec_out_policy;
26361 		ASSERT(pp != NULL);
26362 		ap = pp->ipsp_act;
26363 		ASSERT(ap != NULL);
26364 	}
26365 
26366 	/*
26367 	 * We have an action.  now, let's select SA's.
26368 	 * (In the future, we can cache this in the conn_t..)
26369 	 */
26370 	if (ap->ipa_want_esp) {
26371 		if (io->ipsec_out_esp_sa == NULL) {
26372 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26373 			    IPPROTO_ESP);
26374 		}
26375 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26376 	}
26377 
26378 	if (ap->ipa_want_ah) {
26379 		if (io->ipsec_out_ah_sa == NULL) {
26380 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26381 			    IPPROTO_AH);
26382 		}
26383 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26384 		/*
26385 		 * The ESP and AH processing order needs to be preserved
26386 		 * when both protocols are required (ESP should be applied
26387 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26388 		 * when both ESP and AH are required, and an AH ACQUIRE
26389 		 * is needed.
26390 		 */
26391 		if (ap->ipa_want_esp && need_ah_acquire)
26392 			need_esp_acquire = B_TRUE;
26393 	}
26394 
26395 	/*
26396 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26397 	 * Release SAs that got referenced, but will not be used until we
26398 	 * acquire _all_ of the SAs we need.
26399 	 */
26400 	if (need_ah_acquire || need_esp_acquire) {
26401 		if (io->ipsec_out_ah_sa != NULL) {
26402 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26403 			io->ipsec_out_ah_sa = NULL;
26404 		}
26405 		if (io->ipsec_out_esp_sa != NULL) {
26406 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26407 			io->ipsec_out_esp_sa = NULL;
26408 		}
26409 
26410 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26411 		return (B_FALSE);
26412 	}
26413 
26414 	return (B_TRUE);
26415 }
26416 
26417 /*
26418  * Process an IPSEC_OUT message and see what you can
26419  * do with it.
26420  * IPQoS Notes:
26421  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26422  * IPsec.
26423  * XXX would like to nuke ire_t.
26424  * XXX ill_index better be "real"
26425  */
26426 void
26427 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26428 {
26429 	ipsec_out_t *io;
26430 	ipsec_policy_t *pp;
26431 	ipsec_action_t *ap;
26432 	ipha_t *ipha;
26433 	ip6_t *ip6h;
26434 	mblk_t *mp;
26435 	ill_t *ill;
26436 	zoneid_t zoneid;
26437 	ipsec_status_t ipsec_rc;
26438 	boolean_t ill_need_rele = B_FALSE;
26439 	ip_stack_t	*ipst;
26440 	ipsec_stack_t	*ipss;
26441 
26442 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26443 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26444 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26445 	ipst = io->ipsec_out_ns->netstack_ip;
26446 	mp = ipsec_mp->b_cont;
26447 
26448 	/*
26449 	 * Initiate IPPF processing. We do it here to account for packets
26450 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26451 	 * We can check for ipsec_out_proc_begin even for such packets, as
26452 	 * they will always be false (asserted below).
26453 	 */
26454 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26455 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26456 		    io->ipsec_out_ill_index : ill_index);
26457 		if (mp == NULL) {
26458 			ip2dbg(("ipsec_out_process: packet dropped "\
26459 			    "during IPPF processing\n"));
26460 			freeb(ipsec_mp);
26461 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26462 			return;
26463 		}
26464 	}
26465 
26466 	if (!io->ipsec_out_secure) {
26467 		/*
26468 		 * We came here by mistake.
26469 		 * Don't bother with ipsec processing
26470 		 * Should "discourage" this path in the future.
26471 		 */
26472 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26473 		goto done;
26474 	}
26475 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26476 	ASSERT((io->ipsec_out_policy != NULL) ||
26477 	    (io->ipsec_out_act != NULL));
26478 	ASSERT(io->ipsec_out_failed == B_FALSE);
26479 
26480 	ipss = ipst->ips_netstack->netstack_ipsec;
26481 	if (!ipsec_loaded(ipss)) {
26482 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26483 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26484 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26485 		} else {
26486 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26487 		}
26488 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26489 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26490 		    &ipss->ipsec_dropper);
26491 		return;
26492 	}
26493 
26494 	/*
26495 	 * IPsec processing has started.
26496 	 */
26497 	io->ipsec_out_proc_begin = B_TRUE;
26498 	ap = io->ipsec_out_act;
26499 	if (ap == NULL) {
26500 		pp = io->ipsec_out_policy;
26501 		ASSERT(pp != NULL);
26502 		ap = pp->ipsp_act;
26503 		ASSERT(ap != NULL);
26504 	}
26505 
26506 	/*
26507 	 * Save the outbound ill index. When the packet comes back
26508 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26509 	 * before sending it the accelerated packet.
26510 	 */
26511 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26512 		ill = ire_to_ill(ire);
26513 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26514 	}
26515 
26516 	/*
26517 	 * The order of processing is first insert a IP header if needed.
26518 	 * Then insert the ESP header and then the AH header.
26519 	 */
26520 	if ((io->ipsec_out_se_done == B_FALSE) &&
26521 	    (ap->ipa_want_se)) {
26522 		/*
26523 		 * First get the outer IP header before sending
26524 		 * it to ESP.
26525 		 */
26526 		ipha_t *oipha, *iipha;
26527 		mblk_t *outer_mp, *inner_mp;
26528 
26529 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26530 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26531 			    "ipsec_out_process: "
26532 			    "Self-Encapsulation failed: Out of memory\n");
26533 			freemsg(ipsec_mp);
26534 			if (ill != NULL) {
26535 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26536 			} else {
26537 				BUMP_MIB(&ipst->ips_ip_mib,
26538 				    ipIfStatsOutDiscards);
26539 			}
26540 			return;
26541 		}
26542 		inner_mp = ipsec_mp->b_cont;
26543 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26544 		oipha = (ipha_t *)outer_mp->b_rptr;
26545 		iipha = (ipha_t *)inner_mp->b_rptr;
26546 		*oipha = *iipha;
26547 		outer_mp->b_wptr += sizeof (ipha_t);
26548 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26549 		    sizeof (ipha_t));
26550 		oipha->ipha_protocol = IPPROTO_ENCAP;
26551 		oipha->ipha_version_and_hdr_length =
26552 		    IP_SIMPLE_HDR_VERSION;
26553 		oipha->ipha_hdr_checksum = 0;
26554 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26555 		outer_mp->b_cont = inner_mp;
26556 		ipsec_mp->b_cont = outer_mp;
26557 
26558 		io->ipsec_out_se_done = B_TRUE;
26559 		io->ipsec_out_tunnel = B_TRUE;
26560 	}
26561 
26562 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26563 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26564 	    !ipsec_out_select_sa(ipsec_mp))
26565 		return;
26566 
26567 	/*
26568 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26569 	 * to do the heavy lifting.
26570 	 */
26571 	zoneid = io->ipsec_out_zoneid;
26572 	ASSERT(zoneid != ALL_ZONES);
26573 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26574 		ASSERT(io->ipsec_out_esp_sa != NULL);
26575 		io->ipsec_out_esp_done = B_TRUE;
26576 		/*
26577 		 * Note that since hw accel can only apply one transform,
26578 		 * not two, we skip hw accel for ESP if we also have AH
26579 		 * This is an design limitation of the interface
26580 		 * which should be revisited.
26581 		 */
26582 		ASSERT(ire != NULL);
26583 		if (io->ipsec_out_ah_sa == NULL) {
26584 			ill = (ill_t *)ire->ire_stq->q_ptr;
26585 			ipsec_out_is_accelerated(ipsec_mp,
26586 			    io->ipsec_out_esp_sa, ill, ire);
26587 		}
26588 
26589 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26590 		switch (ipsec_rc) {
26591 		case IPSEC_STATUS_SUCCESS:
26592 			break;
26593 		case IPSEC_STATUS_FAILED:
26594 			if (ill != NULL) {
26595 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26596 			} else {
26597 				BUMP_MIB(&ipst->ips_ip_mib,
26598 				    ipIfStatsOutDiscards);
26599 			}
26600 			/* FALLTHRU */
26601 		case IPSEC_STATUS_PENDING:
26602 			return;
26603 		}
26604 	}
26605 
26606 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26607 		ASSERT(io->ipsec_out_ah_sa != NULL);
26608 		io->ipsec_out_ah_done = B_TRUE;
26609 		if (ire == NULL) {
26610 			int idx = io->ipsec_out_capab_ill_index;
26611 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26612 			    NULL, NULL, NULL, NULL, ipst);
26613 			ill_need_rele = B_TRUE;
26614 		} else {
26615 			ill = (ill_t *)ire->ire_stq->q_ptr;
26616 		}
26617 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26618 		    ire);
26619 
26620 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26621 		switch (ipsec_rc) {
26622 		case IPSEC_STATUS_SUCCESS:
26623 			break;
26624 		case IPSEC_STATUS_FAILED:
26625 			if (ill != NULL) {
26626 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26627 			} else {
26628 				BUMP_MIB(&ipst->ips_ip_mib,
26629 				    ipIfStatsOutDiscards);
26630 			}
26631 			/* FALLTHRU */
26632 		case IPSEC_STATUS_PENDING:
26633 			if (ill != NULL && ill_need_rele)
26634 				ill_refrele(ill);
26635 			return;
26636 		}
26637 	}
26638 	/*
26639 	 * We are done with IPsec processing. Send it over the wire.
26640 	 */
26641 done:
26642 	mp = ipsec_mp->b_cont;
26643 	ipha = (ipha_t *)mp->b_rptr;
26644 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26645 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26646 		    ire);
26647 	} else {
26648 		ip6h = (ip6_t *)ipha;
26649 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26650 		    ire);
26651 	}
26652 	if (ill != NULL && ill_need_rele)
26653 		ill_refrele(ill);
26654 }
26655 
26656 /* ARGSUSED */
26657 void
26658 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26659 {
26660 	opt_restart_t	*or;
26661 	int	err;
26662 	conn_t	*connp;
26663 	cred_t	*cr;
26664 
26665 	ASSERT(CONN_Q(q));
26666 	connp = Q_TO_CONN(q);
26667 
26668 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26669 	or = (opt_restart_t *)first_mp->b_rptr;
26670 	/*
26671 	 * We checked for a db_credp the first time svr4_optcom_req
26672 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26673 	 */
26674 	cr = msg_getcred(first_mp, NULL);
26675 	ASSERT(cr != NULL);
26676 
26677 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26678 		err = svr4_optcom_req(q, first_mp, cr,
26679 		    &ip_opt_obj, B_FALSE);
26680 	} else {
26681 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26682 		err = tpi_optcom_req(q, first_mp, cr,
26683 		    &ip_opt_obj, B_FALSE);
26684 	}
26685 	if (err != EINPROGRESS) {
26686 		/* operation is done */
26687 		CONN_OPER_PENDING_DONE(connp);
26688 	}
26689 }
26690 
26691 /*
26692  * ioctls that go through a down/up sequence may need to wait for the down
26693  * to complete. This involves waiting for the ire and ipif refcnts to go down
26694  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26695  */
26696 /* ARGSUSED */
26697 void
26698 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26699 {
26700 	struct iocblk *iocp;
26701 	mblk_t *mp1;
26702 	ip_ioctl_cmd_t *ipip;
26703 	int err;
26704 	sin_t	*sin;
26705 	struct lifreq *lifr;
26706 	struct ifreq *ifr;
26707 
26708 	iocp = (struct iocblk *)mp->b_rptr;
26709 	ASSERT(ipsq != NULL);
26710 	/* Existence of mp1 verified in ip_wput_nondata */
26711 	mp1 = mp->b_cont->b_cont;
26712 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26713 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26714 		/*
26715 		 * Special case where ipx_current_ipif is not set:
26716 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26717 		 * We are here as were not able to complete the operation in
26718 		 * ipif_set_values because we could not become exclusive on
26719 		 * the new ipsq.
26720 		 */
26721 		ill_t *ill = q->q_ptr;
26722 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26723 	}
26724 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26725 
26726 	if (ipip->ipi_cmd_type == IF_CMD) {
26727 		/* This a old style SIOC[GS]IF* command */
26728 		ifr = (struct ifreq *)mp1->b_rptr;
26729 		sin = (sin_t *)&ifr->ifr_addr;
26730 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26731 		/* This a new style SIOC[GS]LIF* command */
26732 		lifr = (struct lifreq *)mp1->b_rptr;
26733 		sin = (sin_t *)&lifr->lifr_addr;
26734 	} else {
26735 		sin = NULL;
26736 	}
26737 
26738 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26739 	    q, mp, ipip, mp1->b_rptr);
26740 
26741 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26742 }
26743 
26744 /*
26745  * ioctl processing
26746  *
26747  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26748  * the ioctl command in the ioctl tables, determines the copyin data size
26749  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26750  *
26751  * ioctl processing then continues when the M_IOCDATA makes its way down to
26752  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26753  * associated 'conn' is refheld till the end of the ioctl and the general
26754  * ioctl processing function ip_process_ioctl() is called to extract the
26755  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26756  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26757  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26758  * is used to extract the ioctl's arguments.
26759  *
26760  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26761  * so goes thru the serialization primitive ipsq_try_enter. Then the
26762  * appropriate function to handle the ioctl is called based on the entry in
26763  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26764  * which also refreleases the 'conn' that was refheld at the start of the
26765  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26766  *
26767  * Many exclusive ioctls go thru an internal down up sequence as part of
26768  * the operation. For example an attempt to change the IP address of an
26769  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26770  * does all the cleanup such as deleting all ires that use this address.
26771  * Then we need to wait till all references to the interface go away.
26772  */
26773 void
26774 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26775 {
26776 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26777 	ip_ioctl_cmd_t *ipip = arg;
26778 	ip_extract_func_t *extract_funcp;
26779 	cmd_info_t ci;
26780 	int err;
26781 	boolean_t entered_ipsq = B_FALSE;
26782 
26783 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26784 
26785 	if (ipip == NULL)
26786 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26787 
26788 	/*
26789 	 * SIOCLIFADDIF needs to go thru a special path since the
26790 	 * ill may not exist yet. This happens in the case of lo0
26791 	 * which is created using this ioctl.
26792 	 */
26793 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26794 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26795 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26796 		return;
26797 	}
26798 
26799 	ci.ci_ipif = NULL;
26800 	if (ipip->ipi_cmd_type == MISC_CMD) {
26801 		/*
26802 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26803 		 */
26804 		if (ipip->ipi_cmd == IF_UNITSEL) {
26805 			/* ioctl comes down the ill */
26806 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26807 			ipif_refhold(ci.ci_ipif);
26808 		}
26809 		err = 0;
26810 		ci.ci_sin = NULL;
26811 		ci.ci_sin6 = NULL;
26812 		ci.ci_lifr = NULL;
26813 	} else {
26814 		switch (ipip->ipi_cmd_type) {
26815 		case IF_CMD:
26816 		case LIF_CMD:
26817 			extract_funcp = ip_extract_lifreq;
26818 			break;
26819 
26820 		case ARP_CMD:
26821 		case XARP_CMD:
26822 			extract_funcp = ip_extract_arpreq;
26823 			break;
26824 
26825 		case MSFILT_CMD:
26826 			extract_funcp = ip_extract_msfilter;
26827 			break;
26828 
26829 		default:
26830 			ASSERT(0);
26831 		}
26832 
26833 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26834 		if (err != 0) {
26835 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26836 			return;
26837 		}
26838 
26839 		/*
26840 		 * All of the extraction functions return a refheld ipif.
26841 		 */
26842 		ASSERT(ci.ci_ipif != NULL);
26843 	}
26844 
26845 	if (!(ipip->ipi_flags & IPI_WR)) {
26846 		/*
26847 		 * A return value of EINPROGRESS means the ioctl is
26848 		 * either queued and waiting for some reason or has
26849 		 * already completed.
26850 		 */
26851 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26852 		    ci.ci_lifr);
26853 		if (ci.ci_ipif != NULL)
26854 			ipif_refrele(ci.ci_ipif);
26855 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26856 		return;
26857 	}
26858 
26859 	ASSERT(ci.ci_ipif != NULL);
26860 
26861 	/*
26862 	 * If ipsq is non-NULL, we are already being called exclusively.
26863 	 */
26864 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26865 	if (ipsq == NULL) {
26866 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26867 		    NEW_OP, B_TRUE);
26868 		if (ipsq == NULL) {
26869 			ipif_refrele(ci.ci_ipif);
26870 			return;
26871 		}
26872 		entered_ipsq = B_TRUE;
26873 	}
26874 
26875 	/*
26876 	 * Release the ipif so that ipif_down and friends that wait for
26877 	 * references to go away are not misled about the current ipif_refcnt
26878 	 * values. We are writer so we can access the ipif even after releasing
26879 	 * the ipif.
26880 	 */
26881 	ipif_refrele(ci.ci_ipif);
26882 
26883 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26884 
26885 	/*
26886 	 * A return value of EINPROGRESS means the ioctl is
26887 	 * either queued and waiting for some reason or has
26888 	 * already completed.
26889 	 */
26890 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26891 
26892 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26893 
26894 	if (entered_ipsq)
26895 		ipsq_exit(ipsq);
26896 }
26897 
26898 /*
26899  * Complete the ioctl. Typically ioctls use the mi package and need to
26900  * do mi_copyout/mi_copy_done.
26901  */
26902 void
26903 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26904 {
26905 	conn_t	*connp = NULL;
26906 
26907 	if (err == EINPROGRESS)
26908 		return;
26909 
26910 	if (CONN_Q(q)) {
26911 		connp = Q_TO_CONN(q);
26912 		ASSERT(connp->conn_ref >= 2);
26913 	}
26914 
26915 	switch (mode) {
26916 	case COPYOUT:
26917 		if (err == 0)
26918 			mi_copyout(q, mp);
26919 		else
26920 			mi_copy_done(q, mp, err);
26921 		break;
26922 
26923 	case NO_COPYOUT:
26924 		mi_copy_done(q, mp, err);
26925 		break;
26926 
26927 	default:
26928 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26929 		break;
26930 	}
26931 
26932 	/*
26933 	 * The refhold placed at the start of the ioctl is released here.
26934 	 */
26935 	if (connp != NULL)
26936 		CONN_OPER_PENDING_DONE(connp);
26937 
26938 	if (ipsq != NULL)
26939 		ipsq_current_finish(ipsq);
26940 }
26941 
26942 /* Called from ip_wput for all non data messages */
26943 /* ARGSUSED */
26944 void
26945 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26946 {
26947 	mblk_t		*mp1;
26948 	ire_t		*ire, *fake_ire;
26949 	ill_t		*ill;
26950 	struct iocblk	*iocp;
26951 	ip_ioctl_cmd_t	*ipip;
26952 	cred_t		*cr;
26953 	conn_t		*connp;
26954 	int		err;
26955 	nce_t		*nce;
26956 	ipif_t		*ipif;
26957 	ip_stack_t	*ipst;
26958 	char		*proto_str;
26959 
26960 	if (CONN_Q(q)) {
26961 		connp = Q_TO_CONN(q);
26962 		ipst = connp->conn_netstack->netstack_ip;
26963 	} else {
26964 		connp = NULL;
26965 		ipst = ILLQ_TO_IPST(q);
26966 	}
26967 
26968 	switch (DB_TYPE(mp)) {
26969 	case M_IOCTL:
26970 		/*
26971 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26972 		 * will arrange to copy in associated control structures.
26973 		 */
26974 		ip_sioctl_copyin_setup(q, mp);
26975 		return;
26976 	case M_IOCDATA:
26977 		/*
26978 		 * Ensure that this is associated with one of our trans-
26979 		 * parent ioctls.  If it's not ours, discard it if we're
26980 		 * running as a driver, or pass it on if we're a module.
26981 		 */
26982 		iocp = (struct iocblk *)mp->b_rptr;
26983 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26984 		if (ipip == NULL) {
26985 			if (q->q_next == NULL) {
26986 				goto nak;
26987 			} else {
26988 				putnext(q, mp);
26989 			}
26990 			return;
26991 		}
26992 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
26993 			/*
26994 			 * the ioctl is one we recognise, but is not
26995 			 * consumed by IP as a module, pass M_IOCDATA
26996 			 * for processing downstream, but only for
26997 			 * common Streams ioctls.
26998 			 */
26999 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27000 				putnext(q, mp);
27001 				return;
27002 			} else {
27003 				goto nak;
27004 			}
27005 		}
27006 
27007 		/* IOCTL continuation following copyin or copyout. */
27008 		if (mi_copy_state(q, mp, NULL) == -1) {
27009 			/*
27010 			 * The copy operation failed.  mi_copy_state already
27011 			 * cleaned up, so we're out of here.
27012 			 */
27013 			return;
27014 		}
27015 		/*
27016 		 * If we just completed a copy in, we become writer and
27017 		 * continue processing in ip_sioctl_copyin_done.  If it
27018 		 * was a copy out, we call mi_copyout again.  If there is
27019 		 * nothing more to copy out, it will complete the IOCTL.
27020 		 */
27021 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27022 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27023 				mi_copy_done(q, mp, EPROTO);
27024 				return;
27025 			}
27026 			/*
27027 			 * Check for cases that need more copying.  A return
27028 			 * value of 0 means a second copyin has been started,
27029 			 * so we return; a return value of 1 means no more
27030 			 * copying is needed, so we continue.
27031 			 */
27032 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27033 			    MI_COPY_COUNT(mp) == 1) {
27034 				if (ip_copyin_msfilter(q, mp) == 0)
27035 					return;
27036 			}
27037 			/*
27038 			 * Refhold the conn, till the ioctl completes. This is
27039 			 * needed in case the ioctl ends up in the pending mp
27040 			 * list. Every mp in the ill_pending_mp list and
27041 			 * the ipx_pending_mp must have a refhold on the conn
27042 			 * to resume processing. The refhold is released when
27043 			 * the ioctl completes. (normally or abnormally)
27044 			 * In all cases ip_ioctl_finish is called to finish
27045 			 * the ioctl.
27046 			 */
27047 			if (connp != NULL) {
27048 				/* This is not a reentry */
27049 				ASSERT(ipsq == NULL);
27050 				CONN_INC_REF(connp);
27051 			} else {
27052 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27053 					mi_copy_done(q, mp, EINVAL);
27054 					return;
27055 				}
27056 			}
27057 
27058 			ip_process_ioctl(ipsq, q, mp, ipip);
27059 
27060 		} else {
27061 			mi_copyout(q, mp);
27062 		}
27063 		return;
27064 nak:
27065 		iocp->ioc_error = EINVAL;
27066 		mp->b_datap->db_type = M_IOCNAK;
27067 		iocp->ioc_count = 0;
27068 		qreply(q, mp);
27069 		return;
27070 
27071 	case M_IOCNAK:
27072 		/*
27073 		 * The only way we could get here is if a resolver didn't like
27074 		 * an IOCTL we sent it.	 This shouldn't happen.
27075 		 */
27076 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27077 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27078 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27079 		freemsg(mp);
27080 		return;
27081 	case M_IOCACK:
27082 		/* /dev/ip shouldn't see this */
27083 		if (CONN_Q(q))
27084 			goto nak;
27085 
27086 		/*
27087 		 * Finish socket ioctls passed through to ARP.  We use the
27088 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27089 		 * we need to become writer before calling ip_sioctl_iocack().
27090 		 * Note that qwriter_ip() will release the refhold, and that a
27091 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27092 		 * ill stream.
27093 		 */
27094 		iocp = (struct iocblk *)mp->b_rptr;
27095 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27096 			ip_sioctl_iocack(NULL, q, mp, NULL);
27097 			return;
27098 		}
27099 
27100 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27101 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27102 		ill = q->q_ptr;
27103 		ill_refhold(ill);
27104 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27105 		return;
27106 	case M_FLUSH:
27107 		if (*mp->b_rptr & FLUSHW)
27108 			flushq(q, FLUSHALL);
27109 		if (q->q_next) {
27110 			putnext(q, mp);
27111 			return;
27112 		}
27113 		if (*mp->b_rptr & FLUSHR) {
27114 			*mp->b_rptr &= ~FLUSHW;
27115 			qreply(q, mp);
27116 			return;
27117 		}
27118 		freemsg(mp);
27119 		return;
27120 	case IRE_DB_REQ_TYPE:
27121 		if (connp == NULL) {
27122 			proto_str = "IRE_DB_REQ_TYPE";
27123 			goto protonak;
27124 		}
27125 		/* An Upper Level Protocol wants a copy of an IRE. */
27126 		ip_ire_req(q, mp);
27127 		return;
27128 	case M_CTL:
27129 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27130 			break;
27131 
27132 		/* M_CTL messages are used by ARP to tell us things. */
27133 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27134 			break;
27135 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27136 		case AR_ENTRY_SQUERY:
27137 			putnext(q, mp);
27138 			return;
27139 		case AR_CLIENT_NOTIFY:
27140 			ip_arp_news(q, mp);
27141 			return;
27142 		case AR_DLPIOP_DONE:
27143 			ASSERT(q->q_next != NULL);
27144 			ill = (ill_t *)q->q_ptr;
27145 			/* qwriter_ip releases the refhold */
27146 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27147 			ill_refhold(ill);
27148 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27149 			return;
27150 		case AR_ARP_CLOSING:
27151 			/*
27152 			 * ARP (above us) is closing. If no ARP bringup is
27153 			 * currently pending, ack the message so that ARP
27154 			 * can complete its close. Also mark ill_arp_closing
27155 			 * so that new ARP bringups will fail. If any
27156 			 * ARP bringup is currently in progress, we will
27157 			 * ack this when the current ARP bringup completes.
27158 			 */
27159 			ASSERT(q->q_next != NULL);
27160 			ill = (ill_t *)q->q_ptr;
27161 			mutex_enter(&ill->ill_lock);
27162 			ill->ill_arp_closing = 1;
27163 			if (!ill->ill_arp_bringup_pending) {
27164 				mutex_exit(&ill->ill_lock);
27165 				qreply(q, mp);
27166 			} else {
27167 				mutex_exit(&ill->ill_lock);
27168 				freemsg(mp);
27169 			}
27170 			return;
27171 		case AR_ARP_EXTEND:
27172 			/*
27173 			 * The ARP module above us is capable of duplicate
27174 			 * address detection.  Old ATM drivers will not send
27175 			 * this message.
27176 			 */
27177 			ASSERT(q->q_next != NULL);
27178 			ill = (ill_t *)q->q_ptr;
27179 			ill->ill_arp_extend = B_TRUE;
27180 			freemsg(mp);
27181 			return;
27182 		default:
27183 			break;
27184 		}
27185 		break;
27186 	case M_PROTO:
27187 	case M_PCPROTO:
27188 		/*
27189 		 * The only PROTO messages we expect are copies of option
27190 		 * negotiation acknowledgements, AH and ESP bind requests
27191 		 * are also expected.
27192 		 */
27193 		switch (((union T_primitives *)mp->b_rptr)->type) {
27194 		case O_T_BIND_REQ:
27195 		case T_BIND_REQ: {
27196 			/* Request can get queued in bind */
27197 			if (connp == NULL) {
27198 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27199 				goto protonak;
27200 			}
27201 			/*
27202 			 * The transports except SCTP call ip_bind_{v4,v6}()
27203 			 * directly instead of a a putnext. SCTP doesn't
27204 			 * generate any T_BIND_REQ since it has its own
27205 			 * fanout data structures. However, ESP and AH
27206 			 * come in for regular binds; all other cases are
27207 			 * bind retries.
27208 			 */
27209 			ASSERT(!IPCL_IS_SCTP(connp));
27210 
27211 			/* Don't increment refcnt if this is a re-entry */
27212 			if (ipsq == NULL)
27213 				CONN_INC_REF(connp);
27214 
27215 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27216 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27217 			ASSERT(mp != NULL);
27218 
27219 			ASSERT(!IPCL_IS_TCP(connp));
27220 			ASSERT(!IPCL_IS_UDP(connp));
27221 			ASSERT(!IPCL_IS_RAWIP(connp));
27222 			ASSERT(!IPCL_IS_IPTUN(connp));
27223 
27224 			/* The case of AH and ESP */
27225 			qreply(q, mp);
27226 			CONN_OPER_PENDING_DONE(connp);
27227 			return;
27228 		}
27229 		case T_SVR4_OPTMGMT_REQ:
27230 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27231 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27232 
27233 			if (connp == NULL) {
27234 				proto_str = "T_SVR4_OPTMGMT_REQ";
27235 				goto protonak;
27236 			}
27237 
27238 			/*
27239 			 * All Solaris components should pass a db_credp
27240 			 * for this TPI message, hence we ASSERT.
27241 			 * But in case there is some other M_PROTO that looks
27242 			 * like a TPI message sent by some other kernel
27243 			 * component, we check and return an error.
27244 			 */
27245 			cr = msg_getcred(mp, NULL);
27246 			ASSERT(cr != NULL);
27247 			if (cr == NULL) {
27248 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27249 				if (mp != NULL)
27250 					qreply(q, mp);
27251 				return;
27252 			}
27253 
27254 			if (!snmpcom_req(q, mp, ip_snmp_set,
27255 			    ip_snmp_get, cr)) {
27256 				/*
27257 				 * Call svr4_optcom_req so that it can
27258 				 * generate the ack. We don't come here
27259 				 * if this operation is being restarted.
27260 				 * ip_restart_optmgmt will drop the conn ref.
27261 				 * In the case of ipsec option after the ipsec
27262 				 * load is complete conn_restart_ipsec_waiter
27263 				 * drops the conn ref.
27264 				 */
27265 				ASSERT(ipsq == NULL);
27266 				CONN_INC_REF(connp);
27267 				if (ip_check_for_ipsec_opt(q, mp))
27268 					return;
27269 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27270 				    B_FALSE);
27271 				if (err != EINPROGRESS) {
27272 					/* Operation is done */
27273 					CONN_OPER_PENDING_DONE(connp);
27274 				}
27275 			}
27276 			return;
27277 		case T_OPTMGMT_REQ:
27278 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27279 			/*
27280 			 * Note: No snmpcom_req support through new
27281 			 * T_OPTMGMT_REQ.
27282 			 * Call tpi_optcom_req so that it can
27283 			 * generate the ack.
27284 			 */
27285 			if (connp == NULL) {
27286 				proto_str = "T_OPTMGMT_REQ";
27287 				goto protonak;
27288 			}
27289 
27290 			/*
27291 			 * All Solaris components should pass a db_credp
27292 			 * for this TPI message, hence we ASSERT.
27293 			 * But in case there is some other M_PROTO that looks
27294 			 * like a TPI message sent by some other kernel
27295 			 * component, we check and return an error.
27296 			 */
27297 			cr = msg_getcred(mp, NULL);
27298 			ASSERT(cr != NULL);
27299 			if (cr == NULL) {
27300 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27301 				if (mp != NULL)
27302 					qreply(q, mp);
27303 				return;
27304 			}
27305 			ASSERT(ipsq == NULL);
27306 			/*
27307 			 * We don't come here for restart. ip_restart_optmgmt
27308 			 * will drop the conn ref. In the case of ipsec option
27309 			 * after the ipsec load is complete
27310 			 * conn_restart_ipsec_waiter drops the conn ref.
27311 			 */
27312 			CONN_INC_REF(connp);
27313 			if (ip_check_for_ipsec_opt(q, mp))
27314 				return;
27315 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27316 			if (err != EINPROGRESS) {
27317 				/* Operation is done */
27318 				CONN_OPER_PENDING_DONE(connp);
27319 			}
27320 			return;
27321 		case T_UNBIND_REQ:
27322 			if (connp == NULL) {
27323 				proto_str = "T_UNBIND_REQ";
27324 				goto protonak;
27325 			}
27326 			ip_unbind(Q_TO_CONN(q));
27327 			mp = mi_tpi_ok_ack_alloc(mp);
27328 			qreply(q, mp);
27329 			return;
27330 		default:
27331 			/*
27332 			 * Have to drop any DLPI messages coming down from
27333 			 * arp (such as an info_req which would cause ip
27334 			 * to receive an extra info_ack if it was passed
27335 			 * through.
27336 			 */
27337 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27338 			    (int)*(uint_t *)mp->b_rptr));
27339 			freemsg(mp);
27340 			return;
27341 		}
27342 		/* NOTREACHED */
27343 	case IRE_DB_TYPE: {
27344 		nce_t		*nce;
27345 		ill_t		*ill;
27346 		in6_addr_t	gw_addr_v6;
27347 
27348 		/*
27349 		 * This is a response back from a resolver.  It
27350 		 * consists of a message chain containing:
27351 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27352 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27353 		 * The LL_HDR_MBLK is the DLPI header to use to get
27354 		 * the attached packet, and subsequent ones for the
27355 		 * same destination, transmitted.
27356 		 */
27357 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27358 			break;
27359 		/*
27360 		 * First, check to make sure the resolution succeeded.
27361 		 * If it failed, the second mblk will be empty.
27362 		 * If it is, free the chain, dropping the packet.
27363 		 * (We must ire_delete the ire; that frees the ire mblk)
27364 		 * We're doing this now to support PVCs for ATM; it's
27365 		 * a partial xresolv implementation. When we fully implement
27366 		 * xresolv interfaces, instead of freeing everything here
27367 		 * we'll initiate neighbor discovery.
27368 		 *
27369 		 * For v4 (ARP and other external resolvers) the resolver
27370 		 * frees the message, so no check is needed. This check
27371 		 * is required, though, for a full xresolve implementation.
27372 		 * Including this code here now both shows how external
27373 		 * resolvers can NACK a resolution request using an
27374 		 * existing design that has no specific provisions for NACKs,
27375 		 * and also takes into account that the current non-ARP
27376 		 * external resolver has been coded to use this method of
27377 		 * NACKing for all IPv6 (xresolv) cases,
27378 		 * whether our xresolv implementation is complete or not.
27379 		 *
27380 		 */
27381 		ire = (ire_t *)mp->b_rptr;
27382 		ill = ire_to_ill(ire);
27383 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27384 		if (mp1->b_rptr == mp1->b_wptr) {
27385 			if (ire->ire_ipversion == IPV6_VERSION) {
27386 				/*
27387 				 * XRESOLV interface.
27388 				 */
27389 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27390 				mutex_enter(&ire->ire_lock);
27391 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27392 				mutex_exit(&ire->ire_lock);
27393 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27394 					nce = ndp_lookup_v6(ill, B_FALSE,
27395 					    &ire->ire_addr_v6, B_FALSE);
27396 				} else {
27397 					nce = ndp_lookup_v6(ill, B_FALSE,
27398 					    &gw_addr_v6, B_FALSE);
27399 				}
27400 				if (nce != NULL) {
27401 					nce_resolv_failed(nce);
27402 					ndp_delete(nce);
27403 					NCE_REFRELE(nce);
27404 				}
27405 			}
27406 			mp->b_cont = NULL;
27407 			freemsg(mp1);		/* frees the pkt as well */
27408 			ASSERT(ire->ire_nce == NULL);
27409 			ire_delete((ire_t *)mp->b_rptr);
27410 			return;
27411 		}
27412 
27413 		/*
27414 		 * Split them into IRE_MBLK and pkt and feed it into
27415 		 * ire_add_then_send. Then in ire_add_then_send
27416 		 * the IRE will be added, and then the packet will be
27417 		 * run back through ip_wput. This time it will make
27418 		 * it to the wire.
27419 		 */
27420 		mp->b_cont = NULL;
27421 		mp = mp1->b_cont;		/* now, mp points to pkt */
27422 		mp1->b_cont = NULL;
27423 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27424 		if (ire->ire_ipversion == IPV6_VERSION) {
27425 			/*
27426 			 * XRESOLV interface. Find the nce and put a copy
27427 			 * of the dl_unitdata_req in nce_res_mp
27428 			 */
27429 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27430 			mutex_enter(&ire->ire_lock);
27431 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27432 			mutex_exit(&ire->ire_lock);
27433 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27434 				nce = ndp_lookup_v6(ill, B_FALSE,
27435 				    &ire->ire_addr_v6, B_FALSE);
27436 			} else {
27437 				nce = ndp_lookup_v6(ill, B_FALSE,
27438 				    &gw_addr_v6, B_FALSE);
27439 			}
27440 			if (nce != NULL) {
27441 				/*
27442 				 * We have to protect nce_res_mp here
27443 				 * from being accessed by other threads
27444 				 * while we change the mblk pointer.
27445 				 * Other functions will also lock the nce when
27446 				 * accessing nce_res_mp.
27447 				 *
27448 				 * The reason we change the mblk pointer
27449 				 * here rather than copying the resolved address
27450 				 * into the template is that, unlike with
27451 				 * ethernet, we have no guarantee that the
27452 				 * resolved address length will be
27453 				 * smaller than or equal to the lla length
27454 				 * with which the template was allocated,
27455 				 * (for ethernet, they're equal)
27456 				 * so we have to use the actual resolved
27457 				 * address mblk - which holds the real
27458 				 * dl_unitdata_req with the resolved address.
27459 				 *
27460 				 * Doing this is the same behavior as was
27461 				 * previously used in the v4 ARP case.
27462 				 */
27463 				mutex_enter(&nce->nce_lock);
27464 				if (nce->nce_res_mp != NULL)
27465 					freemsg(nce->nce_res_mp);
27466 				nce->nce_res_mp = mp1;
27467 				mutex_exit(&nce->nce_lock);
27468 				/*
27469 				 * We do a fastpath probe here because
27470 				 * we have resolved the address without
27471 				 * using Neighbor Discovery.
27472 				 * In the non-XRESOLV v6 case, the fastpath
27473 				 * probe is done right after neighbor
27474 				 * discovery completes.
27475 				 */
27476 				if (nce->nce_res_mp != NULL) {
27477 					int res;
27478 					nce_fastpath_list_add(nce);
27479 					res = ill_fastpath_probe(ill,
27480 					    nce->nce_res_mp);
27481 					if (res != 0 && res != EAGAIN)
27482 						nce_fastpath_list_delete(nce);
27483 				}
27484 
27485 				ire_add_then_send(q, ire, mp);
27486 				/*
27487 				 * Now we have to clean out any packets
27488 				 * that may have been queued on the nce
27489 				 * while it was waiting for address resolution
27490 				 * to complete.
27491 				 */
27492 				mutex_enter(&nce->nce_lock);
27493 				mp1 = nce->nce_qd_mp;
27494 				nce->nce_qd_mp = NULL;
27495 				mutex_exit(&nce->nce_lock);
27496 				while (mp1 != NULL) {
27497 					mblk_t *nxt_mp;
27498 					queue_t *fwdq = NULL;
27499 					ill_t   *inbound_ill;
27500 					uint_t ifindex;
27501 
27502 					nxt_mp = mp1->b_next;
27503 					mp1->b_next = NULL;
27504 					/*
27505 					 * Retrieve ifindex stored in
27506 					 * ip_rput_data_v6()
27507 					 */
27508 					ifindex =
27509 					    (uint_t)(uintptr_t)mp1->b_prev;
27510 					inbound_ill =
27511 					    ill_lookup_on_ifindex(ifindex,
27512 					    B_TRUE, NULL, NULL, NULL,
27513 					    NULL, ipst);
27514 					mp1->b_prev = NULL;
27515 					if (inbound_ill != NULL)
27516 						fwdq = inbound_ill->ill_rq;
27517 
27518 					if (fwdq != NULL) {
27519 						put(fwdq, mp1);
27520 						ill_refrele(inbound_ill);
27521 					} else
27522 						put(WR(ill->ill_rq), mp1);
27523 					mp1 = nxt_mp;
27524 				}
27525 				NCE_REFRELE(nce);
27526 			} else {	/* nce is NULL; clean up */
27527 				ire_delete(ire);
27528 				freemsg(mp);
27529 				freemsg(mp1);
27530 				return;
27531 			}
27532 		} else {
27533 			nce_t *arpce;
27534 			/*
27535 			 * Link layer resolution succeeded. Recompute the
27536 			 * ire_nce.
27537 			 */
27538 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27539 			if ((arpce = ndp_lookup_v4(ill,
27540 			    (ire->ire_gateway_addr != INADDR_ANY ?
27541 			    &ire->ire_gateway_addr : &ire->ire_addr),
27542 			    B_FALSE)) == NULL) {
27543 				freeb(ire->ire_mp);
27544 				freeb(mp1);
27545 				freemsg(mp);
27546 				return;
27547 			}
27548 			mutex_enter(&arpce->nce_lock);
27549 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27550 			if (arpce->nce_state == ND_REACHABLE) {
27551 				/*
27552 				 * Someone resolved this before us;
27553 				 * cleanup the res_mp. Since ire has
27554 				 * not been added yet, the call to ire_add_v4
27555 				 * from ire_add_then_send (when a dup is
27556 				 * detected) will clean up the ire.
27557 				 */
27558 				freeb(mp1);
27559 			} else {
27560 				ASSERT(arpce->nce_res_mp == NULL);
27561 				arpce->nce_res_mp = mp1;
27562 				arpce->nce_state = ND_REACHABLE;
27563 			}
27564 			mutex_exit(&arpce->nce_lock);
27565 			if (ire->ire_marks & IRE_MARK_NOADD) {
27566 				/*
27567 				 * this ire will not be added to the ire
27568 				 * cache table, so we can set the ire_nce
27569 				 * here, as there are no atomicity constraints.
27570 				 */
27571 				ire->ire_nce = arpce;
27572 				/*
27573 				 * We are associating this nce with the ire
27574 				 * so change the nce ref taken in
27575 				 * ndp_lookup_v4() from
27576 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27577 				 */
27578 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27579 			} else {
27580 				NCE_REFRELE(arpce);
27581 			}
27582 			ire_add_then_send(q, ire, mp);
27583 		}
27584 		return;	/* All is well, the packet has been sent. */
27585 	}
27586 	case IRE_ARPRESOLVE_TYPE: {
27587 
27588 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27589 			break;
27590 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27591 		mp->b_cont = NULL;
27592 		/*
27593 		 * First, check to make sure the resolution succeeded.
27594 		 * If it failed, the second mblk will be empty.
27595 		 */
27596 		if (mp1->b_rptr == mp1->b_wptr) {
27597 			/* cleanup  the incomplete ire, free queued packets */
27598 			freemsg(mp); /* fake ire */
27599 			freeb(mp1);  /* dl_unitdata response */
27600 			return;
27601 		}
27602 
27603 		/*
27604 		 * Update any incomplete nce_t found. We search the ctable
27605 		 * and find the nce from the ire->ire_nce because we need
27606 		 * to pass the ire to ip_xmit_v4 later, and can find both
27607 		 * ire and nce in one lookup.
27608 		 */
27609 		fake_ire = (ire_t *)mp->b_rptr;
27610 
27611 		/*
27612 		 * By the time we come back here from ARP the logical outgoing
27613 		 * interface of the incomplete ire we added in ire_forward()
27614 		 * could have disappeared, causing the incomplete ire to also
27615 		 * disappear.  So we need to retreive the proper ipif for the
27616 		 * ire before looking in ctable.  In the case of IPMP, the
27617 		 * ipif may be on the IPMP ill, so look it up based on the
27618 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27619 		 * Then, we can verify that ire_ipif_seqid still exists.
27620 		 */
27621 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27622 		    NULL, NULL, NULL, NULL, ipst);
27623 		if (ill == NULL) {
27624 			ip1dbg(("ill for incomplete ire vanished\n"));
27625 			freemsg(mp); /* fake ire */
27626 			freeb(mp1);  /* dl_unitdata response */
27627 			return;
27628 		}
27629 
27630 		/* Get the outgoing ipif */
27631 		mutex_enter(&ill->ill_lock);
27632 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27633 		if (ipif == NULL) {
27634 			mutex_exit(&ill->ill_lock);
27635 			ill_refrele(ill);
27636 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27637 			freemsg(mp); /* fake_ire */
27638 			freeb(mp1);  /* dl_unitdata response */
27639 			return;
27640 		}
27641 
27642 		ipif_refhold_locked(ipif);
27643 		mutex_exit(&ill->ill_lock);
27644 		ill_refrele(ill);
27645 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27646 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27647 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27648 		ipif_refrele(ipif);
27649 		if (ire == NULL) {
27650 			/*
27651 			 * no ire was found; check if there is an nce
27652 			 * for this lookup; if it has no ire's pointing at it
27653 			 * cleanup.
27654 			 */
27655 			if ((nce = ndp_lookup_v4(q->q_ptr,
27656 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27657 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27658 			    B_FALSE)) != NULL) {
27659 				/*
27660 				 * cleanup:
27661 				 * We check for refcnt 2 (one for the nce
27662 				 * hash list + 1 for the ref taken by
27663 				 * ndp_lookup_v4) to check that there are
27664 				 * no ire's pointing at the nce.
27665 				 */
27666 				if (nce->nce_refcnt == 2)
27667 					ndp_delete(nce);
27668 				NCE_REFRELE(nce);
27669 			}
27670 			freeb(mp1);  /* dl_unitdata response */
27671 			freemsg(mp); /* fake ire */
27672 			return;
27673 		}
27674 
27675 		nce = ire->ire_nce;
27676 		DTRACE_PROBE2(ire__arpresolve__type,
27677 		    ire_t *, ire, nce_t *, nce);
27678 		mutex_enter(&nce->nce_lock);
27679 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27680 		if (nce->nce_state == ND_REACHABLE) {
27681 			/*
27682 			 * Someone resolved this before us;
27683 			 * our response is not needed any more.
27684 			 */
27685 			mutex_exit(&nce->nce_lock);
27686 			freeb(mp1);  /* dl_unitdata response */
27687 		} else {
27688 			ASSERT(nce->nce_res_mp == NULL);
27689 			nce->nce_res_mp = mp1;
27690 			nce->nce_state = ND_REACHABLE;
27691 			mutex_exit(&nce->nce_lock);
27692 			nce_fastpath(nce);
27693 		}
27694 		/*
27695 		 * The cached nce_t has been updated to be reachable;
27696 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27697 		 */
27698 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27699 		freemsg(mp);
27700 		/*
27701 		 * send out queued packets.
27702 		 */
27703 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27704 
27705 		IRE_REFRELE(ire);
27706 		return;
27707 	}
27708 	default:
27709 		break;
27710 	}
27711 	if (q->q_next) {
27712 		putnext(q, mp);
27713 	} else
27714 		freemsg(mp);
27715 	return;
27716 
27717 protonak:
27718 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27719 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27720 		qreply(q, mp);
27721 }
27722 
27723 /*
27724  * Process IP options in an outbound packet.  Modify the destination if there
27725  * is a source route option.
27726  * Returns non-zero if something fails in which case an ICMP error has been
27727  * sent and mp freed.
27728  */
27729 static int
27730 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27731     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27732 {
27733 	ipoptp_t	opts;
27734 	uchar_t		*opt;
27735 	uint8_t		optval;
27736 	uint8_t		optlen;
27737 	ipaddr_t	dst;
27738 	intptr_t	code = 0;
27739 	mblk_t		*mp;
27740 	ire_t		*ire = NULL;
27741 
27742 	ip2dbg(("ip_wput_options\n"));
27743 	mp = ipsec_mp;
27744 	if (mctl_present) {
27745 		mp = ipsec_mp->b_cont;
27746 	}
27747 
27748 	dst = ipha->ipha_dst;
27749 	for (optval = ipoptp_first(&opts, ipha);
27750 	    optval != IPOPT_EOL;
27751 	    optval = ipoptp_next(&opts)) {
27752 		opt = opts.ipoptp_cur;
27753 		optlen = opts.ipoptp_len;
27754 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27755 		    optval, optlen));
27756 		switch (optval) {
27757 			uint32_t off;
27758 		case IPOPT_SSRR:
27759 		case IPOPT_LSRR:
27760 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27761 				ip1dbg((
27762 				    "ip_wput_options: bad option offset\n"));
27763 				code = (char *)&opt[IPOPT_OLEN] -
27764 				    (char *)ipha;
27765 				goto param_prob;
27766 			}
27767 			off = opt[IPOPT_OFFSET];
27768 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27769 			    ntohl(dst)));
27770 			/*
27771 			 * For strict: verify that dst is directly
27772 			 * reachable.
27773 			 */
27774 			if (optval == IPOPT_SSRR) {
27775 				ire = ire_ftable_lookup(dst, 0, 0,
27776 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27777 				    msg_getlabel(mp),
27778 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27779 				if (ire == NULL) {
27780 					ip1dbg(("ip_wput_options: SSRR not"
27781 					    " directly reachable: 0x%x\n",
27782 					    ntohl(dst)));
27783 					goto bad_src_route;
27784 				}
27785 				ire_refrele(ire);
27786 			}
27787 			break;
27788 		case IPOPT_RR:
27789 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27790 				ip1dbg((
27791 				    "ip_wput_options: bad option offset\n"));
27792 				code = (char *)&opt[IPOPT_OLEN] -
27793 				    (char *)ipha;
27794 				goto param_prob;
27795 			}
27796 			break;
27797 		case IPOPT_TS:
27798 			/*
27799 			 * Verify that length >=5 and that there is either
27800 			 * room for another timestamp or that the overflow
27801 			 * counter is not maxed out.
27802 			 */
27803 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27804 			if (optlen < IPOPT_MINLEN_IT) {
27805 				goto param_prob;
27806 			}
27807 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27808 				ip1dbg((
27809 				    "ip_wput_options: bad option offset\n"));
27810 				code = (char *)&opt[IPOPT_OFFSET] -
27811 				    (char *)ipha;
27812 				goto param_prob;
27813 			}
27814 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27815 			case IPOPT_TS_TSONLY:
27816 				off = IPOPT_TS_TIMELEN;
27817 				break;
27818 			case IPOPT_TS_TSANDADDR:
27819 			case IPOPT_TS_PRESPEC:
27820 			case IPOPT_TS_PRESPEC_RFC791:
27821 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27822 				break;
27823 			default:
27824 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27825 				    (char *)ipha;
27826 				goto param_prob;
27827 			}
27828 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27829 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27830 				/*
27831 				 * No room and the overflow counter is 15
27832 				 * already.
27833 				 */
27834 				goto param_prob;
27835 			}
27836 			break;
27837 		}
27838 	}
27839 
27840 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27841 		return (0);
27842 
27843 	ip1dbg(("ip_wput_options: error processing IP options."));
27844 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27845 
27846 param_prob:
27847 	/*
27848 	 * Since ip_wput() isn't close to finished, we fill
27849 	 * in enough of the header for credible error reporting.
27850 	 */
27851 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27852 		/* Failed */
27853 		freemsg(ipsec_mp);
27854 		return (-1);
27855 	}
27856 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27857 	return (-1);
27858 
27859 bad_src_route:
27860 	/*
27861 	 * Since ip_wput() isn't close to finished, we fill
27862 	 * in enough of the header for credible error reporting.
27863 	 */
27864 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27865 		/* Failed */
27866 		freemsg(ipsec_mp);
27867 		return (-1);
27868 	}
27869 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27870 	return (-1);
27871 }
27872 
27873 /*
27874  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27875  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27876  * thru /etc/system.
27877  */
27878 #define	CONN_MAXDRAINCNT	64
27879 
27880 static void
27881 conn_drain_init(ip_stack_t *ipst)
27882 {
27883 	int i, j;
27884 	idl_tx_list_t *itl_tx;
27885 
27886 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27887 
27888 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27889 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27890 		/*
27891 		 * Default value of the number of drainers is the
27892 		 * number of cpus, subject to maximum of 8 drainers.
27893 		 */
27894 		if (boot_max_ncpus != -1)
27895 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27896 		else
27897 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27898 	}
27899 
27900 	ipst->ips_idl_tx_list =
27901 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
27902 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27903 		itl_tx =  &ipst->ips_idl_tx_list[i];
27904 		itl_tx->txl_drain_list =
27905 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27906 		    sizeof (idl_t), KM_SLEEP);
27907 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
27908 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
27909 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
27910 			    MUTEX_DEFAULT, NULL);
27911 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
27912 		}
27913 	}
27914 }
27915 
27916 static void
27917 conn_drain_fini(ip_stack_t *ipst)
27918 {
27919 	int i;
27920 	idl_tx_list_t *itl_tx;
27921 
27922 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
27923 		itl_tx =  &ipst->ips_idl_tx_list[i];
27924 		kmem_free(itl_tx->txl_drain_list,
27925 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27926 	}
27927 	kmem_free(ipst->ips_idl_tx_list,
27928 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
27929 	ipst->ips_idl_tx_list = NULL;
27930 }
27931 
27932 /*
27933  * Note: For an overview of how flowcontrol is handled in IP please see the
27934  * IP Flowcontrol notes at the top of this file.
27935  *
27936  * Flow control has blocked us from proceeding. Insert the given conn in one
27937  * of the conn drain lists. These conn wq's will be qenabled later on when
27938  * STREAMS flow control does a backenable. conn_walk_drain will enable
27939  * the first conn in each of these drain lists. Each of these qenabled conns
27940  * in turn enables the next in the list, after it runs, or when it closes,
27941  * thus sustaining the drain process.
27942  */
27943 void
27944 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
27945 {
27946 	idl_t	*idl = tx_list->txl_drain_list;
27947 	uint_t	index;
27948 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27949 
27950 	mutex_enter(&connp->conn_lock);
27951 	if (connp->conn_state_flags & CONN_CLOSING) {
27952 		/*
27953 		 * The conn is closing as a result of which CONN_CLOSING
27954 		 * is set. Return.
27955 		 */
27956 		mutex_exit(&connp->conn_lock);
27957 		return;
27958 	} else if (connp->conn_idl == NULL) {
27959 		/*
27960 		 * Assign the next drain list round robin. We dont' use
27961 		 * a lock, and thus it may not be strictly round robin.
27962 		 * Atomicity of load/stores is enough to make sure that
27963 		 * conn_drain_list_index is always within bounds.
27964 		 */
27965 		index = tx_list->txl_drain_index;
27966 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27967 		connp->conn_idl = &tx_list->txl_drain_list[index];
27968 		index++;
27969 		if (index == ipst->ips_conn_drain_list_cnt)
27970 			index = 0;
27971 		tx_list->txl_drain_index = index;
27972 	}
27973 	mutex_exit(&connp->conn_lock);
27974 
27975 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27976 	if ((connp->conn_drain_prev != NULL) ||
27977 	    (connp->conn_state_flags & CONN_CLOSING)) {
27978 		/*
27979 		 * The conn is already in the drain list, OR
27980 		 * the conn is closing. We need to check again for
27981 		 * the closing case again since close can happen
27982 		 * after we drop the conn_lock, and before we
27983 		 * acquire the CONN_DRAIN_LIST_LOCK.
27984 		 */
27985 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27986 		return;
27987 	} else {
27988 		idl = connp->conn_idl;
27989 	}
27990 
27991 	/*
27992 	 * The conn is not in the drain list. Insert it at the
27993 	 * tail of the drain list. The drain list is circular
27994 	 * and doubly linked. idl_conn points to the 1st element
27995 	 * in the list.
27996 	 */
27997 	if (idl->idl_conn == NULL) {
27998 		idl->idl_conn = connp;
27999 		connp->conn_drain_next = connp;
28000 		connp->conn_drain_prev = connp;
28001 	} else {
28002 		conn_t *head = idl->idl_conn;
28003 
28004 		connp->conn_drain_next = head;
28005 		connp->conn_drain_prev = head->conn_drain_prev;
28006 		head->conn_drain_prev->conn_drain_next = connp;
28007 		head->conn_drain_prev = connp;
28008 	}
28009 	/*
28010 	 * For non streams based sockets assert flow control.
28011 	 */
28012 	if (IPCL_IS_NONSTR(connp)) {
28013 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28014 		(*connp->conn_upcalls->su_txq_full)
28015 		    (connp->conn_upper_handle, B_TRUE);
28016 	} else {
28017 		conn_setqfull(connp);
28018 		noenable(connp->conn_wq);
28019 	}
28020 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28021 }
28022 
28023 /*
28024  * This conn is closing, and we are called from ip_close. OR
28025  * This conn has been serviced by ip_wsrv, and we need to do the tail
28026  * processing.
28027  * If this conn is part of the drain list, we may need to sustain the drain
28028  * process by qenabling the next conn in the drain list. We may also need to
28029  * remove this conn from the list, if it is done.
28030  */
28031 static void
28032 conn_drain_tail(conn_t *connp, boolean_t closing)
28033 {
28034 	idl_t *idl;
28035 
28036 	/*
28037 	 * connp->conn_idl is stable at this point, and no lock is needed
28038 	 * to check it. If we are called from ip_close, close has already
28039 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28040 	 * called us only because conn_idl is non-null. If we are called thru
28041 	 * service, conn_idl could be null, but it cannot change because
28042 	 * service is single-threaded per queue, and there cannot be another
28043 	 * instance of service trying to call conn_drain_insert on this conn
28044 	 * now.
28045 	 */
28046 	ASSERT(!closing || (connp->conn_idl != NULL));
28047 
28048 	/*
28049 	 * If connp->conn_idl is null, the conn has not been inserted into any
28050 	 * drain list even once since creation of the conn. Just return.
28051 	 */
28052 	if (connp->conn_idl == NULL)
28053 		return;
28054 
28055 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28056 
28057 	if (connp->conn_drain_prev == NULL) {
28058 		/* This conn is currently not in the drain list.  */
28059 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28060 		return;
28061 	}
28062 	idl = connp->conn_idl;
28063 	if (idl->idl_conn_draining == connp) {
28064 		/*
28065 		 * This conn is the current drainer. If this is the last conn
28066 		 * in the drain list, we need to do more checks, in the 'if'
28067 		 * below. Otherwwise we need to just qenable the next conn,
28068 		 * to sustain the draining, and is handled in the 'else'
28069 		 * below.
28070 		 */
28071 		if (connp->conn_drain_next == idl->idl_conn) {
28072 			/*
28073 			 * This conn is the last in this list. This round
28074 			 * of draining is complete. If idl_repeat is set,
28075 			 * it means another flow enabling has happened from
28076 			 * the driver/streams and we need to another round
28077 			 * of draining.
28078 			 * If there are more than 2 conns in the drain list,
28079 			 * do a left rotate by 1, so that all conns except the
28080 			 * conn at the head move towards the head by 1, and the
28081 			 * the conn at the head goes to the tail. This attempts
28082 			 * a more even share for all queues that are being
28083 			 * drained.
28084 			 */
28085 			if ((connp->conn_drain_next != connp) &&
28086 			    (idl->idl_conn->conn_drain_next != connp)) {
28087 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28088 			}
28089 			if (idl->idl_repeat) {
28090 				qenable(idl->idl_conn->conn_wq);
28091 				idl->idl_conn_draining = idl->idl_conn;
28092 				idl->idl_repeat = 0;
28093 			} else {
28094 				idl->idl_conn_draining = NULL;
28095 			}
28096 		} else {
28097 			/*
28098 			 * If the next queue that we are now qenable'ing,
28099 			 * is closing, it will remove itself from this list
28100 			 * and qenable the subsequent queue in ip_close().
28101 			 * Serialization is acheived thru idl_lock.
28102 			 */
28103 			qenable(connp->conn_drain_next->conn_wq);
28104 			idl->idl_conn_draining = connp->conn_drain_next;
28105 		}
28106 	}
28107 	if (!connp->conn_did_putbq || closing) {
28108 		/*
28109 		 * Remove ourself from the drain list, if we did not do
28110 		 * a putbq, or if the conn is closing.
28111 		 * Note: It is possible that q->q_first is non-null. It means
28112 		 * that these messages landed after we did a enableok() in
28113 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28114 		 * service them.
28115 		 */
28116 		if (connp->conn_drain_next == connp) {
28117 			/* Singleton in the list */
28118 			ASSERT(connp->conn_drain_prev == connp);
28119 			idl->idl_conn = NULL;
28120 			idl->idl_conn_draining = NULL;
28121 		} else {
28122 			connp->conn_drain_prev->conn_drain_next =
28123 			    connp->conn_drain_next;
28124 			connp->conn_drain_next->conn_drain_prev =
28125 			    connp->conn_drain_prev;
28126 			if (idl->idl_conn == connp)
28127 				idl->idl_conn = connp->conn_drain_next;
28128 			ASSERT(idl->idl_conn_draining != connp);
28129 
28130 		}
28131 		connp->conn_drain_next = NULL;
28132 		connp->conn_drain_prev = NULL;
28133 
28134 		/*
28135 		 * For non streams based sockets open up flow control.
28136 		 */
28137 		if (IPCL_IS_NONSTR(connp)) {
28138 			(*connp->conn_upcalls->su_txq_full)
28139 			    (connp->conn_upper_handle, B_FALSE);
28140 		} else {
28141 			conn_clrqfull(connp);
28142 			enableok(connp->conn_wq);
28143 		}
28144 	}
28145 
28146 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28147 }
28148 
28149 /*
28150  * Write service routine. Shared perimeter entry point.
28151  * ip_wsrv can be called in any of the following ways.
28152  * 1. The device queue's messages has fallen below the low water mark
28153  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28154  *    the drain lists and backenable the first conn in each list.
28155  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28156  *    qenabled non-tcp upper layers. We start dequeing messages and call
28157  *    ip_wput for each message.
28158  */
28159 
28160 void
28161 ip_wsrv(queue_t *q)
28162 {
28163 	conn_t	*connp;
28164 	ill_t	*ill;
28165 	mblk_t	*mp;
28166 
28167 	if (q->q_next) {
28168 		ill = (ill_t *)q->q_ptr;
28169 		if (ill->ill_state_flags == 0) {
28170 			ip_stack_t *ipst = ill->ill_ipst;
28171 
28172 			/*
28173 			 * The device flow control has opened up.
28174 			 * Walk through conn drain lists and qenable the
28175 			 * first conn in each list. This makes sense only
28176 			 * if the stream is fully plumbed and setup.
28177 			 * Hence the if check above.
28178 			 */
28179 			ip1dbg(("ip_wsrv: walking\n"));
28180 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28181 		}
28182 		return;
28183 	}
28184 
28185 	connp = Q_TO_CONN(q);
28186 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28187 
28188 	/*
28189 	 * 1. Set conn_draining flag to signal that service is active.
28190 	 *
28191 	 * 2. ip_output determines whether it has been called from service,
28192 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28193 	 *    has been called from service.
28194 	 *
28195 	 * 3. Message ordering is preserved by the following logic.
28196 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28197 	 *    the message at the tail, if conn_draining is set (i.e. service
28198 	 *    is running) or if q->q_first is non-null.
28199 	 *
28200 	 *    ii. If ip_output is called from service, and if ip_output cannot
28201 	 *    putnext due to flow control, it does a putbq.
28202 	 *
28203 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28204 	 *    (causing an infinite loop).
28205 	 */
28206 	ASSERT(!connp->conn_did_putbq);
28207 
28208 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28209 		connp->conn_draining = 1;
28210 		noenable(q);
28211 		while ((mp = getq(q)) != NULL) {
28212 			ASSERT(CONN_Q(q));
28213 
28214 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28215 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28216 			if (connp->conn_did_putbq) {
28217 				/* ip_wput did a putbq */
28218 				break;
28219 			}
28220 		}
28221 		/*
28222 		 * At this point, a thread coming down from top, calling
28223 		 * ip_wput, may end up queueing the message. We have not yet
28224 		 * enabled the queue, so ip_wsrv won't be called again.
28225 		 * To avoid this race, check q->q_first again (in the loop)
28226 		 * If the other thread queued the message before we call
28227 		 * enableok(), we will catch it in the q->q_first check.
28228 		 * If the other thread queues the message after we call
28229 		 * enableok(), ip_wsrv will be called again by STREAMS.
28230 		 */
28231 		connp->conn_draining = 0;
28232 		enableok(q);
28233 	}
28234 
28235 	/* Enable the next conn for draining */
28236 	conn_drain_tail(connp, B_FALSE);
28237 
28238 	/*
28239 	 * conn_direct_blocked is used to indicate blocked
28240 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28241 	 * This is the only place where it is set without
28242 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28243 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28244 	 */
28245 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28246 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28247 		connp->conn_direct_blocked = B_FALSE;
28248 	}
28249 
28250 	connp->conn_did_putbq = 0;
28251 }
28252 
28253 /*
28254  * Callback to disable flow control in IP.
28255  *
28256  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28257  * is enabled.
28258  *
28259  * When MAC_TX() is not able to send any more packets, dld sets its queue
28260  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28261  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28262  * function and wakes up corresponding mac worker threads, which in turn
28263  * calls this callback function, and disables flow control.
28264  */
28265 void
28266 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28267 {
28268 	ill_t *ill = (ill_t *)arg;
28269 	ip_stack_t *ipst = ill->ill_ipst;
28270 	idl_tx_list_t *idl_txl;
28271 
28272 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28273 	mutex_enter(&idl_txl->txl_lock);
28274 	/* add code to to set a flag to indicate idl_txl is enabled */
28275 	conn_walk_drain(ipst, idl_txl);
28276 	mutex_exit(&idl_txl->txl_lock);
28277 }
28278 
28279 /*
28280  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28281  * of conns that need to be drained, check if drain is already in progress.
28282  * If so set the idl_repeat bit, indicating that the last conn in the list
28283  * needs to reinitiate the drain once again, for the list. If drain is not
28284  * in progress for the list, initiate the draining, by qenabling the 1st
28285  * conn in the list. The drain is self-sustaining, each qenabled conn will
28286  * in turn qenable the next conn, when it is done/blocked/closing.
28287  */
28288 static void
28289 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28290 {
28291 	int i;
28292 	idl_t *idl;
28293 
28294 	IP_STAT(ipst, ip_conn_walk_drain);
28295 
28296 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28297 		idl = &tx_list->txl_drain_list[i];
28298 		mutex_enter(&idl->idl_lock);
28299 		if (idl->idl_conn == NULL) {
28300 			mutex_exit(&idl->idl_lock);
28301 			continue;
28302 		}
28303 		/*
28304 		 * If this list is not being drained currently by
28305 		 * an ip_wsrv thread, start the process.
28306 		 */
28307 		if (idl->idl_conn_draining == NULL) {
28308 			ASSERT(idl->idl_repeat == 0);
28309 			qenable(idl->idl_conn->conn_wq);
28310 			idl->idl_conn_draining = idl->idl_conn;
28311 		} else {
28312 			idl->idl_repeat = 1;
28313 		}
28314 		mutex_exit(&idl->idl_lock);
28315 	}
28316 }
28317 
28318 /*
28319  * Determine if the ill and multicast aspects of that packets
28320  * "matches" the conn.
28321  */
28322 boolean_t
28323 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28324     zoneid_t zoneid)
28325 {
28326 	ill_t *bound_ill;
28327 	boolean_t found;
28328 	ipif_t *ipif;
28329 	ire_t *ire;
28330 	ipaddr_t dst, src;
28331 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28332 
28333 	dst = ipha->ipha_dst;
28334 	src = ipha->ipha_src;
28335 
28336 	/*
28337 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28338 	 * unicast, broadcast and multicast reception to
28339 	 * conn_incoming_ill. conn_wantpacket itself is called
28340 	 * only for BROADCAST and multicast.
28341 	 */
28342 	bound_ill = connp->conn_incoming_ill;
28343 	if (bound_ill != NULL) {
28344 		if (IS_IPMP(bound_ill)) {
28345 			if (bound_ill->ill_grp != ill->ill_grp)
28346 				return (B_FALSE);
28347 		} else {
28348 			if (bound_ill != ill)
28349 				return (B_FALSE);
28350 		}
28351 	}
28352 
28353 	if (!CLASSD(dst)) {
28354 		if (IPCL_ZONE_MATCH(connp, zoneid))
28355 			return (B_TRUE);
28356 		/*
28357 		 * The conn is in a different zone; we need to check that this
28358 		 * broadcast address is configured in the application's zone.
28359 		 */
28360 		ipif = ipif_get_next_ipif(NULL, ill);
28361 		if (ipif == NULL)
28362 			return (B_FALSE);
28363 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28364 		    connp->conn_zoneid, NULL,
28365 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28366 		ipif_refrele(ipif);
28367 		if (ire != NULL) {
28368 			ire_refrele(ire);
28369 			return (B_TRUE);
28370 		} else {
28371 			return (B_FALSE);
28372 		}
28373 	}
28374 
28375 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28376 	    connp->conn_zoneid == zoneid) {
28377 		/*
28378 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28379 		 * disabled, therefore we don't dispatch the multicast packet to
28380 		 * the sending zone.
28381 		 */
28382 		return (B_FALSE);
28383 	}
28384 
28385 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28386 		/*
28387 		 * Multicast packet on the loopback interface: we only match
28388 		 * conns who joined the group in the specified zone.
28389 		 */
28390 		return (B_FALSE);
28391 	}
28392 
28393 	if (connp->conn_multi_router) {
28394 		/* multicast packet and multicast router socket: send up */
28395 		return (B_TRUE);
28396 	}
28397 
28398 	mutex_enter(&connp->conn_lock);
28399 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28400 	mutex_exit(&connp->conn_lock);
28401 	return (found);
28402 }
28403 
28404 static void
28405 conn_setqfull(conn_t *connp)
28406 {
28407 	queue_t *q = connp->conn_wq;
28408 
28409 	if (!(q->q_flag & QFULL)) {
28410 		mutex_enter(QLOCK(q));
28411 		if (!(q->q_flag & QFULL)) {
28412 			/* still need to set QFULL */
28413 			q->q_flag |= QFULL;
28414 			mutex_exit(QLOCK(q));
28415 		} else {
28416 			mutex_exit(QLOCK(q));
28417 		}
28418 	}
28419 }
28420 
28421 static void
28422 conn_clrqfull(conn_t *connp)
28423 {
28424 	queue_t *q = connp->conn_wq;
28425 
28426 	if (q->q_flag & QFULL) {
28427 		mutex_enter(QLOCK(q));
28428 		if (q->q_flag & QFULL) {
28429 			q->q_flag &= ~QFULL;
28430 			mutex_exit(QLOCK(q));
28431 			if (q->q_flag & QWANTW)
28432 				qbackenable(q, 0);
28433 		} else {
28434 			mutex_exit(QLOCK(q));
28435 		}
28436 	}
28437 }
28438 
28439 /*
28440  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28441  */
28442 /* ARGSUSED */
28443 static void
28444 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28445 {
28446 	ill_t *ill = (ill_t *)q->q_ptr;
28447 	mblk_t	*mp1, *mp2;
28448 	ipif_t  *ipif;
28449 	int err = 0;
28450 	conn_t *connp = NULL;
28451 	ipsq_t	*ipsq;
28452 	arc_t	*arc;
28453 
28454 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28455 
28456 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28457 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28458 
28459 	ASSERT(IAM_WRITER_ILL(ill));
28460 	mp2 = mp->b_cont;
28461 	mp->b_cont = NULL;
28462 
28463 	/*
28464 	 * We have now received the arp bringup completion message
28465 	 * from ARP. Mark the arp bringup as done. Also if the arp
28466 	 * stream has already started closing, send up the AR_ARP_CLOSING
28467 	 * ack now since ARP is waiting in close for this ack.
28468 	 */
28469 	mutex_enter(&ill->ill_lock);
28470 	ill->ill_arp_bringup_pending = 0;
28471 	if (ill->ill_arp_closing) {
28472 		mutex_exit(&ill->ill_lock);
28473 		/* Let's reuse the mp for sending the ack */
28474 		arc = (arc_t *)mp->b_rptr;
28475 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28476 		arc->arc_cmd = AR_ARP_CLOSING;
28477 		qreply(q, mp);
28478 	} else {
28479 		mutex_exit(&ill->ill_lock);
28480 		freeb(mp);
28481 	}
28482 
28483 	ipsq = ill->ill_phyint->phyint_ipsq;
28484 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28485 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28486 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28487 	if (mp1 == NULL) {
28488 		/* bringup was aborted by the user */
28489 		freemsg(mp2);
28490 		return;
28491 	}
28492 
28493 	/*
28494 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28495 	 * must have an associated conn_t.  Otherwise, we're bringing this
28496 	 * interface back up as part of handling an asynchronous event (e.g.,
28497 	 * physical address change).
28498 	 */
28499 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28500 		ASSERT(connp != NULL);
28501 		q = CONNP_TO_WQ(connp);
28502 	} else {
28503 		ASSERT(connp == NULL);
28504 		q = ill->ill_rq;
28505 	}
28506 
28507 	/*
28508 	 * If the DL_BIND_REQ fails, it is noted
28509 	 * in arc_name_offset.
28510 	 */
28511 	err = *((int *)mp2->b_rptr);
28512 	if (err == 0) {
28513 		if (ipif->ipif_isv6) {
28514 			if ((err = ipif_up_done_v6(ipif)) != 0)
28515 				ip0dbg(("ip_arp_done: init failed\n"));
28516 		} else {
28517 			if ((err = ipif_up_done(ipif)) != 0)
28518 				ip0dbg(("ip_arp_done: init failed\n"));
28519 		}
28520 	} else {
28521 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28522 	}
28523 
28524 	freemsg(mp2);
28525 
28526 	if ((err == 0) && (ill->ill_up_ipifs)) {
28527 		err = ill_up_ipifs(ill, q, mp1);
28528 		if (err == EINPROGRESS)
28529 			return;
28530 	}
28531 
28532 	/*
28533 	 * If we have a moved ipif to bring up, and everything has succeeded
28534 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28535 	 * down -- the admin can try to bring it up by hand if need be.
28536 	 */
28537 	if (ill->ill_move_ipif != NULL) {
28538 		ipif = ill->ill_move_ipif;
28539 		ill->ill_move_ipif = NULL;
28540 		if (err == 0) {
28541 			err = ipif_up(ipif, q, mp1);
28542 			if (err == EINPROGRESS)
28543 				return;
28544 		}
28545 	}
28546 
28547 	/*
28548 	 * The operation must complete without EINPROGRESS since
28549 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28550 	 * operation will be stuck forever in the ipsq.
28551 	 */
28552 	ASSERT(err != EINPROGRESS);
28553 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28554 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28555 	else
28556 		ipsq_current_finish(ipsq);
28557 }
28558 
28559 /* Allocate the private structure */
28560 static int
28561 ip_priv_alloc(void **bufp)
28562 {
28563 	void	*buf;
28564 
28565 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28566 		return (ENOMEM);
28567 
28568 	*bufp = buf;
28569 	return (0);
28570 }
28571 
28572 /* Function to delete the private structure */
28573 void
28574 ip_priv_free(void *buf)
28575 {
28576 	ASSERT(buf != NULL);
28577 	kmem_free(buf, sizeof (ip_priv_t));
28578 }
28579 
28580 /*
28581  * The entry point for IPPF processing.
28582  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28583  * routine just returns.
28584  *
28585  * When called, ip_process generates an ipp_packet_t structure
28586  * which holds the state information for this packet and invokes the
28587  * the classifier (via ipp_packet_process). The classification, depending on
28588  * configured filters, results in a list of actions for this packet. Invoking
28589  * an action may cause the packet to be dropped, in which case the resulting
28590  * mblk (*mpp) is NULL. proc indicates the callout position for
28591  * this packet and ill_index is the interface this packet on or will leave
28592  * on (inbound and outbound resp.).
28593  */
28594 void
28595 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28596 {
28597 	mblk_t		*mp;
28598 	ip_priv_t	*priv;
28599 	ipp_action_id_t	aid;
28600 	int		rc = 0;
28601 	ipp_packet_t	*pp;
28602 #define	IP_CLASS	"ip"
28603 
28604 	/* If the classifier is not loaded, return  */
28605 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28606 		return;
28607 	}
28608 
28609 	mp = *mpp;
28610 	ASSERT(mp != NULL);
28611 
28612 	/* Allocate the packet structure */
28613 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28614 	if (rc != 0) {
28615 		*mpp = NULL;
28616 		freemsg(mp);
28617 		return;
28618 	}
28619 
28620 	/* Allocate the private structure */
28621 	rc = ip_priv_alloc((void **)&priv);
28622 	if (rc != 0) {
28623 		*mpp = NULL;
28624 		freemsg(mp);
28625 		ipp_packet_free(pp);
28626 		return;
28627 	}
28628 	priv->proc = proc;
28629 	priv->ill_index = ill_index;
28630 	ipp_packet_set_private(pp, priv, ip_priv_free);
28631 	ipp_packet_set_data(pp, mp);
28632 
28633 	/* Invoke the classifier */
28634 	rc = ipp_packet_process(&pp);
28635 	if (pp != NULL) {
28636 		mp = ipp_packet_get_data(pp);
28637 		ipp_packet_free(pp);
28638 		if (rc != 0) {
28639 			freemsg(mp);
28640 			*mpp = NULL;
28641 		}
28642 	} else {
28643 		*mpp = NULL;
28644 	}
28645 #undef	IP_CLASS
28646 }
28647 
28648 /*
28649  * Propagate a multicast group membership operation (add/drop) on
28650  * all the interfaces crossed by the related multirt routes.
28651  * The call is considered successful if the operation succeeds
28652  * on at least one interface.
28653  */
28654 static int
28655 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28656     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28657     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28658     mblk_t *first_mp)
28659 {
28660 	ire_t		*ire_gw;
28661 	irb_t		*irb;
28662 	int		error = 0;
28663 	opt_restart_t	*or;
28664 	ip_stack_t	*ipst = ire->ire_ipst;
28665 
28666 	irb = ire->ire_bucket;
28667 	ASSERT(irb != NULL);
28668 
28669 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28670 
28671 	or = (opt_restart_t *)first_mp->b_rptr;
28672 	IRB_REFHOLD(irb);
28673 	for (; ire != NULL; ire = ire->ire_next) {
28674 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28675 			continue;
28676 		if (ire->ire_addr != group)
28677 			continue;
28678 
28679 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28680 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28681 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28682 		/* No resolver exists for the gateway; skip this ire. */
28683 		if (ire_gw == NULL)
28684 			continue;
28685 
28686 		/*
28687 		 * This function can return EINPROGRESS. If so the operation
28688 		 * will be restarted from ip_restart_optmgmt which will
28689 		 * call ip_opt_set and option processing will restart for
28690 		 * this option. So we may end up calling 'fn' more than once.
28691 		 * This requires that 'fn' is idempotent except for the
28692 		 * return value. The operation is considered a success if
28693 		 * it succeeds at least once on any one interface.
28694 		 */
28695 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28696 		    NULL, fmode, src, first_mp);
28697 		if (error == 0)
28698 			or->or_private = CGTP_MCAST_SUCCESS;
28699 
28700 		if (ip_debug > 0) {
28701 			ulong_t	off;
28702 			char	*ksym;
28703 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28704 			ip2dbg(("ip_multirt_apply_membership: "
28705 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28706 			    "error %d [success %u]\n",
28707 			    ksym ? ksym : "?",
28708 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28709 			    error, or->or_private));
28710 		}
28711 
28712 		ire_refrele(ire_gw);
28713 		if (error == EINPROGRESS) {
28714 			IRB_REFRELE(irb);
28715 			return (error);
28716 		}
28717 	}
28718 	IRB_REFRELE(irb);
28719 	/*
28720 	 * Consider the call as successful if we succeeded on at least
28721 	 * one interface. Otherwise, return the last encountered error.
28722 	 */
28723 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28724 }
28725 
28726 /*
28727  * Issue a warning regarding a route crossing an interface with an
28728  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28729  * amount of time is logged.
28730  */
28731 static void
28732 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28733 {
28734 	hrtime_t	current = gethrtime();
28735 	char		buf[INET_ADDRSTRLEN];
28736 	ip_stack_t	*ipst = ire->ire_ipst;
28737 
28738 	/* Convert interval in ms to hrtime in ns */
28739 	if (ipst->ips_multirt_bad_mtu_last_time +
28740 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28741 	    current) {
28742 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28743 		    "to %s, incorrect MTU %u (expected %u)\n",
28744 		    ip_dot_addr(ire->ire_addr, buf),
28745 		    ire->ire_max_frag, max_frag);
28746 
28747 		ipst->ips_multirt_bad_mtu_last_time = current;
28748 	}
28749 }
28750 
28751 /*
28752  * Get the CGTP (multirouting) filtering status.
28753  * If 0, the CGTP hooks are transparent.
28754  */
28755 /* ARGSUSED */
28756 static int
28757 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28758 {
28759 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28760 
28761 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28762 	return (0);
28763 }
28764 
28765 /*
28766  * Set the CGTP (multirouting) filtering status.
28767  * If the status is changed from active to transparent
28768  * or from transparent to active, forward the new status
28769  * to the filtering module (if loaded).
28770  */
28771 /* ARGSUSED */
28772 static int
28773 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28774     cred_t *ioc_cr)
28775 {
28776 	long		new_value;
28777 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28778 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28779 
28780 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28781 		return (EPERM);
28782 
28783 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28784 	    new_value < 0 || new_value > 1) {
28785 		return (EINVAL);
28786 	}
28787 
28788 	if ((!*ip_cgtp_filter_value) && new_value) {
28789 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28790 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28791 		    " (module not loaded)" : "");
28792 	}
28793 	if (*ip_cgtp_filter_value && (!new_value)) {
28794 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28795 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28796 		    " (module not loaded)" : "");
28797 	}
28798 
28799 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28800 		int	res;
28801 		netstackid_t stackid;
28802 
28803 		stackid = ipst->ips_netstack->netstack_stackid;
28804 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28805 		    new_value);
28806 		if (res)
28807 			return (res);
28808 	}
28809 
28810 	*ip_cgtp_filter_value = (boolean_t)new_value;
28811 
28812 	return (0);
28813 }
28814 
28815 /*
28816  * Return the expected CGTP hooks version number.
28817  */
28818 int
28819 ip_cgtp_filter_supported(void)
28820 {
28821 	return (ip_cgtp_filter_rev);
28822 }
28823 
28824 /*
28825  * CGTP hooks can be registered by invoking this function.
28826  * Checks that the version number matches.
28827  */
28828 int
28829 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28830 {
28831 	netstack_t *ns;
28832 	ip_stack_t *ipst;
28833 
28834 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28835 		return (ENOTSUP);
28836 
28837 	ns = netstack_find_by_stackid(stackid);
28838 	if (ns == NULL)
28839 		return (EINVAL);
28840 	ipst = ns->netstack_ip;
28841 	ASSERT(ipst != NULL);
28842 
28843 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28844 		netstack_rele(ns);
28845 		return (EALREADY);
28846 	}
28847 
28848 	ipst->ips_ip_cgtp_filter_ops = ops;
28849 	netstack_rele(ns);
28850 	return (0);
28851 }
28852 
28853 /*
28854  * CGTP hooks can be unregistered by invoking this function.
28855  * Returns ENXIO if there was no registration.
28856  * Returns EBUSY if the ndd variable has not been turned off.
28857  */
28858 int
28859 ip_cgtp_filter_unregister(netstackid_t stackid)
28860 {
28861 	netstack_t *ns;
28862 	ip_stack_t *ipst;
28863 
28864 	ns = netstack_find_by_stackid(stackid);
28865 	if (ns == NULL)
28866 		return (EINVAL);
28867 	ipst = ns->netstack_ip;
28868 	ASSERT(ipst != NULL);
28869 
28870 	if (ipst->ips_ip_cgtp_filter) {
28871 		netstack_rele(ns);
28872 		return (EBUSY);
28873 	}
28874 
28875 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28876 		netstack_rele(ns);
28877 		return (ENXIO);
28878 	}
28879 	ipst->ips_ip_cgtp_filter_ops = NULL;
28880 	netstack_rele(ns);
28881 	return (0);
28882 }
28883 
28884 /*
28885  * Check whether there is a CGTP filter registration.
28886  * Returns non-zero if there is a registration, otherwise returns zero.
28887  * Note: returns zero if bad stackid.
28888  */
28889 int
28890 ip_cgtp_filter_is_registered(netstackid_t stackid)
28891 {
28892 	netstack_t *ns;
28893 	ip_stack_t *ipst;
28894 	int ret;
28895 
28896 	ns = netstack_find_by_stackid(stackid);
28897 	if (ns == NULL)
28898 		return (0);
28899 	ipst = ns->netstack_ip;
28900 	ASSERT(ipst != NULL);
28901 
28902 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28903 		ret = 1;
28904 	else
28905 		ret = 0;
28906 
28907 	netstack_rele(ns);
28908 	return (ret);
28909 }
28910 
28911 static int
28912 ip_squeue_switch(int val)
28913 {
28914 	int rval = SQ_FILL;
28915 
28916 	switch (val) {
28917 	case IP_SQUEUE_ENTER_NODRAIN:
28918 		rval = SQ_NODRAIN;
28919 		break;
28920 	case IP_SQUEUE_ENTER:
28921 		rval = SQ_PROCESS;
28922 		break;
28923 	default:
28924 		break;
28925 	}
28926 	return (rval);
28927 }
28928 
28929 /* ARGSUSED */
28930 static int
28931 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28932     caddr_t addr, cred_t *cr)
28933 {
28934 	int *v = (int *)addr;
28935 	long new_value;
28936 
28937 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28938 		return (EPERM);
28939 
28940 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28941 		return (EINVAL);
28942 
28943 	ip_squeue_flag = ip_squeue_switch(new_value);
28944 	*v = new_value;
28945 	return (0);
28946 }
28947 
28948 /*
28949  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
28950  * ip_debug.
28951  */
28952 /* ARGSUSED */
28953 static int
28954 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28955     caddr_t addr, cred_t *cr)
28956 {
28957 	int *v = (int *)addr;
28958 	long new_value;
28959 
28960 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28961 		return (EPERM);
28962 
28963 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28964 		return (EINVAL);
28965 
28966 	*v = new_value;
28967 	return (0);
28968 }
28969 
28970 static void *
28971 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
28972 {
28973 	kstat_t *ksp;
28974 
28975 	ip_stat_t template = {
28976 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
28977 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
28978 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
28979 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
28980 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
28981 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
28982 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
28983 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
28984 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
28985 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
28986 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
28987 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
28988 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
28989 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
28990 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
28991 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
28992 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
28993 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
28994 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
28995 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
28996 		{ "ip_opt",			KSTAT_DATA_UINT64 },
28997 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
28998 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
28999 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29000 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29001 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29002 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29003 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29004 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29005 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29006 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29007 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29008 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29009 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29010 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29011 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29012 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29013 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29014 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29015 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29016 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29017 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29018 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29019 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29020 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29021 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29022 	};
29023 
29024 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29025 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29026 	    KSTAT_FLAG_VIRTUAL, stackid);
29027 
29028 	if (ksp == NULL)
29029 		return (NULL);
29030 
29031 	bcopy(&template, ip_statisticsp, sizeof (template));
29032 	ksp->ks_data = (void *)ip_statisticsp;
29033 	ksp->ks_private = (void *)(uintptr_t)stackid;
29034 
29035 	kstat_install(ksp);
29036 	return (ksp);
29037 }
29038 
29039 static void
29040 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29041 {
29042 	if (ksp != NULL) {
29043 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29044 		kstat_delete_netstack(ksp, stackid);
29045 	}
29046 }
29047 
29048 static void *
29049 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29050 {
29051 	kstat_t	*ksp;
29052 
29053 	ip_named_kstat_t template = {
29054 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29055 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29056 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29057 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29058 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29059 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29060 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29061 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29062 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29063 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29064 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29065 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29066 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29067 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29068 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29069 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29070 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29071 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29072 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29073 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29074 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29075 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29076 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29077 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29078 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29079 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29080 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29081 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29082 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29083 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29084 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29085 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29086 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29087 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29088 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29089 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29090 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29091 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29092 	};
29093 
29094 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29095 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29096 	if (ksp == NULL || ksp->ks_data == NULL)
29097 		return (NULL);
29098 
29099 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29100 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29101 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29102 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29103 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29104 
29105 	template.netToMediaEntrySize.value.i32 =
29106 	    sizeof (mib2_ipNetToMediaEntry_t);
29107 
29108 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29109 
29110 	bcopy(&template, ksp->ks_data, sizeof (template));
29111 	ksp->ks_update = ip_kstat_update;
29112 	ksp->ks_private = (void *)(uintptr_t)stackid;
29113 
29114 	kstat_install(ksp);
29115 	return (ksp);
29116 }
29117 
29118 static void
29119 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29120 {
29121 	if (ksp != NULL) {
29122 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29123 		kstat_delete_netstack(ksp, stackid);
29124 	}
29125 }
29126 
29127 static int
29128 ip_kstat_update(kstat_t *kp, int rw)
29129 {
29130 	ip_named_kstat_t *ipkp;
29131 	mib2_ipIfStatsEntry_t ipmib;
29132 	ill_walk_context_t ctx;
29133 	ill_t *ill;
29134 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29135 	netstack_t	*ns;
29136 	ip_stack_t	*ipst;
29137 
29138 	if (kp == NULL || kp->ks_data == NULL)
29139 		return (EIO);
29140 
29141 	if (rw == KSTAT_WRITE)
29142 		return (EACCES);
29143 
29144 	ns = netstack_find_by_stackid(stackid);
29145 	if (ns == NULL)
29146 		return (-1);
29147 	ipst = ns->netstack_ip;
29148 	if (ipst == NULL) {
29149 		netstack_rele(ns);
29150 		return (-1);
29151 	}
29152 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29153 
29154 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29155 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29156 	ill = ILL_START_WALK_V4(&ctx, ipst);
29157 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29158 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29159 	rw_exit(&ipst->ips_ill_g_lock);
29160 
29161 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29162 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29163 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29164 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29165 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29166 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29167 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29168 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29169 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29170 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29171 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29172 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29173 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29174 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29175 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29176 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29177 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29178 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29179 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29180 
29181 	ipkp->routingDiscards.value.ui32 =	0;
29182 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29183 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29184 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29185 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29186 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29187 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29188 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29189 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29190 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29191 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29192 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29193 
29194 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29195 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29196 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29197 
29198 	netstack_rele(ns);
29199 
29200 	return (0);
29201 }
29202 
29203 static void *
29204 icmp_kstat_init(netstackid_t stackid)
29205 {
29206 	kstat_t	*ksp;
29207 
29208 	icmp_named_kstat_t template = {
29209 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29210 		{ "inErrors",		KSTAT_DATA_UINT32 },
29211 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29212 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29213 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29214 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29215 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29216 		{ "inEchos",		KSTAT_DATA_UINT32 },
29217 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29218 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29219 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29220 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29221 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29222 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29223 		{ "outErrors",		KSTAT_DATA_UINT32 },
29224 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29225 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29226 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29227 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29228 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29229 		{ "outEchos",		KSTAT_DATA_UINT32 },
29230 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29231 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29232 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29233 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29234 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29235 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29236 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29237 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29238 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29239 		{ "outDrops",		KSTAT_DATA_UINT32 },
29240 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29241 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29242 	};
29243 
29244 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29245 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29246 	if (ksp == NULL || ksp->ks_data == NULL)
29247 		return (NULL);
29248 
29249 	bcopy(&template, ksp->ks_data, sizeof (template));
29250 
29251 	ksp->ks_update = icmp_kstat_update;
29252 	ksp->ks_private = (void *)(uintptr_t)stackid;
29253 
29254 	kstat_install(ksp);
29255 	return (ksp);
29256 }
29257 
29258 static void
29259 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29260 {
29261 	if (ksp != NULL) {
29262 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29263 		kstat_delete_netstack(ksp, stackid);
29264 	}
29265 }
29266 
29267 static int
29268 icmp_kstat_update(kstat_t *kp, int rw)
29269 {
29270 	icmp_named_kstat_t *icmpkp;
29271 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29272 	netstack_t	*ns;
29273 	ip_stack_t	*ipst;
29274 
29275 	if ((kp == NULL) || (kp->ks_data == NULL))
29276 		return (EIO);
29277 
29278 	if (rw == KSTAT_WRITE)
29279 		return (EACCES);
29280 
29281 	ns = netstack_find_by_stackid(stackid);
29282 	if (ns == NULL)
29283 		return (-1);
29284 	ipst = ns->netstack_ip;
29285 	if (ipst == NULL) {
29286 		netstack_rele(ns);
29287 		return (-1);
29288 	}
29289 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29290 
29291 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29292 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29293 	icmpkp->inDestUnreachs.value.ui32 =
29294 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29295 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29296 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29297 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29298 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29299 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29300 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29301 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29302 	icmpkp->inTimestampReps.value.ui32 =
29303 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29304 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29305 	icmpkp->inAddrMaskReps.value.ui32 =
29306 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29307 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29308 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29309 	icmpkp->outDestUnreachs.value.ui32 =
29310 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29311 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29312 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29313 	icmpkp->outSrcQuenchs.value.ui32 =
29314 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29315 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29316 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29317 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29318 	icmpkp->outTimestamps.value.ui32 =
29319 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29320 	icmpkp->outTimestampReps.value.ui32 =
29321 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29322 	icmpkp->outAddrMasks.value.ui32 =
29323 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29324 	icmpkp->outAddrMaskReps.value.ui32 =
29325 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29326 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29327 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29328 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29329 	icmpkp->outFragNeeded.value.ui32 =
29330 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29331 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29332 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29333 	icmpkp->inBadRedirects.value.ui32 =
29334 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29335 
29336 	netstack_rele(ns);
29337 	return (0);
29338 }
29339 
29340 /*
29341  * This is the fanout function for raw socket opened for SCTP.  Note
29342  * that it is called after SCTP checks that there is no socket which
29343  * wants a packet.  Then before SCTP handles this out of the blue packet,
29344  * this function is called to see if there is any raw socket for SCTP.
29345  * If there is and it is bound to the correct address, the packet will
29346  * be sent to that socket.  Note that only one raw socket can be bound to
29347  * a port.  This is assured in ipcl_sctp_hash_insert();
29348  */
29349 void
29350 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29351     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29352     zoneid_t zoneid)
29353 {
29354 	conn_t		*connp;
29355 	queue_t		*rq;
29356 	mblk_t		*first_mp;
29357 	boolean_t	secure;
29358 	ip6_t		*ip6h;
29359 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29360 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29361 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29362 	boolean_t	sctp_csum_err = B_FALSE;
29363 
29364 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29365 		sctp_csum_err = B_TRUE;
29366 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29367 	}
29368 
29369 	first_mp = mp;
29370 	if (mctl_present) {
29371 		mp = first_mp->b_cont;
29372 		secure = ipsec_in_is_secure(first_mp);
29373 		ASSERT(mp != NULL);
29374 	} else {
29375 		secure = B_FALSE;
29376 	}
29377 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29378 
29379 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29380 	if (connp == NULL) {
29381 		/*
29382 		 * Although raw sctp is not summed, OOB chunks must be.
29383 		 * Drop the packet here if the sctp checksum failed.
29384 		 */
29385 		if (sctp_csum_err) {
29386 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29387 			freemsg(first_mp);
29388 			return;
29389 		}
29390 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29391 		return;
29392 	}
29393 	rq = connp->conn_rq;
29394 	if (!canputnext(rq)) {
29395 		CONN_DEC_REF(connp);
29396 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29397 		freemsg(first_mp);
29398 		return;
29399 	}
29400 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29401 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29402 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29403 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29404 		if (first_mp == NULL) {
29405 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29406 			CONN_DEC_REF(connp);
29407 			return;
29408 		}
29409 	}
29410 	/*
29411 	 * We probably should not send M_CTL message up to
29412 	 * raw socket.
29413 	 */
29414 	if (mctl_present)
29415 		freeb(first_mp);
29416 
29417 	/* Initiate IPPF processing here if needed. */
29418 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29419 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29420 		ip_process(IPP_LOCAL_IN, &mp,
29421 		    recv_ill->ill_phyint->phyint_ifindex);
29422 		if (mp == NULL) {
29423 			CONN_DEC_REF(connp);
29424 			return;
29425 		}
29426 	}
29427 
29428 	if (connp->conn_recvif || connp->conn_recvslla ||
29429 	    ((connp->conn_ip_recvpktinfo ||
29430 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29431 	    (flags & IP_FF_IPINFO))) {
29432 		int in_flags = 0;
29433 
29434 		/*
29435 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29436 		 * IPF_RECVIF.
29437 		 */
29438 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29439 			in_flags = IPF_RECVIF;
29440 		}
29441 		if (connp->conn_recvslla) {
29442 			in_flags |= IPF_RECVSLLA;
29443 		}
29444 		if (isv4) {
29445 			mp = ip_add_info(mp, recv_ill, in_flags,
29446 			    IPCL_ZONEID(connp), ipst);
29447 		} else {
29448 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29449 			if (mp == NULL) {
29450 				BUMP_MIB(recv_ill->ill_ip_mib,
29451 				    ipIfStatsInDiscards);
29452 				CONN_DEC_REF(connp);
29453 				return;
29454 			}
29455 		}
29456 	}
29457 
29458 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29459 	/*
29460 	 * We are sending the IPSEC_IN message also up. Refer
29461 	 * to comments above this function.
29462 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29463 	 */
29464 	(connp->conn_recv)(connp, mp, NULL);
29465 	CONN_DEC_REF(connp);
29466 }
29467 
29468 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29469 {									\
29470 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29471 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29472 }
29473 /*
29474  * This function should be called only if all packet processing
29475  * including fragmentation is complete. Callers of this function
29476  * must set mp->b_prev to one of these values:
29477  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29478  * prior to handing over the mp as first argument to this function.
29479  *
29480  * If the ire passed by caller is incomplete, this function
29481  * queues the packet and if necessary, sends ARP request and bails.
29482  * If the ire passed is fully resolved, we simply prepend
29483  * the link-layer header to the packet, do ipsec hw acceleration
29484  * work if necessary, and send the packet out on the wire.
29485  *
29486  * NOTE: IPsec will only call this function with fully resolved
29487  * ires if hw acceleration is involved.
29488  * TODO list :
29489  * 	a Handle M_MULTIDATA so that
29490  *	  tcp_multisend->tcp_multisend_data can
29491  *	  call ip_xmit_v4 directly
29492  *	b Handle post-ARP work for fragments so that
29493  *	  ip_wput_frag can call this function.
29494  */
29495 ipxmit_state_t
29496 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29497     boolean_t flow_ctl_enabled, conn_t *connp)
29498 {
29499 	nce_t		*arpce;
29500 	ipha_t		*ipha;
29501 	queue_t		*q;
29502 	int		ill_index;
29503 	mblk_t		*nxt_mp, *first_mp;
29504 	boolean_t	xmit_drop = B_FALSE;
29505 	ip_proc_t	proc;
29506 	ill_t		*out_ill;
29507 	int		pkt_len;
29508 
29509 	arpce = ire->ire_nce;
29510 	ASSERT(arpce != NULL);
29511 
29512 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29513 
29514 	mutex_enter(&arpce->nce_lock);
29515 	switch (arpce->nce_state) {
29516 	case ND_REACHABLE:
29517 		/* If there are other queued packets, queue this packet */
29518 		if (arpce->nce_qd_mp != NULL) {
29519 			if (mp != NULL)
29520 				nce_queue_mp_common(arpce, mp, B_FALSE);
29521 			mp = arpce->nce_qd_mp;
29522 		}
29523 		arpce->nce_qd_mp = NULL;
29524 		mutex_exit(&arpce->nce_lock);
29525 
29526 		/*
29527 		 * Flush the queue.  In the common case, where the
29528 		 * ARP is already resolved,  it will go through the
29529 		 * while loop only once.
29530 		 */
29531 		while (mp != NULL) {
29532 
29533 			nxt_mp = mp->b_next;
29534 			mp->b_next = NULL;
29535 			ASSERT(mp->b_datap->db_type != M_CTL);
29536 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29537 			/*
29538 			 * This info is needed for IPQOS to do COS marking
29539 			 * in ip_wput_attach_llhdr->ip_process.
29540 			 */
29541 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29542 			mp->b_prev = NULL;
29543 
29544 			/* set up ill index for outbound qos processing */
29545 			out_ill = ire_to_ill(ire);
29546 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29547 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29548 			    ill_index, &ipha);
29549 			if (first_mp == NULL) {
29550 				xmit_drop = B_TRUE;
29551 				BUMP_MIB(out_ill->ill_ip_mib,
29552 				    ipIfStatsOutDiscards);
29553 				goto next_mp;
29554 			}
29555 
29556 			/* non-ipsec hw accel case */
29557 			if (io == NULL || !io->ipsec_out_accelerated) {
29558 				/* send it */
29559 				q = ire->ire_stq;
29560 				if (proc == IPP_FWD_OUT) {
29561 					UPDATE_IB_PKT_COUNT(ire);
29562 				} else {
29563 					UPDATE_OB_PKT_COUNT(ire);
29564 				}
29565 				ire->ire_last_used_time = lbolt;
29566 
29567 				if (flow_ctl_enabled || canputnext(q)) {
29568 					if (proc == IPP_FWD_OUT) {
29569 
29570 					BUMP_MIB(out_ill->ill_ip_mib,
29571 					    ipIfStatsHCOutForwDatagrams);
29572 
29573 					}
29574 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29575 					    pkt_len);
29576 
29577 					DTRACE_IP7(send, mblk_t *, first_mp,
29578 					    conn_t *, NULL, void_ip_t *, ipha,
29579 					    __dtrace_ipsr_ill_t *, out_ill,
29580 					    ipha_t *, ipha, ip6_t *, NULL, int,
29581 					    0);
29582 
29583 					ILL_SEND_TX(out_ill,
29584 					    ire, connp, first_mp, 0, connp);
29585 				} else {
29586 					BUMP_MIB(out_ill->ill_ip_mib,
29587 					    ipIfStatsOutDiscards);
29588 					xmit_drop = B_TRUE;
29589 					freemsg(first_mp);
29590 				}
29591 			} else {
29592 				/*
29593 				 * Safety Pup says: make sure this
29594 				 *  is going to the right interface!
29595 				 */
29596 				ill_t *ill1 =
29597 				    (ill_t *)ire->ire_stq->q_ptr;
29598 				int ifindex =
29599 				    ill1->ill_phyint->phyint_ifindex;
29600 				if (ifindex !=
29601 				    io->ipsec_out_capab_ill_index) {
29602 					xmit_drop = B_TRUE;
29603 					freemsg(mp);
29604 				} else {
29605 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29606 					    pkt_len);
29607 
29608 					DTRACE_IP7(send, mblk_t *, first_mp,
29609 					    conn_t *, NULL, void_ip_t *, ipha,
29610 					    __dtrace_ipsr_ill_t *, ill1,
29611 					    ipha_t *, ipha, ip6_t *, NULL,
29612 					    int, 0);
29613 
29614 					ipsec_hw_putnext(ire->ire_stq, mp);
29615 				}
29616 			}
29617 next_mp:
29618 			mp = nxt_mp;
29619 		} /* while (mp != NULL) */
29620 		if (xmit_drop)
29621 			return (SEND_FAILED);
29622 		else
29623 			return (SEND_PASSED);
29624 
29625 	case ND_INITIAL:
29626 	case ND_INCOMPLETE:
29627 
29628 		/*
29629 		 * While we do send off packets to dests that
29630 		 * use fully-resolved CGTP routes, we do not
29631 		 * handle unresolved CGTP routes.
29632 		 */
29633 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29634 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29635 
29636 		if (mp != NULL) {
29637 			/* queue the packet */
29638 			nce_queue_mp_common(arpce, mp, B_FALSE);
29639 		}
29640 
29641 		if (arpce->nce_state == ND_INCOMPLETE) {
29642 			mutex_exit(&arpce->nce_lock);
29643 			DTRACE_PROBE3(ip__xmit__incomplete,
29644 			    (ire_t *), ire, (mblk_t *), mp,
29645 			    (ipsec_out_t *), io);
29646 			return (LOOKUP_IN_PROGRESS);
29647 		}
29648 
29649 		arpce->nce_state = ND_INCOMPLETE;
29650 		mutex_exit(&arpce->nce_lock);
29651 
29652 		/*
29653 		 * Note that ire_add() (called from ire_forward())
29654 		 * holds a ref on the ire until ARP is completed.
29655 		 */
29656 		ire_arpresolve(ire);
29657 		return (LOOKUP_IN_PROGRESS);
29658 	default:
29659 		ASSERT(0);
29660 		mutex_exit(&arpce->nce_lock);
29661 		return (LLHDR_RESLV_FAILED);
29662 	}
29663 }
29664 
29665 #undef	UPDATE_IP_MIB_OB_COUNTERS
29666 
29667 /*
29668  * Return B_TRUE if the buffers differ in length or content.
29669  * This is used for comparing extension header buffers.
29670  * Note that an extension header would be declared different
29671  * even if all that changed was the next header value in that header i.e.
29672  * what really changed is the next extension header.
29673  */
29674 boolean_t
29675 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29676     uint_t blen)
29677 {
29678 	if (!b_valid)
29679 		blen = 0;
29680 
29681 	if (alen != blen)
29682 		return (B_TRUE);
29683 	if (alen == 0)
29684 		return (B_FALSE);	/* Both zero length */
29685 	return (bcmp(abuf, bbuf, alen));
29686 }
29687 
29688 /*
29689  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29690  * Return B_FALSE if memory allocation fails - don't change any state!
29691  */
29692 boolean_t
29693 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29694     const void *src, uint_t srclen)
29695 {
29696 	void *dst;
29697 
29698 	if (!src_valid)
29699 		srclen = 0;
29700 
29701 	ASSERT(*dstlenp == 0);
29702 	if (src != NULL && srclen != 0) {
29703 		dst = mi_alloc(srclen, BPRI_MED);
29704 		if (dst == NULL)
29705 			return (B_FALSE);
29706 	} else {
29707 		dst = NULL;
29708 	}
29709 	if (*dstp != NULL)
29710 		mi_free(*dstp);
29711 	*dstp = dst;
29712 	*dstlenp = dst == NULL ? 0 : srclen;
29713 	return (B_TRUE);
29714 }
29715 
29716 /*
29717  * Replace what is in *dst, *dstlen with the source.
29718  * Assumes ip_allocbuf has already been called.
29719  */
29720 void
29721 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29722     const void *src, uint_t srclen)
29723 {
29724 	if (!src_valid)
29725 		srclen = 0;
29726 
29727 	ASSERT(*dstlenp == srclen);
29728 	if (src != NULL && srclen != 0)
29729 		bcopy(src, *dstp, srclen);
29730 }
29731 
29732 /*
29733  * Free the storage pointed to by the members of an ip6_pkt_t.
29734  */
29735 void
29736 ip6_pkt_free(ip6_pkt_t *ipp)
29737 {
29738 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29739 
29740 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29741 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29742 		ipp->ipp_hopopts = NULL;
29743 		ipp->ipp_hopoptslen = 0;
29744 	}
29745 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29746 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29747 		ipp->ipp_rtdstopts = NULL;
29748 		ipp->ipp_rtdstoptslen = 0;
29749 	}
29750 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29751 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29752 		ipp->ipp_dstopts = NULL;
29753 		ipp->ipp_dstoptslen = 0;
29754 	}
29755 	if (ipp->ipp_fields & IPPF_RTHDR) {
29756 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29757 		ipp->ipp_rthdr = NULL;
29758 		ipp->ipp_rthdrlen = 0;
29759 	}
29760 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29761 	    IPPF_RTHDR);
29762 }
29763 
29764 zoneid_t
29765 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29766     zoneid_t lookup_zoneid)
29767 {
29768 	ire_t		*ire;
29769 	int		ire_flags = MATCH_IRE_TYPE;
29770 	zoneid_t	zoneid = ALL_ZONES;
29771 
29772 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29773 		return (ALL_ZONES);
29774 
29775 	if (lookup_zoneid != ALL_ZONES)
29776 		ire_flags |= MATCH_IRE_ZONEONLY;
29777 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29778 	    lookup_zoneid, NULL, ire_flags, ipst);
29779 	if (ire != NULL) {
29780 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29781 		ire_refrele(ire);
29782 	}
29783 	return (zoneid);
29784 }
29785 
29786 zoneid_t
29787 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29788     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29789 {
29790 	ire_t		*ire;
29791 	int		ire_flags = MATCH_IRE_TYPE;
29792 	zoneid_t	zoneid = ALL_ZONES;
29793 	ipif_t		*ipif_arg = NULL;
29794 
29795 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29796 		return (ALL_ZONES);
29797 
29798 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29799 		ire_flags |= MATCH_IRE_ILL;
29800 		ipif_arg = ill->ill_ipif;
29801 	}
29802 	if (lookup_zoneid != ALL_ZONES)
29803 		ire_flags |= MATCH_IRE_ZONEONLY;
29804 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29805 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29806 	if (ire != NULL) {
29807 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29808 		ire_refrele(ire);
29809 	}
29810 	return (zoneid);
29811 }
29812 
29813 /*
29814  * IP obserability hook support functions.
29815  */
29816 static void
29817 ipobs_init(ip_stack_t *ipst)
29818 {
29819 	netid_t id;
29820 
29821 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
29822 
29823 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
29824 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
29825 
29826 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
29827 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
29828 }
29829 
29830 static void
29831 ipobs_fini(ip_stack_t *ipst)
29832 {
29833 
29834 	net_protocol_release(ipst->ips_ip4_observe_pr);
29835 	net_protocol_release(ipst->ips_ip6_observe_pr);
29836 }
29837 
29838 /*
29839  * hook_pkt_observe_t is composed in network byte order so that the
29840  * entire mblk_t chain handed into hook_run can be used as-is.
29841  * The caveat is that use of the fields, such as the zone fields,
29842  * requires conversion into host byte order first.
29843  */
29844 void
29845 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
29846     const ill_t *ill, ip_stack_t *ipst)
29847 {
29848 	hook_pkt_observe_t *hdr;
29849 	uint64_t grifindex;
29850 	mblk_t *imp;
29851 
29852 	imp = allocb(sizeof (*hdr), BPRI_HI);
29853 	if (imp == NULL)
29854 		return;
29855 
29856 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
29857 	/*
29858 	 * b_wptr is set to make the apparent size of the data in the mblk_t
29859 	 * to exclude the pointers at the end of hook_pkt_observer_t.
29860 	 */
29861 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
29862 	imp->b_cont = mp;
29863 
29864 	ASSERT(DB_TYPE(mp) == M_DATA);
29865 
29866 	if (IS_UNDER_IPMP(ill))
29867 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
29868 	else
29869 		grifindex = 0;
29870 
29871 	hdr->hpo_version = 1;
29872 	hdr->hpo_htype = htype;
29873 	hdr->hpo_pktlen = htons((ushort_t)msgdsize(mp));
29874 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
29875 	hdr->hpo_grifindex = htonl(grifindex);
29876 	hdr->hpo_zsrc = htonl(zsrc);
29877 	hdr->hpo_zdst = htonl(zdst);
29878 	hdr->hpo_pkt = imp;
29879 	hdr->hpo_ctx = ipst->ips_netstack;
29880 
29881 	if (ill->ill_isv6) {
29882 		hdr->hpo_family = AF_INET6;
29883 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
29884 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
29885 	} else {
29886 		hdr->hpo_family = AF_INET;
29887 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
29888 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
29889 	}
29890 
29891 	imp->b_cont = NULL;
29892 	freemsg(imp);
29893 }
29894