xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 524b24f9)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
823     zoneid_t);
824 static void	conn_setqfull(conn_t *);
825 static void	conn_clrqfull(conn_t *);
826 
827 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
828 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
829 static void	ip_stack_fini(netstackid_t stackid, void *arg);
830 
831 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
832     zoneid_t);
833 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
834     void *dummy_arg);
835 
836 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
837 
838 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
839     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
840     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
841 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
842 
843 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
844 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
845     caddr_t, cred_t *);
846 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
847     cred_t *, boolean_t);
848 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
849     caddr_t cp, cred_t *cr);
850 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
851     cred_t *);
852 static int	ip_squeue_switch(int);
853 
854 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
855 static void	ip_kstat_fini(netstackid_t, kstat_t *);
856 static int	ip_kstat_update(kstat_t *kp, int rw);
857 static void	*icmp_kstat_init(netstackid_t);
858 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
859 static int	icmp_kstat_update(kstat_t *kp, int rw);
860 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
861 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
862 
863 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
864 
865 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
866     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
867 
868 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
869     ipha_t *, ill_t *, boolean_t, boolean_t);
870 
871 static void ipobs_init(ip_stack_t *);
872 static void ipobs_fini(ip_stack_t *);
873 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
874 
875 /* How long, in seconds, we allow frags to hang around. */
876 #define	IP_FRAG_TIMEOUT	15
877 
878 /*
879  * Threshold which determines whether MDT should be used when
880  * generating IP fragments; payload size must be greater than
881  * this threshold for MDT to take place.
882  */
883 #define	IP_WPUT_FRAG_MDT_MIN	32768
884 
885 /* Setable in /etc/system only */
886 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
887 
888 static long ip_rput_pullups;
889 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
890 
891 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
892 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
893 
894 int	ip_debug;
895 
896 #ifdef DEBUG
897 uint32_t ipsechw_debug = 0;
898 #endif
899 
900 /*
901  * Multirouting/CGTP stuff
902  */
903 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
904 
905 /*
906  * XXX following really should only be in a header. Would need more
907  * header and .c clean up first.
908  */
909 extern optdb_obj_t	ip_opt_obj;
910 
911 ulong_t ip_squeue_enter_unbound = 0;
912 
913 /*
914  * Named Dispatch Parameter Table.
915  * All of these are alterable, within the min/max values given, at run time.
916  */
917 static ipparam_t	lcl_param_arr[] = {
918 	/* min	max	value	name */
919 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
920 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
921 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
922 	{  0,	1,	0,	"ip_respond_to_timestamp"},
923 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
924 	{  0,	1,	1,	"ip_send_redirects"},
925 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
926 	{  0,	10,	0,	"ip_mrtdebug"},
927 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
928 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
929 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
930 	{  1,	255,	255,	"ip_def_ttl" },
931 	{  0,	1,	0,	"ip_forward_src_routed"},
932 	{  0,	256,	32,	"ip_wroff_extra" },
933 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
934 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
935 	{  0,	1,	1,	"ip_path_mtu_discovery" },
936 	{  0,	240,	30,	"ip_ignore_delete_time" },
937 	{  0,	1,	0,	"ip_ignore_redirect" },
938 	{  0,	1,	1,	"ip_output_queue" },
939 	{  1,	254,	1,	"ip_broadcast_ttl" },
940 	{  0,	99999,	100,	"ip_icmp_err_interval" },
941 	{  1,	99999,	10,	"ip_icmp_err_burst" },
942 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
943 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
944 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
945 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
946 	{  0,	1,	1,	"icmp_accept_clear_messages" },
947 	{  0,	1,	1,	"igmp_accept_clear_messages" },
948 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
949 				"ip_ndp_delay_first_probe_time"},
950 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
951 				"ip_ndp_max_unicast_solicit"},
952 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
953 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
954 	{  0,	1,	0,	"ip6_forward_src_routed"},
955 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
956 	{  0,	1,	1,	"ip6_send_redirects"},
957 	{  0,	1,	0,	"ip6_ignore_redirect" },
958 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
959 
960 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
961 
962 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
963 
964 	{  0,	1,	1,	"pim_accept_clear_messages" },
965 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
966 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
967 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
968 	{  0,	15,	0,	"ip_policy_mask" },
969 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
970 	{  0,	255,	1,	"ip_multirt_ttl" },
971 	{  0,	1,	1,	"ip_multidata_outbound" },
972 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
973 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
974 	{  0,	1000,	1,	"ip_max_temp_defend" },
975 	{  0,	1000,	3,	"ip_max_defend" },
976 	{  0,	999999,	30,	"ip_defend_interval" },
977 	{  0,	3600000, 300000, "ip_dup_recovery" },
978 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
979 	{  0,	1,	1,	"ip_lso_outbound" },
980 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
981 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
982 	{ 68,	65535,	576,	"ip_pmtu_min" },
983 #ifdef DEBUG
984 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
985 #else
986 	{  0,	0,	0,	"" },
987 #endif
988 };
989 
990 /*
991  * Extended NDP table
992  * The addresses for the first two are filled in to be ips_ip_g_forward
993  * and ips_ipv6_forward at init time.
994  */
995 static ipndp_t	lcl_ndp_arr[] = {
996 	/* getf			setf		data			name */
997 #define	IPNDP_IP_FORWARDING_OFFSET	0
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip_forwarding" },
1000 #define	IPNDP_IP6_FORWARDING_OFFSET	1
1001 	{  ip_param_generic_get,	ip_forward_set,	NULL,
1002 	    "ip6_forwarding" },
1003 	{  ip_ill_report,	NULL,		NULL,
1004 	    "ip_ill_status" },
1005 	{  ip_ipif_report,	NULL,		NULL,
1006 	    "ip_ipif_status" },
1007 	{  ip_conn_report,	NULL,		NULL,
1008 	    "ip_conn_status" },
1009 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1010 	    "ip_rput_pullups" },
1011 	{  ip_srcid_report,	NULL,		NULL,
1012 	    "ip_srcid_status" },
1013 	{ ip_param_generic_get, ip_input_proc_set,
1014 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1015 	{ ip_param_generic_get, ip_int_set,
1016 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1017 #define	IPNDP_CGTP_FILTER_OFFSET	9
1018 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1019 	    "ip_cgtp_filter" },
1020 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1021 	    "ip_debug" },
1022 };
1023 
1024 /*
1025  * Table of IP ioctls encoding the various properties of the ioctl and
1026  * indexed based on the last byte of the ioctl command. Occasionally there
1027  * is a clash, and there is more than 1 ioctl with the same last byte.
1028  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1029  * ioctls are encoded in the misc table. An entry in the ndx table is
1030  * retrieved by indexing on the last byte of the ioctl command and comparing
1031  * the ioctl command with the value in the ndx table. In the event of a
1032  * mismatch the misc table is then searched sequentially for the desired
1033  * ioctl command.
1034  *
1035  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1036  */
1037 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1038 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 
1049 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1050 			MISC_CMD, ip_siocaddrt, NULL },
1051 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1052 			MISC_CMD, ip_siocdelrt, NULL },
1053 
1054 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1055 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1056 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1057 			IF_CMD, ip_sioctl_get_addr, NULL },
1058 
1059 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1060 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1061 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1062 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1063 
1064 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1065 			IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1067 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1068 			IPI_MODOK | IPI_GET_CMD,
1069 			IF_CMD, ip_sioctl_get_flags, NULL },
1070 
1071 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 
1074 	/* copyin size cannot be coded for SIOCGIFCONF */
1075 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1076 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1077 
1078 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1079 			IF_CMD, ip_sioctl_mtu, NULL },
1080 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1081 			IF_CMD, ip_sioctl_get_mtu, NULL },
1082 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1083 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1084 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1085 			IF_CMD, ip_sioctl_brdaddr, NULL },
1086 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1087 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1088 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1089 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1090 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1091 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1092 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1093 			IF_CMD, ip_sioctl_metric, NULL },
1094 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 
1096 	/* See 166-168 below for extended SIOC*XARP ioctls */
1097 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1098 			ARP_CMD, ip_sioctl_arp, NULL },
1099 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1100 			ARP_CMD, ip_sioctl_arp, NULL },
1101 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1102 			ARP_CMD, ip_sioctl_arp, NULL },
1103 
1104 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 
1126 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1127 			MISC_CMD, if_unitsel, if_unitsel_restart },
1128 
1129 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 
1148 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1149 			IPI_PRIV | IPI_WR | IPI_MODOK,
1150 			IF_CMD, ip_sioctl_sifname, NULL },
1151 
1152 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 
1166 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1167 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1168 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1169 			IF_CMD, ip_sioctl_get_muxid, NULL },
1170 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1171 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1172 
1173 	/* Both if and lif variants share same func */
1174 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1175 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1176 	/* Both if and lif variants share same func */
1177 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1178 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1179 
1180 	/* copyin size cannot be coded for SIOCGIFCONF */
1181 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1182 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1183 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 
1201 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1202 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1203 			ip_sioctl_removeif_restart },
1204 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1205 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1206 			LIF_CMD, ip_sioctl_addif, NULL },
1207 #define	SIOCLIFADDR_NDX 112
1208 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1209 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1210 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1211 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1212 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1213 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1214 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1215 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1216 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1217 			IPI_PRIV | IPI_WR,
1218 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1219 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1220 			IPI_GET_CMD | IPI_MODOK,
1221 			LIF_CMD, ip_sioctl_get_flags, NULL },
1222 
1223 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 
1226 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1227 			ip_sioctl_get_lifconf, NULL },
1228 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_mtu, NULL },
1230 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1231 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1232 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1233 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1234 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1235 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1236 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1237 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1238 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1239 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1240 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1241 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1242 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 			LIF_CMD, ip_sioctl_metric, NULL },
1244 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR | IPI_MODOK,
1246 			LIF_CMD, ip_sioctl_slifname,
1247 			ip_sioctl_slifname_restart },
1248 
1249 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1250 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1251 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1252 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1253 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1255 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1256 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1257 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1258 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1259 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1260 			LIF_CMD, ip_sioctl_token, NULL },
1261 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1262 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1263 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1264 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1265 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1266 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1267 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1268 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1269 
1270 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1271 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1272 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1273 			LIF_CMD, ip_siocdelndp_v6, NULL },
1274 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1275 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1276 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1277 			LIF_CMD, ip_siocsetndp_v6, NULL },
1278 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1279 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1280 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1281 			MISC_CMD, ip_sioctl_tonlink, NULL },
1282 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1283 			MISC_CMD, ip_sioctl_tmysite, NULL },
1284 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1285 			TUN_CMD, ip_sioctl_tunparam, NULL },
1286 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1287 		    IPI_PRIV | IPI_WR,
1288 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1289 
1290 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1291 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1292 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1293 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1294 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1295 
1296 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 
1298 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1299 			LIF_CMD, ip_sioctl_get_binding, NULL },
1300 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR,
1302 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1303 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1304 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1305 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1306 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1307 
1308 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1309 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1310 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1311 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1312 
1313 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1314 
1315 	/* These are handled in ip_sioctl_copyin_setup itself */
1316 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1317 			MISC_CMD, NULL, NULL },
1318 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1319 			MISC_CMD, NULL, NULL },
1320 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1321 
1322 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1323 			ip_sioctl_get_lifconf, NULL },
1324 
1325 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1326 			XARP_CMD, ip_sioctl_arp, NULL },
1327 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1328 			XARP_CMD, ip_sioctl_arp, NULL },
1329 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1330 			XARP_CMD, ip_sioctl_arp, NULL },
1331 
1332 	/* SIOCPOPSOCKFS is not handled by IP */
1333 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1334 
1335 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1336 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1337 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1338 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1339 			ip_sioctl_slifzone_restart },
1340 	/* 172-174 are SCTP ioctls and not handled by IP */
1341 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1342 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1343 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1344 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1345 			IPI_GET_CMD, LIF_CMD,
1346 			ip_sioctl_get_lifusesrc, 0 },
1347 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1348 			IPI_PRIV | IPI_WR,
1349 			LIF_CMD, ip_sioctl_slifusesrc,
1350 			NULL },
1351 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1352 			ip_sioctl_get_lifsrcof, NULL },
1353 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1354 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1355 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1356 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1357 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1358 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1359 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1360 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1361 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* SIOCSENABLESDP is handled by SDP */
1363 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1364 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1365 };
1366 
1367 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1368 
1369 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1370 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1371 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1372 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1373 		TUN_CMD, ip_sioctl_tunparam, NULL },
1374 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1375 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1376 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1377 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1378 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1379 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1380 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1381 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1382 		MISC_CMD, mrt_ioctl},
1383 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1384 		MISC_CMD, mrt_ioctl},
1385 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1386 		MISC_CMD, mrt_ioctl}
1387 };
1388 
1389 int ip_misc_ioctl_count =
1390     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1391 
1392 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1393 					/* Settable in /etc/system */
1394 /* Defined in ip_ire.c */
1395 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1396 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1397 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1398 
1399 static nv_t	ire_nv_arr[] = {
1400 	{ IRE_BROADCAST, "BROADCAST" },
1401 	{ IRE_LOCAL, "LOCAL" },
1402 	{ IRE_LOOPBACK, "LOOPBACK" },
1403 	{ IRE_CACHE, "CACHE" },
1404 	{ IRE_DEFAULT, "DEFAULT" },
1405 	{ IRE_PREFIX, "PREFIX" },
1406 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1407 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1408 	{ IRE_HOST, "HOST" },
1409 	{ 0 }
1410 };
1411 
1412 nv_t	*ire_nv_tbl = ire_nv_arr;
1413 
1414 /* Simple ICMP IP Header Template */
1415 static ipha_t icmp_ipha = {
1416 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1417 };
1418 
1419 struct module_info ip_mod_info = {
1420 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1421 	IP_MOD_LOWAT
1422 };
1423 
1424 /*
1425  * Duplicate static symbols within a module confuses mdb; so we avoid the
1426  * problem by making the symbols here distinct from those in udp.c.
1427  */
1428 
1429 /*
1430  * Entry points for IP as a device and as a module.
1431  * FIXME: down the road we might want a separate module and driver qinit.
1432  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1433  */
1434 static struct qinit iprinitv4 = {
1435 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1436 	&ip_mod_info
1437 };
1438 
1439 struct qinit iprinitv6 = {
1440 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1441 	&ip_mod_info
1442 };
1443 
1444 static struct qinit ipwinitv4 = {
1445 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1446 	&ip_mod_info
1447 };
1448 
1449 struct qinit ipwinitv6 = {
1450 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1451 	&ip_mod_info
1452 };
1453 
1454 static struct qinit iplrinit = {
1455 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1456 	&ip_mod_info
1457 };
1458 
1459 static struct qinit iplwinit = {
1460 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1461 	&ip_mod_info
1462 };
1463 
1464 /* For AF_INET aka /dev/ip */
1465 struct streamtab ipinfov4 = {
1466 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1467 };
1468 
1469 /* For AF_INET6 aka /dev/ip6 */
1470 struct streamtab ipinfov6 = {
1471 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1472 };
1473 
1474 #ifdef	DEBUG
1475 static boolean_t skip_sctp_cksum = B_FALSE;
1476 #endif
1477 
1478 /*
1479  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1480  * ip_rput_v6(), ip_output(), etc.  If the message
1481  * block already has a M_CTL at the front of it, then simply set the zoneid
1482  * appropriately.
1483  */
1484 mblk_t *
1485 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1486 {
1487 	mblk_t		*first_mp;
1488 	ipsec_out_t	*io;
1489 
1490 	ASSERT(zoneid != ALL_ZONES);
1491 	if (mp->b_datap->db_type == M_CTL) {
1492 		io = (ipsec_out_t *)mp->b_rptr;
1493 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1494 		io->ipsec_out_zoneid = zoneid;
1495 		return (mp);
1496 	}
1497 
1498 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1499 	if (first_mp == NULL)
1500 		return (NULL);
1501 	io = (ipsec_out_t *)first_mp->b_rptr;
1502 	/* This is not a secure packet */
1503 	io->ipsec_out_secure = B_FALSE;
1504 	io->ipsec_out_zoneid = zoneid;
1505 	first_mp->b_cont = mp;
1506 	return (first_mp);
1507 }
1508 
1509 /*
1510  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1511  */
1512 mblk_t *
1513 ip_copymsg(mblk_t *mp)
1514 {
1515 	mblk_t *nmp;
1516 	ipsec_info_t *in;
1517 
1518 	if (mp->b_datap->db_type != M_CTL)
1519 		return (copymsg(mp));
1520 
1521 	in = (ipsec_info_t *)mp->b_rptr;
1522 
1523 	/*
1524 	 * Note that M_CTL is also used for delivering ICMP error messages
1525 	 * upstream to transport layers.
1526 	 */
1527 	if (in->ipsec_info_type != IPSEC_OUT &&
1528 	    in->ipsec_info_type != IPSEC_IN)
1529 		return (copymsg(mp));
1530 
1531 	nmp = copymsg(mp->b_cont);
1532 
1533 	if (in->ipsec_info_type == IPSEC_OUT) {
1534 		return (ipsec_out_tag(mp, nmp,
1535 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1536 	} else {
1537 		return (ipsec_in_tag(mp, nmp,
1538 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1539 	}
1540 }
1541 
1542 /* Generate an ICMP fragmentation needed message. */
1543 static void
1544 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1545     ip_stack_t *ipst)
1546 {
1547 	icmph_t	icmph;
1548 	mblk_t *first_mp;
1549 	boolean_t mctl_present;
1550 
1551 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1552 
1553 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1554 		if (mctl_present)
1555 			freeb(first_mp);
1556 		return;
1557 	}
1558 
1559 	bzero(&icmph, sizeof (icmph_t));
1560 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1561 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1562 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1563 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1564 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1565 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1566 	    ipst);
1567 }
1568 
1569 /*
1570  * icmp_inbound deals with ICMP messages in the following ways.
1571  *
1572  * 1) It needs to send a reply back and possibly delivering it
1573  *    to the "interested" upper clients.
1574  * 2) It needs to send it to the upper clients only.
1575  * 3) It needs to change some values in IP only.
1576  * 4) It needs to change some values in IP and upper layers e.g TCP.
1577  *
1578  * We need to accomodate icmp messages coming in clear until we get
1579  * everything secure from the wire. If icmp_accept_clear_messages
1580  * is zero we check with the global policy and act accordingly. If
1581  * it is non-zero, we accept the message without any checks. But
1582  * *this does not mean* that this will be delivered to the upper
1583  * clients. By accepting we might send replies back, change our MTU
1584  * value etc. but delivery to the ULP/clients depends on their policy
1585  * dispositions.
1586  *
1587  * We handle the above 4 cases in the context of IPsec in the
1588  * following way :
1589  *
1590  * 1) Send the reply back in the same way as the request came in.
1591  *    If it came in encrypted, it goes out encrypted. If it came in
1592  *    clear, it goes out in clear. Thus, this will prevent chosen
1593  *    plain text attack.
1594  * 2) The client may or may not expect things to come in secure.
1595  *    If it comes in secure, the policy constraints are checked
1596  *    before delivering it to the upper layers. If it comes in
1597  *    clear, ipsec_inbound_accept_clear will decide whether to
1598  *    accept this in clear or not. In both the cases, if the returned
1599  *    message (IP header + 8 bytes) that caused the icmp message has
1600  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1601  *    sending up. If there are only 8 bytes of returned message, then
1602  *    upper client will not be notified.
1603  * 3) Check with global policy to see whether it matches the constaints.
1604  *    But this will be done only if icmp_accept_messages_in_clear is
1605  *    zero.
1606  * 4) If we need to change both in IP and ULP, then the decision taken
1607  *    while affecting the values in IP and while delivering up to TCP
1608  *    should be the same.
1609  *
1610  * 	There are two cases.
1611  *
1612  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1613  *	   failed), we will not deliver it to the ULP, even though they
1614  *	   are *willing* to accept in *clear*. This is fine as our global
1615  *	   disposition to icmp messages asks us reject the datagram.
1616  *
1617  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1618  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1619  *	   to deliver it to ULP (policy failed), it can lead to
1620  *	   consistency problems. The cases known at this time are
1621  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1622  *	   values :
1623  *
1624  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1625  *	     and Upper layer rejects. Then the communication will
1626  *	     come to a stop. This is solved by making similar decisions
1627  *	     at both levels. Currently, when we are unable to deliver
1628  *	     to the Upper Layer (due to policy failures) while IP has
1629  *	     adjusted ire_max_frag, the next outbound datagram would
1630  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1631  *	     will be with the right level of protection. Thus the right
1632  *	     value will be communicated even if we are not able to
1633  *	     communicate when we get from the wire initially. But this
1634  *	     assumes there would be at least one outbound datagram after
1635  *	     IP has adjusted its ire_max_frag value. To make things
1636  *	     simpler, we accept in clear after the validation of
1637  *	     AH/ESP headers.
1638  *
1639  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1640  *	     upper layer depending on the level of protection the upper
1641  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1642  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1643  *	     should be accepted in clear when the Upper layer expects secure.
1644  *	     Thus the communication may get aborted by some bad ICMP
1645  *	     packets.
1646  *
1647  * IPQoS Notes:
1648  * The only instance when a packet is sent for processing is when there
1649  * isn't an ICMP client and if we are interested in it.
1650  * If there is a client, IPPF processing will take place in the
1651  * ip_fanout_proto routine.
1652  *
1653  * Zones notes:
1654  * The packet is only processed in the context of the specified zone: typically
1655  * only this zone will reply to an echo request, and only interested clients in
1656  * this zone will receive a copy of the packet. This means that the caller must
1657  * call icmp_inbound() for each relevant zone.
1658  */
1659 static void
1660 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1661     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1662     ill_t *recv_ill, zoneid_t zoneid)
1663 {
1664 	icmph_t	*icmph;
1665 	ipha_t	*ipha;
1666 	int	iph_hdr_length;
1667 	int	hdr_length;
1668 	boolean_t	interested;
1669 	uint32_t	ts;
1670 	uchar_t	*wptr;
1671 	ipif_t	*ipif;
1672 	mblk_t *first_mp;
1673 	ipsec_in_t *ii;
1674 	timestruc_t now;
1675 	uint32_t ill_index;
1676 	ip_stack_t *ipst;
1677 
1678 	ASSERT(ill != NULL);
1679 	ipst = ill->ill_ipst;
1680 
1681 	first_mp = mp;
1682 	if (mctl_present) {
1683 		mp = first_mp->b_cont;
1684 		ASSERT(mp != NULL);
1685 	}
1686 
1687 	ipha = (ipha_t *)mp->b_rptr;
1688 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1689 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1690 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1691 		if (first_mp == NULL)
1692 			return;
1693 	}
1694 
1695 	/*
1696 	 * On a labeled system, we have to check whether the zone itself is
1697 	 * permitted to receive raw traffic.
1698 	 */
1699 	if (is_system_labeled()) {
1700 		if (zoneid == ALL_ZONES)
1701 			zoneid = tsol_packet_to_zoneid(mp);
1702 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1703 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1704 			    zoneid));
1705 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1706 			freemsg(first_mp);
1707 			return;
1708 		}
1709 	}
1710 
1711 	/*
1712 	 * We have accepted the ICMP message. It means that we will
1713 	 * respond to the packet if needed. It may not be delivered
1714 	 * to the upper client depending on the policy constraints
1715 	 * and the disposition in ipsec_inbound_accept_clear.
1716 	 */
1717 
1718 	ASSERT(ill != NULL);
1719 
1720 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1721 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1722 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1723 		/* Last chance to get real. */
1724 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1725 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1726 			freemsg(first_mp);
1727 			return;
1728 		}
1729 		/* Refresh iph following the pullup. */
1730 		ipha = (ipha_t *)mp->b_rptr;
1731 	}
1732 	/* ICMP header checksum, including checksum field, should be zero. */
1733 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1734 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1736 		freemsg(first_mp);
1737 		return;
1738 	}
1739 	/* The IP header will always be a multiple of four bytes */
1740 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1741 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1742 	    icmph->icmph_code));
1743 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1744 	/* We will set "interested" to "true" if we want a copy */
1745 	interested = B_FALSE;
1746 	switch (icmph->icmph_type) {
1747 	case ICMP_ECHO_REPLY:
1748 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1749 		break;
1750 	case ICMP_DEST_UNREACHABLE:
1751 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1752 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1753 		interested = B_TRUE;	/* Pass up to transport */
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1755 		break;
1756 	case ICMP_SOURCE_QUENCH:
1757 		interested = B_TRUE;	/* Pass up to transport */
1758 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1759 		break;
1760 	case ICMP_REDIRECT:
1761 		if (!ipst->ips_ip_ignore_redirect)
1762 			interested = B_TRUE;
1763 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1764 		break;
1765 	case ICMP_ECHO_REQUEST:
1766 		/*
1767 		 * Whether to respond to echo requests that come in as IP
1768 		 * broadcasts or as IP multicast is subject to debate
1769 		 * (what isn't?).  We aim to please, you pick it.
1770 		 * Default is do it.
1771 		 */
1772 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1773 			/* unicast: always respond */
1774 			interested = B_TRUE;
1775 		} else if (CLASSD(ipha->ipha_dst)) {
1776 			/* multicast: respond based on tunable */
1777 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1778 		} else if (broadcast) {
1779 			/* broadcast: respond based on tunable */
1780 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1781 		}
1782 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1783 		break;
1784 	case ICMP_ROUTER_ADVERTISEMENT:
1785 	case ICMP_ROUTER_SOLICITATION:
1786 		break;
1787 	case ICMP_TIME_EXCEEDED:
1788 		interested = B_TRUE;	/* Pass up to transport */
1789 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1790 		break;
1791 	case ICMP_PARAM_PROBLEM:
1792 		interested = B_TRUE;	/* Pass up to transport */
1793 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1794 		break;
1795 	case ICMP_TIME_STAMP_REQUEST:
1796 		/* Response to Time Stamp Requests is local policy. */
1797 		if (ipst->ips_ip_g_resp_to_timestamp &&
1798 		    /* So is whether to respond if it was an IP broadcast. */
1799 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1800 			int tstamp_len = 3 * sizeof (uint32_t);
1801 
1802 			if (wptr +  tstamp_len > mp->b_wptr) {
1803 				if (!pullupmsg(mp, wptr + tstamp_len -
1804 				    mp->b_rptr)) {
1805 					BUMP_MIB(ill->ill_ip_mib,
1806 					    ipIfStatsInDiscards);
1807 					freemsg(first_mp);
1808 					return;
1809 				}
1810 				/* Refresh ipha following the pullup. */
1811 				ipha = (ipha_t *)mp->b_rptr;
1812 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1813 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1814 			}
1815 			interested = B_TRUE;
1816 		}
1817 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1818 		break;
1819 	case ICMP_TIME_STAMP_REPLY:
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1821 		break;
1822 	case ICMP_INFO_REQUEST:
1823 		/* Per RFC 1122 3.2.2.7, ignore this. */
1824 	case ICMP_INFO_REPLY:
1825 		break;
1826 	case ICMP_ADDRESS_MASK_REQUEST:
1827 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1828 		    !broadcast) &&
1829 		    /* TODO m_pullup of complete header? */
1830 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1831 			interested = B_TRUE;
1832 		}
1833 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1834 		break;
1835 	case ICMP_ADDRESS_MASK_REPLY:
1836 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1837 		break;
1838 	default:
1839 		interested = B_TRUE;	/* Pass up to transport */
1840 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1841 		break;
1842 	}
1843 	/* See if there is an ICMP client. */
1844 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1845 		/* If there is an ICMP client and we want one too, copy it. */
1846 		mblk_t *first_mp1;
1847 
1848 		if (!interested) {
1849 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1850 			    ip_policy, recv_ill, zoneid);
1851 			return;
1852 		}
1853 		first_mp1 = ip_copymsg(first_mp);
1854 		if (first_mp1 != NULL) {
1855 			ip_fanout_proto(q, first_mp1, ill, ipha,
1856 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1857 		}
1858 	} else if (!interested) {
1859 		freemsg(first_mp);
1860 		return;
1861 	} else {
1862 		/*
1863 		 * Initiate policy processing for this packet if ip_policy
1864 		 * is true.
1865 		 */
1866 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1867 			ill_index = ill->ill_phyint->phyint_ifindex;
1868 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1869 			if (mp == NULL) {
1870 				if (mctl_present) {
1871 					freeb(first_mp);
1872 				}
1873 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1874 				return;
1875 			}
1876 		}
1877 	}
1878 	/* We want to do something with it. */
1879 	/* Check db_ref to make sure we can modify the packet. */
1880 	if (mp->b_datap->db_ref > 1) {
1881 		mblk_t	*first_mp1;
1882 
1883 		first_mp1 = ip_copymsg(first_mp);
1884 		freemsg(first_mp);
1885 		if (!first_mp1) {
1886 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1887 			return;
1888 		}
1889 		first_mp = first_mp1;
1890 		if (mctl_present) {
1891 			mp = first_mp->b_cont;
1892 			ASSERT(mp != NULL);
1893 		} else {
1894 			mp = first_mp;
1895 		}
1896 		ipha = (ipha_t *)mp->b_rptr;
1897 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1898 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1899 	}
1900 	switch (icmph->icmph_type) {
1901 	case ICMP_ADDRESS_MASK_REQUEST:
1902 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1903 		if (ipif == NULL) {
1904 			freemsg(first_mp);
1905 			return;
1906 		}
1907 		/*
1908 		 * outging interface must be IPv4
1909 		 */
1910 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1911 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1912 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1913 		ipif_refrele(ipif);
1914 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1915 		break;
1916 	case ICMP_ECHO_REQUEST:
1917 		icmph->icmph_type = ICMP_ECHO_REPLY;
1918 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1919 		break;
1920 	case ICMP_TIME_STAMP_REQUEST: {
1921 		uint32_t *tsp;
1922 
1923 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1924 		tsp = (uint32_t *)wptr;
1925 		tsp++;		/* Skip past 'originate time' */
1926 		/* Compute # of milliseconds since midnight */
1927 		gethrestime(&now);
1928 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1929 		    now.tv_nsec / (NANOSEC / MILLISEC);
1930 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1931 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1932 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1933 		break;
1934 	}
1935 	default:
1936 		ipha = (ipha_t *)&icmph[1];
1937 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1938 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1939 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1940 				freemsg(first_mp);
1941 				return;
1942 			}
1943 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1944 			ipha = (ipha_t *)&icmph[1];
1945 		}
1946 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1947 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 			freemsg(first_mp);
1949 			return;
1950 		}
1951 		hdr_length = IPH_HDR_LENGTH(ipha);
1952 		if (hdr_length < sizeof (ipha_t)) {
1953 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1954 			freemsg(first_mp);
1955 			return;
1956 		}
1957 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1958 			if (!pullupmsg(mp,
1959 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1960 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1961 				freemsg(first_mp);
1962 				return;
1963 			}
1964 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1965 			ipha = (ipha_t *)&icmph[1];
1966 		}
1967 		switch (icmph->icmph_type) {
1968 		case ICMP_REDIRECT:
1969 			/*
1970 			 * As there is no upper client to deliver, we don't
1971 			 * need the first_mp any more.
1972 			 */
1973 			if (mctl_present) {
1974 				freeb(first_mp);
1975 			}
1976 			icmp_redirect(ill, mp);
1977 			return;
1978 		case ICMP_DEST_UNREACHABLE:
1979 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1980 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1981 				    zoneid, mp, iph_hdr_length, ipst)) {
1982 					freemsg(first_mp);
1983 					return;
1984 				}
1985 				/*
1986 				 * icmp_inbound_too_big() may alter mp.
1987 				 * Resynch ipha and icmph accordingly.
1988 				 */
1989 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1990 				ipha = (ipha_t *)&icmph[1];
1991 			}
1992 			/* FALLTHRU */
1993 		default :
1994 			/*
1995 			 * IPQoS notes: Since we have already done IPQoS
1996 			 * processing we don't want to do it again in
1997 			 * the fanout routines called by
1998 			 * icmp_inbound_error_fanout, hence the last
1999 			 * argument, ip_policy, is B_FALSE.
2000 			 */
2001 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2002 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2003 			    B_FALSE, recv_ill, zoneid);
2004 		}
2005 		return;
2006 	}
2007 	/* Send out an ICMP packet */
2008 	icmph->icmph_checksum = 0;
2009 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2010 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2011 		ipif_t	*ipif_chosen;
2012 		/*
2013 		 * Make it look like it was directed to us, so we don't look
2014 		 * like a fool with a broadcast or multicast source address.
2015 		 */
2016 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2017 		/*
2018 		 * Make sure that we haven't grabbed an interface that's DOWN.
2019 		 */
2020 		if (ipif != NULL) {
2021 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2022 			    ipha->ipha_src, zoneid);
2023 			if (ipif_chosen != NULL) {
2024 				ipif_refrele(ipif);
2025 				ipif = ipif_chosen;
2026 			}
2027 		}
2028 		if (ipif == NULL) {
2029 			ip0dbg(("icmp_inbound: "
2030 			    "No source for broadcast/multicast:\n"
2031 			    "\tsrc 0x%x dst 0x%x ill %p "
2032 			    "ipif_lcl_addr 0x%x\n",
2033 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2034 			    (void *)ill,
2035 			    ill->ill_ipif->ipif_lcl_addr));
2036 			freemsg(first_mp);
2037 			return;
2038 		}
2039 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2040 		ipha->ipha_dst = ipif->ipif_src_addr;
2041 		ipif_refrele(ipif);
2042 	}
2043 	/* Reset time to live. */
2044 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2045 	{
2046 		/* Swap source and destination addresses */
2047 		ipaddr_t tmp;
2048 
2049 		tmp = ipha->ipha_src;
2050 		ipha->ipha_src = ipha->ipha_dst;
2051 		ipha->ipha_dst = tmp;
2052 	}
2053 	ipha->ipha_ident = 0;
2054 	if (!IS_SIMPLE_IPH(ipha))
2055 		icmp_options_update(ipha);
2056 
2057 	if (!mctl_present) {
2058 		/*
2059 		 * This packet should go out the same way as it
2060 		 * came in i.e in clear. To make sure that global
2061 		 * policy will not be applied to this in ip_wput_ire,
2062 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2063 		 */
2064 		ASSERT(first_mp == mp);
2065 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2066 		if (first_mp == NULL) {
2067 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2068 			freemsg(mp);
2069 			return;
2070 		}
2071 		ii = (ipsec_in_t *)first_mp->b_rptr;
2072 
2073 		/* This is not a secure packet */
2074 		ii->ipsec_in_secure = B_FALSE;
2075 		first_mp->b_cont = mp;
2076 	} else {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2079 	}
2080 	ii->ipsec_in_zoneid = zoneid;
2081 	ASSERT(zoneid != ALL_ZONES);
2082 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2083 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2084 		return;
2085 	}
2086 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2087 	put(WR(q), first_mp);
2088 }
2089 
2090 static ipaddr_t
2091 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2092 {
2093 	conn_t *connp;
2094 	connf_t *connfp;
2095 	ipaddr_t nexthop_addr = INADDR_ANY;
2096 	int hdr_length = IPH_HDR_LENGTH(ipha);
2097 	uint16_t *up;
2098 	uint32_t ports;
2099 	ip_stack_t *ipst = ill->ill_ipst;
2100 
2101 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 	switch (ipha->ipha_protocol) {
2103 		case IPPROTO_TCP:
2104 		{
2105 			tcph_t *tcph;
2106 
2107 			/* do a reverse lookup */
2108 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2109 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2110 			    TCPS_LISTEN, ipst);
2111 			break;
2112 		}
2113 		case IPPROTO_UDP:
2114 		{
2115 			uint32_t dstport, srcport;
2116 
2117 			((uint16_t *)&ports)[0] = up[1];
2118 			((uint16_t *)&ports)[1] = up[0];
2119 
2120 			/* Extract ports in net byte order */
2121 			dstport = htons(ntohl(ports) & 0xFFFF);
2122 			srcport = htons(ntohl(ports) >> 16);
2123 
2124 			connfp = &ipst->ips_ipcl_udp_fanout[
2125 			    IPCL_UDP_HASH(dstport, ipst)];
2126 			mutex_enter(&connfp->connf_lock);
2127 			connp = connfp->connf_head;
2128 
2129 			/* do a reverse lookup */
2130 			while ((connp != NULL) &&
2131 			    (!IPCL_UDP_MATCH(connp, dstport,
2132 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2133 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2134 				connp = connp->conn_next;
2135 			}
2136 			if (connp != NULL)
2137 				CONN_INC_REF(connp);
2138 			mutex_exit(&connfp->connf_lock);
2139 			break;
2140 		}
2141 		case IPPROTO_SCTP:
2142 		{
2143 			in6_addr_t map_src, map_dst;
2144 
2145 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2146 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2147 			((uint16_t *)&ports)[0] = up[1];
2148 			((uint16_t *)&ports)[1] = up[0];
2149 
2150 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2151 			    zoneid, ipst->ips_netstack->netstack_sctp);
2152 			if (connp == NULL) {
2153 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2154 				    zoneid, ports, ipha, ipst);
2155 			} else {
2156 				CONN_INC_REF(connp);
2157 				SCTP_REFRELE(CONN2SCTP(connp));
2158 			}
2159 			break;
2160 		}
2161 		default:
2162 		{
2163 			ipha_t ripha;
2164 
2165 			ripha.ipha_src = ipha->ipha_dst;
2166 			ripha.ipha_dst = ipha->ipha_src;
2167 			ripha.ipha_protocol = ipha->ipha_protocol;
2168 
2169 			connfp = &ipst->ips_ipcl_proto_fanout[
2170 			    ipha->ipha_protocol];
2171 			mutex_enter(&connfp->connf_lock);
2172 			connp = connfp->connf_head;
2173 			for (connp = connfp->connf_head; connp != NULL;
2174 			    connp = connp->conn_next) {
2175 				if (IPCL_PROTO_MATCH(connp,
2176 				    ipha->ipha_protocol, &ripha, ill,
2177 				    0, zoneid)) {
2178 					CONN_INC_REF(connp);
2179 					break;
2180 				}
2181 			}
2182 			mutex_exit(&connfp->connf_lock);
2183 		}
2184 	}
2185 	if (connp != NULL) {
2186 		if (connp->conn_nexthop_set)
2187 			nexthop_addr = connp->conn_nexthop_v4;
2188 		CONN_DEC_REF(connp);
2189 	}
2190 	return (nexthop_addr);
2191 }
2192 
2193 /* Table from RFC 1191 */
2194 static int icmp_frag_size_table[] =
2195 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2196 
2197 /*
2198  * Process received ICMP Packet too big.
2199  * After updating any IRE it does the fanout to any matching transport streams.
2200  * Assumes the message has been pulled up till the IP header that caused
2201  * the error.
2202  *
2203  * Returns B_FALSE on failure and B_TRUE on success.
2204  */
2205 static boolean_t
2206 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2207     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2208     ip_stack_t *ipst)
2209 {
2210 	ire_t	*ire, *first_ire;
2211 	int	mtu, orig_mtu;
2212 	int	hdr_length;
2213 	ipaddr_t nexthop_addr;
2214 	boolean_t disable_pmtud;
2215 
2216 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2217 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2218 	ASSERT(ill != NULL);
2219 
2220 	hdr_length = IPH_HDR_LENGTH(ipha);
2221 
2222 	/* Drop if the original packet contained a source route */
2223 	if (ip_source_route_included(ipha)) {
2224 		return (B_FALSE);
2225 	}
2226 	/*
2227 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2228 	 * header.
2229 	 */
2230 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2231 	    mp->b_wptr) {
2232 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2233 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2234 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2235 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2236 			return (B_FALSE);
2237 		}
2238 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2239 		ipha = (ipha_t *)&icmph[1];
2240 	}
2241 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2242 	if (nexthop_addr != INADDR_ANY) {
2243 		/* nexthop set */
2244 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2245 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2246 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2247 	} else {
2248 		/* nexthop not set */
2249 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2250 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2251 	}
2252 
2253 	if (!first_ire) {
2254 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2255 		    ntohl(ipha->ipha_dst)));
2256 		return (B_FALSE);
2257 	}
2258 
2259 	/* Check for MTU discovery advice as described in RFC 1191 */
2260 	mtu = ntohs(icmph->icmph_du_mtu);
2261 	orig_mtu = mtu;
2262 	disable_pmtud = B_FALSE;
2263 
2264 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2265 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2266 	    ire = ire->ire_next) {
2267 		/*
2268 		 * Look for the connection to which this ICMP message is
2269 		 * directed. If it has the IP_NEXTHOP option set, then the
2270 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2271 		 * option. Else the search is limited to regular IREs.
2272 		 */
2273 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2274 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2275 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2276 		    (nexthop_addr != INADDR_ANY)))
2277 			continue;
2278 
2279 		mutex_enter(&ire->ire_lock);
2280 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2281 			uint32_t length;
2282 			int	i;
2283 
2284 			/*
2285 			 * Use the table from RFC 1191 to figure out
2286 			 * the next "plateau" based on the length in
2287 			 * the original IP packet.
2288 			 */
2289 			length = ntohs(ipha->ipha_length);
2290 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2291 			    uint32_t, length);
2292 			if (ire->ire_max_frag <= length &&
2293 			    ire->ire_max_frag >= length - hdr_length) {
2294 				/*
2295 				 * Handle broken BSD 4.2 systems that
2296 				 * return the wrong iph_length in ICMP
2297 				 * errors.
2298 				 */
2299 				length -= hdr_length;
2300 			}
2301 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2302 				if (length > icmp_frag_size_table[i])
2303 					break;
2304 			}
2305 			if (i == A_CNT(icmp_frag_size_table)) {
2306 				/* Smaller than 68! */
2307 				disable_pmtud = B_TRUE;
2308 				mtu = ipst->ips_ip_pmtu_min;
2309 			} else {
2310 				mtu = icmp_frag_size_table[i];
2311 				if (mtu < ipst->ips_ip_pmtu_min) {
2312 					mtu = ipst->ips_ip_pmtu_min;
2313 					disable_pmtud = B_TRUE;
2314 				}
2315 			}
2316 			/* Fool the ULP into believing our guessed PMTU. */
2317 			icmph->icmph_du_zero = 0;
2318 			icmph->icmph_du_mtu = htons(mtu);
2319 		}
2320 		if (disable_pmtud)
2321 			ire->ire_frag_flag = 0;
2322 		/* Reduce the IRE max frag value as advised. */
2323 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2324 		mutex_exit(&ire->ire_lock);
2325 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2326 		    ire, int, orig_mtu, int, mtu);
2327 	}
2328 	rw_exit(&first_ire->ire_bucket->irb_lock);
2329 	ire_refrele(first_ire);
2330 	return (B_TRUE);
2331 }
2332 
2333 /*
2334  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2335  * calls this function.
2336  */
2337 static mblk_t *
2338 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2339 {
2340 	ipha_t *ipha;
2341 	icmph_t *icmph;
2342 	ipha_t *in_ipha;
2343 	int length;
2344 
2345 	ASSERT(mp->b_datap->db_type == M_DATA);
2346 
2347 	/*
2348 	 * For Self-encapsulated packets, we added an extra IP header
2349 	 * without the options. Inner IP header is the one from which
2350 	 * the outer IP header was formed. Thus, we need to remove the
2351 	 * outer IP header. To do this, we pullup the whole message
2352 	 * and overlay whatever follows the outer IP header over the
2353 	 * outer IP header.
2354 	 */
2355 
2356 	if (!pullupmsg(mp, -1))
2357 		return (NULL);
2358 
2359 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2360 	ipha = (ipha_t *)&icmph[1];
2361 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2362 
2363 	/*
2364 	 * The length that we want to overlay is following the inner
2365 	 * IP header. Subtracting the IP header + icmp header + outer
2366 	 * IP header's length should give us the length that we want to
2367 	 * overlay.
2368 	 */
2369 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2370 	    hdr_length;
2371 	/*
2372 	 * Overlay whatever follows the inner header over the
2373 	 * outer header.
2374 	 */
2375 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2376 
2377 	/* Set the wptr to account for the outer header */
2378 	mp->b_wptr -= hdr_length;
2379 	return (mp);
2380 }
2381 
2382 /*
2383  * Try to pass the ICMP message upstream in case the ULP cares.
2384  *
2385  * If the packet that caused the ICMP error is secure, we send
2386  * it to AH/ESP to make sure that the attached packet has a
2387  * valid association. ipha in the code below points to the
2388  * IP header of the packet that caused the error.
2389  *
2390  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2391  * in the context of IPsec. Normally we tell the upper layer
2392  * whenever we send the ire (including ip_bind), the IPsec header
2393  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2394  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2395  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2396  * same thing. As TCP has the IPsec options size that needs to be
2397  * adjusted, we just pass the MTU unchanged.
2398  *
2399  * IFN could have been generated locally or by some router.
2400  *
2401  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2402  *	    This happens because IP adjusted its value of MTU on an
2403  *	    earlier IFN message and could not tell the upper layer,
2404  *	    the new adjusted value of MTU e.g. Packet was encrypted
2405  *	    or there was not enough information to fanout to upper
2406  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2407  *	    generates the IFN, where IPsec processing has *not* been
2408  *	    done.
2409  *
2410  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2411  *	    could have generated this. This happens because ire_max_frag
2412  *	    value in IP was set to a new value, while the IPsec processing
2413  *	    was being done and after we made the fragmentation check in
2414  *	    ip_wput_ire. Thus on return from IPsec processing,
2415  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2416  *	    and generates the IFN. As IPsec processing is over, we fanout
2417  *	    to AH/ESP to remove the header.
2418  *
2419  *	    In both these cases, ipsec_in_loopback will be set indicating
2420  *	    that IFN was generated locally.
2421  *
2422  * ROUTER : IFN could be secure or non-secure.
2423  *
2424  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2425  *	      packet in error has AH/ESP headers to validate the AH/ESP
2426  *	      headers. AH/ESP will verify whether there is a valid SA or
2427  *	      not and send it back. We will fanout again if we have more
2428  *	      data in the packet.
2429  *
2430  *	      If the packet in error does not have AH/ESP, we handle it
2431  *	      like any other case.
2432  *
2433  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2434  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2435  *	      for validation. AH/ESP will verify whether there is a
2436  *	      valid SA or not and send it back. We will fanout again if
2437  *	      we have more data in the packet.
2438  *
2439  *	      If the packet in error does not have AH/ESP, we handle it
2440  *	      like any other case.
2441  */
2442 static void
2443 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2444     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2445     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2446     zoneid_t zoneid)
2447 {
2448 	uint16_t *up;	/* Pointer to ports in ULP header */
2449 	uint32_t ports;	/* reversed ports for fanout */
2450 	ipha_t ripha;	/* With reversed addresses */
2451 	mblk_t *first_mp;
2452 	ipsec_in_t *ii;
2453 	tcph_t	*tcph;
2454 	conn_t	*connp;
2455 	ip_stack_t *ipst;
2456 
2457 	ASSERT(ill != NULL);
2458 
2459 	ASSERT(recv_ill != NULL);
2460 	ipst = recv_ill->ill_ipst;
2461 
2462 	first_mp = mp;
2463 	if (mctl_present) {
2464 		mp = first_mp->b_cont;
2465 		ASSERT(mp != NULL);
2466 
2467 		ii = (ipsec_in_t *)first_mp->b_rptr;
2468 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2469 	} else {
2470 		ii = NULL;
2471 	}
2472 
2473 	switch (ipha->ipha_protocol) {
2474 	case IPPROTO_UDP:
2475 		/*
2476 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2477 		 * transport header.
2478 		 */
2479 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2480 		    mp->b_wptr) {
2481 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2482 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2483 				goto discard_pkt;
2484 			}
2485 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2486 			ipha = (ipha_t *)&icmph[1];
2487 		}
2488 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2489 
2490 		/*
2491 		 * Attempt to find a client stream based on port.
2492 		 * Note that we do a reverse lookup since the header is
2493 		 * in the form we sent it out.
2494 		 * The ripha header is only used for the IP_UDP_MATCH and we
2495 		 * only set the src and dst addresses and protocol.
2496 		 */
2497 		ripha.ipha_src = ipha->ipha_dst;
2498 		ripha.ipha_dst = ipha->ipha_src;
2499 		ripha.ipha_protocol = ipha->ipha_protocol;
2500 		((uint16_t *)&ports)[0] = up[1];
2501 		((uint16_t *)&ports)[1] = up[0];
2502 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2503 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2504 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2505 		    icmph->icmph_type, icmph->icmph_code));
2506 
2507 		/* Have to change db_type after any pullupmsg */
2508 		DB_TYPE(mp) = M_CTL;
2509 
2510 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2511 		    mctl_present, ip_policy, recv_ill, zoneid);
2512 		return;
2513 
2514 	case IPPROTO_TCP:
2515 		/*
2516 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2517 		 * transport header.
2518 		 */
2519 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2520 		    mp->b_wptr) {
2521 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2522 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2523 				goto discard_pkt;
2524 			}
2525 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2526 			ipha = (ipha_t *)&icmph[1];
2527 		}
2528 		/*
2529 		 * Find a TCP client stream for this packet.
2530 		 * Note that we do a reverse lookup since the header is
2531 		 * in the form we sent it out.
2532 		 */
2533 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2534 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2535 		    ipst);
2536 		if (connp == NULL)
2537 			goto discard_pkt;
2538 
2539 		/* Have to change db_type after any pullupmsg */
2540 		DB_TYPE(mp) = M_CTL;
2541 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2542 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2543 		return;
2544 
2545 	case IPPROTO_SCTP:
2546 		/*
2547 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2548 		 * transport header.
2549 		 */
2550 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2551 		    mp->b_wptr) {
2552 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2553 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2554 				goto discard_pkt;
2555 			}
2556 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2557 			ipha = (ipha_t *)&icmph[1];
2558 		}
2559 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2560 		/*
2561 		 * Find a SCTP client stream for this packet.
2562 		 * Note that we do a reverse lookup since the header is
2563 		 * in the form we sent it out.
2564 		 * The ripha header is only used for the matching and we
2565 		 * only set the src and dst addresses, protocol, and version.
2566 		 */
2567 		ripha.ipha_src = ipha->ipha_dst;
2568 		ripha.ipha_dst = ipha->ipha_src;
2569 		ripha.ipha_protocol = ipha->ipha_protocol;
2570 		ripha.ipha_version_and_hdr_length =
2571 		    ipha->ipha_version_and_hdr_length;
2572 		((uint16_t *)&ports)[0] = up[1];
2573 		((uint16_t *)&ports)[1] = up[0];
2574 
2575 		/* Have to change db_type after any pullupmsg */
2576 		DB_TYPE(mp) = M_CTL;
2577 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2578 		    mctl_present, ip_policy, zoneid);
2579 		return;
2580 
2581 	case IPPROTO_ESP:
2582 	case IPPROTO_AH: {
2583 		int ipsec_rc;
2584 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2585 
2586 		/*
2587 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2588 		 * We will re-use the IPSEC_IN if it is already present as
2589 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2590 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2591 		 * one and attach it in the front.
2592 		 */
2593 		if (ii != NULL) {
2594 			/*
2595 			 * ip_fanout_proto_again converts the ICMP errors
2596 			 * that come back from AH/ESP to M_DATA so that
2597 			 * if it is non-AH/ESP and we do a pullupmsg in
2598 			 * this function, it would work. Convert it back
2599 			 * to M_CTL before we send up as this is a ICMP
2600 			 * error. This could have been generated locally or
2601 			 * by some router. Validate the inner IPsec
2602 			 * headers.
2603 			 *
2604 			 * NOTE : ill_index is used by ip_fanout_proto_again
2605 			 * to locate the ill.
2606 			 */
2607 			ASSERT(ill != NULL);
2608 			ii->ipsec_in_ill_index =
2609 			    ill->ill_phyint->phyint_ifindex;
2610 			ii->ipsec_in_rill_index =
2611 			    recv_ill->ill_phyint->phyint_ifindex;
2612 			DB_TYPE(first_mp->b_cont) = M_CTL;
2613 		} else {
2614 			/*
2615 			 * IPSEC_IN is not present. We attach a ipsec_in
2616 			 * message and send up to IPsec for validating
2617 			 * and removing the IPsec headers. Clear
2618 			 * ipsec_in_secure so that when we return
2619 			 * from IPsec, we don't mistakenly think that this
2620 			 * is a secure packet came from the network.
2621 			 *
2622 			 * NOTE : ill_index is used by ip_fanout_proto_again
2623 			 * to locate the ill.
2624 			 */
2625 			ASSERT(first_mp == mp);
2626 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2627 			if (first_mp == NULL) {
2628 				freemsg(mp);
2629 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2630 				return;
2631 			}
2632 			ii = (ipsec_in_t *)first_mp->b_rptr;
2633 
2634 			/* This is not a secure packet */
2635 			ii->ipsec_in_secure = B_FALSE;
2636 			first_mp->b_cont = mp;
2637 			DB_TYPE(mp) = M_CTL;
2638 			ASSERT(ill != NULL);
2639 			ii->ipsec_in_ill_index =
2640 			    ill->ill_phyint->phyint_ifindex;
2641 			ii->ipsec_in_rill_index =
2642 			    recv_ill->ill_phyint->phyint_ifindex;
2643 		}
2644 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2645 
2646 		if (!ipsec_loaded(ipss)) {
2647 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2648 			return;
2649 		}
2650 
2651 		if (ipha->ipha_protocol == IPPROTO_ESP)
2652 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2653 		else
2654 			ipsec_rc = ipsecah_icmp_error(first_mp);
2655 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2656 			return;
2657 
2658 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2659 		return;
2660 	}
2661 	default:
2662 		/*
2663 		 * The ripha header is only used for the lookup and we
2664 		 * only set the src and dst addresses and protocol.
2665 		 */
2666 		ripha.ipha_src = ipha->ipha_dst;
2667 		ripha.ipha_dst = ipha->ipha_src;
2668 		ripha.ipha_protocol = ipha->ipha_protocol;
2669 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2670 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2671 		    ntohl(ipha->ipha_dst),
2672 		    icmph->icmph_type, icmph->icmph_code));
2673 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2674 			ipha_t *in_ipha;
2675 
2676 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2677 			    mp->b_wptr) {
2678 				if (!pullupmsg(mp, (uchar_t *)ipha +
2679 				    hdr_length + sizeof (ipha_t) -
2680 				    mp->b_rptr)) {
2681 					goto discard_pkt;
2682 				}
2683 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2684 				ipha = (ipha_t *)&icmph[1];
2685 			}
2686 			/*
2687 			 * Caller has verified that length has to be
2688 			 * at least the size of IP header.
2689 			 */
2690 			ASSERT(hdr_length >= sizeof (ipha_t));
2691 			/*
2692 			 * Check the sanity of the inner IP header like
2693 			 * we did for the outer header.
2694 			 */
2695 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2696 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2697 				goto discard_pkt;
2698 			}
2699 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2700 				goto discard_pkt;
2701 			}
2702 			/* Check for Self-encapsulated tunnels */
2703 			if (in_ipha->ipha_src == ipha->ipha_src &&
2704 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2705 
2706 				mp = icmp_inbound_self_encap_error(mp,
2707 				    iph_hdr_length, hdr_length);
2708 				if (mp == NULL)
2709 					goto discard_pkt;
2710 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2711 				ipha = (ipha_t *)&icmph[1];
2712 				hdr_length = IPH_HDR_LENGTH(ipha);
2713 				/*
2714 				 * The packet in error is self-encapsualted.
2715 				 * And we are finding it further encapsulated
2716 				 * which we could not have possibly generated.
2717 				 */
2718 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2719 					goto discard_pkt;
2720 				}
2721 				icmp_inbound_error_fanout(q, ill, first_mp,
2722 				    icmph, ipha, iph_hdr_length, hdr_length,
2723 				    mctl_present, ip_policy, recv_ill, zoneid);
2724 				return;
2725 			}
2726 		}
2727 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2728 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2729 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2730 		    ii != NULL &&
2731 		    ii->ipsec_in_loopback &&
2732 		    ii->ipsec_in_secure) {
2733 			/*
2734 			 * For IP tunnels that get a looped-back
2735 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2736 			 * reported new MTU to take into account the IPsec
2737 			 * headers protecting this configured tunnel.
2738 			 *
2739 			 * This allows the tunnel module (tun.c) to blindly
2740 			 * accept the MTU reported in an ICMP "too big"
2741 			 * message.
2742 			 *
2743 			 * Non-looped back ICMP messages will just be
2744 			 * handled by the security protocols (if needed),
2745 			 * and the first subsequent packet will hit this
2746 			 * path.
2747 			 */
2748 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2749 			    ipsec_in_extra_length(first_mp));
2750 		}
2751 		/* Have to change db_type after any pullupmsg */
2752 		DB_TYPE(mp) = M_CTL;
2753 
2754 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2755 		    ip_policy, recv_ill, zoneid);
2756 		return;
2757 	}
2758 	/* NOTREACHED */
2759 discard_pkt:
2760 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2761 drop_pkt:;
2762 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2763 	freemsg(first_mp);
2764 }
2765 
2766 /*
2767  * Common IP options parser.
2768  *
2769  * Setup routine: fill in *optp with options-parsing state, then
2770  * tail-call ipoptp_next to return the first option.
2771  */
2772 uint8_t
2773 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2774 {
2775 	uint32_t totallen; /* total length of all options */
2776 
2777 	totallen = ipha->ipha_version_and_hdr_length -
2778 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2779 	totallen <<= 2;
2780 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2781 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2782 	optp->ipoptp_flags = 0;
2783 	return (ipoptp_next(optp));
2784 }
2785 
2786 /*
2787  * Common IP options parser: extract next option.
2788  */
2789 uint8_t
2790 ipoptp_next(ipoptp_t *optp)
2791 {
2792 	uint8_t *end = optp->ipoptp_end;
2793 	uint8_t *cur = optp->ipoptp_next;
2794 	uint8_t opt, len, pointer;
2795 
2796 	/*
2797 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2798 	 * has been corrupted.
2799 	 */
2800 	ASSERT(cur <= end);
2801 
2802 	if (cur == end)
2803 		return (IPOPT_EOL);
2804 
2805 	opt = cur[IPOPT_OPTVAL];
2806 
2807 	/*
2808 	 * Skip any NOP options.
2809 	 */
2810 	while (opt == IPOPT_NOP) {
2811 		cur++;
2812 		if (cur == end)
2813 			return (IPOPT_EOL);
2814 		opt = cur[IPOPT_OPTVAL];
2815 	}
2816 
2817 	if (opt == IPOPT_EOL)
2818 		return (IPOPT_EOL);
2819 
2820 	/*
2821 	 * Option requiring a length.
2822 	 */
2823 	if ((cur + 1) >= end) {
2824 		optp->ipoptp_flags |= IPOPTP_ERROR;
2825 		return (IPOPT_EOL);
2826 	}
2827 	len = cur[IPOPT_OLEN];
2828 	if (len < 2) {
2829 		optp->ipoptp_flags |= IPOPTP_ERROR;
2830 		return (IPOPT_EOL);
2831 	}
2832 	optp->ipoptp_cur = cur;
2833 	optp->ipoptp_len = len;
2834 	optp->ipoptp_next = cur + len;
2835 	if (cur + len > end) {
2836 		optp->ipoptp_flags |= IPOPTP_ERROR;
2837 		return (IPOPT_EOL);
2838 	}
2839 
2840 	/*
2841 	 * For the options which require a pointer field, make sure
2842 	 * its there, and make sure it points to either something
2843 	 * inside this option, or the end of the option.
2844 	 */
2845 	switch (opt) {
2846 	case IPOPT_RR:
2847 	case IPOPT_TS:
2848 	case IPOPT_LSRR:
2849 	case IPOPT_SSRR:
2850 		if (len <= IPOPT_OFFSET) {
2851 			optp->ipoptp_flags |= IPOPTP_ERROR;
2852 			return (opt);
2853 		}
2854 		pointer = cur[IPOPT_OFFSET];
2855 		if (pointer - 1 > len) {
2856 			optp->ipoptp_flags |= IPOPTP_ERROR;
2857 			return (opt);
2858 		}
2859 		break;
2860 	}
2861 
2862 	/*
2863 	 * Sanity check the pointer field based on the type of the
2864 	 * option.
2865 	 */
2866 	switch (opt) {
2867 	case IPOPT_RR:
2868 	case IPOPT_SSRR:
2869 	case IPOPT_LSRR:
2870 		if (pointer < IPOPT_MINOFF_SR)
2871 			optp->ipoptp_flags |= IPOPTP_ERROR;
2872 		break;
2873 	case IPOPT_TS:
2874 		if (pointer < IPOPT_MINOFF_IT)
2875 			optp->ipoptp_flags |= IPOPTP_ERROR;
2876 		/*
2877 		 * Note that the Internet Timestamp option also
2878 		 * contains two four bit fields (the Overflow field,
2879 		 * and the Flag field), which follow the pointer
2880 		 * field.  We don't need to check that these fields
2881 		 * fall within the length of the option because this
2882 		 * was implicitely done above.  We've checked that the
2883 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2884 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2885 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2886 		 */
2887 		ASSERT(len > IPOPT_POS_OV_FLG);
2888 		break;
2889 	}
2890 
2891 	return (opt);
2892 }
2893 
2894 /*
2895  * Use the outgoing IP header to create an IP_OPTIONS option the way
2896  * it was passed down from the application.
2897  */
2898 int
2899 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2900 {
2901 	ipoptp_t	opts;
2902 	const uchar_t	*opt;
2903 	uint8_t		optval;
2904 	uint8_t		optlen;
2905 	uint32_t	len = 0;
2906 	uchar_t	*buf1 = buf;
2907 
2908 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2909 	len += IP_ADDR_LEN;
2910 	bzero(buf1, IP_ADDR_LEN);
2911 
2912 	/*
2913 	 * OK to cast away const here, as we don't store through the returned
2914 	 * opts.ipoptp_cur pointer.
2915 	 */
2916 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2917 	    optval != IPOPT_EOL;
2918 	    optval = ipoptp_next(&opts)) {
2919 		int	off;
2920 
2921 		opt = opts.ipoptp_cur;
2922 		optlen = opts.ipoptp_len;
2923 		switch (optval) {
2924 		case IPOPT_SSRR:
2925 		case IPOPT_LSRR:
2926 
2927 			/*
2928 			 * Insert ipha_dst as the first entry in the source
2929 			 * route and move down the entries on step.
2930 			 * The last entry gets placed at buf1.
2931 			 */
2932 			buf[IPOPT_OPTVAL] = optval;
2933 			buf[IPOPT_OLEN] = optlen;
2934 			buf[IPOPT_OFFSET] = optlen;
2935 
2936 			off = optlen - IP_ADDR_LEN;
2937 			if (off < 0) {
2938 				/* No entries in source route */
2939 				break;
2940 			}
2941 			/* Last entry in source route */
2942 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2943 			off -= IP_ADDR_LEN;
2944 
2945 			while (off > 0) {
2946 				bcopy(opt + off,
2947 				    buf + off + IP_ADDR_LEN,
2948 				    IP_ADDR_LEN);
2949 				off -= IP_ADDR_LEN;
2950 			}
2951 			/* ipha_dst into first slot */
2952 			bcopy(&ipha->ipha_dst,
2953 			    buf + off + IP_ADDR_LEN,
2954 			    IP_ADDR_LEN);
2955 			buf += optlen;
2956 			len += optlen;
2957 			break;
2958 
2959 		case IPOPT_COMSEC:
2960 		case IPOPT_SECURITY:
2961 			/* if passing up a label is not ok, then remove */
2962 			if (is_system_labeled())
2963 				break;
2964 			/* FALLTHROUGH */
2965 		default:
2966 			bcopy(opt, buf, optlen);
2967 			buf += optlen;
2968 			len += optlen;
2969 			break;
2970 		}
2971 	}
2972 done:
2973 	/* Pad the resulting options */
2974 	while (len & 0x3) {
2975 		*buf++ = IPOPT_EOL;
2976 		len++;
2977 	}
2978 	return (len);
2979 }
2980 
2981 /*
2982  * Update any record route or timestamp options to include this host.
2983  * Reverse any source route option.
2984  * This routine assumes that the options are well formed i.e. that they
2985  * have already been checked.
2986  */
2987 static void
2988 icmp_options_update(ipha_t *ipha)
2989 {
2990 	ipoptp_t	opts;
2991 	uchar_t		*opt;
2992 	uint8_t		optval;
2993 	ipaddr_t	src;		/* Our local address */
2994 	ipaddr_t	dst;
2995 
2996 	ip2dbg(("icmp_options_update\n"));
2997 	src = ipha->ipha_src;
2998 	dst = ipha->ipha_dst;
2999 
3000 	for (optval = ipoptp_first(&opts, ipha);
3001 	    optval != IPOPT_EOL;
3002 	    optval = ipoptp_next(&opts)) {
3003 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3004 		opt = opts.ipoptp_cur;
3005 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3006 		    optval, opts.ipoptp_len));
3007 		switch (optval) {
3008 			int off1, off2;
3009 		case IPOPT_SSRR:
3010 		case IPOPT_LSRR:
3011 			/*
3012 			 * Reverse the source route.  The first entry
3013 			 * should be the next to last one in the current
3014 			 * source route (the last entry is our address).
3015 			 * The last entry should be the final destination.
3016 			 */
3017 			off1 = IPOPT_MINOFF_SR - 1;
3018 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3019 			if (off2 < 0) {
3020 				/* No entries in source route */
3021 				ip1dbg((
3022 				    "icmp_options_update: bad src route\n"));
3023 				break;
3024 			}
3025 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3026 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3027 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3028 			off2 -= IP_ADDR_LEN;
3029 
3030 			while (off1 < off2) {
3031 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3032 				bcopy((char *)opt + off2, (char *)opt + off1,
3033 				    IP_ADDR_LEN);
3034 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3035 				off1 += IP_ADDR_LEN;
3036 				off2 -= IP_ADDR_LEN;
3037 			}
3038 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3039 			break;
3040 		}
3041 	}
3042 }
3043 
3044 /*
3045  * Process received ICMP Redirect messages.
3046  */
3047 static void
3048 icmp_redirect(ill_t *ill, mblk_t *mp)
3049 {
3050 	ipha_t	*ipha;
3051 	int	iph_hdr_length;
3052 	icmph_t	*icmph;
3053 	ipha_t	*ipha_err;
3054 	ire_t	*ire;
3055 	ire_t	*prev_ire;
3056 	ire_t	*save_ire;
3057 	ipaddr_t  src, dst, gateway;
3058 	iulp_t	ulp_info = { 0 };
3059 	int	error;
3060 	ip_stack_t *ipst;
3061 
3062 	ASSERT(ill != NULL);
3063 	ipst = ill->ill_ipst;
3064 
3065 	ipha = (ipha_t *)mp->b_rptr;
3066 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3067 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3068 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3069 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3070 		freemsg(mp);
3071 		return;
3072 	}
3073 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3074 	ipha_err = (ipha_t *)&icmph[1];
3075 	src = ipha->ipha_src;
3076 	dst = ipha_err->ipha_dst;
3077 	gateway = icmph->icmph_rd_gateway;
3078 	/* Make sure the new gateway is reachable somehow. */
3079 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3080 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3081 	/*
3082 	 * Make sure we had a route for the dest in question and that
3083 	 * that route was pointing to the old gateway (the source of the
3084 	 * redirect packet.)
3085 	 */
3086 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3087 	    NULL, MATCH_IRE_GW, ipst);
3088 	/*
3089 	 * Check that
3090 	 *	the redirect was not from ourselves
3091 	 *	the new gateway and the old gateway are directly reachable
3092 	 */
3093 	if (!prev_ire ||
3094 	    !ire ||
3095 	    ire->ire_type == IRE_LOCAL) {
3096 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3097 		freemsg(mp);
3098 		if (ire != NULL)
3099 			ire_refrele(ire);
3100 		if (prev_ire != NULL)
3101 			ire_refrele(prev_ire);
3102 		return;
3103 	}
3104 
3105 	/*
3106 	 * Should we use the old ULP info to create the new gateway?  From
3107 	 * a user's perspective, we should inherit the info so that it
3108 	 * is a "smooth" transition.  If we do not do that, then new
3109 	 * connections going thru the new gateway will have no route metrics,
3110 	 * which is counter-intuitive to user.  From a network point of
3111 	 * view, this may or may not make sense even though the new gateway
3112 	 * is still directly connected to us so the route metrics should not
3113 	 * change much.
3114 	 *
3115 	 * But if the old ire_uinfo is not initialized, we do another
3116 	 * recursive lookup on the dest using the new gateway.  There may
3117 	 * be a route to that.  If so, use it to initialize the redirect
3118 	 * route.
3119 	 */
3120 	if (prev_ire->ire_uinfo.iulp_set) {
3121 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3122 	} else {
3123 		ire_t *tmp_ire;
3124 		ire_t *sire;
3125 
3126 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3127 		    ALL_ZONES, 0, NULL,
3128 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3129 		    ipst);
3130 		if (sire != NULL) {
3131 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3132 			/*
3133 			 * If sire != NULL, ire_ftable_lookup() should not
3134 			 * return a NULL value.
3135 			 */
3136 			ASSERT(tmp_ire != NULL);
3137 			ire_refrele(tmp_ire);
3138 			ire_refrele(sire);
3139 		} else if (tmp_ire != NULL) {
3140 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3141 			    sizeof (iulp_t));
3142 			ire_refrele(tmp_ire);
3143 		}
3144 	}
3145 	if (prev_ire->ire_type == IRE_CACHE)
3146 		ire_delete(prev_ire);
3147 	ire_refrele(prev_ire);
3148 	/*
3149 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3150 	 * require TOS routing
3151 	 */
3152 	switch (icmph->icmph_code) {
3153 	case 0:
3154 	case 1:
3155 		/* TODO: TOS specificity for cases 2 and 3 */
3156 	case 2:
3157 	case 3:
3158 		break;
3159 	default:
3160 		freemsg(mp);
3161 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3162 		ire_refrele(ire);
3163 		return;
3164 	}
3165 	/*
3166 	 * Create a Route Association.  This will allow us to remember that
3167 	 * someone we believe told us to use the particular gateway.
3168 	 */
3169 	save_ire = ire;
3170 	ire = ire_create(
3171 	    (uchar_t *)&dst,			/* dest addr */
3172 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3173 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3174 	    (uchar_t *)&gateway,		/* gateway addr */
3175 	    &save_ire->ire_max_frag,		/* max frag */
3176 	    NULL,				/* no src nce */
3177 	    NULL,				/* no rfq */
3178 	    NULL,				/* no stq */
3179 	    IRE_HOST,
3180 	    NULL,				/* ipif */
3181 	    0,					/* cmask */
3182 	    0,					/* phandle */
3183 	    0,					/* ihandle */
3184 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3185 	    &ulp_info,
3186 	    NULL,				/* tsol_gc_t */
3187 	    NULL,				/* gcgrp */
3188 	    ipst);
3189 
3190 	if (ire == NULL) {
3191 		freemsg(mp);
3192 		ire_refrele(save_ire);
3193 		return;
3194 	}
3195 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3196 	ire_refrele(save_ire);
3197 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3198 
3199 	if (error == 0) {
3200 		ire_refrele(ire);		/* Held in ire_add_v4 */
3201 		/* tell routing sockets that we received a redirect */
3202 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3203 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3204 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3205 	}
3206 
3207 	/*
3208 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3209 	 * This together with the added IRE has the effect of
3210 	 * modifying an existing redirect.
3211 	 */
3212 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3213 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3214 	if (prev_ire != NULL) {
3215 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3216 			ire_delete(prev_ire);
3217 		ire_refrele(prev_ire);
3218 	}
3219 
3220 	freemsg(mp);
3221 }
3222 
3223 /*
3224  * Generate an ICMP parameter problem message.
3225  */
3226 static void
3227 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3228 	ip_stack_t *ipst)
3229 {
3230 	icmph_t	icmph;
3231 	boolean_t mctl_present;
3232 	mblk_t *first_mp;
3233 
3234 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3235 
3236 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3237 		if (mctl_present)
3238 			freeb(first_mp);
3239 		return;
3240 	}
3241 
3242 	bzero(&icmph, sizeof (icmph_t));
3243 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3244 	icmph.icmph_pp_ptr = ptr;
3245 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3246 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3247 	    ipst);
3248 }
3249 
3250 /*
3251  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3252  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3253  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3254  * an icmp error packet can be sent.
3255  * Assigns an appropriate source address to the packet. If ipha_dst is
3256  * one of our addresses use it for source. Otherwise pick a source based
3257  * on a route lookup back to ipha_src.
3258  * Note that ipha_src must be set here since the
3259  * packet is likely to arrive on an ill queue in ip_wput() which will
3260  * not set a source address.
3261  */
3262 static void
3263 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3264     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3265 {
3266 	ipaddr_t dst;
3267 	icmph_t	*icmph;
3268 	ipha_t	*ipha;
3269 	uint_t	len_needed;
3270 	size_t	msg_len;
3271 	mblk_t	*mp1;
3272 	ipaddr_t src;
3273 	ire_t	*ire;
3274 	mblk_t *ipsec_mp;
3275 	ipsec_out_t	*io = NULL;
3276 
3277 	if (mctl_present) {
3278 		/*
3279 		 * If it is :
3280 		 *
3281 		 * 1) a IPSEC_OUT, then this is caused by outbound
3282 		 *    datagram originating on this host. IPsec processing
3283 		 *    may or may not have been done. Refer to comments above
3284 		 *    icmp_inbound_error_fanout for details.
3285 		 *
3286 		 * 2) a IPSEC_IN if we are generating a icmp_message
3287 		 *    for an incoming datagram destined for us i.e called
3288 		 *    from ip_fanout_send_icmp.
3289 		 */
3290 		ipsec_info_t *in;
3291 		ipsec_mp = mp;
3292 		mp = ipsec_mp->b_cont;
3293 
3294 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3295 		ipha = (ipha_t *)mp->b_rptr;
3296 
3297 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3298 		    in->ipsec_info_type == IPSEC_IN);
3299 
3300 		if (in->ipsec_info_type == IPSEC_IN) {
3301 			/*
3302 			 * Convert the IPSEC_IN to IPSEC_OUT.
3303 			 */
3304 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3305 				BUMP_MIB(&ipst->ips_ip_mib,
3306 				    ipIfStatsOutDiscards);
3307 				return;
3308 			}
3309 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3310 		} else {
3311 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3312 			io = (ipsec_out_t *)in;
3313 			/*
3314 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3315 			 * ire lookup.
3316 			 */
3317 			io->ipsec_out_proc_begin = B_FALSE;
3318 		}
3319 		ASSERT(zoneid == io->ipsec_out_zoneid);
3320 		ASSERT(zoneid != ALL_ZONES);
3321 	} else {
3322 		/*
3323 		 * This is in clear. The icmp message we are building
3324 		 * here should go out in clear.
3325 		 *
3326 		 * Pardon the convolution of it all, but it's easier to
3327 		 * allocate a "use cleartext" IPSEC_IN message and convert
3328 		 * it than it is to allocate a new one.
3329 		 */
3330 		ipsec_in_t *ii;
3331 		ASSERT(DB_TYPE(mp) == M_DATA);
3332 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3333 		if (ipsec_mp == NULL) {
3334 			freemsg(mp);
3335 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3336 			return;
3337 		}
3338 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3339 
3340 		/* This is not a secure packet */
3341 		ii->ipsec_in_secure = B_FALSE;
3342 		/*
3343 		 * For trusted extensions using a shared IP address we can
3344 		 * send using any zoneid.
3345 		 */
3346 		if (zoneid == ALL_ZONES)
3347 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3348 		else
3349 			ii->ipsec_in_zoneid = zoneid;
3350 		ipsec_mp->b_cont = mp;
3351 		ipha = (ipha_t *)mp->b_rptr;
3352 		/*
3353 		 * Convert the IPSEC_IN to IPSEC_OUT.
3354 		 */
3355 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3356 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3357 			return;
3358 		}
3359 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3360 	}
3361 
3362 	/* Remember our eventual destination */
3363 	dst = ipha->ipha_src;
3364 
3365 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3366 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3367 	if (ire != NULL &&
3368 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3369 		src = ipha->ipha_dst;
3370 	} else {
3371 		if (ire != NULL)
3372 			ire_refrele(ire);
3373 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3374 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3375 		    ipst);
3376 		if (ire == NULL) {
3377 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3378 			freemsg(ipsec_mp);
3379 			return;
3380 		}
3381 		src = ire->ire_src_addr;
3382 	}
3383 
3384 	if (ire != NULL)
3385 		ire_refrele(ire);
3386 
3387 	/*
3388 	 * Check if we can send back more then 8 bytes in addition to
3389 	 * the IP header.  We try to send 64 bytes of data and the internal
3390 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3391 	 */
3392 	len_needed = IPH_HDR_LENGTH(ipha);
3393 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3394 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3395 
3396 		if (!pullupmsg(mp, -1)) {
3397 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3398 			freemsg(ipsec_mp);
3399 			return;
3400 		}
3401 		ipha = (ipha_t *)mp->b_rptr;
3402 
3403 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3404 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3405 			    len_needed));
3406 		} else {
3407 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3408 
3409 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3410 			len_needed += ip_hdr_length_v6(mp, ip6h);
3411 		}
3412 	}
3413 	len_needed += ipst->ips_ip_icmp_return;
3414 	msg_len = msgdsize(mp);
3415 	if (msg_len > len_needed) {
3416 		(void) adjmsg(mp, len_needed - msg_len);
3417 		msg_len = len_needed;
3418 	}
3419 	/* Make sure we propagate the cred/label for TX */
3420 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3421 	if (mp1 == NULL) {
3422 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3423 		freemsg(ipsec_mp);
3424 		return;
3425 	}
3426 	mp1->b_cont = mp;
3427 	mp = mp1;
3428 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3429 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3430 	    io->ipsec_out_type == IPSEC_OUT);
3431 	ipsec_mp->b_cont = mp;
3432 
3433 	/*
3434 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3435 	 * node generates be accepted in peace by all on-host destinations.
3436 	 * If we do NOT assume that all on-host destinations trust
3437 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3438 	 * (Look for ipsec_out_icmp_loopback).
3439 	 */
3440 	io->ipsec_out_icmp_loopback = B_TRUE;
3441 
3442 	ipha = (ipha_t *)mp->b_rptr;
3443 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3444 	*ipha = icmp_ipha;
3445 	ipha->ipha_src = src;
3446 	ipha->ipha_dst = dst;
3447 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3448 	msg_len += sizeof (icmp_ipha) + len;
3449 	if (msg_len > IP_MAXPACKET) {
3450 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3451 		msg_len = IP_MAXPACKET;
3452 	}
3453 	ipha->ipha_length = htons((uint16_t)msg_len);
3454 	icmph = (icmph_t *)&ipha[1];
3455 	bcopy(stuff, icmph, len);
3456 	icmph->icmph_checksum = 0;
3457 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3458 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3459 	put(q, ipsec_mp);
3460 }
3461 
3462 /*
3463  * Determine if an ICMP error packet can be sent given the rate limit.
3464  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3465  * in milliseconds) and a burst size. Burst size number of packets can
3466  * be sent arbitrarely closely spaced.
3467  * The state is tracked using two variables to implement an approximate
3468  * token bucket filter:
3469  *	icmp_pkt_err_last - lbolt value when the last burst started
3470  *	icmp_pkt_err_sent - number of packets sent in current burst
3471  */
3472 boolean_t
3473 icmp_err_rate_limit(ip_stack_t *ipst)
3474 {
3475 	clock_t now = TICK_TO_MSEC(lbolt);
3476 	uint_t refilled; /* Number of packets refilled in tbf since last */
3477 	/* Guard against changes by loading into local variable */
3478 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3479 
3480 	if (err_interval == 0)
3481 		return (B_FALSE);
3482 
3483 	if (ipst->ips_icmp_pkt_err_last > now) {
3484 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3485 		ipst->ips_icmp_pkt_err_last = 0;
3486 		ipst->ips_icmp_pkt_err_sent = 0;
3487 	}
3488 	/*
3489 	 * If we are in a burst update the token bucket filter.
3490 	 * Update the "last" time to be close to "now" but make sure
3491 	 * we don't loose precision.
3492 	 */
3493 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3494 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3495 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3496 			ipst->ips_icmp_pkt_err_sent = 0;
3497 		} else {
3498 			ipst->ips_icmp_pkt_err_sent -= refilled;
3499 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3500 		}
3501 	}
3502 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3503 		/* Start of new burst */
3504 		ipst->ips_icmp_pkt_err_last = now;
3505 	}
3506 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3507 		ipst->ips_icmp_pkt_err_sent++;
3508 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3509 		    ipst->ips_icmp_pkt_err_sent));
3510 		return (B_FALSE);
3511 	}
3512 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3513 	return (B_TRUE);
3514 }
3515 
3516 /*
3517  * Check if it is ok to send an IPv4 ICMP error packet in
3518  * response to the IPv4 packet in mp.
3519  * Free the message and return null if no
3520  * ICMP error packet should be sent.
3521  */
3522 static mblk_t *
3523 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3524 {
3525 	icmph_t	*icmph;
3526 	ipha_t	*ipha;
3527 	uint_t	len_needed;
3528 	ire_t	*src_ire;
3529 	ire_t	*dst_ire;
3530 
3531 	if (!mp)
3532 		return (NULL);
3533 	ipha = (ipha_t *)mp->b_rptr;
3534 	if (ip_csum_hdr(ipha)) {
3535 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3536 		freemsg(mp);
3537 		return (NULL);
3538 	}
3539 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3540 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3541 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3542 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3543 	if (src_ire != NULL || dst_ire != NULL ||
3544 	    CLASSD(ipha->ipha_dst) ||
3545 	    CLASSD(ipha->ipha_src) ||
3546 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3547 		/* Note: only errors to the fragment with offset 0 */
3548 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3549 		freemsg(mp);
3550 		if (src_ire != NULL)
3551 			ire_refrele(src_ire);
3552 		if (dst_ire != NULL)
3553 			ire_refrele(dst_ire);
3554 		return (NULL);
3555 	}
3556 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3557 		/*
3558 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3559 		 * errors in response to any ICMP errors.
3560 		 */
3561 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3562 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3563 			if (!pullupmsg(mp, len_needed)) {
3564 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3565 				freemsg(mp);
3566 				return (NULL);
3567 			}
3568 			ipha = (ipha_t *)mp->b_rptr;
3569 		}
3570 		icmph = (icmph_t *)
3571 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3572 		switch (icmph->icmph_type) {
3573 		case ICMP_DEST_UNREACHABLE:
3574 		case ICMP_SOURCE_QUENCH:
3575 		case ICMP_TIME_EXCEEDED:
3576 		case ICMP_PARAM_PROBLEM:
3577 		case ICMP_REDIRECT:
3578 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3579 			freemsg(mp);
3580 			return (NULL);
3581 		default:
3582 			break;
3583 		}
3584 	}
3585 	/*
3586 	 * If this is a labeled system, then check to see if we're allowed to
3587 	 * send a response to this particular sender.  If not, then just drop.
3588 	 */
3589 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3590 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3591 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3592 		freemsg(mp);
3593 		return (NULL);
3594 	}
3595 	if (icmp_err_rate_limit(ipst)) {
3596 		/*
3597 		 * Only send ICMP error packets every so often.
3598 		 * This should be done on a per port/source basis,
3599 		 * but for now this will suffice.
3600 		 */
3601 		freemsg(mp);
3602 		return (NULL);
3603 	}
3604 	return (mp);
3605 }
3606 
3607 /*
3608  * Generate an ICMP redirect message.
3609  */
3610 static void
3611 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3612 {
3613 	icmph_t	icmph;
3614 
3615 	/*
3616 	 * We are called from ip_rput where we could
3617 	 * not have attached an IPSEC_IN.
3618 	 */
3619 	ASSERT(mp->b_datap->db_type == M_DATA);
3620 
3621 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3622 		return;
3623 	}
3624 
3625 	bzero(&icmph, sizeof (icmph_t));
3626 	icmph.icmph_type = ICMP_REDIRECT;
3627 	icmph.icmph_code = 1;
3628 	icmph.icmph_rd_gateway = gateway;
3629 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3630 	/* Redirects sent by router, and router is global zone */
3631 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3632 }
3633 
3634 /*
3635  * Generate an ICMP time exceeded message.
3636  */
3637 void
3638 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3639     ip_stack_t *ipst)
3640 {
3641 	icmph_t	icmph;
3642 	boolean_t mctl_present;
3643 	mblk_t *first_mp;
3644 
3645 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3646 
3647 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3648 		if (mctl_present)
3649 			freeb(first_mp);
3650 		return;
3651 	}
3652 
3653 	bzero(&icmph, sizeof (icmph_t));
3654 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3655 	icmph.icmph_code = code;
3656 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3657 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3658 	    ipst);
3659 }
3660 
3661 /*
3662  * Generate an ICMP unreachable message.
3663  */
3664 void
3665 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3666     ip_stack_t *ipst)
3667 {
3668 	icmph_t	icmph;
3669 	mblk_t *first_mp;
3670 	boolean_t mctl_present;
3671 
3672 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3673 
3674 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3675 		if (mctl_present)
3676 			freeb(first_mp);
3677 		return;
3678 	}
3679 
3680 	bzero(&icmph, sizeof (icmph_t));
3681 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3682 	icmph.icmph_code = code;
3683 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3684 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3685 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3686 	    zoneid, ipst);
3687 }
3688 
3689 /*
3690  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3691  * duplicate.  As long as someone else holds the address, the interface will
3692  * stay down.  When that conflict goes away, the interface is brought back up.
3693  * This is done so that accidental shutdowns of addresses aren't made
3694  * permanent.  Your server will recover from a failure.
3695  *
3696  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3697  * user space process (dhcpagent).
3698  *
3699  * Recovery completes if ARP reports that the address is now ours (via
3700  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3701  *
3702  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3703  */
3704 static void
3705 ipif_dup_recovery(void *arg)
3706 {
3707 	ipif_t *ipif = arg;
3708 	ill_t *ill = ipif->ipif_ill;
3709 	mblk_t *arp_add_mp;
3710 	mblk_t *arp_del_mp;
3711 	ip_stack_t *ipst = ill->ill_ipst;
3712 
3713 	ipif->ipif_recovery_id = 0;
3714 
3715 	/*
3716 	 * No lock needed for moving or condemned check, as this is just an
3717 	 * optimization.
3718 	 */
3719 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3720 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3721 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3722 		/* No reason to try to bring this address back. */
3723 		return;
3724 	}
3725 
3726 	/* ACE_F_UNVERIFIED restarts DAD */
3727 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3728 		goto alloc_fail;
3729 
3730 	if (ipif->ipif_arp_del_mp == NULL) {
3731 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3732 			goto alloc_fail;
3733 		ipif->ipif_arp_del_mp = arp_del_mp;
3734 	}
3735 
3736 	putnext(ill->ill_rq, arp_add_mp);
3737 	return;
3738 
3739 alloc_fail:
3740 	/*
3741 	 * On allocation failure, just restart the timer.  Note that the ipif
3742 	 * is down here, so no other thread could be trying to start a recovery
3743 	 * timer.  The ill_lock protects the condemned flag and the recovery
3744 	 * timer ID.
3745 	 */
3746 	freemsg(arp_add_mp);
3747 	mutex_enter(&ill->ill_lock);
3748 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3749 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3750 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3751 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3752 	}
3753 	mutex_exit(&ill->ill_lock);
3754 }
3755 
3756 /*
3757  * This is for exclusive changes due to ARP.  Either tear down an interface due
3758  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3759  */
3760 /* ARGSUSED */
3761 static void
3762 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3763 {
3764 	ill_t	*ill = rq->q_ptr;
3765 	arh_t *arh;
3766 	ipaddr_t src;
3767 	ipif_t	*ipif;
3768 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3769 	char hbuf[MAC_STR_LEN];
3770 	char sbuf[INET_ADDRSTRLEN];
3771 	const char *failtype;
3772 	boolean_t bring_up;
3773 	ip_stack_t *ipst = ill->ill_ipst;
3774 
3775 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3776 	case AR_CN_READY:
3777 		failtype = NULL;
3778 		bring_up = B_TRUE;
3779 		break;
3780 	case AR_CN_FAILED:
3781 		failtype = "in use";
3782 		bring_up = B_FALSE;
3783 		break;
3784 	default:
3785 		failtype = "claimed";
3786 		bring_up = B_FALSE;
3787 		break;
3788 	}
3789 
3790 	arh = (arh_t *)mp->b_cont->b_rptr;
3791 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3792 
3793 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3794 	    sizeof (hbuf));
3795 	(void) ip_dot_addr(src, sbuf);
3796 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3797 
3798 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3799 		    ipif->ipif_lcl_addr != src) {
3800 			continue;
3801 		}
3802 
3803 		/*
3804 		 * If we failed on a recovery probe, then restart the timer to
3805 		 * try again later.
3806 		 */
3807 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3808 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3809 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3810 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3811 		    ipst->ips_ip_dup_recovery > 0 &&
3812 		    ipif->ipif_recovery_id == 0) {
3813 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3814 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3815 			continue;
3816 		}
3817 
3818 		/*
3819 		 * If what we're trying to do has already been done, then do
3820 		 * nothing.
3821 		 */
3822 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3823 			continue;
3824 
3825 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3826 
3827 		if (failtype == NULL) {
3828 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3829 			    ibuf);
3830 		} else {
3831 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3832 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3833 		}
3834 
3835 		if (bring_up) {
3836 			ASSERT(ill->ill_dl_up);
3837 			/*
3838 			 * Free up the ARP delete message so we can allocate
3839 			 * a fresh one through the normal path.
3840 			 */
3841 			freemsg(ipif->ipif_arp_del_mp);
3842 			ipif->ipif_arp_del_mp = NULL;
3843 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3844 			    EINPROGRESS) {
3845 				ipif->ipif_addr_ready = 1;
3846 				(void) ipif_up_done(ipif);
3847 				ASSERT(ill->ill_move_ipif == NULL);
3848 			}
3849 			continue;
3850 		}
3851 
3852 		mutex_enter(&ill->ill_lock);
3853 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3854 		ipif->ipif_flags |= IPIF_DUPLICATE;
3855 		ill->ill_ipif_dup_count++;
3856 		mutex_exit(&ill->ill_lock);
3857 		/*
3858 		 * Already exclusive on the ill; no need to handle deferred
3859 		 * processing here.
3860 		 */
3861 		(void) ipif_down(ipif, NULL, NULL);
3862 		ipif_down_tail(ipif);
3863 		mutex_enter(&ill->ill_lock);
3864 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3865 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3866 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3867 		    ipst->ips_ip_dup_recovery > 0) {
3868 			ASSERT(ipif->ipif_recovery_id == 0);
3869 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3870 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3871 		}
3872 		mutex_exit(&ill->ill_lock);
3873 	}
3874 	freemsg(mp);
3875 }
3876 
3877 /* ARGSUSED */
3878 static void
3879 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3880 {
3881 	ill_t	*ill = rq->q_ptr;
3882 	arh_t *arh;
3883 	ipaddr_t src;
3884 	ipif_t	*ipif;
3885 
3886 	arh = (arh_t *)mp->b_cont->b_rptr;
3887 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3888 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3889 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3890 			(void) ipif_resolver_up(ipif, Res_act_defend);
3891 	}
3892 	freemsg(mp);
3893 }
3894 
3895 /*
3896  * News from ARP.  ARP sends notification of interesting events down
3897  * to its clients using M_CTL messages with the interesting ARP packet
3898  * attached via b_cont.
3899  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3900  * queue as opposed to ARP sending the message to all the clients, i.e. all
3901  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3902  * table if a cache IRE is found to delete all the entries for the address in
3903  * the packet.
3904  */
3905 static void
3906 ip_arp_news(queue_t *q, mblk_t *mp)
3907 {
3908 	arcn_t		*arcn;
3909 	arh_t		*arh;
3910 	ire_t		*ire = NULL;
3911 	char		hbuf[MAC_STR_LEN];
3912 	char		sbuf[INET_ADDRSTRLEN];
3913 	ipaddr_t	src;
3914 	in6_addr_t	v6src;
3915 	boolean_t	isv6 = B_FALSE;
3916 	ipif_t		*ipif;
3917 	ill_t		*ill;
3918 	ip_stack_t	*ipst;
3919 
3920 	if (CONN_Q(q)) {
3921 		conn_t *connp = Q_TO_CONN(q);
3922 
3923 		ipst = connp->conn_netstack->netstack_ip;
3924 	} else {
3925 		ill_t *ill = (ill_t *)q->q_ptr;
3926 
3927 		ipst = ill->ill_ipst;
3928 	}
3929 
3930 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3931 		if (q->q_next) {
3932 			putnext(q, mp);
3933 		} else
3934 			freemsg(mp);
3935 		return;
3936 	}
3937 	arh = (arh_t *)mp->b_cont->b_rptr;
3938 	/* Is it one we are interested in? */
3939 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3940 		isv6 = B_TRUE;
3941 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3942 		    IPV6_ADDR_LEN);
3943 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3944 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3945 		    IP_ADDR_LEN);
3946 	} else {
3947 		freemsg(mp);
3948 		return;
3949 	}
3950 
3951 	ill = q->q_ptr;
3952 
3953 	arcn = (arcn_t *)mp->b_rptr;
3954 	switch (arcn->arcn_code) {
3955 	case AR_CN_BOGON:
3956 		/*
3957 		 * Someone is sending ARP packets with a source protocol
3958 		 * address that we have published and for which we believe our
3959 		 * entry is authoritative and (when ill_arp_extend is set)
3960 		 * verified to be unique on the network.
3961 		 *
3962 		 * The ARP module internally handles the cases where the sender
3963 		 * is just probing (for DAD) and where the hardware address of
3964 		 * a non-authoritative entry has changed.  Thus, these are the
3965 		 * real conflicts, and we have to do resolution.
3966 		 *
3967 		 * We back away quickly from the address if it's from DHCP or
3968 		 * otherwise temporary and hasn't been used recently (or at
3969 		 * all).  We'd like to include "deprecated" addresses here as
3970 		 * well (as there's no real reason to defend something we're
3971 		 * discarding), but IPMP "reuses" this flag to mean something
3972 		 * other than the standard meaning.
3973 		 *
3974 		 * If the ARP module above is not extended (meaning that it
3975 		 * doesn't know how to defend the address), then we just log
3976 		 * the problem as we always did and continue on.  It's not
3977 		 * right, but there's little else we can do, and those old ATM
3978 		 * users are going away anyway.
3979 		 */
3980 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3981 		    hbuf, sizeof (hbuf));
3982 		(void) ip_dot_addr(src, sbuf);
3983 		if (isv6) {
3984 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3985 			    ipst);
3986 		} else {
3987 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3988 		}
3989 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3990 			uint32_t now;
3991 			uint32_t maxage;
3992 			clock_t lused;
3993 			uint_t maxdefense;
3994 			uint_t defs;
3995 
3996 			/*
3997 			 * First, figure out if this address hasn't been used
3998 			 * in a while.  If it hasn't, then it's a better
3999 			 * candidate for abandoning.
4000 			 */
4001 			ipif = ire->ire_ipif;
4002 			ASSERT(ipif != NULL);
4003 			now = gethrestime_sec();
4004 			maxage = now - ire->ire_create_time;
4005 			if (maxage > ipst->ips_ip_max_temp_idle)
4006 				maxage = ipst->ips_ip_max_temp_idle;
4007 			lused = drv_hztousec(ddi_get_lbolt() -
4008 			    ire->ire_last_used_time) / MICROSEC + 1;
4009 			if (lused >= maxage && (ipif->ipif_flags &
4010 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4011 				maxdefense = ipst->ips_ip_max_temp_defend;
4012 			else
4013 				maxdefense = ipst->ips_ip_max_defend;
4014 
4015 			/*
4016 			 * Now figure out how many times we've defended
4017 			 * ourselves.  Ignore defenses that happened long in
4018 			 * the past.
4019 			 */
4020 			mutex_enter(&ire->ire_lock);
4021 			if ((defs = ire->ire_defense_count) > 0 &&
4022 			    now - ire->ire_defense_time >
4023 			    ipst->ips_ip_defend_interval) {
4024 				ire->ire_defense_count = defs = 0;
4025 			}
4026 			ire->ire_defense_count++;
4027 			ire->ire_defense_time = now;
4028 			mutex_exit(&ire->ire_lock);
4029 			ill_refhold(ill);
4030 			ire_refrele(ire);
4031 
4032 			/*
4033 			 * If we've defended ourselves too many times already,
4034 			 * then give up and tear down the interface(s) using
4035 			 * this address.  Otherwise, defend by sending out a
4036 			 * gratuitous ARP.
4037 			 */
4038 			if (defs >= maxdefense && ill->ill_arp_extend) {
4039 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4040 				    B_FALSE);
4041 			} else {
4042 				cmn_err(CE_WARN,
4043 				    "node %s is using our IP address %s on %s",
4044 				    hbuf, sbuf, ill->ill_name);
4045 				/*
4046 				 * If this is an old (ATM) ARP module, then
4047 				 * don't try to defend the address.  Remain
4048 				 * compatible with the old behavior.  Defend
4049 				 * only with new ARP.
4050 				 */
4051 				if (ill->ill_arp_extend) {
4052 					qwriter_ip(ill, q, mp, ip_arp_defend,
4053 					    NEW_OP, B_FALSE);
4054 				} else {
4055 					ill_refrele(ill);
4056 				}
4057 			}
4058 			return;
4059 		}
4060 		cmn_err(CE_WARN,
4061 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4062 		    hbuf, sbuf, ill->ill_name);
4063 		if (ire != NULL)
4064 			ire_refrele(ire);
4065 		break;
4066 	case AR_CN_ANNOUNCE:
4067 		if (isv6) {
4068 			/*
4069 			 * For XRESOLV interfaces.
4070 			 * Delete the IRE cache entry and NCE for this
4071 			 * v6 address
4072 			 */
4073 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4074 			/*
4075 			 * If v6src is a non-zero, it's a router address
4076 			 * as below. Do the same sort of thing to clean
4077 			 * out off-net IRE_CACHE entries that go through
4078 			 * the router.
4079 			 */
4080 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4081 				ire_walk_v6(ire_delete_cache_gw_v6,
4082 				    (char *)&v6src, ALL_ZONES, ipst);
4083 			}
4084 		} else {
4085 			nce_hw_map_t hwm;
4086 
4087 			/*
4088 			 * ARP gives us a copy of any packet where it thinks
4089 			 * the address has changed, so that we can update our
4090 			 * caches.  We're responsible for caching known answers
4091 			 * in the current design.  We check whether the
4092 			 * hardware address really has changed in all of our
4093 			 * entries that have cached this mapping, and if so, we
4094 			 * blow them away.  This way we will immediately pick
4095 			 * up the rare case of a host changing hardware
4096 			 * address.
4097 			 */
4098 			if (src == 0)
4099 				break;
4100 			hwm.hwm_addr = src;
4101 			hwm.hwm_hwlen = arh->arh_hlen;
4102 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4103 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4104 			ndp_walk_common(ipst->ips_ndp4, NULL,
4105 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4106 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4107 		}
4108 		break;
4109 	case AR_CN_READY:
4110 		/* No external v6 resolver has a contract to use this */
4111 		if (isv6)
4112 			break;
4113 		/* If the link is down, we'll retry this later */
4114 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4115 			break;
4116 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4117 		    NULL, NULL, ipst);
4118 		if (ipif != NULL) {
4119 			/*
4120 			 * If this is a duplicate recovery, then we now need to
4121 			 * go exclusive to bring this thing back up.
4122 			 */
4123 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4124 			    IPIF_DUPLICATE) {
4125 				ipif_refrele(ipif);
4126 				ill_refhold(ill);
4127 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4128 				    B_FALSE);
4129 				return;
4130 			}
4131 			/*
4132 			 * If this is the first notice that this address is
4133 			 * ready, then let the user know now.
4134 			 */
4135 			if ((ipif->ipif_flags & IPIF_UP) &&
4136 			    !ipif->ipif_addr_ready) {
4137 				ipif_mask_reply(ipif);
4138 				ipif_up_notify(ipif);
4139 			}
4140 			ipif->ipif_addr_ready = 1;
4141 			ipif_refrele(ipif);
4142 		}
4143 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4144 		if (ire != NULL) {
4145 			ire->ire_defense_count = 0;
4146 			ire_refrele(ire);
4147 		}
4148 		break;
4149 	case AR_CN_FAILED:
4150 		/* No external v6 resolver has a contract to use this */
4151 		if (isv6)
4152 			break;
4153 		if (!ill->ill_arp_extend) {
4154 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4155 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4156 			(void) ip_dot_addr(src, sbuf);
4157 
4158 			cmn_err(CE_WARN,
4159 			    "node %s is using our IP address %s on %s",
4160 			    hbuf, sbuf, ill->ill_name);
4161 			break;
4162 		}
4163 		ill_refhold(ill);
4164 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4165 		return;
4166 	}
4167 	freemsg(mp);
4168 }
4169 
4170 /*
4171  * Create a mblk suitable for carrying the interface index and/or source link
4172  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4173  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4174  * application.
4175  */
4176 mblk_t *
4177 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4178     ip_stack_t *ipst)
4179 {
4180 	mblk_t		*mp;
4181 	ip_pktinfo_t	*pinfo;
4182 	ipha_t 		*ipha;
4183 	struct ether_header *pether;
4184 	boolean_t	ipmp_ill_held = B_FALSE;
4185 
4186 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4187 	if (mp == NULL) {
4188 		ip1dbg(("ip_add_info: allocation failure.\n"));
4189 		return (data_mp);
4190 	}
4191 
4192 	ipha = (ipha_t *)data_mp->b_rptr;
4193 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4194 	bzero(pinfo, sizeof (ip_pktinfo_t));
4195 	pinfo->ip_pkt_flags = (uchar_t)flags;
4196 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4197 
4198 	pether = (struct ether_header *)((char *)ipha
4199 	    - sizeof (struct ether_header));
4200 
4201 	/*
4202 	 * Make sure the interface is an ethernet type, since this option
4203 	 * is currently supported only on this type of interface. Also make
4204 	 * sure we are pointing correctly above db_base.
4205 	 */
4206 	if ((flags & IPF_RECVSLLA) &&
4207 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4208 	    (ill->ill_type == IFT_ETHER) &&
4209 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4210 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4211 		bcopy(pether->ether_shost.ether_addr_octet,
4212 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4213 	} else {
4214 		/*
4215 		 * Clear the bit. Indicate to upper layer that IP is not
4216 		 * sending this ancillary info.
4217 		 */
4218 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4219 	}
4220 
4221 	/*
4222 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4223 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4224 	 * IPF_RECVADDR support on test addresses is not needed.)
4225 	 *
4226 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4227 	 * processing a packet looped back to an IPMP data address
4228 	 * (since those IRE_LOCALs are tied to IPMP ills).
4229 	 */
4230 	if (IS_UNDER_IPMP(ill)) {
4231 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4232 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4233 			freemsg(mp);
4234 			return (data_mp);
4235 		}
4236 		ipmp_ill_held = B_TRUE;
4237 	}
4238 
4239 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4240 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4241 	if (flags & IPF_RECVADDR) {
4242 		ipif_t	*ipif;
4243 		ire_t	*ire;
4244 
4245 		/*
4246 		 * Only valid for V4
4247 		 */
4248 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4249 		    (IPV4_VERSION << 4));
4250 
4251 		ipif = ipif_get_next_ipif(NULL, ill);
4252 		if (ipif != NULL) {
4253 			/*
4254 			 * Since a decision has already been made to deliver the
4255 			 * packet, there is no need to test for SECATTR and
4256 			 * ZONEONLY.
4257 			 * When a multicast packet is transmitted
4258 			 * a cache entry is created for the multicast address.
4259 			 * When delivering a copy of the packet or when new
4260 			 * packets are received we do not want to match on the
4261 			 * cached entry so explicitly match on
4262 			 * IRE_LOCAL and IRE_LOOPBACK
4263 			 */
4264 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4265 			    IRE_LOCAL | IRE_LOOPBACK,
4266 			    ipif, zoneid, NULL,
4267 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4268 			if (ire == NULL) {
4269 				/*
4270 				 * packet must have come on a different
4271 				 * interface.
4272 				 * Since a decision has already been made to
4273 				 * deliver the packet, there is no need to test
4274 				 * for SECATTR and ZONEONLY.
4275 				 * Only match on local and broadcast ire's.
4276 				 * See detailed comment above.
4277 				 */
4278 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4279 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4280 				    NULL, MATCH_IRE_TYPE, ipst);
4281 			}
4282 
4283 			if (ire == NULL) {
4284 				/*
4285 				 * This is either a multicast packet or
4286 				 * the address has been removed since
4287 				 * the packet was received.
4288 				 * Return INADDR_ANY so that normal source
4289 				 * selection occurs for the response.
4290 				 */
4291 
4292 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4293 			} else {
4294 				pinfo->ip_pkt_match_addr.s_addr =
4295 				    ire->ire_src_addr;
4296 				ire_refrele(ire);
4297 			}
4298 			ipif_refrele(ipif);
4299 		} else {
4300 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4301 		}
4302 	}
4303 
4304 	if (ipmp_ill_held)
4305 		ill_refrele(ill);
4306 
4307 	mp->b_datap->db_type = M_CTL;
4308 	mp->b_wptr += sizeof (ip_pktinfo_t);
4309 	mp->b_cont = data_mp;
4310 
4311 	return (mp);
4312 }
4313 
4314 /*
4315  * Used to determine the most accurate cred_t to use for TX.
4316  * First priority is SCM_UCRED having set the label in the message,
4317  * which is used for MLP on UDP. Second priority is the peers label (aka
4318  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4319  * open credentials.
4320  */
4321 cred_t *
4322 ip_best_cred(mblk_t *mp, conn_t *connp)
4323 {
4324 	cred_t *cr;
4325 
4326 	cr = msg_getcred(mp, NULL);
4327 	if (cr != NULL && crgetlabel(cr) != NULL)
4328 		return (cr);
4329 	return (CONN_CRED(connp));
4330 }
4331 
4332 /*
4333  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4334  * part of the bind request.
4335  */
4336 
4337 boolean_t
4338 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4339 {
4340 	ipsec_in_t *ii;
4341 
4342 	ASSERT(policy_mp != NULL);
4343 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4344 
4345 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4346 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4347 
4348 	connp->conn_policy = ii->ipsec_in_policy;
4349 	ii->ipsec_in_policy = NULL;
4350 
4351 	if (ii->ipsec_in_action != NULL) {
4352 		if (connp->conn_latch == NULL) {
4353 			connp->conn_latch = iplatch_create();
4354 			if (connp->conn_latch == NULL)
4355 				return (B_FALSE);
4356 		}
4357 		ipsec_latch_inbound(connp->conn_latch, ii);
4358 	}
4359 	return (B_TRUE);
4360 }
4361 
4362 static void
4363 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4364 {
4365 	/*
4366 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4367 	 * We can't do this in ip_bind_get_ire because the policy
4368 	 * may not have been inherited at that point in time and hence
4369 	 * conn_out_enforce_policy may not be set.
4370 	 */
4371 	if (ire_requested && connp->conn_out_enforce_policy &&
4372 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4373 		ire_t *ire = (ire_t *)mp->b_rptr;
4374 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4375 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4376 	}
4377 }
4378 
4379 /*
4380  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4381  * and to arrange for power-fanout assist.  The ULP is identified by
4382  * adding a single byte at the end of the original bind message.
4383  * A ULP other than UDP or TCP that wishes to be recognized passes
4384  * down a bind with a zero length address.
4385  *
4386  * The binding works as follows:
4387  * - A zero byte address means just bind to the protocol.
4388  * - A four byte address is treated as a request to validate
4389  *   that the address is a valid local address, appropriate for
4390  *   an application to bind to. This does not affect any fanout
4391  *   information in IP.
4392  * - A sizeof sin_t byte address is used to bind to only the local address
4393  *   and port.
4394  * - A sizeof ipa_conn_t byte address contains complete fanout information
4395  *   consisting of local and remote addresses and ports.  In
4396  *   this case, the addresses are both validated as appropriate
4397  *   for this operation, and, if so, the information is retained
4398  *   for use in the inbound fanout.
4399  *
4400  * The ULP (except in the zero-length bind) can append an
4401  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4402  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4403  * a copy of the source or destination IRE (source for local bind;
4404  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4405  * policy information contained should be copied on to the conn.
4406  *
4407  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4408  */
4409 mblk_t *
4410 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4411 {
4412 	ssize_t		len;
4413 	struct T_bind_req	*tbr;
4414 	sin_t		*sin;
4415 	ipa_conn_t	*ac;
4416 	uchar_t		*ucp;
4417 	mblk_t		*mp1;
4418 	boolean_t	ire_requested;
4419 	int		error = 0;
4420 	int		protocol;
4421 	ipa_conn_x_t	*acx;
4422 	cred_t		*cr;
4423 
4424 	/*
4425 	 * All Solaris components should pass a db_credp
4426 	 * for this TPI message, hence we ASSERT.
4427 	 * But in case there is some other M_PROTO that looks
4428 	 * like a TPI message sent by some other kernel
4429 	 * component, we check and return an error.
4430 	 */
4431 	cr = msg_getcred(mp, NULL);
4432 	ASSERT(cr != NULL);
4433 	if (cr == NULL) {
4434 		error = EINVAL;
4435 		goto bad_addr;
4436 	}
4437 
4438 	ASSERT(!connp->conn_af_isv6);
4439 	connp->conn_pkt_isv6 = B_FALSE;
4440 
4441 	len = MBLKL(mp);
4442 	if (len < (sizeof (*tbr) + 1)) {
4443 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4444 		    "ip_bind: bogus msg, len %ld", len);
4445 		/* XXX: Need to return something better */
4446 		goto bad_addr;
4447 	}
4448 	/* Back up and extract the protocol identifier. */
4449 	mp->b_wptr--;
4450 	protocol = *mp->b_wptr & 0xFF;
4451 	tbr = (struct T_bind_req *)mp->b_rptr;
4452 	/* Reset the message type in preparation for shipping it back. */
4453 	DB_TYPE(mp) = M_PCPROTO;
4454 
4455 	connp->conn_ulp = (uint8_t)protocol;
4456 
4457 	/*
4458 	 * Check for a zero length address.  This is from a protocol that
4459 	 * wants to register to receive all packets of its type.
4460 	 */
4461 	if (tbr->ADDR_length == 0) {
4462 		/*
4463 		 * These protocols are now intercepted in ip_bind_v6().
4464 		 * Reject protocol-level binds here for now.
4465 		 *
4466 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4467 		 * so that the protocol type cannot be SCTP.
4468 		 */
4469 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4470 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4471 			goto bad_addr;
4472 		}
4473 
4474 		/*
4475 		 *
4476 		 * The udp module never sends down a zero-length address,
4477 		 * and allowing this on a labeled system will break MLP
4478 		 * functionality.
4479 		 */
4480 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4481 			goto bad_addr;
4482 
4483 		if (connp->conn_mac_exempt)
4484 			goto bad_addr;
4485 
4486 		/* No hash here really.  The table is big enough. */
4487 		connp->conn_srcv6 = ipv6_all_zeros;
4488 
4489 		ipcl_proto_insert(connp, protocol);
4490 
4491 		tbr->PRIM_type = T_BIND_ACK;
4492 		return (mp);
4493 	}
4494 
4495 	/* Extract the address pointer from the message. */
4496 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4497 	    tbr->ADDR_length);
4498 	if (ucp == NULL) {
4499 		ip1dbg(("ip_bind: no address\n"));
4500 		goto bad_addr;
4501 	}
4502 	if (!OK_32PTR(ucp)) {
4503 		ip1dbg(("ip_bind: unaligned address\n"));
4504 		goto bad_addr;
4505 	}
4506 	/*
4507 	 * Check for trailing mps.
4508 	 */
4509 
4510 	mp1 = mp->b_cont;
4511 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4512 
4513 	switch (tbr->ADDR_length) {
4514 	default:
4515 		ip1dbg(("ip_bind: bad address length %d\n",
4516 		    (int)tbr->ADDR_length));
4517 		goto bad_addr;
4518 
4519 	case IP_ADDR_LEN:
4520 		/* Verification of local address only */
4521 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4522 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4523 		break;
4524 
4525 	case sizeof (sin_t):
4526 		sin = (sin_t *)ucp;
4527 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4528 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4529 		break;
4530 
4531 	case sizeof (ipa_conn_t):
4532 		ac = (ipa_conn_t *)ucp;
4533 		/* For raw socket, the local port is not set. */
4534 		if (ac->ac_lport == 0)
4535 			ac->ac_lport = connp->conn_lport;
4536 		/* Always verify destination reachability. */
4537 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4538 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4539 		    B_TRUE, B_TRUE, cr);
4540 		break;
4541 
4542 	case sizeof (ipa_conn_x_t):
4543 		acx = (ipa_conn_x_t *)ucp;
4544 		/*
4545 		 * Whether or not to verify destination reachability depends
4546 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4547 		 */
4548 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4549 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4550 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4551 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4552 		break;
4553 	}
4554 	ASSERT(error != EINPROGRESS);
4555 	if (error != 0)
4556 		goto bad_addr;
4557 
4558 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4559 
4560 	/* Send it home. */
4561 	mp->b_datap->db_type = M_PCPROTO;
4562 	tbr->PRIM_type = T_BIND_ACK;
4563 	return (mp);
4564 
4565 bad_addr:
4566 	/*
4567 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4568 	 * a unix errno.
4569 	 */
4570 	if (error > 0)
4571 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4572 	else
4573 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4574 	return (mp);
4575 }
4576 
4577 /*
4578  * Here address is verified to be a valid local address.
4579  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4580  * address is also considered a valid local address.
4581  * In the case of a broadcast/multicast address, however, the
4582  * upper protocol is expected to reset the src address
4583  * to 0 if it sees a IRE_BROADCAST type returned so that
4584  * no packets are emitted with broadcast/multicast address as
4585  * source address (that violates hosts requirements RFC 1122)
4586  * The addresses valid for bind are:
4587  *	(1) - INADDR_ANY (0)
4588  *	(2) - IP address of an UP interface
4589  *	(3) - IP address of a DOWN interface
4590  *	(4) - valid local IP broadcast addresses. In this case
4591  *	the conn will only receive packets destined to
4592  *	the specified broadcast address.
4593  *	(5) - a multicast address. In this case
4594  *	the conn will only receive packets destined to
4595  *	the specified multicast address. Note: the
4596  *	application still has to issue an
4597  *	IP_ADD_MEMBERSHIP socket option.
4598  *
4599  * On error, return -1 for TBADADDR otherwise pass the
4600  * errno with TSYSERR reply.
4601  *
4602  * In all the above cases, the bound address must be valid in the current zone.
4603  * When the address is loopback, multicast or broadcast, there might be many
4604  * matching IREs so bind has to look up based on the zone.
4605  *
4606  * Note: lport is in network byte order.
4607  *
4608  */
4609 int
4610 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4611     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4612 {
4613 	int		error = 0;
4614 	ire_t		*src_ire;
4615 	zoneid_t	zoneid;
4616 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4617 	mblk_t		*mp = NULL;
4618 	boolean_t	ire_requested = B_FALSE;
4619 	boolean_t	ipsec_policy_set = B_FALSE;
4620 
4621 	if (mpp)
4622 		mp = *mpp;
4623 
4624 	if (mp != NULL) {
4625 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4626 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4627 	}
4628 
4629 	/*
4630 	 * If it was previously connected, conn_fully_bound would have
4631 	 * been set.
4632 	 */
4633 	connp->conn_fully_bound = B_FALSE;
4634 
4635 	src_ire = NULL;
4636 
4637 	zoneid = IPCL_ZONEID(connp);
4638 
4639 	if (src_addr) {
4640 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4641 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4642 		/*
4643 		 * If an address other than 0.0.0.0 is requested,
4644 		 * we verify that it is a valid address for bind
4645 		 * Note: Following code is in if-else-if form for
4646 		 * readability compared to a condition check.
4647 		 */
4648 		/* LINTED - statement has no consequence */
4649 		if (IRE_IS_LOCAL(src_ire)) {
4650 			/*
4651 			 * (2) Bind to address of local UP interface
4652 			 */
4653 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4654 			/*
4655 			 * (4) Bind to broadcast address
4656 			 * Note: permitted only from transports that
4657 			 * request IRE
4658 			 */
4659 			if (!ire_requested)
4660 				error = EADDRNOTAVAIL;
4661 		} else {
4662 			/*
4663 			 * (3) Bind to address of local DOWN interface
4664 			 * (ipif_lookup_addr() looks up all interfaces
4665 			 * but we do not get here for UP interfaces
4666 			 * - case (2) above)
4667 			 */
4668 			/* LINTED - statement has no consequent */
4669 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4670 				/* The address exists */
4671 			} else if (CLASSD(src_addr)) {
4672 				error = 0;
4673 				if (src_ire != NULL)
4674 					ire_refrele(src_ire);
4675 				/*
4676 				 * (5) bind to multicast address.
4677 				 * Fake out the IRE returned to upper
4678 				 * layer to be a broadcast IRE.
4679 				 */
4680 				src_ire = ire_ctable_lookup(
4681 				    INADDR_BROADCAST, INADDR_ANY,
4682 				    IRE_BROADCAST, NULL, zoneid, NULL,
4683 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4684 				    ipst);
4685 				if (src_ire == NULL || !ire_requested)
4686 					error = EADDRNOTAVAIL;
4687 			} else {
4688 				/*
4689 				 * Not a valid address for bind
4690 				 */
4691 				error = EADDRNOTAVAIL;
4692 			}
4693 		}
4694 		if (error) {
4695 			/* Red Alert!  Attempting to be a bogon! */
4696 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4697 			    ntohl(src_addr)));
4698 			goto bad_addr;
4699 		}
4700 	}
4701 
4702 	/*
4703 	 * Allow setting new policies. For example, disconnects come
4704 	 * down as ipa_t bind. As we would have set conn_policy_cached
4705 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4706 	 * can change after the disconnect.
4707 	 */
4708 	connp->conn_policy_cached = B_FALSE;
4709 
4710 	/*
4711 	 * If not fanout_insert this was just an address verification
4712 	 */
4713 	if (fanout_insert) {
4714 		/*
4715 		 * The addresses have been verified. Time to insert in
4716 		 * the correct fanout list.
4717 		 */
4718 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4719 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4720 		connp->conn_lport = lport;
4721 		connp->conn_fport = 0;
4722 		/*
4723 		 * Do we need to add a check to reject Multicast packets
4724 		 */
4725 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4726 	}
4727 
4728 	if (error == 0) {
4729 		if (ire_requested) {
4730 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4731 				error = -1;
4732 				/* Falls through to bad_addr */
4733 			}
4734 		} else if (ipsec_policy_set) {
4735 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4736 				error = -1;
4737 				/* Falls through to bad_addr */
4738 			}
4739 		}
4740 	}
4741 bad_addr:
4742 	if (error != 0) {
4743 		if (connp->conn_anon_port) {
4744 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4745 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4746 			    B_FALSE);
4747 		}
4748 		connp->conn_mlp_type = mlptSingle;
4749 	}
4750 	if (src_ire != NULL)
4751 		IRE_REFRELE(src_ire);
4752 	return (error);
4753 }
4754 
4755 int
4756 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4757     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4758 {
4759 	int error;
4760 	mblk_t	*mp = NULL;
4761 	boolean_t ire_requested;
4762 
4763 	if (ire_mpp)
4764 		mp = *ire_mpp;
4765 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4766 
4767 	ASSERT(!connp->conn_af_isv6);
4768 	connp->conn_pkt_isv6 = B_FALSE;
4769 	connp->conn_ulp = protocol;
4770 
4771 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4772 	    fanout_insert);
4773 	if (error == 0) {
4774 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4775 		    ire_requested);
4776 	} else if (error < 0) {
4777 		error = -TBADADDR;
4778 	}
4779 	return (error);
4780 }
4781 
4782 /*
4783  * Verify that both the source and destination addresses
4784  * are valid.  If verify_dst is false, then the destination address may be
4785  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4786  * destination reachability, while tunnels do not.
4787  * Note that we allow connect to broadcast and multicast
4788  * addresses when ire_requested is set. Thus the ULP
4789  * has to check for IRE_BROADCAST and multicast.
4790  *
4791  * Returns zero if ok.
4792  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4793  * (for use with TSYSERR reply).
4794  *
4795  * Note: lport and fport are in network byte order.
4796  */
4797 int
4798 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4799     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4800     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4801 {
4802 
4803 	ire_t		*src_ire;
4804 	ire_t		*dst_ire;
4805 	int		error = 0;
4806 	ire_t		*sire = NULL;
4807 	ire_t		*md_dst_ire = NULL;
4808 	ire_t		*lso_dst_ire = NULL;
4809 	ill_t		*ill = NULL;
4810 	zoneid_t	zoneid;
4811 	ipaddr_t	src_addr = *src_addrp;
4812 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4813 	mblk_t		*mp = NULL;
4814 	boolean_t	ire_requested = B_FALSE;
4815 	boolean_t	ipsec_policy_set = B_FALSE;
4816 	ts_label_t	*tsl = NULL;
4817 
4818 	if (mpp)
4819 		mp = *mpp;
4820 
4821 	if (mp != NULL) {
4822 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4823 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4824 	}
4825 	if (cr != NULL)
4826 		tsl = crgetlabel(cr);
4827 
4828 	src_ire = dst_ire = NULL;
4829 
4830 	/*
4831 	 * If we never got a disconnect before, clear it now.
4832 	 */
4833 	connp->conn_fully_bound = B_FALSE;
4834 
4835 	zoneid = IPCL_ZONEID(connp);
4836 
4837 	if (CLASSD(dst_addr)) {
4838 		/* Pick up an IRE_BROADCAST */
4839 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4840 		    NULL, zoneid, tsl,
4841 		    (MATCH_IRE_RECURSIVE |
4842 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4843 		    MATCH_IRE_SECATTR), ipst);
4844 	} else {
4845 		/*
4846 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4847 		 * and onlink ipif is not found set ENETUNREACH error.
4848 		 */
4849 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4850 			ipif_t *ipif;
4851 
4852 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4853 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4854 			if (ipif == NULL) {
4855 				error = ENETUNREACH;
4856 				goto bad_addr;
4857 			}
4858 			ipif_refrele(ipif);
4859 		}
4860 
4861 		if (connp->conn_nexthop_set) {
4862 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4863 			    0, 0, NULL, NULL, zoneid, tsl,
4864 			    MATCH_IRE_SECATTR, ipst);
4865 		} else {
4866 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4867 			    &sire, zoneid, tsl,
4868 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4869 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4870 			    MATCH_IRE_SECATTR), ipst);
4871 		}
4872 	}
4873 	/*
4874 	 * dst_ire can't be a broadcast when not ire_requested.
4875 	 * We also prevent ire's with src address INADDR_ANY to
4876 	 * be used, which are created temporarily for
4877 	 * sending out packets from endpoints that have
4878 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4879 	 * reachable.  If verify_dst is false, the destination needn't be
4880 	 * reachable.
4881 	 *
4882 	 * If we match on a reject or black hole, then we've got a
4883 	 * local failure.  May as well fail out the connect() attempt,
4884 	 * since it's never going to succeed.
4885 	 */
4886 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4887 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4888 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4889 		/*
4890 		 * If we're verifying destination reachability, we always want
4891 		 * to complain here.
4892 		 *
4893 		 * If we're not verifying destination reachability but the
4894 		 * destination has a route, we still want to fail on the
4895 		 * temporary address and broadcast address tests.
4896 		 */
4897 		if (verify_dst || (dst_ire != NULL)) {
4898 			if (ip_debug > 2) {
4899 				pr_addr_dbg("ip_bind_connected_v4:"
4900 				    "bad connected dst %s\n",
4901 				    AF_INET, &dst_addr);
4902 			}
4903 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4904 				error = ENETUNREACH;
4905 			else
4906 				error = EHOSTUNREACH;
4907 			goto bad_addr;
4908 		}
4909 	}
4910 
4911 	/*
4912 	 * We now know that routing will allow us to reach the destination.
4913 	 * Check whether Trusted Solaris policy allows communication with this
4914 	 * host, and pretend that the destination is unreachable if not.
4915 	 *
4916 	 * This is never a problem for TCP, since that transport is known to
4917 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4918 	 * handling.  If the remote is unreachable, it will be detected at that
4919 	 * point, so there's no reason to check it here.
4920 	 *
4921 	 * Note that for sendto (and other datagram-oriented friends), this
4922 	 * check is done as part of the data path label computation instead.
4923 	 * The check here is just to make non-TCP connect() report the right
4924 	 * error.
4925 	 */
4926 	if (dst_ire != NULL && is_system_labeled() &&
4927 	    !IPCL_IS_TCP(connp) &&
4928 	    tsol_compute_label(cr, dst_addr, NULL,
4929 	    connp->conn_mac_exempt, ipst) != 0) {
4930 		error = EHOSTUNREACH;
4931 		if (ip_debug > 2) {
4932 			pr_addr_dbg("ip_bind_connected_v4:"
4933 			    " no label for dst %s\n",
4934 			    AF_INET, &dst_addr);
4935 		}
4936 		goto bad_addr;
4937 	}
4938 
4939 	/*
4940 	 * If the app does a connect(), it means that it will most likely
4941 	 * send more than 1 packet to the destination.  It makes sense
4942 	 * to clear the temporary flag.
4943 	 */
4944 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4945 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4946 		irb_t *irb = dst_ire->ire_bucket;
4947 
4948 		rw_enter(&irb->irb_lock, RW_WRITER);
4949 		/*
4950 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4951 		 * the lock to guarantee irb_tmp_ire_cnt.
4952 		 */
4953 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4954 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4955 			irb->irb_tmp_ire_cnt--;
4956 		}
4957 		rw_exit(&irb->irb_lock);
4958 	}
4959 
4960 	/*
4961 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4962 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4963 	 * eligibility tests for passive connects are handled separately
4964 	 * through tcp_adapt_ire().  We do this before the source address
4965 	 * selection, because dst_ire may change after a call to
4966 	 * ipif_select_source().  This is a best-effort check, as the
4967 	 * packet for this connection may not actually go through
4968 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4969 	 * calling ip_newroute().  This is why we further check on the
4970 	 * IRE during LSO/Multidata packet transmission in
4971 	 * tcp_lsosend()/tcp_multisend().
4972 	 */
4973 	if (!ipsec_policy_set && dst_ire != NULL &&
4974 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4975 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4976 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4977 			lso_dst_ire = dst_ire;
4978 			IRE_REFHOLD(lso_dst_ire);
4979 		} else if (ipst->ips_ip_multidata_outbound &&
4980 		    ILL_MDT_CAPABLE(ill)) {
4981 			md_dst_ire = dst_ire;
4982 			IRE_REFHOLD(md_dst_ire);
4983 		}
4984 	}
4985 
4986 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4987 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4988 		/*
4989 		 * If the IRE belongs to a different zone, look for a matching
4990 		 * route in the forwarding table and use the source address from
4991 		 * that route.
4992 		 */
4993 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4994 		    zoneid, 0, NULL,
4995 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4996 		    MATCH_IRE_RJ_BHOLE, ipst);
4997 		if (src_ire == NULL) {
4998 			error = EHOSTUNREACH;
4999 			goto bad_addr;
5000 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5001 			if (!(src_ire->ire_type & IRE_HOST))
5002 				error = ENETUNREACH;
5003 			else
5004 				error = EHOSTUNREACH;
5005 			goto bad_addr;
5006 		}
5007 		if (src_addr == INADDR_ANY)
5008 			src_addr = src_ire->ire_src_addr;
5009 		ire_refrele(src_ire);
5010 		src_ire = NULL;
5011 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5012 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5013 			src_addr = sire->ire_src_addr;
5014 			ire_refrele(dst_ire);
5015 			dst_ire = sire;
5016 			sire = NULL;
5017 		} else {
5018 			/*
5019 			 * Pick a source address so that a proper inbound
5020 			 * load spreading would happen.
5021 			 */
5022 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5023 			ipif_t *src_ipif = NULL;
5024 			ire_t *ipif_ire;
5025 
5026 			/*
5027 			 * Supply a local source address such that inbound
5028 			 * load spreading happens.
5029 			 *
5030 			 * Determine the best source address on this ill for
5031 			 * the destination.
5032 			 *
5033 			 * 1) For broadcast, we should return a broadcast ire
5034 			 *    found above so that upper layers know that the
5035 			 *    destination address is a broadcast address.
5036 			 *
5037 			 * 2) If the ipif is DEPRECATED, select a better
5038 			 *    source address.  Similarly, if the ipif is on
5039 			 *    the IPMP meta-interface, pick a source address
5040 			 *    at random to improve inbound load spreading.
5041 			 *
5042 			 * 3) If the outgoing interface is part of a usesrc
5043 			 *    group, then try selecting a source address from
5044 			 *    the usesrc ILL.
5045 			 */
5046 			if ((dst_ire->ire_zoneid != zoneid &&
5047 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5048 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5049 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5050 			    (IS_IPMP(ire_ill) ||
5051 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5052 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5053 				/*
5054 				 * If the destination is reachable via a
5055 				 * given gateway, the selected source address
5056 				 * should be in the same subnet as the gateway.
5057 				 * Otherwise, the destination is not reachable.
5058 				 *
5059 				 * If there are no interfaces on the same subnet
5060 				 * as the destination, ipif_select_source gives
5061 				 * first non-deprecated interface which might be
5062 				 * on a different subnet than the gateway.
5063 				 * This is not desirable. Hence pass the dst_ire
5064 				 * source address to ipif_select_source.
5065 				 * It is sure that the destination is reachable
5066 				 * with the dst_ire source address subnet.
5067 				 * So passing dst_ire source address to
5068 				 * ipif_select_source will make sure that the
5069 				 * selected source will be on the same subnet
5070 				 * as dst_ire source address.
5071 				 */
5072 				ipaddr_t saddr =
5073 				    dst_ire->ire_ipif->ipif_src_addr;
5074 				src_ipif = ipif_select_source(ire_ill,
5075 				    saddr, zoneid);
5076 				if (src_ipif != NULL) {
5077 					if (IS_VNI(src_ipif->ipif_ill)) {
5078 						/*
5079 						 * For VNI there is no
5080 						 * interface route
5081 						 */
5082 						src_addr =
5083 						    src_ipif->ipif_src_addr;
5084 					} else {
5085 						ipif_ire =
5086 						    ipif_to_ire(src_ipif);
5087 						if (ipif_ire != NULL) {
5088 							IRE_REFRELE(dst_ire);
5089 							dst_ire = ipif_ire;
5090 						}
5091 						src_addr =
5092 						    dst_ire->ire_src_addr;
5093 					}
5094 					ipif_refrele(src_ipif);
5095 				} else {
5096 					src_addr = dst_ire->ire_src_addr;
5097 				}
5098 			} else {
5099 				src_addr = dst_ire->ire_src_addr;
5100 			}
5101 		}
5102 	}
5103 
5104 	/*
5105 	 * We do ire_route_lookup() here (and not
5106 	 * interface lookup as we assert that
5107 	 * src_addr should only come from an
5108 	 * UP interface for hard binding.
5109 	 */
5110 	ASSERT(src_ire == NULL);
5111 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5112 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5113 	/* src_ire must be a local|loopback */
5114 	if (!IRE_IS_LOCAL(src_ire)) {
5115 		if (ip_debug > 2) {
5116 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5117 			    "src %s\n", AF_INET, &src_addr);
5118 		}
5119 		error = EADDRNOTAVAIL;
5120 		goto bad_addr;
5121 	}
5122 
5123 	/*
5124 	 * If the source address is a loopback address, the
5125 	 * destination had best be local or multicast.
5126 	 * The transports that can't handle multicast will reject
5127 	 * those addresses.
5128 	 */
5129 	if (src_ire->ire_type == IRE_LOOPBACK &&
5130 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5131 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5132 		error = -1;
5133 		goto bad_addr;
5134 	}
5135 
5136 	/*
5137 	 * Allow setting new policies. For example, disconnects come
5138 	 * down as ipa_t bind. As we would have set conn_policy_cached
5139 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5140 	 * can change after the disconnect.
5141 	 */
5142 	connp->conn_policy_cached = B_FALSE;
5143 
5144 	/*
5145 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5146 	 * can handle their passed-in conn's.
5147 	 */
5148 
5149 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5150 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5151 	connp->conn_lport = lport;
5152 	connp->conn_fport = fport;
5153 	*src_addrp = src_addr;
5154 
5155 	ASSERT(!(ipsec_policy_set && ire_requested));
5156 	if (ire_requested) {
5157 		iulp_t *ulp_info = NULL;
5158 
5159 		/*
5160 		 * Note that sire will not be NULL if this is an off-link
5161 		 * connection and there is not cache for that dest yet.
5162 		 *
5163 		 * XXX Because of an existing bug, if there are multiple
5164 		 * default routes, the IRE returned now may not be the actual
5165 		 * default route used (default routes are chosen in a
5166 		 * round robin fashion).  So if the metrics for different
5167 		 * default routes are different, we may return the wrong
5168 		 * metrics.  This will not be a problem if the existing
5169 		 * bug is fixed.
5170 		 */
5171 		if (sire != NULL) {
5172 			ulp_info = &(sire->ire_uinfo);
5173 		}
5174 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5175 			error = -1;
5176 			goto bad_addr;
5177 		}
5178 		mp = *mpp;
5179 	} else if (ipsec_policy_set) {
5180 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5181 			error = -1;
5182 			goto bad_addr;
5183 		}
5184 	}
5185 
5186 	/*
5187 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5188 	 * we'll cache that.  If we don't, we'll inherit global policy.
5189 	 *
5190 	 * We can't insert until the conn reflects the policy. Note that
5191 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5192 	 * connections where we don't have a policy. This is to prevent
5193 	 * global policy lookups in the inbound path.
5194 	 *
5195 	 * If we insert before we set conn_policy_cached,
5196 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5197 	 * because global policy cound be non-empty. We normally call
5198 	 * ipsec_check_policy() for conn_policy_cached connections only if
5199 	 * ipc_in_enforce_policy is set. But in this case,
5200 	 * conn_policy_cached can get set anytime since we made the
5201 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5202 	 * called, which will make the above assumption false.  Thus, we
5203 	 * need to insert after we set conn_policy_cached.
5204 	 */
5205 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5206 		goto bad_addr;
5207 
5208 	if (fanout_insert) {
5209 		/*
5210 		 * The addresses have been verified. Time to insert in
5211 		 * the correct fanout list.
5212 		 */
5213 		error = ipcl_conn_insert(connp, protocol, src_addr,
5214 		    dst_addr, connp->conn_ports);
5215 	}
5216 
5217 	if (error == 0) {
5218 		connp->conn_fully_bound = B_TRUE;
5219 		/*
5220 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5221 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5222 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5223 		 * ip_xxinfo_return(), which performs further checks
5224 		 * against them and upon success, returns the LSO/MDT info
5225 		 * mblk which we will attach to the bind acknowledgment.
5226 		 */
5227 		if (lso_dst_ire != NULL) {
5228 			mblk_t *lsoinfo_mp;
5229 
5230 			ASSERT(ill->ill_lso_capab != NULL);
5231 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5232 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5233 				if (mp == NULL) {
5234 					*mpp = lsoinfo_mp;
5235 				} else {
5236 					linkb(mp, lsoinfo_mp);
5237 				}
5238 			}
5239 		} else if (md_dst_ire != NULL) {
5240 			mblk_t *mdinfo_mp;
5241 
5242 			ASSERT(ill->ill_mdt_capab != NULL);
5243 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5244 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5245 				if (mp == NULL) {
5246 					*mpp = mdinfo_mp;
5247 				} else {
5248 					linkb(mp, mdinfo_mp);
5249 				}
5250 			}
5251 		}
5252 	}
5253 bad_addr:
5254 	if (ipsec_policy_set) {
5255 		ASSERT(mp != NULL);
5256 		freeb(mp);
5257 		/*
5258 		 * As of now assume that nothing else accompanies
5259 		 * IPSEC_POLICY_SET.
5260 		 */
5261 		*mpp = NULL;
5262 	}
5263 	if (src_ire != NULL)
5264 		IRE_REFRELE(src_ire);
5265 	if (dst_ire != NULL)
5266 		IRE_REFRELE(dst_ire);
5267 	if (sire != NULL)
5268 		IRE_REFRELE(sire);
5269 	if (md_dst_ire != NULL)
5270 		IRE_REFRELE(md_dst_ire);
5271 	if (lso_dst_ire != NULL)
5272 		IRE_REFRELE(lso_dst_ire);
5273 	return (error);
5274 }
5275 
5276 int
5277 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5278     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5279     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5280 {
5281 	int error;
5282 	mblk_t	*mp = NULL;
5283 	boolean_t ire_requested;
5284 
5285 	if (ire_mpp)
5286 		mp = *ire_mpp;
5287 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5288 
5289 	ASSERT(!connp->conn_af_isv6);
5290 	connp->conn_pkt_isv6 = B_FALSE;
5291 	connp->conn_ulp = protocol;
5292 
5293 	/* For raw socket, the local port is not set. */
5294 	if (lport == 0)
5295 		lport = connp->conn_lport;
5296 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5297 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5298 	if (error == 0) {
5299 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5300 		    ire_requested);
5301 	} else if (error < 0) {
5302 		error = -TBADADDR;
5303 	}
5304 	return (error);
5305 }
5306 
5307 /*
5308  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5309  * Prefers dst_ire over src_ire.
5310  */
5311 static boolean_t
5312 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5313 {
5314 	mblk_t	*mp = *mpp;
5315 	ire_t	*ret_ire;
5316 
5317 	ASSERT(mp != NULL);
5318 
5319 	if (ire != NULL) {
5320 		/*
5321 		 * mp initialized above to IRE_DB_REQ_TYPE
5322 		 * appended mblk. Its <upper protocol>'s
5323 		 * job to make sure there is room.
5324 		 */
5325 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5326 			return (B_FALSE);
5327 
5328 		mp->b_datap->db_type = IRE_DB_TYPE;
5329 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5330 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5331 		ret_ire = (ire_t *)mp->b_rptr;
5332 		/*
5333 		 * Pass the latest setting of the ip_path_mtu_discovery and
5334 		 * copy the ulp info if any.
5335 		 */
5336 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5337 		    IPH_DF : 0;
5338 		if (ulp_info != NULL) {
5339 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5340 			    sizeof (iulp_t));
5341 		}
5342 		ret_ire->ire_mp = mp;
5343 	} else {
5344 		/*
5345 		 * No IRE was found. Remove IRE mblk.
5346 		 */
5347 		*mpp = mp->b_cont;
5348 		freeb(mp);
5349 	}
5350 	return (B_TRUE);
5351 }
5352 
5353 /*
5354  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5355  * the final piece where we don't.  Return a pointer to the first mblk in the
5356  * result, and update the pointer to the next mblk to chew on.  If anything
5357  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5358  * NULL pointer.
5359  */
5360 mblk_t *
5361 ip_carve_mp(mblk_t **mpp, ssize_t len)
5362 {
5363 	mblk_t	*mp0;
5364 	mblk_t	*mp1;
5365 	mblk_t	*mp2;
5366 
5367 	if (!len || !mpp || !(mp0 = *mpp))
5368 		return (NULL);
5369 	/* If we aren't going to consume the first mblk, we need a dup. */
5370 	if (mp0->b_wptr - mp0->b_rptr > len) {
5371 		mp1 = dupb(mp0);
5372 		if (mp1) {
5373 			/* Partition the data between the two mblks. */
5374 			mp1->b_wptr = mp1->b_rptr + len;
5375 			mp0->b_rptr = mp1->b_wptr;
5376 			/*
5377 			 * after adjustments if mblk not consumed is now
5378 			 * unaligned, try to align it. If this fails free
5379 			 * all messages and let upper layer recover.
5380 			 */
5381 			if (!OK_32PTR(mp0->b_rptr)) {
5382 				if (!pullupmsg(mp0, -1)) {
5383 					freemsg(mp0);
5384 					freemsg(mp1);
5385 					*mpp = NULL;
5386 					return (NULL);
5387 				}
5388 			}
5389 		}
5390 		return (mp1);
5391 	}
5392 	/* Eat through as many mblks as we need to get len bytes. */
5393 	len -= mp0->b_wptr - mp0->b_rptr;
5394 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5395 		if (mp2->b_wptr - mp2->b_rptr > len) {
5396 			/*
5397 			 * We won't consume the entire last mblk.  Like
5398 			 * above, dup and partition it.
5399 			 */
5400 			mp1->b_cont = dupb(mp2);
5401 			mp1 = mp1->b_cont;
5402 			if (!mp1) {
5403 				/*
5404 				 * Trouble.  Rather than go to a lot of
5405 				 * trouble to clean up, we free the messages.
5406 				 * This won't be any worse than losing it on
5407 				 * the wire.
5408 				 */
5409 				freemsg(mp0);
5410 				freemsg(mp2);
5411 				*mpp = NULL;
5412 				return (NULL);
5413 			}
5414 			mp1->b_wptr = mp1->b_rptr + len;
5415 			mp2->b_rptr = mp1->b_wptr;
5416 			/*
5417 			 * after adjustments if mblk not consumed is now
5418 			 * unaligned, try to align it. If this fails free
5419 			 * all messages and let upper layer recover.
5420 			 */
5421 			if (!OK_32PTR(mp2->b_rptr)) {
5422 				if (!pullupmsg(mp2, -1)) {
5423 					freemsg(mp0);
5424 					freemsg(mp2);
5425 					*mpp = NULL;
5426 					return (NULL);
5427 				}
5428 			}
5429 			*mpp = mp2;
5430 			return (mp0);
5431 		}
5432 		/* Decrement len by the amount we just got. */
5433 		len -= mp2->b_wptr - mp2->b_rptr;
5434 	}
5435 	/*
5436 	 * len should be reduced to zero now.  If not our caller has
5437 	 * screwed up.
5438 	 */
5439 	if (len) {
5440 		/* Shouldn't happen! */
5441 		freemsg(mp0);
5442 		*mpp = NULL;
5443 		return (NULL);
5444 	}
5445 	/*
5446 	 * We consumed up to exactly the end of an mblk.  Detach the part
5447 	 * we are returning from the rest of the chain.
5448 	 */
5449 	mp1->b_cont = NULL;
5450 	*mpp = mp2;
5451 	return (mp0);
5452 }
5453 
5454 /* The ill stream is being unplumbed. Called from ip_close */
5455 int
5456 ip_modclose(ill_t *ill)
5457 {
5458 	boolean_t success;
5459 	ipsq_t	*ipsq;
5460 	ipif_t	*ipif;
5461 	queue_t	*q = ill->ill_rq;
5462 	ip_stack_t	*ipst = ill->ill_ipst;
5463 	int	i;
5464 
5465 	/*
5466 	 * The punlink prior to this may have initiated a capability
5467 	 * negotiation. But ipsq_enter will block until that finishes or
5468 	 * times out.
5469 	 */
5470 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5471 
5472 	/*
5473 	 * Open/close/push/pop is guaranteed to be single threaded
5474 	 * per stream by STREAMS. FS guarantees that all references
5475 	 * from top are gone before close is called. So there can't
5476 	 * be another close thread that has set CONDEMNED on this ill.
5477 	 * and cause ipsq_enter to return failure.
5478 	 */
5479 	ASSERT(success);
5480 	ipsq = ill->ill_phyint->phyint_ipsq;
5481 
5482 	/*
5483 	 * Mark it condemned. No new reference will be made to this ill.
5484 	 * Lookup functions will return an error. Threads that try to
5485 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5486 	 * that the refcnt will drop down to zero.
5487 	 */
5488 	mutex_enter(&ill->ill_lock);
5489 	ill->ill_state_flags |= ILL_CONDEMNED;
5490 	for (ipif = ill->ill_ipif; ipif != NULL;
5491 	    ipif = ipif->ipif_next) {
5492 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5493 	}
5494 	/*
5495 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5496 	 * returns  error if ILL_CONDEMNED is set
5497 	 */
5498 	cv_broadcast(&ill->ill_cv);
5499 	mutex_exit(&ill->ill_lock);
5500 
5501 	/*
5502 	 * Send all the deferred DLPI messages downstream which came in
5503 	 * during the small window right before ipsq_enter(). We do this
5504 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5505 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5506 	 */
5507 	ill_dlpi_send_deferred(ill);
5508 
5509 	/*
5510 	 * Shut down fragmentation reassembly.
5511 	 * ill_frag_timer won't start a timer again.
5512 	 * Now cancel any existing timer
5513 	 */
5514 	(void) untimeout(ill->ill_frag_timer_id);
5515 	(void) ill_frag_timeout(ill, 0);
5516 
5517 	/*
5518 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5519 	 * this ill. Then wait for the refcnts to drop to zero.
5520 	 * ill_is_freeable checks whether the ill is really quiescent.
5521 	 * Then make sure that threads that are waiting to enter the
5522 	 * ipsq have seen the error returned by ipsq_enter and have
5523 	 * gone away. Then we call ill_delete_tail which does the
5524 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5525 	 */
5526 	ill_delete(ill);
5527 	mutex_enter(&ill->ill_lock);
5528 	while (!ill_is_freeable(ill))
5529 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5530 	while (ill->ill_waiters)
5531 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5532 
5533 	mutex_exit(&ill->ill_lock);
5534 
5535 	/*
5536 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5537 	 * it held until the end of the function since the cleanup
5538 	 * below needs to be able to use the ip_stack_t.
5539 	 */
5540 	netstack_hold(ipst->ips_netstack);
5541 
5542 	/* qprocsoff is done via ill_delete_tail */
5543 	ill_delete_tail(ill);
5544 	ASSERT(ill->ill_ipst == NULL);
5545 
5546 	/*
5547 	 * Walk through all upper (conn) streams and qenable
5548 	 * those that have queued data.
5549 	 * close synchronization needs this to
5550 	 * be done to ensure that all upper layers blocked
5551 	 * due to flow control to the closing device
5552 	 * get unblocked.
5553 	 */
5554 	ip1dbg(("ip_wsrv: walking\n"));
5555 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5556 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5557 	}
5558 
5559 	mutex_enter(&ipst->ips_ip_mi_lock);
5560 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5561 	mutex_exit(&ipst->ips_ip_mi_lock);
5562 
5563 	/*
5564 	 * credp could be null if the open didn't succeed and ip_modopen
5565 	 * itself calls ip_close.
5566 	 */
5567 	if (ill->ill_credp != NULL)
5568 		crfree(ill->ill_credp);
5569 
5570 	/*
5571 	 * Now we are done with the module close pieces that
5572 	 * need the netstack_t.
5573 	 */
5574 	netstack_rele(ipst->ips_netstack);
5575 
5576 	mi_close_free((IDP)ill);
5577 	q->q_ptr = WR(q)->q_ptr = NULL;
5578 
5579 	ipsq_exit(ipsq);
5580 
5581 	return (0);
5582 }
5583 
5584 /*
5585  * This is called as part of close() for IP, UDP, ICMP, and RTS
5586  * in order to quiesce the conn.
5587  */
5588 void
5589 ip_quiesce_conn(conn_t *connp)
5590 {
5591 	boolean_t	drain_cleanup_reqd = B_FALSE;
5592 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5593 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5594 	ip_stack_t	*ipst;
5595 
5596 	ASSERT(!IPCL_IS_TCP(connp));
5597 	ipst = connp->conn_netstack->netstack_ip;
5598 
5599 	/*
5600 	 * Mark the conn as closing, and this conn must not be
5601 	 * inserted in future into any list. Eg. conn_drain_insert(),
5602 	 * won't insert this conn into the conn_drain_list.
5603 	 * Similarly ill_pending_mp_add() will not add any mp to
5604 	 * the pending mp list, after this conn has started closing.
5605 	 *
5606 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5607 	 * cannot get set henceforth.
5608 	 */
5609 	mutex_enter(&connp->conn_lock);
5610 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5611 	connp->conn_state_flags |= CONN_CLOSING;
5612 	if (connp->conn_idl != NULL)
5613 		drain_cleanup_reqd = B_TRUE;
5614 	if (connp->conn_oper_pending_ill != NULL)
5615 		conn_ioctl_cleanup_reqd = B_TRUE;
5616 	if (connp->conn_dhcpinit_ill != NULL) {
5617 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5618 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5619 		connp->conn_dhcpinit_ill = NULL;
5620 	}
5621 	if (connp->conn_ilg_inuse != 0)
5622 		ilg_cleanup_reqd = B_TRUE;
5623 	mutex_exit(&connp->conn_lock);
5624 
5625 	if (conn_ioctl_cleanup_reqd)
5626 		conn_ioctl_cleanup(connp);
5627 
5628 	if (is_system_labeled() && connp->conn_anon_port) {
5629 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5630 		    connp->conn_mlp_type, connp->conn_ulp,
5631 		    ntohs(connp->conn_lport), B_FALSE);
5632 		connp->conn_anon_port = 0;
5633 	}
5634 	connp->conn_mlp_type = mlptSingle;
5635 
5636 	/*
5637 	 * Remove this conn from any fanout list it is on.
5638 	 * and then wait for any threads currently operating
5639 	 * on this endpoint to finish
5640 	 */
5641 	ipcl_hash_remove(connp);
5642 
5643 	/*
5644 	 * Remove this conn from the drain list, and do
5645 	 * any other cleanup that may be required.
5646 	 * (Only non-tcp streams may have a non-null conn_idl.
5647 	 * TCP streams are never flow controlled, and
5648 	 * conn_idl will be null)
5649 	 */
5650 	if (drain_cleanup_reqd)
5651 		conn_drain_tail(connp, B_TRUE);
5652 
5653 	if (connp == ipst->ips_ip_g_mrouter)
5654 		(void) ip_mrouter_done(NULL, ipst);
5655 
5656 	if (ilg_cleanup_reqd)
5657 		ilg_delete_all(connp);
5658 
5659 	conn_delete_ire(connp, NULL);
5660 
5661 	/*
5662 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5663 	 * callers from write side can't be there now because close
5664 	 * is in progress. The only other caller is ipcl_walk
5665 	 * which checks for the condemned flag.
5666 	 */
5667 	mutex_enter(&connp->conn_lock);
5668 	connp->conn_state_flags |= CONN_CONDEMNED;
5669 	while (connp->conn_ref != 1)
5670 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5671 	connp->conn_state_flags |= CONN_QUIESCED;
5672 	mutex_exit(&connp->conn_lock);
5673 }
5674 
5675 /* ARGSUSED */
5676 int
5677 ip_close(queue_t *q, int flags)
5678 {
5679 	conn_t		*connp;
5680 
5681 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5682 
5683 	/*
5684 	 * Call the appropriate delete routine depending on whether this is
5685 	 * a module or device.
5686 	 */
5687 	if (WR(q)->q_next != NULL) {
5688 		/* This is a module close */
5689 		return (ip_modclose((ill_t *)q->q_ptr));
5690 	}
5691 
5692 	connp = q->q_ptr;
5693 	ip_quiesce_conn(connp);
5694 
5695 	qprocsoff(q);
5696 
5697 	/*
5698 	 * Now we are truly single threaded on this stream, and can
5699 	 * delete the things hanging off the connp, and finally the connp.
5700 	 * We removed this connp from the fanout list, it cannot be
5701 	 * accessed thru the fanouts, and we already waited for the
5702 	 * conn_ref to drop to 0. We are already in close, so
5703 	 * there cannot be any other thread from the top. qprocsoff
5704 	 * has completed, and service has completed or won't run in
5705 	 * future.
5706 	 */
5707 	ASSERT(connp->conn_ref == 1);
5708 
5709 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5710 
5711 	connp->conn_ref--;
5712 	ipcl_conn_destroy(connp);
5713 
5714 	q->q_ptr = WR(q)->q_ptr = NULL;
5715 	return (0);
5716 }
5717 
5718 /*
5719  * Wapper around putnext() so that ip_rts_request can merely use
5720  * conn_recv.
5721  */
5722 /*ARGSUSED2*/
5723 static void
5724 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5725 {
5726 	conn_t *connp = (conn_t *)arg1;
5727 
5728 	putnext(connp->conn_rq, mp);
5729 }
5730 
5731 /*
5732  * Called when the module is about to be unloaded
5733  */
5734 void
5735 ip_ddi_destroy(void)
5736 {
5737 	tnet_fini();
5738 
5739 	icmp_ddi_g_destroy();
5740 	rts_ddi_g_destroy();
5741 	udp_ddi_g_destroy();
5742 	sctp_ddi_g_destroy();
5743 	tcp_ddi_g_destroy();
5744 	ipsec_policy_g_destroy();
5745 	ipcl_g_destroy();
5746 	ip_net_g_destroy();
5747 	ip_ire_g_fini();
5748 	inet_minor_destroy(ip_minor_arena_sa);
5749 #if defined(_LP64)
5750 	inet_minor_destroy(ip_minor_arena_la);
5751 #endif
5752 
5753 #ifdef DEBUG
5754 	list_destroy(&ip_thread_list);
5755 	rw_destroy(&ip_thread_rwlock);
5756 	tsd_destroy(&ip_thread_data);
5757 #endif
5758 
5759 	netstack_unregister(NS_IP);
5760 }
5761 
5762 /*
5763  * First step in cleanup.
5764  */
5765 /* ARGSUSED */
5766 static void
5767 ip_stack_shutdown(netstackid_t stackid, void *arg)
5768 {
5769 	ip_stack_t *ipst = (ip_stack_t *)arg;
5770 
5771 #ifdef NS_DEBUG
5772 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5773 #endif
5774 
5775 	/* Get rid of loopback interfaces and their IREs */
5776 	ip_loopback_cleanup(ipst);
5777 
5778 	/*
5779 	 * The *_hook_shutdown()s start the process of notifying any
5780 	 * consumers that things are going away.... nothing is destroyed.
5781 	 */
5782 	ipv4_hook_shutdown(ipst);
5783 	ipv6_hook_shutdown(ipst);
5784 
5785 	mutex_enter(&ipst->ips_capab_taskq_lock);
5786 	ipst->ips_capab_taskq_quit = B_TRUE;
5787 	cv_signal(&ipst->ips_capab_taskq_cv);
5788 	mutex_exit(&ipst->ips_capab_taskq_lock);
5789 
5790 	mutex_enter(&ipst->ips_mrt_lock);
5791 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5792 	cv_signal(&ipst->ips_mrt_cv);
5793 	mutex_exit(&ipst->ips_mrt_lock);
5794 }
5795 
5796 /*
5797  * Free the IP stack instance.
5798  */
5799 static void
5800 ip_stack_fini(netstackid_t stackid, void *arg)
5801 {
5802 	ip_stack_t *ipst = (ip_stack_t *)arg;
5803 	int ret;
5804 
5805 #ifdef NS_DEBUG
5806 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5807 #endif
5808 	/*
5809 	 * At this point, all of the notifications that the events and
5810 	 * protocols are going away have been run, meaning that we can
5811 	 * now set about starting to clean things up.
5812 	 */
5813 	ipv4_hook_destroy(ipst);
5814 	ipv6_hook_destroy(ipst);
5815 	ip_net_destroy(ipst);
5816 
5817 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5818 	cv_destroy(&ipst->ips_capab_taskq_cv);
5819 	list_destroy(&ipst->ips_capab_taskq_list);
5820 
5821 	mutex_enter(&ipst->ips_mrt_lock);
5822 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5823 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5824 	mutex_destroy(&ipst->ips_mrt_lock);
5825 	cv_destroy(&ipst->ips_mrt_cv);
5826 	cv_destroy(&ipst->ips_mrt_done_cv);
5827 
5828 	ipmp_destroy(ipst);
5829 	rw_destroy(&ipst->ips_srcid_lock);
5830 
5831 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5832 	ipst->ips_ip_mibkp = NULL;
5833 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5834 	ipst->ips_icmp_mibkp = NULL;
5835 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5836 	ipst->ips_ip_kstat = NULL;
5837 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5838 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5839 	ipst->ips_ip6_kstat = NULL;
5840 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5841 
5842 	nd_free(&ipst->ips_ip_g_nd);
5843 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5844 	ipst->ips_param_arr = NULL;
5845 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5846 	ipst->ips_ndp_arr = NULL;
5847 
5848 	ip_mrouter_stack_destroy(ipst);
5849 
5850 	mutex_destroy(&ipst->ips_ip_mi_lock);
5851 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5852 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5853 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5854 
5855 	ret = untimeout(ipst->ips_igmp_timeout_id);
5856 	if (ret == -1) {
5857 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5858 	} else {
5859 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5860 		ipst->ips_igmp_timeout_id = 0;
5861 	}
5862 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5867 		ipst->ips_igmp_slowtimeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_mld_timeout_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_mld_timeout_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_mld_timeout_id != 0);
5874 		ipst->ips_mld_timeout_id = 0;
5875 	}
5876 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5877 	if (ret == -1) {
5878 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5879 	} else {
5880 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5881 		ipst->ips_mld_slowtimeout_id = 0;
5882 	}
5883 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5884 	if (ret == -1) {
5885 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5886 	} else {
5887 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5888 		ipst->ips_ip_ire_expire_id = 0;
5889 	}
5890 
5891 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5892 	mutex_destroy(&ipst->ips_mld_timer_lock);
5893 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5894 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5895 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5896 	rw_destroy(&ipst->ips_ill_g_lock);
5897 
5898 	ipobs_fini(ipst);
5899 	ip_ire_fini(ipst);
5900 	ip6_asp_free(ipst);
5901 	conn_drain_fini(ipst);
5902 	ipcl_destroy(ipst);
5903 
5904 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5905 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5906 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5907 	ipst->ips_ndp4 = NULL;
5908 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5909 	ipst->ips_ndp6 = NULL;
5910 
5911 	if (ipst->ips_loopback_ksp != NULL) {
5912 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5913 		ipst->ips_loopback_ksp = NULL;
5914 	}
5915 
5916 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5917 	ipst->ips_phyint_g_list = NULL;
5918 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5919 	ipst->ips_ill_g_heads = NULL;
5920 
5921 	ldi_ident_release(ipst->ips_ldi_ident);
5922 	kmem_free(ipst, sizeof (*ipst));
5923 }
5924 
5925 /*
5926  * This function is called from the TSD destructor, and is used to debug
5927  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5928  * details.
5929  */
5930 static void
5931 ip_thread_exit(void *phash)
5932 {
5933 	th_hash_t *thh = phash;
5934 
5935 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5936 	list_remove(&ip_thread_list, thh);
5937 	rw_exit(&ip_thread_rwlock);
5938 	mod_hash_destroy_hash(thh->thh_hash);
5939 	kmem_free(thh, sizeof (*thh));
5940 }
5941 
5942 /*
5943  * Called when the IP kernel module is loaded into the kernel
5944  */
5945 void
5946 ip_ddi_init(void)
5947 {
5948 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5949 
5950 	/*
5951 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5952 	 * initial devices: ip, ip6, tcp, tcp6.
5953 	 */
5954 	/*
5955 	 * If this is a 64-bit kernel, then create two separate arenas -
5956 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5957 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5958 	 */
5959 	ip_minor_arena_la = NULL;
5960 	ip_minor_arena_sa = NULL;
5961 #if defined(_LP64)
5962 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5963 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5964 		cmn_err(CE_PANIC,
5965 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5966 	}
5967 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5968 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5969 		cmn_err(CE_PANIC,
5970 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5971 	}
5972 #else
5973 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5974 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5975 		cmn_err(CE_PANIC,
5976 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5977 	}
5978 #endif
5979 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5980 
5981 	ipcl_g_init();
5982 	ip_ire_g_init();
5983 	ip_net_g_init();
5984 
5985 #ifdef DEBUG
5986 	tsd_create(&ip_thread_data, ip_thread_exit);
5987 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5988 	list_create(&ip_thread_list, sizeof (th_hash_t),
5989 	    offsetof(th_hash_t, thh_link));
5990 #endif
5991 
5992 	/*
5993 	 * We want to be informed each time a stack is created or
5994 	 * destroyed in the kernel, so we can maintain the
5995 	 * set of udp_stack_t's.
5996 	 */
5997 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5998 	    ip_stack_fini);
5999 
6000 	ipsec_policy_g_init();
6001 	tcp_ddi_g_init();
6002 	sctp_ddi_g_init();
6003 
6004 	tnet_init();
6005 
6006 	udp_ddi_g_init();
6007 	rts_ddi_g_init();
6008 	icmp_ddi_g_init();
6009 }
6010 
6011 /*
6012  * Initialize the IP stack instance.
6013  */
6014 static void *
6015 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6016 {
6017 	ip_stack_t	*ipst;
6018 	ipparam_t	*pa;
6019 	ipndp_t		*na;
6020 	major_t		major;
6021 
6022 #ifdef NS_DEBUG
6023 	printf("ip_stack_init(stack %d)\n", stackid);
6024 #endif
6025 
6026 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6027 	ipst->ips_netstack = ns;
6028 
6029 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6030 	    KM_SLEEP);
6031 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6032 	    KM_SLEEP);
6033 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6034 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6035 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6036 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6037 
6038 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6039 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6040 	ipst->ips_igmp_deferred_next = INFINITY;
6041 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6042 	ipst->ips_mld_deferred_next = INFINITY;
6043 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6044 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6045 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6046 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6048 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6049 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6050 
6051 	ipcl_init(ipst);
6052 	ip_ire_init(ipst);
6053 	ip6_asp_init(ipst);
6054 	ipif_init(ipst);
6055 	conn_drain_init(ipst);
6056 	ip_mrouter_stack_init(ipst);
6057 
6058 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6059 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6060 
6061 	ipst->ips_ip_multirt_log_interval = 1000;
6062 
6063 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6064 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6065 	ipst->ips_ill_index = 1;
6066 
6067 	ipst->ips_saved_ip_g_forward = -1;
6068 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6069 
6070 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6071 	ipst->ips_param_arr = pa;
6072 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6073 
6074 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6075 	ipst->ips_ndp_arr = na;
6076 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6077 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6078 	    (caddr_t)&ipst->ips_ip_g_forward;
6079 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6080 	    (caddr_t)&ipst->ips_ipv6_forward;
6081 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6082 	    "ip_cgtp_filter") == 0);
6083 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6084 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6085 
6086 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6087 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6088 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6089 
6090 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6091 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6092 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6093 	ipst->ips_ip6_kstat =
6094 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6095 
6096 	ipst->ips_ip_src_id = 1;
6097 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6098 
6099 	ipobs_init(ipst);
6100 	ip_net_init(ipst, ns);
6101 	ipv4_hook_init(ipst);
6102 	ipv6_hook_init(ipst);
6103 	ipmp_init(ipst);
6104 
6105 	/*
6106 	 * Create the taskq dispatcher thread and initialize related stuff.
6107 	 */
6108 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6109 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6110 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6111 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6112 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6113 	    offsetof(mblk_t, b_next));
6114 
6115 	/*
6116 	 * Create the mcast_restart_timers_thread() worker thread.
6117 	 */
6118 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6119 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6120 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6121 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6122 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6123 
6124 	major = mod_name_to_major(INET_NAME);
6125 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6126 	return (ipst);
6127 }
6128 
6129 /*
6130  * Allocate and initialize a DLPI template of the specified length.  (May be
6131  * called as writer.)
6132  */
6133 mblk_t *
6134 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6135 {
6136 	mblk_t	*mp;
6137 
6138 	mp = allocb(len, BPRI_MED);
6139 	if (!mp)
6140 		return (NULL);
6141 
6142 	/*
6143 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6144 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6145 	 * that other DLPI are M_PROTO.
6146 	 */
6147 	if (prim == DL_INFO_REQ) {
6148 		mp->b_datap->db_type = M_PCPROTO;
6149 	} else {
6150 		mp->b_datap->db_type = M_PROTO;
6151 	}
6152 
6153 	mp->b_wptr = mp->b_rptr + len;
6154 	bzero(mp->b_rptr, len);
6155 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6156 	return (mp);
6157 }
6158 
6159 /*
6160  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6161  */
6162 mblk_t *
6163 ip_dlnotify_alloc(uint_t notification, uint_t data)
6164 {
6165 	dl_notify_ind_t	*notifyp;
6166 	mblk_t		*mp;
6167 
6168 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6169 		return (NULL);
6170 
6171 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6172 	notifyp->dl_notification = notification;
6173 	notifyp->dl_data = data;
6174 	return (mp);
6175 }
6176 
6177 /*
6178  * Debug formatting routine.  Returns a character string representation of the
6179  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6180  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6181  *
6182  * Once the ndd table-printing interfaces are removed, this can be changed to
6183  * standard dotted-decimal form.
6184  */
6185 char *
6186 ip_dot_addr(ipaddr_t addr, char *buf)
6187 {
6188 	uint8_t *ap = (uint8_t *)&addr;
6189 
6190 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6191 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6192 	return (buf);
6193 }
6194 
6195 /*
6196  * Write the given MAC address as a printable string in the usual colon-
6197  * separated format.
6198  */
6199 const char *
6200 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6201 {
6202 	char *bp;
6203 
6204 	if (alen == 0 || buflen < 4)
6205 		return ("?");
6206 	bp = buf;
6207 	for (;;) {
6208 		/*
6209 		 * If there are more MAC address bytes available, but we won't
6210 		 * have any room to print them, then add "..." to the string
6211 		 * instead.  See below for the 'magic number' explanation.
6212 		 */
6213 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6214 			(void) strcpy(bp, "...");
6215 			break;
6216 		}
6217 		(void) sprintf(bp, "%02x", *addr++);
6218 		bp += 2;
6219 		if (--alen == 0)
6220 			break;
6221 		*bp++ = ':';
6222 		buflen -= 3;
6223 		/*
6224 		 * At this point, based on the first 'if' statement above,
6225 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6226 		 * buflen >= 4.  The first case leaves room for the final "xx"
6227 		 * number and trailing NUL byte.  The second leaves room for at
6228 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6229 		 * that statement.
6230 		 */
6231 	}
6232 	return (buf);
6233 }
6234 
6235 /*
6236  * Send an ICMP error after patching up the packet appropriately.  Returns
6237  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6238  */
6239 static boolean_t
6240 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6241     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6242     zoneid_t zoneid, ip_stack_t *ipst)
6243 {
6244 	ipha_t *ipha;
6245 	mblk_t *first_mp;
6246 	boolean_t secure;
6247 	unsigned char db_type;
6248 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6249 
6250 	first_mp = mp;
6251 	if (mctl_present) {
6252 		mp = mp->b_cont;
6253 		secure = ipsec_in_is_secure(first_mp);
6254 		ASSERT(mp != NULL);
6255 	} else {
6256 		/*
6257 		 * If this is an ICMP error being reported - which goes
6258 		 * up as M_CTLs, we need to convert them to M_DATA till
6259 		 * we finish checking with global policy because
6260 		 * ipsec_check_global_policy() assumes M_DATA as clear
6261 		 * and M_CTL as secure.
6262 		 */
6263 		db_type = DB_TYPE(mp);
6264 		DB_TYPE(mp) = M_DATA;
6265 		secure = B_FALSE;
6266 	}
6267 	/*
6268 	 * We are generating an icmp error for some inbound packet.
6269 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6270 	 * Before we generate an error, check with global policy
6271 	 * to see whether this is allowed to enter the system. As
6272 	 * there is no "conn", we are checking with global policy.
6273 	 */
6274 	ipha = (ipha_t *)mp->b_rptr;
6275 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6276 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6277 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6278 		if (first_mp == NULL)
6279 			return (B_FALSE);
6280 	}
6281 
6282 	if (!mctl_present)
6283 		DB_TYPE(mp) = db_type;
6284 
6285 	if (flags & IP_FF_SEND_ICMP) {
6286 		if (flags & IP_FF_HDR_COMPLETE) {
6287 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6288 				freemsg(first_mp);
6289 				return (B_TRUE);
6290 			}
6291 		}
6292 		if (flags & IP_FF_CKSUM) {
6293 			/*
6294 			 * Have to correct checksum since
6295 			 * the packet might have been
6296 			 * fragmented and the reassembly code in ip_rput
6297 			 * does not restore the IP checksum.
6298 			 */
6299 			ipha->ipha_hdr_checksum = 0;
6300 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6301 		}
6302 		switch (icmp_type) {
6303 		case ICMP_DEST_UNREACHABLE:
6304 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6305 			    ipst);
6306 			break;
6307 		default:
6308 			freemsg(first_mp);
6309 			break;
6310 		}
6311 	} else {
6312 		freemsg(first_mp);
6313 		return (B_FALSE);
6314 	}
6315 
6316 	return (B_TRUE);
6317 }
6318 
6319 /*
6320  * Used to send an ICMP error message when a packet is received for
6321  * a protocol that is not supported. The mblk passed as argument
6322  * is consumed by this function.
6323  */
6324 void
6325 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6326     ip_stack_t *ipst)
6327 {
6328 	mblk_t *mp;
6329 	ipha_t *ipha;
6330 	ill_t *ill;
6331 	ipsec_in_t *ii;
6332 
6333 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6334 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6335 
6336 	mp = ipsec_mp->b_cont;
6337 	ipsec_mp->b_cont = NULL;
6338 	ipha = (ipha_t *)mp->b_rptr;
6339 	/* Get ill from index in ipsec_in_t. */
6340 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6341 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6342 	    ipst);
6343 	if (ill != NULL) {
6344 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6345 			if (ip_fanout_send_icmp(q, mp, flags,
6346 			    ICMP_DEST_UNREACHABLE,
6347 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6348 				BUMP_MIB(ill->ill_ip_mib,
6349 				    ipIfStatsInUnknownProtos);
6350 			}
6351 		} else {
6352 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6353 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6354 			    0, B_FALSE, zoneid, ipst)) {
6355 				BUMP_MIB(ill->ill_ip_mib,
6356 				    ipIfStatsInUnknownProtos);
6357 			}
6358 		}
6359 		ill_refrele(ill);
6360 	} else { /* re-link for the freemsg() below. */
6361 		ipsec_mp->b_cont = mp;
6362 	}
6363 
6364 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6365 	freemsg(ipsec_mp);
6366 }
6367 
6368 /*
6369  * See if the inbound datagram has had IPsec processing applied to it.
6370  */
6371 boolean_t
6372 ipsec_in_is_secure(mblk_t *ipsec_mp)
6373 {
6374 	ipsec_in_t *ii;
6375 
6376 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6377 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6378 
6379 	if (ii->ipsec_in_loopback) {
6380 		return (ii->ipsec_in_secure);
6381 	} else {
6382 		return (ii->ipsec_in_ah_sa != NULL ||
6383 		    ii->ipsec_in_esp_sa != NULL ||
6384 		    ii->ipsec_in_decaps);
6385 	}
6386 }
6387 
6388 /*
6389  * Handle protocols with which IP is less intimate.  There
6390  * can be more than one stream bound to a particular
6391  * protocol.  When this is the case, normally each one gets a copy
6392  * of any incoming packets.
6393  *
6394  * IPsec NOTE :
6395  *
6396  * Don't allow a secure packet going up a non-secure connection.
6397  * We don't allow this because
6398  *
6399  * 1) Reply might go out in clear which will be dropped at
6400  *    the sending side.
6401  * 2) If the reply goes out in clear it will give the
6402  *    adversary enough information for getting the key in
6403  *    most of the cases.
6404  *
6405  * Moreover getting a secure packet when we expect clear
6406  * implies that SA's were added without checking for
6407  * policy on both ends. This should not happen once ISAKMP
6408  * is used to negotiate SAs as SAs will be added only after
6409  * verifying the policy.
6410  *
6411  * NOTE : If the packet was tunneled and not multicast we only send
6412  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6413  * back to delivering packets to AF_INET6 raw sockets.
6414  *
6415  * IPQoS Notes:
6416  * Once we have determined the client, invoke IPPF processing.
6417  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6418  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6419  * ip_policy will be false.
6420  *
6421  * Zones notes:
6422  * Currently only applications in the global zone can create raw sockets for
6423  * protocols other than ICMP. So unlike the broadcast / multicast case of
6424  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6425  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6426  */
6427 static void
6428 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6429     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6430     zoneid_t zoneid)
6431 {
6432 	queue_t	*rq;
6433 	mblk_t	*mp1, *first_mp1;
6434 	uint_t	protocol = ipha->ipha_protocol;
6435 	ipaddr_t dst;
6436 	boolean_t one_only;
6437 	mblk_t *first_mp = mp;
6438 	boolean_t secure;
6439 	uint32_t ill_index;
6440 	conn_t	*connp, *first_connp, *next_connp;
6441 	connf_t	*connfp;
6442 	boolean_t shared_addr;
6443 	mib2_ipIfStatsEntry_t *mibptr;
6444 	ip_stack_t *ipst = recv_ill->ill_ipst;
6445 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6446 
6447 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6448 	if (mctl_present) {
6449 		mp = first_mp->b_cont;
6450 		secure = ipsec_in_is_secure(first_mp);
6451 		ASSERT(mp != NULL);
6452 	} else {
6453 		secure = B_FALSE;
6454 	}
6455 	dst = ipha->ipha_dst;
6456 	/*
6457 	 * If the packet was tunneled and not multicast we only send to it
6458 	 * the first match.
6459 	 */
6460 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6461 	    !CLASSD(dst));
6462 
6463 	shared_addr = (zoneid == ALL_ZONES);
6464 	if (shared_addr) {
6465 		/*
6466 		 * We don't allow multilevel ports for raw IP, so no need to
6467 		 * check for that here.
6468 		 */
6469 		zoneid = tsol_packet_to_zoneid(mp);
6470 	}
6471 
6472 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6473 	mutex_enter(&connfp->connf_lock);
6474 	connp = connfp->connf_head;
6475 	for (connp = connfp->connf_head; connp != NULL;
6476 	    connp = connp->conn_next) {
6477 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6478 		    zoneid) &&
6479 		    (!is_system_labeled() ||
6480 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6481 		    connp))) {
6482 			break;
6483 		}
6484 	}
6485 
6486 	if (connp == NULL) {
6487 		/*
6488 		 * No one bound to these addresses.  Is
6489 		 * there a client that wants all
6490 		 * unclaimed datagrams?
6491 		 */
6492 		mutex_exit(&connfp->connf_lock);
6493 		/*
6494 		 * Check for IPPROTO_ENCAP...
6495 		 */
6496 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6497 			/*
6498 			 * If an IPsec mblk is here on a multicast
6499 			 * tunnel (using ip_mroute stuff), check policy here,
6500 			 * THEN ship off to ip_mroute_decap().
6501 			 *
6502 			 * BTW,  If I match a configured IP-in-IP
6503 			 * tunnel, this path will not be reached, and
6504 			 * ip_mroute_decap will never be called.
6505 			 */
6506 			first_mp = ipsec_check_global_policy(first_mp, connp,
6507 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6508 			if (first_mp != NULL) {
6509 				if (mctl_present)
6510 					freeb(first_mp);
6511 				ip_mroute_decap(q, mp, ill);
6512 			} /* Else we already freed everything! */
6513 		} else {
6514 			/*
6515 			 * Otherwise send an ICMP protocol unreachable.
6516 			 */
6517 			if (ip_fanout_send_icmp(q, first_mp, flags,
6518 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6519 			    mctl_present, zoneid, ipst)) {
6520 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6521 			}
6522 		}
6523 		return;
6524 	}
6525 
6526 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6527 
6528 	CONN_INC_REF(connp);
6529 	first_connp = connp;
6530 
6531 	/*
6532 	 * Only send message to one tunnel driver by immediately
6533 	 * terminating the loop.
6534 	 */
6535 	connp = one_only ? NULL : connp->conn_next;
6536 
6537 	for (;;) {
6538 		while (connp != NULL) {
6539 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6540 			    flags, zoneid) &&
6541 			    (!is_system_labeled() ||
6542 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6543 			    shared_addr, connp)))
6544 				break;
6545 			connp = connp->conn_next;
6546 		}
6547 
6548 		/*
6549 		 * Copy the packet.
6550 		 */
6551 		if (connp == NULL ||
6552 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6553 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6554 			/*
6555 			 * No more interested clients or memory
6556 			 * allocation failed
6557 			 */
6558 			connp = first_connp;
6559 			break;
6560 		}
6561 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6562 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6563 		CONN_INC_REF(connp);
6564 		mutex_exit(&connfp->connf_lock);
6565 		rq = connp->conn_rq;
6566 
6567 		/*
6568 		 * Check flow control
6569 		 */
6570 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6571 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6572 			if (flags & IP_FF_RAWIP) {
6573 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6574 			} else {
6575 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6576 			}
6577 
6578 			freemsg(first_mp1);
6579 		} else {
6580 			/*
6581 			 * Don't enforce here if we're an actual tunnel -
6582 			 * let "tun" do it instead.
6583 			 */
6584 			if (!IPCL_IS_IPTUN(connp) &&
6585 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6586 			    secure)) {
6587 				first_mp1 = ipsec_check_inbound_policy
6588 				    (first_mp1, connp, ipha, NULL,
6589 				    mctl_present);
6590 			}
6591 			if (first_mp1 != NULL) {
6592 				int in_flags = 0;
6593 				/*
6594 				 * ip_fanout_proto also gets called from
6595 				 * icmp_inbound_error_fanout, in which case
6596 				 * the msg type is M_CTL.  Don't add info
6597 				 * in this case for the time being. In future
6598 				 * when there is a need for knowing the
6599 				 * inbound iface index for ICMP error msgs,
6600 				 * then this can be changed.
6601 				 */
6602 				if (connp->conn_recvif)
6603 					in_flags = IPF_RECVIF;
6604 				/*
6605 				 * The ULP may support IP_RECVPKTINFO for both
6606 				 * IP v4 and v6 so pass the appropriate argument
6607 				 * based on conn IP version.
6608 				 */
6609 				if (connp->conn_ip_recvpktinfo) {
6610 					if (connp->conn_af_isv6) {
6611 						/*
6612 						 * V6 only needs index
6613 						 */
6614 						in_flags |= IPF_RECVIF;
6615 					} else {
6616 						/*
6617 						 * V4 needs index +
6618 						 * matching address.
6619 						 */
6620 						in_flags |= IPF_RECVADDR;
6621 					}
6622 				}
6623 				if ((in_flags != 0) &&
6624 				    (mp->b_datap->db_type != M_CTL)) {
6625 					/*
6626 					 * the actual data will be
6627 					 * contained in b_cont upon
6628 					 * successful return of the
6629 					 * following call else
6630 					 * original mblk is returned
6631 					 */
6632 					ASSERT(recv_ill != NULL);
6633 					mp1 = ip_add_info(mp1, recv_ill,
6634 					    in_flags, IPCL_ZONEID(connp), ipst);
6635 				}
6636 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6637 				if (mctl_present)
6638 					freeb(first_mp1);
6639 				(connp->conn_recv)(connp, mp1, NULL);
6640 			}
6641 		}
6642 		mutex_enter(&connfp->connf_lock);
6643 		/* Follow the next pointer before releasing the conn. */
6644 		next_connp = connp->conn_next;
6645 		CONN_DEC_REF(connp);
6646 		connp = next_connp;
6647 	}
6648 
6649 	/* Last one.  Send it upstream. */
6650 	mutex_exit(&connfp->connf_lock);
6651 
6652 	/*
6653 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6654 	 * will be set to false.
6655 	 */
6656 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6657 		ill_index = ill->ill_phyint->phyint_ifindex;
6658 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6659 		if (mp == NULL) {
6660 			CONN_DEC_REF(connp);
6661 			if (mctl_present) {
6662 				freeb(first_mp);
6663 			}
6664 			return;
6665 		}
6666 	}
6667 
6668 	rq = connp->conn_rq;
6669 	/*
6670 	 * Check flow control
6671 	 */
6672 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6673 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6674 		if (flags & IP_FF_RAWIP) {
6675 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6676 		} else {
6677 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6678 		}
6679 
6680 		freemsg(first_mp);
6681 	} else {
6682 		if (IPCL_IS_IPTUN(connp)) {
6683 			/*
6684 			 * Tunneled packet.  We enforce policy in the tunnel
6685 			 * module itself.
6686 			 *
6687 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6688 			 * a policy check.
6689 			 * FIXME to use conn_recv for tun later.
6690 			 */
6691 			putnext(rq, first_mp);
6692 			CONN_DEC_REF(connp);
6693 			return;
6694 		}
6695 
6696 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6697 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6698 			    ipha, NULL, mctl_present);
6699 		}
6700 
6701 		if (first_mp != NULL) {
6702 			int in_flags = 0;
6703 
6704 			/*
6705 			 * ip_fanout_proto also gets called
6706 			 * from icmp_inbound_error_fanout, in
6707 			 * which case the msg type is M_CTL.
6708 			 * Don't add info in this case for time
6709 			 * being. In future when there is a
6710 			 * need for knowing the inbound iface
6711 			 * index for ICMP error msgs, then this
6712 			 * can be changed
6713 			 */
6714 			if (connp->conn_recvif)
6715 				in_flags = IPF_RECVIF;
6716 			if (connp->conn_ip_recvpktinfo) {
6717 				if (connp->conn_af_isv6) {
6718 					/*
6719 					 * V6 only needs index
6720 					 */
6721 					in_flags |= IPF_RECVIF;
6722 				} else {
6723 					/*
6724 					 * V4 needs index +
6725 					 * matching address.
6726 					 */
6727 					in_flags |= IPF_RECVADDR;
6728 				}
6729 			}
6730 			if ((in_flags != 0) &&
6731 			    (mp->b_datap->db_type != M_CTL)) {
6732 
6733 				/*
6734 				 * the actual data will be contained in
6735 				 * b_cont upon successful return
6736 				 * of the following call else original
6737 				 * mblk is returned
6738 				 */
6739 				ASSERT(recv_ill != NULL);
6740 				mp = ip_add_info(mp, recv_ill,
6741 				    in_flags, IPCL_ZONEID(connp), ipst);
6742 			}
6743 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6744 			(connp->conn_recv)(connp, mp, NULL);
6745 			if (mctl_present)
6746 				freeb(first_mp);
6747 		}
6748 	}
6749 	CONN_DEC_REF(connp);
6750 }
6751 
6752 /*
6753  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6754  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6755  * the correct squeue, in this case the same squeue as a valid listener with
6756  * no current connection state for the packet we are processing. The function
6757  * is called for synchronizing both IPv4 and IPv6.
6758  */
6759 void
6760 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6761     tcp_stack_t *tcps, conn_t *connp)
6762 {
6763 	mblk_t *rst_mp;
6764 	tcp_xmit_reset_event_t *eventp;
6765 
6766 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6767 
6768 	if (rst_mp == NULL) {
6769 		freemsg(mp);
6770 		return;
6771 	}
6772 
6773 	rst_mp->b_datap->db_type = M_PROTO;
6774 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6775 
6776 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6777 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6778 	eventp->tcp_xre_iphdrlen = hdrlen;
6779 	eventp->tcp_xre_zoneid = zoneid;
6780 	eventp->tcp_xre_tcps = tcps;
6781 
6782 	rst_mp->b_cont = mp;
6783 	mp = rst_mp;
6784 
6785 	/*
6786 	 * Increment the connref, this ref will be released by the squeue
6787 	 * framework.
6788 	 */
6789 	CONN_INC_REF(connp);
6790 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6791 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6792 }
6793 
6794 /*
6795  * Fanout for TCP packets
6796  * The caller puts <fport, lport> in the ports parameter.
6797  *
6798  * IPQoS Notes
6799  * Before sending it to the client, invoke IPPF processing.
6800  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6801  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6802  * ip_policy is false.
6803  */
6804 static void
6805 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6806     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6807 {
6808 	mblk_t  *first_mp;
6809 	boolean_t secure;
6810 	uint32_t ill_index;
6811 	int	ip_hdr_len;
6812 	tcph_t	*tcph;
6813 	boolean_t syn_present = B_FALSE;
6814 	conn_t	*connp;
6815 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6816 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6817 
6818 	ASSERT(recv_ill != NULL);
6819 
6820 	first_mp = mp;
6821 	if (mctl_present) {
6822 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6823 		mp = first_mp->b_cont;
6824 		secure = ipsec_in_is_secure(first_mp);
6825 		ASSERT(mp != NULL);
6826 	} else {
6827 		secure = B_FALSE;
6828 	}
6829 
6830 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6831 
6832 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6833 	    zoneid, ipst)) == NULL) {
6834 		/*
6835 		 * No connected connection or listener. Send a
6836 		 * TH_RST via tcp_xmit_listeners_reset.
6837 		 */
6838 
6839 		/* Initiate IPPf processing, if needed. */
6840 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6841 			uint32_t ill_index;
6842 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6843 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6844 			if (first_mp == NULL)
6845 				return;
6846 		}
6847 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6848 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6849 		    zoneid));
6850 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6851 		    ipst->ips_netstack->netstack_tcp, NULL);
6852 		return;
6853 	}
6854 
6855 	/*
6856 	 * Allocate the SYN for the TCP connection here itself
6857 	 */
6858 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6859 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6860 		if (IPCL_IS_TCP(connp)) {
6861 			squeue_t *sqp;
6862 
6863 			/*
6864 			 * For fused tcp loopback, assign the eager's
6865 			 * squeue to be that of the active connect's.
6866 			 * Note that we don't check for IP_FF_LOOPBACK
6867 			 * here since this routine gets called only
6868 			 * for loopback (unlike the IPv6 counterpart).
6869 			 */
6870 			ASSERT(Q_TO_CONN(q) != NULL);
6871 			if (do_tcp_fusion &&
6872 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6873 			    !secure &&
6874 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6875 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6876 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6877 				sqp = Q_TO_CONN(q)->conn_sqp;
6878 			} else {
6879 				sqp = IP_SQUEUE_GET(lbolt);
6880 			}
6881 
6882 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6883 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6884 			syn_present = B_TRUE;
6885 		}
6886 	}
6887 
6888 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6889 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6890 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6891 		if ((flags & TH_RST) || (flags & TH_URG)) {
6892 			CONN_DEC_REF(connp);
6893 			freemsg(first_mp);
6894 			return;
6895 		}
6896 		if (flags & TH_ACK) {
6897 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6898 			    ipst->ips_netstack->netstack_tcp, connp);
6899 			CONN_DEC_REF(connp);
6900 			return;
6901 		}
6902 
6903 		CONN_DEC_REF(connp);
6904 		freemsg(first_mp);
6905 		return;
6906 	}
6907 
6908 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6909 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6910 		    NULL, mctl_present);
6911 		if (first_mp == NULL) {
6912 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6913 			CONN_DEC_REF(connp);
6914 			return;
6915 		}
6916 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6917 			ASSERT(syn_present);
6918 			if (mctl_present) {
6919 				ASSERT(first_mp != mp);
6920 				first_mp->b_datap->db_struioflag |=
6921 				    STRUIO_POLICY;
6922 			} else {
6923 				ASSERT(first_mp == mp);
6924 				mp->b_datap->db_struioflag &=
6925 				    ~STRUIO_EAGER;
6926 				mp->b_datap->db_struioflag |=
6927 				    STRUIO_POLICY;
6928 			}
6929 		} else {
6930 			/*
6931 			 * Discard first_mp early since we're dealing with a
6932 			 * fully-connected conn_t and tcp doesn't do policy in
6933 			 * this case.
6934 			 */
6935 			if (mctl_present) {
6936 				freeb(first_mp);
6937 				mctl_present = B_FALSE;
6938 			}
6939 			first_mp = mp;
6940 		}
6941 	}
6942 
6943 	/*
6944 	 * Initiate policy processing here if needed. If we get here from
6945 	 * icmp_inbound_error_fanout, ip_policy is false.
6946 	 */
6947 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6948 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6949 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6950 		if (mp == NULL) {
6951 			CONN_DEC_REF(connp);
6952 			if (mctl_present)
6953 				freeb(first_mp);
6954 			return;
6955 		} else if (mctl_present) {
6956 			ASSERT(first_mp != mp);
6957 			first_mp->b_cont = mp;
6958 		} else {
6959 			first_mp = mp;
6960 		}
6961 	}
6962 
6963 	/* Handle socket options. */
6964 	if (!syn_present &&
6965 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6966 		/* Add header */
6967 		ASSERT(recv_ill != NULL);
6968 		/*
6969 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6970 		 * IPF_RECVIF.
6971 		 */
6972 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6973 		    ipst);
6974 		if (mp == NULL) {
6975 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6976 			CONN_DEC_REF(connp);
6977 			if (mctl_present)
6978 				freeb(first_mp);
6979 			return;
6980 		} else if (mctl_present) {
6981 			/*
6982 			 * ip_add_info might return a new mp.
6983 			 */
6984 			ASSERT(first_mp != mp);
6985 			first_mp->b_cont = mp;
6986 		} else {
6987 			first_mp = mp;
6988 		}
6989 	}
6990 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6991 	if (IPCL_IS_TCP(connp)) {
6992 		/* do not drain, certain use cases can blow the stack */
6993 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6994 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6995 	} else {
6996 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6997 		(connp->conn_recv)(connp, first_mp, NULL);
6998 		CONN_DEC_REF(connp);
6999 	}
7000 }
7001 
7002 /*
7003  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
7004  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
7005  * is not consumed.
7006  *
7007  * One of four things can happen, all of which affect the passed-in mblk:
7008  *
7009  * 1.) ICMP messages that go through here just get returned TRUE.
7010  *
7011  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7012  *
7013  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7014  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7015  *
7016  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7017  */
7018 static boolean_t
7019 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7020     ipsec_stack_t *ipss)
7021 {
7022 	int shift, plen, iph_len;
7023 	ipha_t *ipha;
7024 	udpha_t *udpha;
7025 	uint32_t *spi;
7026 	uint32_t esp_ports;
7027 	uint8_t *orptr;
7028 	boolean_t free_ire;
7029 
7030 	if (DB_TYPE(mp) == M_CTL) {
7031 		/*
7032 		 * ICMP message with UDP inside.  Don't bother stripping, just
7033 		 * send it up.
7034 		 *
7035 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7036 		 * to ignore errors set by ICMP anyway ('cause they might be
7037 		 * forged), but that's the app's decision, not ours.
7038 		 */
7039 
7040 		/* Bunch of reality checks for DEBUG kernels... */
7041 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7042 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7043 
7044 		return (B_TRUE);
7045 	}
7046 
7047 	ipha = (ipha_t *)mp->b_rptr;
7048 	iph_len = IPH_HDR_LENGTH(ipha);
7049 	plen = ntohs(ipha->ipha_length);
7050 
7051 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7052 		/*
7053 		 * Most likely a keepalive for the benefit of an intervening
7054 		 * NAT.  These aren't for us, per se, so drop it.
7055 		 *
7056 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7057 		 * byte packets (keepalives are 1-byte), but we'll drop them
7058 		 * also.
7059 		 */
7060 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7061 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7062 		return (B_FALSE);
7063 	}
7064 
7065 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7066 		/* might as well pull it all up - it might be ESP. */
7067 		if (!pullupmsg(mp, -1)) {
7068 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7069 			    DROPPER(ipss, ipds_esp_nomem),
7070 			    &ipss->ipsec_dropper);
7071 			return (B_FALSE);
7072 		}
7073 
7074 		ipha = (ipha_t *)mp->b_rptr;
7075 	}
7076 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7077 	if (*spi == 0) {
7078 		/* UDP packet - remove 0-spi. */
7079 		shift = sizeof (uint32_t);
7080 	} else {
7081 		/* ESP-in-UDP packet - reduce to ESP. */
7082 		ipha->ipha_protocol = IPPROTO_ESP;
7083 		shift = sizeof (udpha_t);
7084 	}
7085 
7086 	/* Fix IP header */
7087 	ipha->ipha_length = htons(plen - shift);
7088 	ipha->ipha_hdr_checksum = 0;
7089 
7090 	orptr = mp->b_rptr;
7091 	mp->b_rptr += shift;
7092 
7093 	udpha = (udpha_t *)(orptr + iph_len);
7094 	if (*spi == 0) {
7095 		ASSERT((uint8_t *)ipha == orptr);
7096 		udpha->uha_length = htons(plen - shift - iph_len);
7097 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7098 		esp_ports = 0;
7099 	} else {
7100 		esp_ports = *((uint32_t *)udpha);
7101 		ASSERT(esp_ports != 0);
7102 	}
7103 	ovbcopy(orptr, orptr + shift, iph_len);
7104 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7105 		ipha = (ipha_t *)(orptr + shift);
7106 
7107 		free_ire = (ire == NULL);
7108 		if (free_ire) {
7109 			/* Re-acquire ire. */
7110 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7111 			    ipss->ipsec_netstack->netstack_ip);
7112 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7113 				if (ire != NULL)
7114 					ire_refrele(ire);
7115 				/*
7116 				 * Do a regular freemsg(), as this is an IP
7117 				 * error (no local route) not an IPsec one.
7118 				 */
7119 				freemsg(mp);
7120 			}
7121 		}
7122 
7123 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7124 		if (free_ire)
7125 			ire_refrele(ire);
7126 	}
7127 
7128 	return (esp_ports == 0);
7129 }
7130 
7131 /*
7132  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7133  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7134  * Caller is responsible for dropping references to the conn, and freeing
7135  * first_mp.
7136  *
7137  * IPQoS Notes
7138  * Before sending it to the client, invoke IPPF processing. Policy processing
7139  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7140  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7141  * ip_wput_local, ip_policy is false.
7142  */
7143 static void
7144 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7145     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7146     boolean_t ip_policy)
7147 {
7148 	boolean_t	mctl_present = (first_mp != NULL);
7149 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7150 	uint32_t	ill_index;
7151 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7152 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7153 
7154 	ASSERT(ill != NULL);
7155 
7156 	if (mctl_present)
7157 		first_mp->b_cont = mp;
7158 	else
7159 		first_mp = mp;
7160 
7161 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7162 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7163 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7164 		freemsg(first_mp);
7165 		return;
7166 	}
7167 
7168 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7169 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7170 		    NULL, mctl_present);
7171 		/* Freed by ipsec_check_inbound_policy(). */
7172 		if (first_mp == NULL) {
7173 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7174 			return;
7175 		}
7176 	}
7177 	if (mctl_present)
7178 		freeb(first_mp);
7179 
7180 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7181 	if (connp->conn_udp->udp_nat_t_endpoint) {
7182 		if (mctl_present) {
7183 			/* mctl_present *shouldn't* happen. */
7184 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7185 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7186 			    &ipss->ipsec_dropper);
7187 			return;
7188 		}
7189 
7190 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7191 			return;
7192 	}
7193 
7194 	/* Handle options. */
7195 	if (connp->conn_recvif)
7196 		in_flags = IPF_RECVIF;
7197 	/*
7198 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7199 	 * passed to ip_add_info is based on IP version of connp.
7200 	 */
7201 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7202 		if (connp->conn_af_isv6) {
7203 			/*
7204 			 * V6 only needs index
7205 			 */
7206 			in_flags |= IPF_RECVIF;
7207 		} else {
7208 			/*
7209 			 * V4 needs index + matching address.
7210 			 */
7211 			in_flags |= IPF_RECVADDR;
7212 		}
7213 	}
7214 
7215 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7216 		in_flags |= IPF_RECVSLLA;
7217 
7218 	/*
7219 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7220 	 * freed if the packet is dropped. The caller will do so.
7221 	 */
7222 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7223 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7224 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7225 		if (mp == NULL) {
7226 			return;
7227 		}
7228 	}
7229 	if ((in_flags != 0) &&
7230 	    (mp->b_datap->db_type != M_CTL)) {
7231 		/*
7232 		 * The actual data will be contained in b_cont
7233 		 * upon successful return of the following call
7234 		 * else original mblk is returned
7235 		 */
7236 		ASSERT(recv_ill != NULL);
7237 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7238 		    ipst);
7239 	}
7240 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7241 	/* Send it upstream */
7242 	(connp->conn_recv)(connp, mp, NULL);
7243 }
7244 
7245 /*
7246  * Fanout for UDP packets.
7247  * The caller puts <fport, lport> in the ports parameter.
7248  *
7249  * If SO_REUSEADDR is set all multicast and broadcast packets
7250  * will be delivered to all streams bound to the same port.
7251  *
7252  * Zones notes:
7253  * Multicast and broadcast packets will be distributed to streams in all zones.
7254  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7255  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7256  * packets. To maintain this behavior with multiple zones, the conns are grouped
7257  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7258  * each zone. If unset, all the following conns in the same zone are skipped.
7259  */
7260 static void
7261 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7262     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7263     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7264 {
7265 	uint32_t	dstport, srcport;
7266 	ipaddr_t	dst;
7267 	mblk_t		*first_mp;
7268 	boolean_t	secure;
7269 	in6_addr_t	v6src;
7270 	conn_t		*connp;
7271 	connf_t		*connfp;
7272 	conn_t		*first_connp;
7273 	conn_t		*next_connp;
7274 	mblk_t		*mp1, *first_mp1;
7275 	ipaddr_t	src;
7276 	zoneid_t	last_zoneid;
7277 	boolean_t	reuseaddr;
7278 	boolean_t	shared_addr;
7279 	boolean_t	unlabeled;
7280 	ip_stack_t	*ipst;
7281 
7282 	ASSERT(recv_ill != NULL);
7283 	ipst = recv_ill->ill_ipst;
7284 
7285 	first_mp = mp;
7286 	if (mctl_present) {
7287 		mp = first_mp->b_cont;
7288 		first_mp->b_cont = NULL;
7289 		secure = ipsec_in_is_secure(first_mp);
7290 		ASSERT(mp != NULL);
7291 	} else {
7292 		first_mp = NULL;
7293 		secure = B_FALSE;
7294 	}
7295 
7296 	/* Extract ports in net byte order */
7297 	dstport = htons(ntohl(ports) & 0xFFFF);
7298 	srcport = htons(ntohl(ports) >> 16);
7299 	dst = ipha->ipha_dst;
7300 	src = ipha->ipha_src;
7301 
7302 	unlabeled = B_FALSE;
7303 	if (is_system_labeled())
7304 		/* Cred cannot be null on IPv4 */
7305 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7306 		    TSLF_UNLABELED) != 0;
7307 	shared_addr = (zoneid == ALL_ZONES);
7308 	if (shared_addr) {
7309 		/*
7310 		 * No need to handle exclusive-stack zones since ALL_ZONES
7311 		 * only applies to the shared stack.
7312 		 */
7313 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7314 		/*
7315 		 * If no shared MLP is found, tsol_mlp_findzone returns
7316 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7317 		 * search for the zone based on the packet label.
7318 		 *
7319 		 * If there is such a zone, we prefer to find a
7320 		 * connection in it.  Otherwise, we look for a
7321 		 * MAC-exempt connection in any zone whose label
7322 		 * dominates the default label on the packet.
7323 		 */
7324 		if (zoneid == ALL_ZONES)
7325 			zoneid = tsol_packet_to_zoneid(mp);
7326 		else
7327 			unlabeled = B_FALSE;
7328 	}
7329 
7330 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7331 	mutex_enter(&connfp->connf_lock);
7332 	connp = connfp->connf_head;
7333 	if (!broadcast && !CLASSD(dst)) {
7334 		/*
7335 		 * Not broadcast or multicast. Send to the one (first)
7336 		 * client we find. No need to check conn_wantpacket()
7337 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7338 		 * IPv4 unicast packets.
7339 		 */
7340 		while ((connp != NULL) &&
7341 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7342 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7343 		    !(unlabeled && connp->conn_mac_exempt)))) {
7344 			/*
7345 			 * We keep searching since the conn did not match,
7346 			 * or its zone did not match and it is not either
7347 			 * an allzones conn or a mac exempt conn (if the
7348 			 * sender is unlabeled.)
7349 			 */
7350 			connp = connp->conn_next;
7351 		}
7352 
7353 		if (connp == NULL ||
7354 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7355 			goto notfound;
7356 
7357 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7358 
7359 		if (is_system_labeled() &&
7360 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7361 		    connp))
7362 			goto notfound;
7363 
7364 		CONN_INC_REF(connp);
7365 		mutex_exit(&connfp->connf_lock);
7366 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7367 		    flags, recv_ill, ip_policy);
7368 		IP_STAT(ipst, ip_udp_fannorm);
7369 		CONN_DEC_REF(connp);
7370 		return;
7371 	}
7372 
7373 	/*
7374 	 * Broadcast and multicast case
7375 	 *
7376 	 * Need to check conn_wantpacket().
7377 	 * If SO_REUSEADDR has been set on the first we send the
7378 	 * packet to all clients that have joined the group and
7379 	 * match the port.
7380 	 */
7381 
7382 	while (connp != NULL) {
7383 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7384 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7385 		    (!is_system_labeled() ||
7386 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7387 		    connp)))
7388 			break;
7389 		connp = connp->conn_next;
7390 	}
7391 
7392 	if (connp == NULL ||
7393 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7394 		goto notfound;
7395 
7396 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7397 
7398 	first_connp = connp;
7399 	/*
7400 	 * When SO_REUSEADDR is not set, send the packet only to the first
7401 	 * matching connection in its zone by keeping track of the zoneid.
7402 	 */
7403 	reuseaddr = first_connp->conn_reuseaddr;
7404 	last_zoneid = first_connp->conn_zoneid;
7405 
7406 	CONN_INC_REF(connp);
7407 	connp = connp->conn_next;
7408 	for (;;) {
7409 		while (connp != NULL) {
7410 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7411 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7412 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7413 			    (!is_system_labeled() ||
7414 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7415 			    shared_addr, connp)))
7416 				break;
7417 			connp = connp->conn_next;
7418 		}
7419 		/*
7420 		 * Just copy the data part alone. The mctl part is
7421 		 * needed just for verifying policy and it is never
7422 		 * sent up.
7423 		 */
7424 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7425 		    ((mp1 = copymsg(mp)) == NULL))) {
7426 			/*
7427 			 * No more interested clients or memory
7428 			 * allocation failed
7429 			 */
7430 			connp = first_connp;
7431 			break;
7432 		}
7433 		if (connp->conn_zoneid != last_zoneid) {
7434 			/*
7435 			 * Update the zoneid so that the packet isn't sent to
7436 			 * any more conns in the same zone unless SO_REUSEADDR
7437 			 * is set.
7438 			 */
7439 			reuseaddr = connp->conn_reuseaddr;
7440 			last_zoneid = connp->conn_zoneid;
7441 		}
7442 		if (first_mp != NULL) {
7443 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7444 			    ipsec_info_type == IPSEC_IN);
7445 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7446 			    ipst->ips_netstack);
7447 			if (first_mp1 == NULL) {
7448 				freemsg(mp1);
7449 				connp = first_connp;
7450 				break;
7451 			}
7452 		} else {
7453 			first_mp1 = NULL;
7454 		}
7455 		CONN_INC_REF(connp);
7456 		mutex_exit(&connfp->connf_lock);
7457 		/*
7458 		 * IPQoS notes: We don't send the packet for policy
7459 		 * processing here, will do it for the last one (below).
7460 		 * i.e. we do it per-packet now, but if we do policy
7461 		 * processing per-conn, then we would need to do it
7462 		 * here too.
7463 		 */
7464 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7465 		    ipha, flags, recv_ill, B_FALSE);
7466 		mutex_enter(&connfp->connf_lock);
7467 		/* Follow the next pointer before releasing the conn. */
7468 		next_connp = connp->conn_next;
7469 		IP_STAT(ipst, ip_udp_fanmb);
7470 		CONN_DEC_REF(connp);
7471 		connp = next_connp;
7472 	}
7473 
7474 	/* Last one.  Send it upstream. */
7475 	mutex_exit(&connfp->connf_lock);
7476 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7477 	    recv_ill, ip_policy);
7478 	IP_STAT(ipst, ip_udp_fanmb);
7479 	CONN_DEC_REF(connp);
7480 	return;
7481 
7482 notfound:
7483 
7484 	mutex_exit(&connfp->connf_lock);
7485 	IP_STAT(ipst, ip_udp_fanothers);
7486 	/*
7487 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7488 	 * have already been matched above, since they live in the IPv4
7489 	 * fanout tables. This implies we only need to
7490 	 * check for IPv6 in6addr_any endpoints here.
7491 	 * Thus we compare using ipv6_all_zeros instead of the destination
7492 	 * address, except for the multicast group membership lookup which
7493 	 * uses the IPv4 destination.
7494 	 */
7495 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7496 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7497 	mutex_enter(&connfp->connf_lock);
7498 	connp = connfp->connf_head;
7499 	if (!broadcast && !CLASSD(dst)) {
7500 		while (connp != NULL) {
7501 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7502 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7503 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7504 			    !connp->conn_ipv6_v6only)
7505 				break;
7506 			connp = connp->conn_next;
7507 		}
7508 
7509 		if (connp != NULL && is_system_labeled() &&
7510 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7511 		    connp))
7512 			connp = NULL;
7513 
7514 		if (connp == NULL ||
7515 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7516 			/*
7517 			 * No one bound to this port.  Is
7518 			 * there a client that wants all
7519 			 * unclaimed datagrams?
7520 			 */
7521 			mutex_exit(&connfp->connf_lock);
7522 
7523 			if (mctl_present)
7524 				first_mp->b_cont = mp;
7525 			else
7526 				first_mp = mp;
7527 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7528 			    connf_head != NULL) {
7529 				ip_fanout_proto(q, first_mp, ill, ipha,
7530 				    flags | IP_FF_RAWIP, mctl_present,
7531 				    ip_policy, recv_ill, zoneid);
7532 			} else {
7533 				if (ip_fanout_send_icmp(q, first_mp, flags,
7534 				    ICMP_DEST_UNREACHABLE,
7535 				    ICMP_PORT_UNREACHABLE,
7536 				    mctl_present, zoneid, ipst)) {
7537 					BUMP_MIB(ill->ill_ip_mib,
7538 					    udpIfStatsNoPorts);
7539 				}
7540 			}
7541 			return;
7542 		}
7543 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7544 
7545 		CONN_INC_REF(connp);
7546 		mutex_exit(&connfp->connf_lock);
7547 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7548 		    flags, recv_ill, ip_policy);
7549 		CONN_DEC_REF(connp);
7550 		return;
7551 	}
7552 	/*
7553 	 * IPv4 multicast packet being delivered to an AF_INET6
7554 	 * in6addr_any endpoint.
7555 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7556 	 * and not conn_wantpacket_v6() since any multicast membership is
7557 	 * for an IPv4-mapped multicast address.
7558 	 * The packet is sent to all clients in all zones that have joined the
7559 	 * group and match the port.
7560 	 */
7561 	while (connp != NULL) {
7562 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7563 		    srcport, v6src) &&
7564 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7565 		    (!is_system_labeled() ||
7566 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7567 		    connp)))
7568 			break;
7569 		connp = connp->conn_next;
7570 	}
7571 
7572 	if (connp == NULL ||
7573 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7574 		/*
7575 		 * No one bound to this port.  Is
7576 		 * there a client that wants all
7577 		 * unclaimed datagrams?
7578 		 */
7579 		mutex_exit(&connfp->connf_lock);
7580 
7581 		if (mctl_present)
7582 			first_mp->b_cont = mp;
7583 		else
7584 			first_mp = mp;
7585 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7586 		    NULL) {
7587 			ip_fanout_proto(q, first_mp, ill, ipha,
7588 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7589 			    recv_ill, zoneid);
7590 		} else {
7591 			/*
7592 			 * We used to attempt to send an icmp error here, but
7593 			 * since this is known to be a multicast packet
7594 			 * and we don't send icmp errors in response to
7595 			 * multicast, just drop the packet and give up sooner.
7596 			 */
7597 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7598 			freemsg(first_mp);
7599 		}
7600 		return;
7601 	}
7602 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7603 
7604 	first_connp = connp;
7605 
7606 	CONN_INC_REF(connp);
7607 	connp = connp->conn_next;
7608 	for (;;) {
7609 		while (connp != NULL) {
7610 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7611 			    ipv6_all_zeros, srcport, v6src) &&
7612 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7613 			    (!is_system_labeled() ||
7614 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7615 			    shared_addr, connp)))
7616 				break;
7617 			connp = connp->conn_next;
7618 		}
7619 		/*
7620 		 * Just copy the data part alone. The mctl part is
7621 		 * needed just for verifying policy and it is never
7622 		 * sent up.
7623 		 */
7624 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7625 		    ((mp1 = copymsg(mp)) == NULL))) {
7626 			/*
7627 			 * No more intested clients or memory
7628 			 * allocation failed
7629 			 */
7630 			connp = first_connp;
7631 			break;
7632 		}
7633 		if (first_mp != NULL) {
7634 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7635 			    ipsec_info_type == IPSEC_IN);
7636 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7637 			    ipst->ips_netstack);
7638 			if (first_mp1 == NULL) {
7639 				freemsg(mp1);
7640 				connp = first_connp;
7641 				break;
7642 			}
7643 		} else {
7644 			first_mp1 = NULL;
7645 		}
7646 		CONN_INC_REF(connp);
7647 		mutex_exit(&connfp->connf_lock);
7648 		/*
7649 		 * IPQoS notes: We don't send the packet for policy
7650 		 * processing here, will do it for the last one (below).
7651 		 * i.e. we do it per-packet now, but if we do policy
7652 		 * processing per-conn, then we would need to do it
7653 		 * here too.
7654 		 */
7655 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7656 		    ipha, flags, recv_ill, B_FALSE);
7657 		mutex_enter(&connfp->connf_lock);
7658 		/* Follow the next pointer before releasing the conn. */
7659 		next_connp = connp->conn_next;
7660 		CONN_DEC_REF(connp);
7661 		connp = next_connp;
7662 	}
7663 
7664 	/* Last one.  Send it upstream. */
7665 	mutex_exit(&connfp->connf_lock);
7666 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7667 	    recv_ill, ip_policy);
7668 	CONN_DEC_REF(connp);
7669 }
7670 
7671 /*
7672  * Complete the ip_wput header so that it
7673  * is possible to generate ICMP
7674  * errors.
7675  */
7676 int
7677 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7678 {
7679 	ire_t *ire;
7680 
7681 	if (ipha->ipha_src == INADDR_ANY) {
7682 		ire = ire_lookup_local(zoneid, ipst);
7683 		if (ire == NULL) {
7684 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7685 			return (1);
7686 		}
7687 		ipha->ipha_src = ire->ire_addr;
7688 		ire_refrele(ire);
7689 	}
7690 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7691 	ipha->ipha_hdr_checksum = 0;
7692 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7693 	return (0);
7694 }
7695 
7696 /*
7697  * Nobody should be sending
7698  * packets up this stream
7699  */
7700 static void
7701 ip_lrput(queue_t *q, mblk_t *mp)
7702 {
7703 	mblk_t *mp1;
7704 
7705 	switch (mp->b_datap->db_type) {
7706 	case M_FLUSH:
7707 		/* Turn around */
7708 		if (*mp->b_rptr & FLUSHW) {
7709 			*mp->b_rptr &= ~FLUSHR;
7710 			qreply(q, mp);
7711 			return;
7712 		}
7713 		break;
7714 	}
7715 	/* Could receive messages that passed through ar_rput */
7716 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7717 		mp1->b_prev = mp1->b_next = NULL;
7718 	freemsg(mp);
7719 }
7720 
7721 /* Nobody should be sending packets down this stream */
7722 /* ARGSUSED */
7723 void
7724 ip_lwput(queue_t *q, mblk_t *mp)
7725 {
7726 	freemsg(mp);
7727 }
7728 
7729 /*
7730  * Move the first hop in any source route to ipha_dst and remove that part of
7731  * the source route.  Called by other protocols.  Errors in option formatting
7732  * are ignored - will be handled by ip_wput_options Return the final
7733  * destination (either ipha_dst or the last entry in a source route.)
7734  */
7735 ipaddr_t
7736 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7737 {
7738 	ipoptp_t	opts;
7739 	uchar_t		*opt;
7740 	uint8_t		optval;
7741 	uint8_t		optlen;
7742 	ipaddr_t	dst;
7743 	int		i;
7744 	ire_t		*ire;
7745 	ip_stack_t	*ipst = ns->netstack_ip;
7746 
7747 	ip2dbg(("ip_massage_options\n"));
7748 	dst = ipha->ipha_dst;
7749 	for (optval = ipoptp_first(&opts, ipha);
7750 	    optval != IPOPT_EOL;
7751 	    optval = ipoptp_next(&opts)) {
7752 		opt = opts.ipoptp_cur;
7753 		switch (optval) {
7754 			uint8_t off;
7755 		case IPOPT_SSRR:
7756 		case IPOPT_LSRR:
7757 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7758 				ip1dbg(("ip_massage_options: bad src route\n"));
7759 				break;
7760 			}
7761 			optlen = opts.ipoptp_len;
7762 			off = opt[IPOPT_OFFSET];
7763 			off--;
7764 		redo_srr:
7765 			if (optlen < IP_ADDR_LEN ||
7766 			    off > optlen - IP_ADDR_LEN) {
7767 				/* End of source route */
7768 				ip1dbg(("ip_massage_options: end of SR\n"));
7769 				break;
7770 			}
7771 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7772 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7773 			    ntohl(dst)));
7774 			/*
7775 			 * Check if our address is present more than
7776 			 * once as consecutive hops in source route.
7777 			 * XXX verify per-interface ip_forwarding
7778 			 * for source route?
7779 			 */
7780 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7781 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7782 			if (ire != NULL) {
7783 				ire_refrele(ire);
7784 				off += IP_ADDR_LEN;
7785 				goto redo_srr;
7786 			}
7787 			if (dst == htonl(INADDR_LOOPBACK)) {
7788 				ip1dbg(("ip_massage_options: loopback addr in "
7789 				    "source route!\n"));
7790 				break;
7791 			}
7792 			/*
7793 			 * Update ipha_dst to be the first hop and remove the
7794 			 * first hop from the source route (by overwriting
7795 			 * part of the option with NOP options).
7796 			 */
7797 			ipha->ipha_dst = dst;
7798 			/* Put the last entry in dst */
7799 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7800 			    3;
7801 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7802 
7803 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7804 			    ntohl(dst)));
7805 			/* Move down and overwrite */
7806 			opt[IP_ADDR_LEN] = opt[0];
7807 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7808 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7809 			for (i = 0; i < IP_ADDR_LEN; i++)
7810 				opt[i] = IPOPT_NOP;
7811 			break;
7812 		}
7813 	}
7814 	return (dst);
7815 }
7816 
7817 /*
7818  * Return the network mask
7819  * associated with the specified address.
7820  */
7821 ipaddr_t
7822 ip_net_mask(ipaddr_t addr)
7823 {
7824 	uchar_t	*up = (uchar_t *)&addr;
7825 	ipaddr_t mask = 0;
7826 	uchar_t	*maskp = (uchar_t *)&mask;
7827 
7828 #if defined(__i386) || defined(__amd64)
7829 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7830 #endif
7831 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7832 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7833 #endif
7834 	if (CLASSD(addr)) {
7835 		maskp[0] = 0xF0;
7836 		return (mask);
7837 	}
7838 
7839 	/* We assume Class E default netmask to be 32 */
7840 	if (CLASSE(addr))
7841 		return (0xffffffffU);
7842 
7843 	if (addr == 0)
7844 		return (0);
7845 	maskp[0] = 0xFF;
7846 	if ((up[0] & 0x80) == 0)
7847 		return (mask);
7848 
7849 	maskp[1] = 0xFF;
7850 	if ((up[0] & 0xC0) == 0x80)
7851 		return (mask);
7852 
7853 	maskp[2] = 0xFF;
7854 	if ((up[0] & 0xE0) == 0xC0)
7855 		return (mask);
7856 
7857 	/* Otherwise return no mask */
7858 	return ((ipaddr_t)0);
7859 }
7860 
7861 /*
7862  * Helper ill lookup function used by IPsec.
7863  */
7864 ill_t *
7865 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7866 {
7867 	ill_t *ret_ill;
7868 
7869 	ASSERT(ifindex != 0);
7870 
7871 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7872 	    ipst);
7873 	if (ret_ill == NULL) {
7874 		if (isv6) {
7875 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7876 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7877 			    ifindex));
7878 		} else {
7879 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7880 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7881 			    ifindex));
7882 		}
7883 		freemsg(first_mp);
7884 		return (NULL);
7885 	}
7886 	return (ret_ill);
7887 }
7888 
7889 /*
7890  * IPv4 -
7891  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7892  * out a packet to a destination address for which we do not have specific
7893  * (or sufficient) routing information.
7894  *
7895  * NOTE : These are the scopes of some of the variables that point at IRE,
7896  *	  which needs to be followed while making any future modifications
7897  *	  to avoid memory leaks.
7898  *
7899  *	- ire and sire are the entries looked up initially by
7900  *	  ire_ftable_lookup.
7901  *	- ipif_ire is used to hold the interface ire associated with
7902  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7903  *	  it before branching out to error paths.
7904  *	- save_ire is initialized before ire_create, so that ire returned
7905  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7906  *	  before breaking out of the switch.
7907  *
7908  *	Thus on failures, we have to REFRELE only ire and sire, if they
7909  *	are not NULL.
7910  */
7911 void
7912 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7913     zoneid_t zoneid, ip_stack_t *ipst)
7914 {
7915 	areq_t	*areq;
7916 	ipaddr_t gw = 0;
7917 	ire_t	*ire = NULL;
7918 	mblk_t	*res_mp;
7919 	ipaddr_t *addrp;
7920 	ipaddr_t nexthop_addr;
7921 	ipif_t  *src_ipif = NULL;
7922 	ill_t	*dst_ill = NULL;
7923 	ipha_t  *ipha;
7924 	ire_t	*sire = NULL;
7925 	mblk_t	*first_mp;
7926 	ire_t	*save_ire;
7927 	ushort_t ire_marks = 0;
7928 	boolean_t mctl_present;
7929 	ipsec_out_t *io;
7930 	mblk_t	*saved_mp;
7931 	ire_t	*first_sire = NULL;
7932 	mblk_t	*copy_mp = NULL;
7933 	mblk_t	*xmit_mp = NULL;
7934 	ipaddr_t save_dst;
7935 	uint32_t multirt_flags =
7936 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7937 	boolean_t multirt_is_resolvable;
7938 	boolean_t multirt_resolve_next;
7939 	boolean_t unspec_src;
7940 	boolean_t ip_nexthop = B_FALSE;
7941 	tsol_ire_gw_secattr_t *attrp = NULL;
7942 	tsol_gcgrp_t *gcgrp = NULL;
7943 	tsol_gcgrp_addr_t ga;
7944 
7945 	if (ip_debug > 2) {
7946 		/* ip1dbg */
7947 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7948 	}
7949 
7950 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7951 	if (mctl_present) {
7952 		io = (ipsec_out_t *)first_mp->b_rptr;
7953 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7954 		ASSERT(zoneid == io->ipsec_out_zoneid);
7955 		ASSERT(zoneid != ALL_ZONES);
7956 	}
7957 
7958 	ipha = (ipha_t *)mp->b_rptr;
7959 
7960 	/* All multicast lookups come through ip_newroute_ipif() */
7961 	if (CLASSD(dst)) {
7962 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7963 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7964 		freemsg(first_mp);
7965 		return;
7966 	}
7967 
7968 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7969 		ip_nexthop = B_TRUE;
7970 		nexthop_addr = io->ipsec_out_nexthop_addr;
7971 	}
7972 	/*
7973 	 * If this IRE is created for forwarding or it is not for
7974 	 * traffic for congestion controlled protocols, mark it as temporary.
7975 	 */
7976 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7977 		ire_marks |= IRE_MARK_TEMPORARY;
7978 
7979 	/*
7980 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7981 	 * chain until it gets the most specific information available.
7982 	 * For example, we know that there is no IRE_CACHE for this dest,
7983 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7984 	 * ire_ftable_lookup will look up the gateway, etc.
7985 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7986 	 * to the destination, of equal netmask length in the forward table,
7987 	 * will be recursively explored. If no information is available
7988 	 * for the final gateway of that route, we force the returned ire
7989 	 * to be equal to sire using MATCH_IRE_PARENT.
7990 	 * At least, in this case we have a starting point (in the buckets)
7991 	 * to look for other routes to the destination in the forward table.
7992 	 * This is actually used only for multirouting, where a list
7993 	 * of routes has to be processed in sequence.
7994 	 *
7995 	 * In the process of coming up with the most specific information,
7996 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7997 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7998 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7999 	 * Two caveats when handling incomplete ire's in ip_newroute:
8000 	 * - we should be careful when accessing its ire_nce (specifically
8001 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8002 	 * - not all legacy code path callers are prepared to handle
8003 	 *   incomplete ire's, so we should not create/add incomplete
8004 	 *   ire_cache entries here. (See discussion about temporary solution
8005 	 *   further below).
8006 	 *
8007 	 * In order to minimize packet dropping, and to preserve existing
8008 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8009 	 * gateway, and instead use the IF_RESOLVER ire to send out
8010 	 * another request to ARP (this is achieved by passing the
8011 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8012 	 * arp response comes back in ip_wput_nondata, we will create
8013 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8014 	 *
8015 	 * Note that this is a temporary solution; the correct solution is
8016 	 * to create an incomplete  per-dst ire_cache entry, and send the
8017 	 * packet out when the gw's nce is resolved. In order to achieve this,
8018 	 * all packet processing must have been completed prior to calling
8019 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8020 	 * to be modified to accomodate this solution.
8021 	 */
8022 	if (ip_nexthop) {
8023 		/*
8024 		 * The first time we come here, we look for an IRE_INTERFACE
8025 		 * entry for the specified nexthop, set the dst to be the
8026 		 * nexthop address and create an IRE_CACHE entry for the
8027 		 * nexthop. The next time around, we are able to find an
8028 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8029 		 * nexthop address and create an IRE_CACHE entry for the
8030 		 * destination address via the specified nexthop.
8031 		 */
8032 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8033 		    msg_getlabel(mp), ipst);
8034 		if (ire != NULL) {
8035 			gw = nexthop_addr;
8036 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8037 		} else {
8038 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8039 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8040 			    msg_getlabel(mp),
8041 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8042 			    ipst);
8043 			if (ire != NULL) {
8044 				dst = nexthop_addr;
8045 			}
8046 		}
8047 	} else {
8048 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8049 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8050 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8051 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8052 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8053 		    ipst);
8054 	}
8055 
8056 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8057 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8058 
8059 	/*
8060 	 * This loop is run only once in most cases.
8061 	 * We loop to resolve further routes only when the destination
8062 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8063 	 */
8064 	do {
8065 		/* Clear the previous iteration's values */
8066 		if (src_ipif != NULL) {
8067 			ipif_refrele(src_ipif);
8068 			src_ipif = NULL;
8069 		}
8070 		if (dst_ill != NULL) {
8071 			ill_refrele(dst_ill);
8072 			dst_ill = NULL;
8073 		}
8074 
8075 		multirt_resolve_next = B_FALSE;
8076 		/*
8077 		 * We check if packets have to be multirouted.
8078 		 * In this case, given the current <ire, sire> couple,
8079 		 * we look for the next suitable <ire, sire>.
8080 		 * This check is done in ire_multirt_lookup(),
8081 		 * which applies various criteria to find the next route
8082 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8083 		 * unchanged if it detects it has not been tried yet.
8084 		 */
8085 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8086 			ip3dbg(("ip_newroute: starting next_resolution "
8087 			    "with first_mp %p, tag %d\n",
8088 			    (void *)first_mp,
8089 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8090 
8091 			ASSERT(sire != NULL);
8092 			multirt_is_resolvable =
8093 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8094 			    msg_getlabel(mp), ipst);
8095 
8096 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8097 			    "ire %p, sire %p\n",
8098 			    multirt_is_resolvable,
8099 			    (void *)ire, (void *)sire));
8100 
8101 			if (!multirt_is_resolvable) {
8102 				/*
8103 				 * No more multirt route to resolve; give up
8104 				 * (all routes resolved or no more
8105 				 * resolvable routes).
8106 				 */
8107 				if (ire != NULL) {
8108 					ire_refrele(ire);
8109 					ire = NULL;
8110 				}
8111 			} else {
8112 				ASSERT(sire != NULL);
8113 				ASSERT(ire != NULL);
8114 				/*
8115 				 * We simply use first_sire as a flag that
8116 				 * indicates if a resolvable multirt route
8117 				 * has already been found.
8118 				 * If it is not the case, we may have to send
8119 				 * an ICMP error to report that the
8120 				 * destination is unreachable.
8121 				 * We do not IRE_REFHOLD first_sire.
8122 				 */
8123 				if (first_sire == NULL) {
8124 					first_sire = sire;
8125 				}
8126 			}
8127 		}
8128 		if (ire == NULL) {
8129 			if (ip_debug > 3) {
8130 				/* ip2dbg */
8131 				pr_addr_dbg("ip_newroute: "
8132 				    "can't resolve %s\n", AF_INET, &dst);
8133 			}
8134 			ip3dbg(("ip_newroute: "
8135 			    "ire %p, sire %p, first_sire %p\n",
8136 			    (void *)ire, (void *)sire, (void *)first_sire));
8137 
8138 			if (sire != NULL) {
8139 				ire_refrele(sire);
8140 				sire = NULL;
8141 			}
8142 
8143 			if (first_sire != NULL) {
8144 				/*
8145 				 * At least one multirt route has been found
8146 				 * in the same call to ip_newroute();
8147 				 * there is no need to report an ICMP error.
8148 				 * first_sire was not IRE_REFHOLDed.
8149 				 */
8150 				MULTIRT_DEBUG_UNTAG(first_mp);
8151 				freemsg(first_mp);
8152 				return;
8153 			}
8154 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8155 			    RTA_DST, ipst);
8156 			goto icmp_err_ret;
8157 		}
8158 
8159 		/*
8160 		 * Verify that the returned IRE does not have either
8161 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8162 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8163 		 */
8164 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8165 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8166 			goto icmp_err_ret;
8167 		}
8168 		/*
8169 		 * Increment the ire_ob_pkt_count field for ire if it is an
8170 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8171 		 * increment the same for the parent IRE, sire, if it is some
8172 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8173 		 */
8174 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8175 			UPDATE_OB_PKT_COUNT(ire);
8176 			ire->ire_last_used_time = lbolt;
8177 		}
8178 
8179 		if (sire != NULL) {
8180 			gw = sire->ire_gateway_addr;
8181 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8182 			    IRE_INTERFACE)) == 0);
8183 			UPDATE_OB_PKT_COUNT(sire);
8184 			sire->ire_last_used_time = lbolt;
8185 		}
8186 		/*
8187 		 * We have a route to reach the destination.  Find the
8188 		 * appropriate ill, then get a source address using
8189 		 * ipif_select_source().
8190 		 *
8191 		 * If we are here trying to create an IRE_CACHE for an offlink
8192 		 * destination and have an IRE_CACHE entry for VNI, then use
8193 		 * ire_stq instead since VNI's queue is a black hole.
8194 		 */
8195 		if ((ire->ire_type == IRE_CACHE) &&
8196 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8197 			dst_ill = ire->ire_stq->q_ptr;
8198 			ill_refhold(dst_ill);
8199 		} else {
8200 			ill_t *ill = ire->ire_ipif->ipif_ill;
8201 
8202 			if (IS_IPMP(ill)) {
8203 				dst_ill =
8204 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8205 			} else {
8206 				dst_ill = ill;
8207 				ill_refhold(dst_ill);
8208 			}
8209 		}
8210 
8211 		if (dst_ill == NULL) {
8212 			if (ip_debug > 2) {
8213 				pr_addr_dbg("ip_newroute: no dst "
8214 				    "ill for dst %s\n", AF_INET, &dst);
8215 			}
8216 			goto icmp_err_ret;
8217 		}
8218 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8219 
8220 		/*
8221 		 * Pick the best source address from dst_ill.
8222 		 *
8223 		 * 1) Try to pick the source address from the destination
8224 		 *    route. Clustering assumes that when we have multiple
8225 		 *    prefixes hosted on an interface, the prefix of the
8226 		 *    source address matches the prefix of the destination
8227 		 *    route. We do this only if the address is not
8228 		 *    DEPRECATED.
8229 		 *
8230 		 * 2) If the conn is in a different zone than the ire, we
8231 		 *    need to pick a source address from the right zone.
8232 		 */
8233 		ASSERT(src_ipif == NULL);
8234 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8235 			/*
8236 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8237 			 * Check that the ipif matching the requested source
8238 			 * address still exists.
8239 			 */
8240 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8241 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8242 		}
8243 
8244 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8245 
8246 		if (src_ipif == NULL &&
8247 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8248 			ire_marks |= IRE_MARK_USESRC_CHECK;
8249 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8250 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8251 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8252 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8253 			    ire->ire_zoneid != ALL_ZONES) ||
8254 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8255 				/*
8256 				 * If the destination is reachable via a
8257 				 * given gateway, the selected source address
8258 				 * should be in the same subnet as the gateway.
8259 				 * Otherwise, the destination is not reachable.
8260 				 *
8261 				 * If there are no interfaces on the same subnet
8262 				 * as the destination, ipif_select_source gives
8263 				 * first non-deprecated interface which might be
8264 				 * on a different subnet than the gateway.
8265 				 * This is not desirable. Hence pass the dst_ire
8266 				 * source address to ipif_select_source.
8267 				 * It is sure that the destination is reachable
8268 				 * with the dst_ire source address subnet.
8269 				 * So passing dst_ire source address to
8270 				 * ipif_select_source will make sure that the
8271 				 * selected source will be on the same subnet
8272 				 * as dst_ire source address.
8273 				 */
8274 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8275 
8276 				src_ipif = ipif_select_source(dst_ill, saddr,
8277 				    zoneid);
8278 				if (src_ipif == NULL) {
8279 					if (ip_debug > 2) {
8280 						pr_addr_dbg("ip_newroute: "
8281 						    "no src for dst %s ",
8282 						    AF_INET, &dst);
8283 						printf("on interface %s\n",
8284 						    dst_ill->ill_name);
8285 					}
8286 					goto icmp_err_ret;
8287 				}
8288 			} else {
8289 				src_ipif = ire->ire_ipif;
8290 				ASSERT(src_ipif != NULL);
8291 				/* hold src_ipif for uniformity */
8292 				ipif_refhold(src_ipif);
8293 			}
8294 		}
8295 
8296 		/*
8297 		 * Assign a source address while we have the conn.
8298 		 * We can't have ip_wput_ire pick a source address when the
8299 		 * packet returns from arp since we need to look at
8300 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8301 		 * going through arp.
8302 		 *
8303 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8304 		 *	  it uses ip6i to store this information.
8305 		 */
8306 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8307 			ipha->ipha_src = src_ipif->ipif_src_addr;
8308 
8309 		if (ip_debug > 3) {
8310 			/* ip2dbg */
8311 			pr_addr_dbg("ip_newroute: first hop %s\n",
8312 			    AF_INET, &gw);
8313 		}
8314 		ip2dbg(("\tire type %s (%d)\n",
8315 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8316 
8317 		/*
8318 		 * The TTL of multirouted packets is bounded by the
8319 		 * ip_multirt_ttl ndd variable.
8320 		 */
8321 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8322 			/* Force TTL of multirouted packets */
8323 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8324 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8325 				ip2dbg(("ip_newroute: forcing multirt TTL "
8326 				    "to %d (was %d), dst 0x%08x\n",
8327 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8328 				    ntohl(sire->ire_addr)));
8329 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8330 			}
8331 		}
8332 		/*
8333 		 * At this point in ip_newroute(), ire is either the
8334 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8335 		 * destination or an IRE_INTERFACE type that should be used
8336 		 * to resolve an on-subnet destination or an on-subnet
8337 		 * next-hop gateway.
8338 		 *
8339 		 * In the IRE_CACHE case, we have the following :
8340 		 *
8341 		 * 1) src_ipif - used for getting a source address.
8342 		 *
8343 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8344 		 *    means packets using this IRE_CACHE will go out on
8345 		 *    dst_ill.
8346 		 *
8347 		 * 3) The IRE sire will point to the prefix that is the
8348 		 *    longest  matching route for the destination. These
8349 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8350 		 *
8351 		 *    The newly created IRE_CACHE entry for the off-subnet
8352 		 *    destination is tied to both the prefix route and the
8353 		 *    interface route used to resolve the next-hop gateway
8354 		 *    via the ire_phandle and ire_ihandle fields,
8355 		 *    respectively.
8356 		 *
8357 		 * In the IRE_INTERFACE case, we have the following :
8358 		 *
8359 		 * 1) src_ipif - used for getting a source address.
8360 		 *
8361 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8362 		 *    means packets using the IRE_CACHE that we will build
8363 		 *    here will go out on dst_ill.
8364 		 *
8365 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8366 		 *    to be created will only be tied to the IRE_INTERFACE
8367 		 *    that was derived from the ire_ihandle field.
8368 		 *
8369 		 *    If sire is non-NULL, it means the destination is
8370 		 *    off-link and we will first create the IRE_CACHE for the
8371 		 *    gateway. Next time through ip_newroute, we will create
8372 		 *    the IRE_CACHE for the final destination as described
8373 		 *    above.
8374 		 *
8375 		 * In both cases, after the current resolution has been
8376 		 * completed (or possibly initialised, in the IRE_INTERFACE
8377 		 * case), the loop may be re-entered to attempt the resolution
8378 		 * of another RTF_MULTIRT route.
8379 		 *
8380 		 * When an IRE_CACHE entry for the off-subnet destination is
8381 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8382 		 * for further processing in emission loops.
8383 		 */
8384 		save_ire = ire;
8385 		switch (ire->ire_type) {
8386 		case IRE_CACHE: {
8387 			ire_t	*ipif_ire;
8388 
8389 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8390 			if (gw == 0)
8391 				gw = ire->ire_gateway_addr;
8392 			/*
8393 			 * We need 3 ire's to create a new cache ire for an
8394 			 * off-link destination from the cache ire of the
8395 			 * gateway.
8396 			 *
8397 			 *	1. The prefix ire 'sire' (Note that this does
8398 			 *	   not apply to the conn_nexthop_set case)
8399 			 *	2. The cache ire of the gateway 'ire'
8400 			 *	3. The interface ire 'ipif_ire'
8401 			 *
8402 			 * We have (1) and (2). We lookup (3) below.
8403 			 *
8404 			 * If there is no interface route to the gateway,
8405 			 * it is a race condition, where we found the cache
8406 			 * but the interface route has been deleted.
8407 			 */
8408 			if (ip_nexthop) {
8409 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8410 			} else {
8411 				ipif_ire =
8412 				    ire_ihandle_lookup_offlink(ire, sire);
8413 			}
8414 			if (ipif_ire == NULL) {
8415 				ip1dbg(("ip_newroute: "
8416 				    "ire_ihandle_lookup_offlink failed\n"));
8417 				goto icmp_err_ret;
8418 			}
8419 
8420 			/*
8421 			 * Check cached gateway IRE for any security
8422 			 * attributes; if found, associate the gateway
8423 			 * credentials group to the destination IRE.
8424 			 */
8425 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8426 				mutex_enter(&attrp->igsa_lock);
8427 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8428 					GCGRP_REFHOLD(gcgrp);
8429 				mutex_exit(&attrp->igsa_lock);
8430 			}
8431 
8432 			/*
8433 			 * XXX For the source of the resolver mp,
8434 			 * we are using the same DL_UNITDATA_REQ
8435 			 * (from save_ire->ire_nce->nce_res_mp)
8436 			 * though the save_ire is not pointing at the same ill.
8437 			 * This is incorrect. We need to send it up to the
8438 			 * resolver to get the right res_mp. For ethernets
8439 			 * this may be okay (ill_type == DL_ETHER).
8440 			 */
8441 
8442 			ire = ire_create(
8443 			    (uchar_t *)&dst,		/* dest address */
8444 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8445 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8446 			    (uchar_t *)&gw,		/* gateway address */
8447 			    &save_ire->ire_max_frag,
8448 			    save_ire->ire_nce,		/* src nce */
8449 			    dst_ill->ill_rq,		/* recv-from queue */
8450 			    dst_ill->ill_wq,		/* send-to queue */
8451 			    IRE_CACHE,			/* IRE type */
8452 			    src_ipif,
8453 			    (sire != NULL) ?
8454 			    sire->ire_mask : 0, 	/* Parent mask */
8455 			    (sire != NULL) ?
8456 			    sire->ire_phandle : 0,	/* Parent handle */
8457 			    ipif_ire->ire_ihandle,	/* Interface handle */
8458 			    (sire != NULL) ? (sire->ire_flags &
8459 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8460 			    (sire != NULL) ?
8461 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8462 			    NULL,
8463 			    gcgrp,
8464 			    ipst);
8465 
8466 			if (ire == NULL) {
8467 				if (gcgrp != NULL) {
8468 					GCGRP_REFRELE(gcgrp);
8469 					gcgrp = NULL;
8470 				}
8471 				ire_refrele(ipif_ire);
8472 				ire_refrele(save_ire);
8473 				break;
8474 			}
8475 
8476 			/* reference now held by IRE */
8477 			gcgrp = NULL;
8478 
8479 			ire->ire_marks |= ire_marks;
8480 
8481 			/*
8482 			 * Prevent sire and ipif_ire from getting deleted.
8483 			 * The newly created ire is tied to both of them via
8484 			 * the phandle and ihandle respectively.
8485 			 */
8486 			if (sire != NULL) {
8487 				IRB_REFHOLD(sire->ire_bucket);
8488 				/* Has it been removed already ? */
8489 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8490 					IRB_REFRELE(sire->ire_bucket);
8491 					ire_refrele(ipif_ire);
8492 					ire_refrele(save_ire);
8493 					break;
8494 				}
8495 			}
8496 
8497 			IRB_REFHOLD(ipif_ire->ire_bucket);
8498 			/* Has it been removed already ? */
8499 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8500 				IRB_REFRELE(ipif_ire->ire_bucket);
8501 				if (sire != NULL)
8502 					IRB_REFRELE(sire->ire_bucket);
8503 				ire_refrele(ipif_ire);
8504 				ire_refrele(save_ire);
8505 				break;
8506 			}
8507 
8508 			xmit_mp = first_mp;
8509 			/*
8510 			 * In the case of multirouting, a copy
8511 			 * of the packet is done before its sending.
8512 			 * The copy is used to attempt another
8513 			 * route resolution, in a next loop.
8514 			 */
8515 			if (ire->ire_flags & RTF_MULTIRT) {
8516 				copy_mp = copymsg(first_mp);
8517 				if (copy_mp != NULL) {
8518 					xmit_mp = copy_mp;
8519 					MULTIRT_DEBUG_TAG(first_mp);
8520 				}
8521 			}
8522 
8523 			ire_add_then_send(q, ire, xmit_mp);
8524 			ire_refrele(save_ire);
8525 
8526 			/* Assert that sire is not deleted yet. */
8527 			if (sire != NULL) {
8528 				ASSERT(sire->ire_ptpn != NULL);
8529 				IRB_REFRELE(sire->ire_bucket);
8530 			}
8531 
8532 			/* Assert that ipif_ire is not deleted yet. */
8533 			ASSERT(ipif_ire->ire_ptpn != NULL);
8534 			IRB_REFRELE(ipif_ire->ire_bucket);
8535 			ire_refrele(ipif_ire);
8536 
8537 			/*
8538 			 * If copy_mp is not NULL, multirouting was
8539 			 * requested. We loop to initiate a next
8540 			 * route resolution attempt, starting from sire.
8541 			 */
8542 			if (copy_mp != NULL) {
8543 				/*
8544 				 * Search for the next unresolved
8545 				 * multirt route.
8546 				 */
8547 				copy_mp = NULL;
8548 				ipif_ire = NULL;
8549 				ire = NULL;
8550 				multirt_resolve_next = B_TRUE;
8551 				continue;
8552 			}
8553 			if (sire != NULL)
8554 				ire_refrele(sire);
8555 			ipif_refrele(src_ipif);
8556 			ill_refrele(dst_ill);
8557 			return;
8558 		}
8559 		case IRE_IF_NORESOLVER: {
8560 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8561 			    dst_ill->ill_resolver_mp == NULL) {
8562 				ip1dbg(("ip_newroute: dst_ill %p "
8563 				    "for IRE_IF_NORESOLVER ire %p has "
8564 				    "no ill_resolver_mp\n",
8565 				    (void *)dst_ill, (void *)ire));
8566 				break;
8567 			}
8568 
8569 			/*
8570 			 * TSol note: We are creating the ire cache for the
8571 			 * destination 'dst'. If 'dst' is offlink, going
8572 			 * through the first hop 'gw', the security attributes
8573 			 * of 'dst' must be set to point to the gateway
8574 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8575 			 * is possible that 'dst' is a potential gateway that is
8576 			 * referenced by some route that has some security
8577 			 * attributes. Thus in the former case, we need to do a
8578 			 * gcgrp_lookup of 'gw' while in the latter case we
8579 			 * need to do gcgrp_lookup of 'dst' itself.
8580 			 */
8581 			ga.ga_af = AF_INET;
8582 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8583 			    &ga.ga_addr);
8584 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8585 
8586 			ire = ire_create(
8587 			    (uchar_t *)&dst,		/* dest address */
8588 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8589 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8590 			    (uchar_t *)&gw,		/* gateway address */
8591 			    &save_ire->ire_max_frag,
8592 			    NULL,			/* no src nce */
8593 			    dst_ill->ill_rq,		/* recv-from queue */
8594 			    dst_ill->ill_wq,		/* send-to queue */
8595 			    IRE_CACHE,
8596 			    src_ipif,
8597 			    save_ire->ire_mask,		/* Parent mask */
8598 			    (sire != NULL) ?		/* Parent handle */
8599 			    sire->ire_phandle : 0,
8600 			    save_ire->ire_ihandle,	/* Interface handle */
8601 			    (sire != NULL) ? sire->ire_flags &
8602 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8603 			    &(save_ire->ire_uinfo),
8604 			    NULL,
8605 			    gcgrp,
8606 			    ipst);
8607 
8608 			if (ire == NULL) {
8609 				if (gcgrp != NULL) {
8610 					GCGRP_REFRELE(gcgrp);
8611 					gcgrp = NULL;
8612 				}
8613 				ire_refrele(save_ire);
8614 				break;
8615 			}
8616 
8617 			/* reference now held by IRE */
8618 			gcgrp = NULL;
8619 
8620 			ire->ire_marks |= ire_marks;
8621 
8622 			/* Prevent save_ire from getting deleted */
8623 			IRB_REFHOLD(save_ire->ire_bucket);
8624 			/* Has it been removed already ? */
8625 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8626 				IRB_REFRELE(save_ire->ire_bucket);
8627 				ire_refrele(save_ire);
8628 				break;
8629 			}
8630 
8631 			/*
8632 			 * In the case of multirouting, a copy
8633 			 * of the packet is made before it is sent.
8634 			 * The copy is used in the next
8635 			 * loop to attempt another resolution.
8636 			 */
8637 			xmit_mp = first_mp;
8638 			if ((sire != NULL) &&
8639 			    (sire->ire_flags & RTF_MULTIRT)) {
8640 				copy_mp = copymsg(first_mp);
8641 				if (copy_mp != NULL) {
8642 					xmit_mp = copy_mp;
8643 					MULTIRT_DEBUG_TAG(first_mp);
8644 				}
8645 			}
8646 			ire_add_then_send(q, ire, xmit_mp);
8647 
8648 			/* Assert that it is not deleted yet. */
8649 			ASSERT(save_ire->ire_ptpn != NULL);
8650 			IRB_REFRELE(save_ire->ire_bucket);
8651 			ire_refrele(save_ire);
8652 
8653 			if (copy_mp != NULL) {
8654 				/*
8655 				 * If we found a (no)resolver, we ignore any
8656 				 * trailing top priority IRE_CACHE in further
8657 				 * loops. This ensures that we do not omit any
8658 				 * (no)resolver.
8659 				 * This IRE_CACHE, if any, will be processed
8660 				 * by another thread entering ip_newroute().
8661 				 * IRE_CACHE entries, if any, will be processed
8662 				 * by another thread entering ip_newroute(),
8663 				 * (upon resolver response, for instance).
8664 				 * This aims to force parallel multirt
8665 				 * resolutions as soon as a packet must be sent.
8666 				 * In the best case, after the tx of only one
8667 				 * packet, all reachable routes are resolved.
8668 				 * Otherwise, the resolution of all RTF_MULTIRT
8669 				 * routes would require several emissions.
8670 				 */
8671 				multirt_flags &= ~MULTIRT_CACHEGW;
8672 
8673 				/*
8674 				 * Search for the next unresolved multirt
8675 				 * route.
8676 				 */
8677 				copy_mp = NULL;
8678 				save_ire = NULL;
8679 				ire = NULL;
8680 				multirt_resolve_next = B_TRUE;
8681 				continue;
8682 			}
8683 
8684 			/*
8685 			 * Don't need sire anymore
8686 			 */
8687 			if (sire != NULL)
8688 				ire_refrele(sire);
8689 
8690 			ipif_refrele(src_ipif);
8691 			ill_refrele(dst_ill);
8692 			return;
8693 		}
8694 		case IRE_IF_RESOLVER:
8695 			/*
8696 			 * We can't build an IRE_CACHE yet, but at least we
8697 			 * found a resolver that can help.
8698 			 */
8699 			res_mp = dst_ill->ill_resolver_mp;
8700 			if (!OK_RESOLVER_MP(res_mp))
8701 				break;
8702 
8703 			/*
8704 			 * To be at this point in the code with a non-zero gw
8705 			 * means that dst is reachable through a gateway that
8706 			 * we have never resolved.  By changing dst to the gw
8707 			 * addr we resolve the gateway first.
8708 			 * When ire_add_then_send() tries to put the IP dg
8709 			 * to dst, it will reenter ip_newroute() at which
8710 			 * time we will find the IRE_CACHE for the gw and
8711 			 * create another IRE_CACHE in case IRE_CACHE above.
8712 			 */
8713 			if (gw != INADDR_ANY) {
8714 				/*
8715 				 * The source ipif that was determined above was
8716 				 * relative to the destination address, not the
8717 				 * gateway's. If src_ipif was not taken out of
8718 				 * the IRE_IF_RESOLVER entry, we'll need to call
8719 				 * ipif_select_source() again.
8720 				 */
8721 				if (src_ipif != ire->ire_ipif) {
8722 					ipif_refrele(src_ipif);
8723 					src_ipif = ipif_select_source(dst_ill,
8724 					    gw, zoneid);
8725 					if (src_ipif == NULL) {
8726 						if (ip_debug > 2) {
8727 							pr_addr_dbg(
8728 							    "ip_newroute: no "
8729 							    "src for gw %s ",
8730 							    AF_INET, &gw);
8731 							printf("on "
8732 							    "interface %s\n",
8733 							    dst_ill->ill_name);
8734 						}
8735 						goto icmp_err_ret;
8736 					}
8737 				}
8738 				save_dst = dst;
8739 				dst = gw;
8740 				gw = INADDR_ANY;
8741 			}
8742 
8743 			/*
8744 			 * We obtain a partial IRE_CACHE which we will pass
8745 			 * along with the resolver query.  When the response
8746 			 * comes back it will be there ready for us to add.
8747 			 * The ire_max_frag is atomically set under the
8748 			 * irebucket lock in ire_add_v[46].
8749 			 */
8750 
8751 			ire = ire_create_mp(
8752 			    (uchar_t *)&dst,		/* dest address */
8753 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8754 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8755 			    (uchar_t *)&gw,		/* gateway address */
8756 			    NULL,			/* ire_max_frag */
8757 			    NULL,			/* no src nce */
8758 			    dst_ill->ill_rq,		/* recv-from queue */
8759 			    dst_ill->ill_wq,		/* send-to queue */
8760 			    IRE_CACHE,
8761 			    src_ipif,			/* Interface ipif */
8762 			    save_ire->ire_mask,		/* Parent mask */
8763 			    0,
8764 			    save_ire->ire_ihandle,	/* Interface handle */
8765 			    0,				/* flags if any */
8766 			    &(save_ire->ire_uinfo),
8767 			    NULL,
8768 			    NULL,
8769 			    ipst);
8770 
8771 			if (ire == NULL) {
8772 				ire_refrele(save_ire);
8773 				break;
8774 			}
8775 
8776 			if ((sire != NULL) &&
8777 			    (sire->ire_flags & RTF_MULTIRT)) {
8778 				copy_mp = copymsg(first_mp);
8779 				if (copy_mp != NULL)
8780 					MULTIRT_DEBUG_TAG(copy_mp);
8781 			}
8782 
8783 			ire->ire_marks |= ire_marks;
8784 
8785 			/*
8786 			 * Construct message chain for the resolver
8787 			 * of the form:
8788 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8789 			 * Packet could contain a IPSEC_OUT mp.
8790 			 *
8791 			 * NOTE : ire will be added later when the response
8792 			 * comes back from ARP. If the response does not
8793 			 * come back, ARP frees the packet. For this reason,
8794 			 * we can't REFHOLD the bucket of save_ire to prevent
8795 			 * deletions. We may not be able to REFRELE the bucket
8796 			 * if the response never comes back. Thus, before
8797 			 * adding the ire, ire_add_v4 will make sure that the
8798 			 * interface route does not get deleted. This is the
8799 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8800 			 * where we can always prevent deletions because of
8801 			 * the synchronous nature of adding IRES i.e
8802 			 * ire_add_then_send is called after creating the IRE.
8803 			 */
8804 			ASSERT(ire->ire_mp != NULL);
8805 			ire->ire_mp->b_cont = first_mp;
8806 			/* Have saved_mp handy, for cleanup if canput fails */
8807 			saved_mp = mp;
8808 			mp = copyb(res_mp);
8809 			if (mp == NULL) {
8810 				/* Prepare for cleanup */
8811 				mp = saved_mp; /* pkt */
8812 				ire_delete(ire); /* ire_mp */
8813 				ire = NULL;
8814 				ire_refrele(save_ire);
8815 				if (copy_mp != NULL) {
8816 					MULTIRT_DEBUG_UNTAG(copy_mp);
8817 					freemsg(copy_mp);
8818 					copy_mp = NULL;
8819 				}
8820 				break;
8821 			}
8822 			linkb(mp, ire->ire_mp);
8823 
8824 			/*
8825 			 * Fill in the source and dest addrs for the resolver.
8826 			 * NOTE: this depends on memory layouts imposed by
8827 			 * ill_init().
8828 			 */
8829 			areq = (areq_t *)mp->b_rptr;
8830 			addrp = (ipaddr_t *)((char *)areq +
8831 			    areq->areq_sender_addr_offset);
8832 			*addrp = save_ire->ire_src_addr;
8833 
8834 			ire_refrele(save_ire);
8835 			addrp = (ipaddr_t *)((char *)areq +
8836 			    areq->areq_target_addr_offset);
8837 			*addrp = dst;
8838 			/* Up to the resolver. */
8839 			if (canputnext(dst_ill->ill_rq) &&
8840 			    !(dst_ill->ill_arp_closing)) {
8841 				putnext(dst_ill->ill_rq, mp);
8842 				ire = NULL;
8843 				if (copy_mp != NULL) {
8844 					/*
8845 					 * If we found a resolver, we ignore
8846 					 * any trailing top priority IRE_CACHE
8847 					 * in the further loops. This ensures
8848 					 * that we do not omit any resolver.
8849 					 * IRE_CACHE entries, if any, will be
8850 					 * processed next time we enter
8851 					 * ip_newroute().
8852 					 */
8853 					multirt_flags &= ~MULTIRT_CACHEGW;
8854 					/*
8855 					 * Search for the next unresolved
8856 					 * multirt route.
8857 					 */
8858 					first_mp = copy_mp;
8859 					copy_mp = NULL;
8860 					/* Prepare the next resolution loop. */
8861 					mp = first_mp;
8862 					EXTRACT_PKT_MP(mp, first_mp,
8863 					    mctl_present);
8864 					if (mctl_present)
8865 						io = (ipsec_out_t *)
8866 						    first_mp->b_rptr;
8867 					ipha = (ipha_t *)mp->b_rptr;
8868 
8869 					ASSERT(sire != NULL);
8870 
8871 					dst = save_dst;
8872 					multirt_resolve_next = B_TRUE;
8873 					continue;
8874 				}
8875 
8876 				if (sire != NULL)
8877 					ire_refrele(sire);
8878 
8879 				/*
8880 				 * The response will come back in ip_wput
8881 				 * with db_type IRE_DB_TYPE.
8882 				 */
8883 				ipif_refrele(src_ipif);
8884 				ill_refrele(dst_ill);
8885 				return;
8886 			} else {
8887 				/* Prepare for cleanup */
8888 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8889 				    mp);
8890 				mp->b_cont = NULL;
8891 				freeb(mp); /* areq */
8892 				/*
8893 				 * this is an ire that is not added to the
8894 				 * cache. ire_freemblk will handle the release
8895 				 * of any resources associated with the ire.
8896 				 */
8897 				ire_delete(ire); /* ire_mp */
8898 				mp = saved_mp; /* pkt */
8899 				ire = NULL;
8900 				if (copy_mp != NULL) {
8901 					MULTIRT_DEBUG_UNTAG(copy_mp);
8902 					freemsg(copy_mp);
8903 					copy_mp = NULL;
8904 				}
8905 				break;
8906 			}
8907 		default:
8908 			break;
8909 		}
8910 	} while (multirt_resolve_next);
8911 
8912 	ip1dbg(("ip_newroute: dropped\n"));
8913 	/* Did this packet originate externally? */
8914 	if (mp->b_prev) {
8915 		mp->b_next = NULL;
8916 		mp->b_prev = NULL;
8917 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8918 	} else {
8919 		if (dst_ill != NULL) {
8920 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8921 		} else {
8922 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8923 		}
8924 	}
8925 	ASSERT(copy_mp == NULL);
8926 	MULTIRT_DEBUG_UNTAG(first_mp);
8927 	freemsg(first_mp);
8928 	if (ire != NULL)
8929 		ire_refrele(ire);
8930 	if (sire != NULL)
8931 		ire_refrele(sire);
8932 	if (src_ipif != NULL)
8933 		ipif_refrele(src_ipif);
8934 	if (dst_ill != NULL)
8935 		ill_refrele(dst_ill);
8936 	return;
8937 
8938 icmp_err_ret:
8939 	ip1dbg(("ip_newroute: no route\n"));
8940 	if (src_ipif != NULL)
8941 		ipif_refrele(src_ipif);
8942 	if (dst_ill != NULL)
8943 		ill_refrele(dst_ill);
8944 	if (sire != NULL)
8945 		ire_refrele(sire);
8946 	/* Did this packet originate externally? */
8947 	if (mp->b_prev) {
8948 		mp->b_next = NULL;
8949 		mp->b_prev = NULL;
8950 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8951 		q = WR(q);
8952 	} else {
8953 		/*
8954 		 * There is no outgoing ill, so just increment the
8955 		 * system MIB.
8956 		 */
8957 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8958 		/*
8959 		 * Since ip_wput() isn't close to finished, we fill
8960 		 * in enough of the header for credible error reporting.
8961 		 */
8962 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8963 			/* Failed */
8964 			MULTIRT_DEBUG_UNTAG(first_mp);
8965 			freemsg(first_mp);
8966 			if (ire != NULL)
8967 				ire_refrele(ire);
8968 			return;
8969 		}
8970 	}
8971 
8972 	/*
8973 	 * At this point we will have ire only if RTF_BLACKHOLE
8974 	 * or RTF_REJECT flags are set on the IRE. It will not
8975 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8976 	 */
8977 	if (ire != NULL) {
8978 		if (ire->ire_flags & RTF_BLACKHOLE) {
8979 			ire_refrele(ire);
8980 			MULTIRT_DEBUG_UNTAG(first_mp);
8981 			freemsg(first_mp);
8982 			return;
8983 		}
8984 		ire_refrele(ire);
8985 	}
8986 	if (ip_source_routed(ipha, ipst)) {
8987 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8988 		    zoneid, ipst);
8989 		return;
8990 	}
8991 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8992 }
8993 
8994 ip_opt_info_t zero_info;
8995 
8996 /*
8997  * IPv4 -
8998  * ip_newroute_ipif is called by ip_wput_multicast and
8999  * ip_rput_forward_multicast whenever we need to send
9000  * out a packet to a destination address for which we do not have specific
9001  * routing information. It is used when the packet will be sent out
9002  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9003  * socket option is set or icmp error message wants to go out on a particular
9004  * interface for a unicast packet.
9005  *
9006  * In most cases, the destination address is resolved thanks to the ipif
9007  * intrinsic resolver. However, there are some cases where the call to
9008  * ip_newroute_ipif must take into account the potential presence of
9009  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9010  * that uses the interface. This is specified through flags,
9011  * which can be a combination of:
9012  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9013  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9014  *   and flags. Additionally, the packet source address has to be set to
9015  *   the specified address. The caller is thus expected to set this flag
9016  *   if the packet has no specific source address yet.
9017  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9018  *   flag, the resulting ire will inherit the flag. All unresolved routes
9019  *   to the destination must be explored in the same call to
9020  *   ip_newroute_ipif().
9021  */
9022 static void
9023 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9024     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9025 {
9026 	areq_t	*areq;
9027 	ire_t	*ire = NULL;
9028 	mblk_t	*res_mp;
9029 	ipaddr_t *addrp;
9030 	mblk_t *first_mp;
9031 	ire_t	*save_ire = NULL;
9032 	ipif_t	*src_ipif = NULL;
9033 	ushort_t ire_marks = 0;
9034 	ill_t	*dst_ill = NULL;
9035 	ipha_t *ipha;
9036 	mblk_t	*saved_mp;
9037 	ire_t   *fire = NULL;
9038 	mblk_t  *copy_mp = NULL;
9039 	boolean_t multirt_resolve_next;
9040 	boolean_t unspec_src;
9041 	ipaddr_t ipha_dst;
9042 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9043 
9044 	/*
9045 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9046 	 * here for uniformity
9047 	 */
9048 	ipif_refhold(ipif);
9049 
9050 	/*
9051 	 * This loop is run only once in most cases.
9052 	 * We loop to resolve further routes only when the destination
9053 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9054 	 */
9055 	do {
9056 		if (dst_ill != NULL) {
9057 			ill_refrele(dst_ill);
9058 			dst_ill = NULL;
9059 		}
9060 		if (src_ipif != NULL) {
9061 			ipif_refrele(src_ipif);
9062 			src_ipif = NULL;
9063 		}
9064 		multirt_resolve_next = B_FALSE;
9065 
9066 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9067 		    ipif->ipif_ill->ill_name));
9068 
9069 		first_mp = mp;
9070 		if (DB_TYPE(mp) == M_CTL)
9071 			mp = mp->b_cont;
9072 		ipha = (ipha_t *)mp->b_rptr;
9073 
9074 		/*
9075 		 * Save the packet destination address, we may need it after
9076 		 * the packet has been consumed.
9077 		 */
9078 		ipha_dst = ipha->ipha_dst;
9079 
9080 		/*
9081 		 * If the interface is a pt-pt interface we look for an
9082 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9083 		 * local_address and the pt-pt destination address. Otherwise
9084 		 * we just match the local address.
9085 		 * NOTE: dst could be different than ipha->ipha_dst in case
9086 		 * of sending igmp multicast packets over a point-to-point
9087 		 * connection.
9088 		 * Thus we must be careful enough to check ipha_dst to be a
9089 		 * multicast address, otherwise it will take xmit_if path for
9090 		 * multicast packets resulting into kernel stack overflow by
9091 		 * repeated calls to ip_newroute_ipif from ire_send().
9092 		 */
9093 		if (CLASSD(ipha_dst) &&
9094 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9095 			goto err_ret;
9096 		}
9097 
9098 		/*
9099 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9100 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9101 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9102 		 * propagate its flags to the new ire.
9103 		 */
9104 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9105 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9106 			ip2dbg(("ip_newroute_ipif: "
9107 			    "ipif_lookup_multi_ire("
9108 			    "ipif %p, dst %08x) = fire %p\n",
9109 			    (void *)ipif, ntohl(dst), (void *)fire));
9110 		}
9111 
9112 		/*
9113 		 * Note: While we pick a dst_ill we are really only
9114 		 * interested in the ill for load spreading. The source
9115 		 * ipif is determined by source address selection below.
9116 		 */
9117 		if (IS_IPMP(ipif->ipif_ill)) {
9118 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9119 
9120 			if (CLASSD(ipha_dst))
9121 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9122 			else
9123 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9124 		} else {
9125 			dst_ill = ipif->ipif_ill;
9126 			ill_refhold(dst_ill);
9127 		}
9128 
9129 		if (dst_ill == NULL) {
9130 			if (ip_debug > 2) {
9131 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9132 				    "for dst %s\n", AF_INET, &dst);
9133 			}
9134 			goto err_ret;
9135 		}
9136 
9137 		/*
9138 		 * Pick a source address preferring non-deprecated ones.
9139 		 * Unlike ip_newroute, we don't do any source address
9140 		 * selection here since for multicast it really does not help
9141 		 * in inbound load spreading as in the unicast case.
9142 		 */
9143 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9144 		    (fire->ire_flags & RTF_SETSRC)) {
9145 			/*
9146 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9147 			 * on that interface. This ire has RTF_SETSRC flag, so
9148 			 * the source address of the packet must be changed.
9149 			 * Check that the ipif matching the requested source
9150 			 * address still exists.
9151 			 */
9152 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9153 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9154 		}
9155 
9156 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9157 
9158 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9159 		    (IS_IPMP(ipif->ipif_ill) ||
9160 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9161 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9162 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9163 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9164 		    (src_ipif == NULL) &&
9165 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9166 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9167 			if (src_ipif == NULL) {
9168 				if (ip_debug > 2) {
9169 					/* ip1dbg */
9170 					pr_addr_dbg("ip_newroute_ipif: "
9171 					    "no src for dst %s",
9172 					    AF_INET, &dst);
9173 				}
9174 				ip1dbg((" on interface %s\n",
9175 				    dst_ill->ill_name));
9176 				goto err_ret;
9177 			}
9178 			ipif_refrele(ipif);
9179 			ipif = src_ipif;
9180 			ipif_refhold(ipif);
9181 		}
9182 		if (src_ipif == NULL) {
9183 			src_ipif = ipif;
9184 			ipif_refhold(src_ipif);
9185 		}
9186 
9187 		/*
9188 		 * Assign a source address while we have the conn.
9189 		 * We can't have ip_wput_ire pick a source address when the
9190 		 * packet returns from arp since conn_unspec_src might be set
9191 		 * and we lose the conn when going through arp.
9192 		 */
9193 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9194 			ipha->ipha_src = src_ipif->ipif_src_addr;
9195 
9196 		/*
9197 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9198 		 * that the outgoing interface does not have an interface ire.
9199 		 */
9200 		if (CLASSD(ipha_dst) && (connp == NULL ||
9201 		    connp->conn_outgoing_ill == NULL) &&
9202 		    infop->ip_opt_ill_index == 0) {
9203 			/* ipif_to_ire returns an held ire */
9204 			ire = ipif_to_ire(ipif);
9205 			if (ire == NULL)
9206 				goto err_ret;
9207 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9208 				goto err_ret;
9209 			save_ire = ire;
9210 
9211 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9212 			    "flags %04x\n",
9213 			    (void *)ire, (void *)ipif, flags));
9214 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9215 			    (fire->ire_flags & RTF_MULTIRT)) {
9216 				/*
9217 				 * As requested by flags, an IRE_OFFSUBNET was
9218 				 * looked up on that interface. This ire has
9219 				 * RTF_MULTIRT flag, so the resolution loop will
9220 				 * be re-entered to resolve additional routes on
9221 				 * other interfaces. For that purpose, a copy of
9222 				 * the packet is performed at this point.
9223 				 */
9224 				fire->ire_last_used_time = lbolt;
9225 				copy_mp = copymsg(first_mp);
9226 				if (copy_mp) {
9227 					MULTIRT_DEBUG_TAG(copy_mp);
9228 				}
9229 			}
9230 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9231 			    (fire->ire_flags & RTF_SETSRC)) {
9232 				/*
9233 				 * As requested by flags, an IRE_OFFSUBET was
9234 				 * looked up on that interface. This ire has
9235 				 * RTF_SETSRC flag, so the source address of the
9236 				 * packet must be changed.
9237 				 */
9238 				ipha->ipha_src = fire->ire_src_addr;
9239 			}
9240 		} else {
9241 			/*
9242 			 * The only ways we can come here are:
9243 			 * 1) IP_BOUND_IF socket option is set
9244 			 * 2) SO_DONTROUTE socket option is set
9245 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9246 			 * In all cases, the new ire will not be added
9247 			 * into cache table.
9248 			 */
9249 			ASSERT(connp == NULL || connp->conn_dontroute ||
9250 			    connp->conn_outgoing_ill != NULL ||
9251 			    infop->ip_opt_ill_index != 0);
9252 			ire_marks |= IRE_MARK_NOADD;
9253 		}
9254 
9255 		switch (ipif->ipif_net_type) {
9256 		case IRE_IF_NORESOLVER: {
9257 			/* We have what we need to build an IRE_CACHE. */
9258 
9259 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9260 			    (dst_ill->ill_resolver_mp == NULL)) {
9261 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9262 				    "for IRE_IF_NORESOLVER ire %p has "
9263 				    "no ill_resolver_mp\n",
9264 				    (void *)dst_ill, (void *)ire));
9265 				break;
9266 			}
9267 
9268 			/*
9269 			 * The new ire inherits the IRE_OFFSUBNET flags
9270 			 * and source address, if this was requested.
9271 			 */
9272 			ire = ire_create(
9273 			    (uchar_t *)&dst,		/* dest address */
9274 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9275 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9276 			    NULL,			/* gateway address */
9277 			    &ipif->ipif_mtu,
9278 			    NULL,			/* no src nce */
9279 			    dst_ill->ill_rq,		/* recv-from queue */
9280 			    dst_ill->ill_wq,		/* send-to queue */
9281 			    IRE_CACHE,
9282 			    src_ipif,
9283 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9284 			    (fire != NULL) ?		/* Parent handle */
9285 			    fire->ire_phandle : 0,
9286 			    (save_ire != NULL) ?	/* Interface handle */
9287 			    save_ire->ire_ihandle : 0,
9288 			    (fire != NULL) ?
9289 			    (fire->ire_flags &
9290 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9291 			    (save_ire == NULL ? &ire_uinfo_null :
9292 			    &save_ire->ire_uinfo),
9293 			    NULL,
9294 			    NULL,
9295 			    ipst);
9296 
9297 			if (ire == NULL) {
9298 				if (save_ire != NULL)
9299 					ire_refrele(save_ire);
9300 				break;
9301 			}
9302 
9303 			ire->ire_marks |= ire_marks;
9304 
9305 			/*
9306 			 * If IRE_MARK_NOADD is set then we need to convert
9307 			 * the max_fragp to a useable value now. This is
9308 			 * normally done in ire_add_v[46]. We also need to
9309 			 * associate the ire with an nce (normally would be
9310 			 * done in ip_wput_nondata()).
9311 			 *
9312 			 * Note that IRE_MARK_NOADD packets created here
9313 			 * do not have a non-null ire_mp pointer. The null
9314 			 * value of ire_bucket indicates that they were
9315 			 * never added.
9316 			 */
9317 			if (ire->ire_marks & IRE_MARK_NOADD) {
9318 				uint_t  max_frag;
9319 
9320 				max_frag = *ire->ire_max_fragp;
9321 				ire->ire_max_fragp = NULL;
9322 				ire->ire_max_frag = max_frag;
9323 
9324 				if ((ire->ire_nce = ndp_lookup_v4(
9325 				    ire_to_ill(ire),
9326 				    (ire->ire_gateway_addr != INADDR_ANY ?
9327 				    &ire->ire_gateway_addr : &ire->ire_addr),
9328 				    B_FALSE)) == NULL) {
9329 					if (save_ire != NULL)
9330 						ire_refrele(save_ire);
9331 					break;
9332 				}
9333 				ASSERT(ire->ire_nce->nce_state ==
9334 				    ND_REACHABLE);
9335 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9336 			}
9337 
9338 			/* Prevent save_ire from getting deleted */
9339 			if (save_ire != NULL) {
9340 				IRB_REFHOLD(save_ire->ire_bucket);
9341 				/* Has it been removed already ? */
9342 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9343 					IRB_REFRELE(save_ire->ire_bucket);
9344 					ire_refrele(save_ire);
9345 					break;
9346 				}
9347 			}
9348 
9349 			ire_add_then_send(q, ire, first_mp);
9350 
9351 			/* Assert that save_ire is not deleted yet. */
9352 			if (save_ire != NULL) {
9353 				ASSERT(save_ire->ire_ptpn != NULL);
9354 				IRB_REFRELE(save_ire->ire_bucket);
9355 				ire_refrele(save_ire);
9356 				save_ire = NULL;
9357 			}
9358 			if (fire != NULL) {
9359 				ire_refrele(fire);
9360 				fire = NULL;
9361 			}
9362 
9363 			/*
9364 			 * the resolution loop is re-entered if this
9365 			 * was requested through flags and if we
9366 			 * actually are in a multirouting case.
9367 			 */
9368 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9369 				boolean_t need_resolve =
9370 				    ire_multirt_need_resolve(ipha_dst,
9371 				    msg_getlabel(copy_mp), ipst);
9372 				if (!need_resolve) {
9373 					MULTIRT_DEBUG_UNTAG(copy_mp);
9374 					freemsg(copy_mp);
9375 					copy_mp = NULL;
9376 				} else {
9377 					/*
9378 					 * ipif_lookup_group() calls
9379 					 * ire_lookup_multi() that uses
9380 					 * ire_ftable_lookup() to find
9381 					 * an IRE_INTERFACE for the group.
9382 					 * In the multirt case,
9383 					 * ire_lookup_multi() then invokes
9384 					 * ire_multirt_lookup() to find
9385 					 * the next resolvable ire.
9386 					 * As a result, we obtain an new
9387 					 * interface, derived from the
9388 					 * next ire.
9389 					 */
9390 					ipif_refrele(ipif);
9391 					ipif = ipif_lookup_group(ipha_dst,
9392 					    zoneid, ipst);
9393 					ip2dbg(("ip_newroute_ipif: "
9394 					    "multirt dst %08x, ipif %p\n",
9395 					    htonl(dst), (void *)ipif));
9396 					if (ipif != NULL) {
9397 						mp = copy_mp;
9398 						copy_mp = NULL;
9399 						multirt_resolve_next = B_TRUE;
9400 						continue;
9401 					} else {
9402 						freemsg(copy_mp);
9403 					}
9404 				}
9405 			}
9406 			if (ipif != NULL)
9407 				ipif_refrele(ipif);
9408 			ill_refrele(dst_ill);
9409 			ipif_refrele(src_ipif);
9410 			return;
9411 		}
9412 		case IRE_IF_RESOLVER:
9413 			/*
9414 			 * We can't build an IRE_CACHE yet, but at least
9415 			 * we found a resolver that can help.
9416 			 */
9417 			res_mp = dst_ill->ill_resolver_mp;
9418 			if (!OK_RESOLVER_MP(res_mp))
9419 				break;
9420 
9421 			/*
9422 			 * We obtain a partial IRE_CACHE which we will pass
9423 			 * along with the resolver query.  When the response
9424 			 * comes back it will be there ready for us to add.
9425 			 * The new ire inherits the IRE_OFFSUBNET flags
9426 			 * and source address, if this was requested.
9427 			 * The ire_max_frag is atomically set under the
9428 			 * irebucket lock in ire_add_v[46]. Only in the
9429 			 * case of IRE_MARK_NOADD, we set it here itself.
9430 			 */
9431 			ire = ire_create_mp(
9432 			    (uchar_t *)&dst,		/* dest address */
9433 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9434 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9435 			    NULL,			/* gateway address */
9436 			    (ire_marks & IRE_MARK_NOADD) ?
9437 			    ipif->ipif_mtu : 0,		/* max_frag */
9438 			    NULL,			/* no src nce */
9439 			    dst_ill->ill_rq,		/* recv-from queue */
9440 			    dst_ill->ill_wq,		/* send-to queue */
9441 			    IRE_CACHE,
9442 			    src_ipif,
9443 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9444 			    (fire != NULL) ?		/* Parent handle */
9445 			    fire->ire_phandle : 0,
9446 			    (save_ire != NULL) ?	/* Interface handle */
9447 			    save_ire->ire_ihandle : 0,
9448 			    (fire != NULL) ?		/* flags if any */
9449 			    (fire->ire_flags &
9450 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9451 			    (save_ire == NULL ? &ire_uinfo_null :
9452 			    &save_ire->ire_uinfo),
9453 			    NULL,
9454 			    NULL,
9455 			    ipst);
9456 
9457 			if (save_ire != NULL) {
9458 				ire_refrele(save_ire);
9459 				save_ire = NULL;
9460 			}
9461 			if (ire == NULL)
9462 				break;
9463 
9464 			ire->ire_marks |= ire_marks;
9465 			/*
9466 			 * Construct message chain for the resolver of the
9467 			 * form:
9468 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9469 			 *
9470 			 * NOTE : ire will be added later when the response
9471 			 * comes back from ARP. If the response does not
9472 			 * come back, ARP frees the packet. For this reason,
9473 			 * we can't REFHOLD the bucket of save_ire to prevent
9474 			 * deletions. We may not be able to REFRELE the
9475 			 * bucket if the response never comes back.
9476 			 * Thus, before adding the ire, ire_add_v4 will make
9477 			 * sure that the interface route does not get deleted.
9478 			 * This is the only case unlike ip_newroute_v6,
9479 			 * ip_newroute_ipif_v6 where we can always prevent
9480 			 * deletions because ire_add_then_send is called after
9481 			 * creating the IRE.
9482 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9483 			 * does not add this IRE into the IRE CACHE.
9484 			 */
9485 			ASSERT(ire->ire_mp != NULL);
9486 			ire->ire_mp->b_cont = first_mp;
9487 			/* Have saved_mp handy, for cleanup if canput fails */
9488 			saved_mp = mp;
9489 			mp = copyb(res_mp);
9490 			if (mp == NULL) {
9491 				/* Prepare for cleanup */
9492 				mp = saved_mp; /* pkt */
9493 				ire_delete(ire); /* ire_mp */
9494 				ire = NULL;
9495 				if (copy_mp != NULL) {
9496 					MULTIRT_DEBUG_UNTAG(copy_mp);
9497 					freemsg(copy_mp);
9498 					copy_mp = NULL;
9499 				}
9500 				break;
9501 			}
9502 			linkb(mp, ire->ire_mp);
9503 
9504 			/*
9505 			 * Fill in the source and dest addrs for the resolver.
9506 			 * NOTE: this depends on memory layouts imposed by
9507 			 * ill_init().  There are corner cases above where we
9508 			 * might've created the IRE with an INADDR_ANY source
9509 			 * address (e.g., if the zeroth ipif on an underlying
9510 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9511 			 * on the ill has a usable test address).  If so, tell
9512 			 * ARP to use ipha_src as its sender address.
9513 			 */
9514 			areq = (areq_t *)mp->b_rptr;
9515 			addrp = (ipaddr_t *)((char *)areq +
9516 			    areq->areq_sender_addr_offset);
9517 			if (ire->ire_src_addr != INADDR_ANY)
9518 				*addrp = ire->ire_src_addr;
9519 			else
9520 				*addrp = ipha->ipha_src;
9521 			addrp = (ipaddr_t *)((char *)areq +
9522 			    areq->areq_target_addr_offset);
9523 			*addrp = dst;
9524 			/* Up to the resolver. */
9525 			if (canputnext(dst_ill->ill_rq) &&
9526 			    !(dst_ill->ill_arp_closing)) {
9527 				putnext(dst_ill->ill_rq, mp);
9528 				/*
9529 				 * The response will come back in ip_wput
9530 				 * with db_type IRE_DB_TYPE.
9531 				 */
9532 			} else {
9533 				mp->b_cont = NULL;
9534 				freeb(mp); /* areq */
9535 				ire_delete(ire); /* ire_mp */
9536 				saved_mp->b_next = NULL;
9537 				saved_mp->b_prev = NULL;
9538 				freemsg(first_mp); /* pkt */
9539 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9540 			}
9541 
9542 			if (fire != NULL) {
9543 				ire_refrele(fire);
9544 				fire = NULL;
9545 			}
9546 
9547 			/*
9548 			 * The resolution loop is re-entered if this was
9549 			 * requested through flags and we actually are
9550 			 * in a multirouting case.
9551 			 */
9552 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9553 				boolean_t need_resolve =
9554 				    ire_multirt_need_resolve(ipha_dst,
9555 				    msg_getlabel(copy_mp), ipst);
9556 				if (!need_resolve) {
9557 					MULTIRT_DEBUG_UNTAG(copy_mp);
9558 					freemsg(copy_mp);
9559 					copy_mp = NULL;
9560 				} else {
9561 					/*
9562 					 * ipif_lookup_group() calls
9563 					 * ire_lookup_multi() that uses
9564 					 * ire_ftable_lookup() to find
9565 					 * an IRE_INTERFACE for the group.
9566 					 * In the multirt case,
9567 					 * ire_lookup_multi() then invokes
9568 					 * ire_multirt_lookup() to find
9569 					 * the next resolvable ire.
9570 					 * As a result, we obtain an new
9571 					 * interface, derived from the
9572 					 * next ire.
9573 					 */
9574 					ipif_refrele(ipif);
9575 					ipif = ipif_lookup_group(ipha_dst,
9576 					    zoneid, ipst);
9577 					if (ipif != NULL) {
9578 						mp = copy_mp;
9579 						copy_mp = NULL;
9580 						multirt_resolve_next = B_TRUE;
9581 						continue;
9582 					} else {
9583 						freemsg(copy_mp);
9584 					}
9585 				}
9586 			}
9587 			if (ipif != NULL)
9588 				ipif_refrele(ipif);
9589 			ill_refrele(dst_ill);
9590 			ipif_refrele(src_ipif);
9591 			return;
9592 		default:
9593 			break;
9594 		}
9595 	} while (multirt_resolve_next);
9596 
9597 err_ret:
9598 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9599 	if (fire != NULL)
9600 		ire_refrele(fire);
9601 	ipif_refrele(ipif);
9602 	/* Did this packet originate externally? */
9603 	if (dst_ill != NULL)
9604 		ill_refrele(dst_ill);
9605 	if (src_ipif != NULL)
9606 		ipif_refrele(src_ipif);
9607 	if (mp->b_prev || mp->b_next) {
9608 		mp->b_next = NULL;
9609 		mp->b_prev = NULL;
9610 	} else {
9611 		/*
9612 		 * Since ip_wput() isn't close to finished, we fill
9613 		 * in enough of the header for credible error reporting.
9614 		 */
9615 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9616 			/* Failed */
9617 			freemsg(first_mp);
9618 			if (ire != NULL)
9619 				ire_refrele(ire);
9620 			return;
9621 		}
9622 	}
9623 	/*
9624 	 * At this point we will have ire only if RTF_BLACKHOLE
9625 	 * or RTF_REJECT flags are set on the IRE. It will not
9626 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9627 	 */
9628 	if (ire != NULL) {
9629 		if (ire->ire_flags & RTF_BLACKHOLE) {
9630 			ire_refrele(ire);
9631 			freemsg(first_mp);
9632 			return;
9633 		}
9634 		ire_refrele(ire);
9635 	}
9636 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9637 }
9638 
9639 /* Name/Value Table Lookup Routine */
9640 char *
9641 ip_nv_lookup(nv_t *nv, int value)
9642 {
9643 	if (!nv)
9644 		return (NULL);
9645 	for (; nv->nv_name; nv++) {
9646 		if (nv->nv_value == value)
9647 			return (nv->nv_name);
9648 	}
9649 	return ("unknown");
9650 }
9651 
9652 /*
9653  * This is a module open, i.e. this is a control stream for access
9654  * to a DLPI device.  We allocate an ill_t as the instance data in
9655  * this case.
9656  */
9657 int
9658 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9659 {
9660 	ill_t	*ill;
9661 	int	err;
9662 	zoneid_t zoneid;
9663 	netstack_t *ns;
9664 	ip_stack_t *ipst;
9665 
9666 	/*
9667 	 * Prevent unprivileged processes from pushing IP so that
9668 	 * they can't send raw IP.
9669 	 */
9670 	if (secpolicy_net_rawaccess(credp) != 0)
9671 		return (EPERM);
9672 
9673 	ns = netstack_find_by_cred(credp);
9674 	ASSERT(ns != NULL);
9675 	ipst = ns->netstack_ip;
9676 	ASSERT(ipst != NULL);
9677 
9678 	/*
9679 	 * For exclusive stacks we set the zoneid to zero
9680 	 * to make IP operate as if in the global zone.
9681 	 */
9682 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9683 		zoneid = GLOBAL_ZONEID;
9684 	else
9685 		zoneid = crgetzoneid(credp);
9686 
9687 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9688 	q->q_ptr = WR(q)->q_ptr = ill;
9689 	ill->ill_ipst = ipst;
9690 	ill->ill_zoneid = zoneid;
9691 
9692 	/*
9693 	 * ill_init initializes the ill fields and then sends down
9694 	 * down a DL_INFO_REQ after calling qprocson.
9695 	 */
9696 	err = ill_init(q, ill);
9697 	if (err != 0) {
9698 		mi_free(ill);
9699 		netstack_rele(ipst->ips_netstack);
9700 		q->q_ptr = NULL;
9701 		WR(q)->q_ptr = NULL;
9702 		return (err);
9703 	}
9704 
9705 	/* ill_init initializes the ipsq marking this thread as writer */
9706 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9707 	/* Wait for the DL_INFO_ACK */
9708 	mutex_enter(&ill->ill_lock);
9709 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9710 		/*
9711 		 * Return value of 0 indicates a pending signal.
9712 		 */
9713 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9714 		if (err == 0) {
9715 			mutex_exit(&ill->ill_lock);
9716 			(void) ip_close(q, 0);
9717 			return (EINTR);
9718 		}
9719 	}
9720 	mutex_exit(&ill->ill_lock);
9721 
9722 	/*
9723 	 * ip_rput_other could have set an error  in ill_error on
9724 	 * receipt of M_ERROR.
9725 	 */
9726 
9727 	err = ill->ill_error;
9728 	if (err != 0) {
9729 		(void) ip_close(q, 0);
9730 		return (err);
9731 	}
9732 
9733 	ill->ill_credp = credp;
9734 	crhold(credp);
9735 
9736 	mutex_enter(&ipst->ips_ip_mi_lock);
9737 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9738 	    credp);
9739 	mutex_exit(&ipst->ips_ip_mi_lock);
9740 	if (err) {
9741 		(void) ip_close(q, 0);
9742 		return (err);
9743 	}
9744 	return (0);
9745 }
9746 
9747 /* For /dev/ip aka AF_INET open */
9748 int
9749 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9750 {
9751 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9752 }
9753 
9754 /* For /dev/ip6 aka AF_INET6 open */
9755 int
9756 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9757 {
9758 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9759 }
9760 
9761 /* IP open routine. */
9762 int
9763 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9764     boolean_t isv6)
9765 {
9766 	conn_t 		*connp;
9767 	major_t		maj;
9768 	zoneid_t	zoneid;
9769 	netstack_t	*ns;
9770 	ip_stack_t	*ipst;
9771 
9772 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9773 
9774 	/* Allow reopen. */
9775 	if (q->q_ptr != NULL)
9776 		return (0);
9777 
9778 	if (sflag & MODOPEN) {
9779 		/* This is a module open */
9780 		return (ip_modopen(q, devp, flag, sflag, credp));
9781 	}
9782 
9783 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9784 		/*
9785 		 * Non streams based socket looking for a stream
9786 		 * to access IP
9787 		 */
9788 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9789 		    credp, isv6));
9790 	}
9791 
9792 	ns = netstack_find_by_cred(credp);
9793 	ASSERT(ns != NULL);
9794 	ipst = ns->netstack_ip;
9795 	ASSERT(ipst != NULL);
9796 
9797 	/*
9798 	 * For exclusive stacks we set the zoneid to zero
9799 	 * to make IP operate as if in the global zone.
9800 	 */
9801 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9802 		zoneid = GLOBAL_ZONEID;
9803 	else
9804 		zoneid = crgetzoneid(credp);
9805 
9806 	/*
9807 	 * We are opening as a device. This is an IP client stream, and we
9808 	 * allocate an conn_t as the instance data.
9809 	 */
9810 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9811 
9812 	/*
9813 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9814 	 * done by netstack_find_by_cred()
9815 	 */
9816 	netstack_rele(ipst->ips_netstack);
9817 
9818 	connp->conn_zoneid = zoneid;
9819 	connp->conn_sqp = NULL;
9820 	connp->conn_initial_sqp = NULL;
9821 	connp->conn_final_sqp = NULL;
9822 
9823 	connp->conn_upq = q;
9824 	q->q_ptr = WR(q)->q_ptr = connp;
9825 
9826 	if (flag & SO_SOCKSTR)
9827 		connp->conn_flags |= IPCL_SOCKET;
9828 
9829 	/* Minor tells us which /dev entry was opened */
9830 	if (isv6) {
9831 		connp->conn_flags |= IPCL_ISV6;
9832 		connp->conn_af_isv6 = B_TRUE;
9833 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9834 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9835 	} else {
9836 		connp->conn_af_isv6 = B_FALSE;
9837 		connp->conn_pkt_isv6 = B_FALSE;
9838 	}
9839 
9840 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9841 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9842 		connp->conn_minor_arena = ip_minor_arena_la;
9843 	} else {
9844 		/*
9845 		 * Either minor numbers in the large arena were exhausted
9846 		 * or a non socket application is doing the open.
9847 		 * Try to allocate from the small arena.
9848 		 */
9849 		if ((connp->conn_dev =
9850 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9851 			/* CONN_DEC_REF takes care of netstack_rele() */
9852 			q->q_ptr = WR(q)->q_ptr = NULL;
9853 			CONN_DEC_REF(connp);
9854 			return (EBUSY);
9855 		}
9856 		connp->conn_minor_arena = ip_minor_arena_sa;
9857 	}
9858 
9859 	maj = getemajor(*devp);
9860 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9861 
9862 	/*
9863 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9864 	 */
9865 	connp->conn_cred = credp;
9866 
9867 	/*
9868 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9869 	 */
9870 	connp->conn_recv = ip_conn_input;
9871 
9872 	crhold(connp->conn_cred);
9873 
9874 	/*
9875 	 * If the caller has the process-wide flag set, then default to MAC
9876 	 * exempt mode.  This allows read-down to unlabeled hosts.
9877 	 */
9878 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9879 		connp->conn_mac_exempt = B_TRUE;
9880 
9881 	connp->conn_rq = q;
9882 	connp->conn_wq = WR(q);
9883 
9884 	/* Non-zero default values */
9885 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9886 
9887 	/*
9888 	 * Make the conn globally visible to walkers
9889 	 */
9890 	ASSERT(connp->conn_ref == 1);
9891 	mutex_enter(&connp->conn_lock);
9892 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9893 	mutex_exit(&connp->conn_lock);
9894 
9895 	qprocson(q);
9896 
9897 	return (0);
9898 }
9899 
9900 /*
9901  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9902  * Note that there is no race since either ip_output function works - it
9903  * is just an optimization to enter the best ip_output routine directly.
9904  */
9905 void
9906 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9907     ip_stack_t *ipst)
9908 {
9909 	if (isv6)  {
9910 		if (bump_mib) {
9911 			BUMP_MIB(&ipst->ips_ip6_mib,
9912 			    ipIfStatsOutSwitchIPVersion);
9913 		}
9914 		connp->conn_send = ip_output_v6;
9915 		connp->conn_pkt_isv6 = B_TRUE;
9916 	} else {
9917 		if (bump_mib) {
9918 			BUMP_MIB(&ipst->ips_ip_mib,
9919 			    ipIfStatsOutSwitchIPVersion);
9920 		}
9921 		connp->conn_send = ip_output;
9922 		connp->conn_pkt_isv6 = B_FALSE;
9923 	}
9924 
9925 }
9926 
9927 /*
9928  * See if IPsec needs loading because of the options in mp.
9929  */
9930 static boolean_t
9931 ipsec_opt_present(mblk_t *mp)
9932 {
9933 	uint8_t *optcp, *next_optcp, *opt_endcp;
9934 	struct opthdr *opt;
9935 	struct T_opthdr *topt;
9936 	int opthdr_len;
9937 	t_uscalar_t optname, optlevel;
9938 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9939 	ipsec_req_t *ipsr;
9940 
9941 	/*
9942 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9943 	 * return TRUE.
9944 	 */
9945 
9946 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9947 	opt_endcp = optcp + tor->OPT_length;
9948 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9949 		opthdr_len = sizeof (struct T_opthdr);
9950 	} else {		/* O_OPTMGMT_REQ */
9951 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9952 		opthdr_len = sizeof (struct opthdr);
9953 	}
9954 	for (; optcp < opt_endcp; optcp = next_optcp) {
9955 		if (optcp + opthdr_len > opt_endcp)
9956 			return (B_FALSE);	/* Not enough option header. */
9957 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9958 			topt = (struct T_opthdr *)optcp;
9959 			optlevel = topt->level;
9960 			optname = topt->name;
9961 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9962 		} else {
9963 			opt = (struct opthdr *)optcp;
9964 			optlevel = opt->level;
9965 			optname = opt->name;
9966 			next_optcp = optcp + opthdr_len +
9967 			    _TPI_ALIGN_OPT(opt->len);
9968 		}
9969 		if ((next_optcp < optcp) || /* wraparound pointer space */
9970 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9971 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9972 			return (B_FALSE); /* bad option buffer */
9973 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9974 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9975 			/*
9976 			 * Check to see if it's an all-bypass or all-zeroes
9977 			 * IPsec request.  Don't bother loading IPsec if
9978 			 * the socket doesn't want to use it.  (A good example
9979 			 * is a bypass request.)
9980 			 *
9981 			 * Basically, if any of the non-NEVER bits are set,
9982 			 * load IPsec.
9983 			 */
9984 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9985 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9986 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9987 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9988 			    != 0)
9989 				return (B_TRUE);
9990 		}
9991 	}
9992 	return (B_FALSE);
9993 }
9994 
9995 /*
9996  * If conn is is waiting for ipsec to finish loading, kick it.
9997  */
9998 /* ARGSUSED */
9999 static void
10000 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10001 {
10002 	t_scalar_t	optreq_prim;
10003 	mblk_t		*mp;
10004 	cred_t		*cr;
10005 	int		err = 0;
10006 
10007 	/*
10008 	 * This function is called, after ipsec loading is complete.
10009 	 * Since IP checks exclusively and atomically (i.e it prevents
10010 	 * ipsec load from completing until ip_optcom_req completes)
10011 	 * whether ipsec load is complete, there cannot be a race with IP
10012 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10013 	 */
10014 	mutex_enter(&connp->conn_lock);
10015 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10016 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10017 		mp = connp->conn_ipsec_opt_mp;
10018 		connp->conn_ipsec_opt_mp = NULL;
10019 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10020 		mutex_exit(&connp->conn_lock);
10021 
10022 		/*
10023 		 * All Solaris components should pass a db_credp
10024 		 * for this TPI message, hence we ASSERT.
10025 		 * But in case there is some other M_PROTO that looks
10026 		 * like a TPI message sent by some other kernel
10027 		 * component, we check and return an error.
10028 		 */
10029 		cr = msg_getcred(mp, NULL);
10030 		ASSERT(cr != NULL);
10031 		if (cr == NULL) {
10032 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10033 			if (mp != NULL)
10034 				qreply(connp->conn_wq, mp);
10035 			return;
10036 		}
10037 
10038 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10039 
10040 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10041 		if (optreq_prim == T_OPTMGMT_REQ) {
10042 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10043 			    &ip_opt_obj, B_FALSE);
10044 		} else {
10045 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10046 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10047 			    &ip_opt_obj, B_FALSE);
10048 		}
10049 		if (err != EINPROGRESS)
10050 			CONN_OPER_PENDING_DONE(connp);
10051 		return;
10052 	}
10053 	mutex_exit(&connp->conn_lock);
10054 }
10055 
10056 /*
10057  * Called from the ipsec_loader thread, outside any perimeter, to tell
10058  * ip qenable any of the queues waiting for the ipsec loader to
10059  * complete.
10060  */
10061 void
10062 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10063 {
10064 	netstack_t *ns = ipss->ipsec_netstack;
10065 
10066 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10067 }
10068 
10069 /*
10070  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10071  * determines the grp on which it has to become exclusive, queues the mp
10072  * and IPSQ draining restarts the optmgmt
10073  */
10074 static boolean_t
10075 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10076 {
10077 	conn_t *connp = Q_TO_CONN(q);
10078 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10079 
10080 	/*
10081 	 * Take IPsec requests and treat them special.
10082 	 */
10083 	if (ipsec_opt_present(mp)) {
10084 		/* First check if IPsec is loaded. */
10085 		mutex_enter(&ipss->ipsec_loader_lock);
10086 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10087 			mutex_exit(&ipss->ipsec_loader_lock);
10088 			return (B_FALSE);
10089 		}
10090 		mutex_enter(&connp->conn_lock);
10091 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10092 
10093 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10094 		connp->conn_ipsec_opt_mp = mp;
10095 		mutex_exit(&connp->conn_lock);
10096 		mutex_exit(&ipss->ipsec_loader_lock);
10097 
10098 		ipsec_loader_loadnow(ipss);
10099 		return (B_TRUE);
10100 	}
10101 	return (B_FALSE);
10102 }
10103 
10104 /*
10105  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10106  * all of them are copied to the conn_t. If the req is "zero", the policy is
10107  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10108  * fields.
10109  * We keep only the latest setting of the policy and thus policy setting
10110  * is not incremental/cumulative.
10111  *
10112  * Requests to set policies with multiple alternative actions will
10113  * go through a different API.
10114  */
10115 int
10116 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10117 {
10118 	uint_t ah_req = 0;
10119 	uint_t esp_req = 0;
10120 	uint_t se_req = 0;
10121 	ipsec_selkey_t sel;
10122 	ipsec_act_t *actp = NULL;
10123 	uint_t nact;
10124 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10125 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10126 	ipsec_policy_root_t *pr;
10127 	ipsec_policy_head_t *ph;
10128 	int fam;
10129 	boolean_t is_pol_reset;
10130 	int error = 0;
10131 	netstack_t	*ns = connp->conn_netstack;
10132 	ip_stack_t	*ipst = ns->netstack_ip;
10133 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10134 
10135 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10136 
10137 	/*
10138 	 * The IP_SEC_OPT option does not allow variable length parameters,
10139 	 * hence a request cannot be NULL.
10140 	 */
10141 	if (req == NULL)
10142 		return (EINVAL);
10143 
10144 	ah_req = req->ipsr_ah_req;
10145 	esp_req = req->ipsr_esp_req;
10146 	se_req = req->ipsr_self_encap_req;
10147 
10148 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10149 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10150 		return (EINVAL);
10151 
10152 	/*
10153 	 * Are we dealing with a request to reset the policy (i.e.
10154 	 * zero requests).
10155 	 */
10156 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10157 	    (esp_req & REQ_MASK) == 0 &&
10158 	    (se_req & REQ_MASK) == 0);
10159 
10160 	if (!is_pol_reset) {
10161 		/*
10162 		 * If we couldn't load IPsec, fail with "protocol
10163 		 * not supported".
10164 		 * IPsec may not have been loaded for a request with zero
10165 		 * policies, so we don't fail in this case.
10166 		 */
10167 		mutex_enter(&ipss->ipsec_loader_lock);
10168 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10169 			mutex_exit(&ipss->ipsec_loader_lock);
10170 			return (EPROTONOSUPPORT);
10171 		}
10172 		mutex_exit(&ipss->ipsec_loader_lock);
10173 
10174 		/*
10175 		 * Test for valid requests. Invalid algorithms
10176 		 * need to be tested by IPsec code because new
10177 		 * algorithms can be added dynamically.
10178 		 */
10179 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10180 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10181 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10182 			return (EINVAL);
10183 		}
10184 
10185 		/*
10186 		 * Only privileged users can issue these
10187 		 * requests.
10188 		 */
10189 		if (((ah_req & IPSEC_PREF_NEVER) ||
10190 		    (esp_req & IPSEC_PREF_NEVER) ||
10191 		    (se_req & IPSEC_PREF_NEVER)) &&
10192 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10193 			return (EPERM);
10194 		}
10195 
10196 		/*
10197 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10198 		 * are mutually exclusive.
10199 		 */
10200 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10201 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10202 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10203 			/* Both of them are set */
10204 			return (EINVAL);
10205 		}
10206 	}
10207 
10208 	mutex_enter(&connp->conn_lock);
10209 
10210 	/*
10211 	 * If we have already cached policies in ip_bind_connected*(), don't
10212 	 * let them change now. We cache policies for connections
10213 	 * whose src,dst [addr, port] is known.
10214 	 */
10215 	if (connp->conn_policy_cached) {
10216 		mutex_exit(&connp->conn_lock);
10217 		return (EINVAL);
10218 	}
10219 
10220 	/*
10221 	 * We have a zero policies, reset the connection policy if already
10222 	 * set. This will cause the connection to inherit the
10223 	 * global policy, if any.
10224 	 */
10225 	if (is_pol_reset) {
10226 		if (connp->conn_policy != NULL) {
10227 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10228 			connp->conn_policy = NULL;
10229 		}
10230 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10231 		connp->conn_in_enforce_policy = B_FALSE;
10232 		connp->conn_out_enforce_policy = B_FALSE;
10233 		mutex_exit(&connp->conn_lock);
10234 		return (0);
10235 	}
10236 
10237 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10238 	    ipst->ips_netstack);
10239 	if (ph == NULL)
10240 		goto enomem;
10241 
10242 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10243 	if (actp == NULL)
10244 		goto enomem;
10245 
10246 	/*
10247 	 * Always allocate IPv4 policy entries, since they can also
10248 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10249 	 */
10250 	bzero(&sel, sizeof (sel));
10251 	sel.ipsl_valid = IPSL_IPV4;
10252 
10253 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10254 	    ipst->ips_netstack);
10255 	if (pin4 == NULL)
10256 		goto enomem;
10257 
10258 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10259 	    ipst->ips_netstack);
10260 	if (pout4 == NULL)
10261 		goto enomem;
10262 
10263 	if (connp->conn_af_isv6) {
10264 		/*
10265 		 * We're looking at a v6 socket, also allocate the
10266 		 * v6-specific entries...
10267 		 */
10268 		sel.ipsl_valid = IPSL_IPV6;
10269 		pin6 = ipsec_policy_create(&sel, actp, nact,
10270 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10271 		if (pin6 == NULL)
10272 			goto enomem;
10273 
10274 		pout6 = ipsec_policy_create(&sel, actp, nact,
10275 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10276 		if (pout6 == NULL)
10277 			goto enomem;
10278 
10279 		/*
10280 		 * .. and file them away in the right place.
10281 		 */
10282 		fam = IPSEC_AF_V6;
10283 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10284 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10285 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10286 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10287 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10288 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10289 	}
10290 
10291 	ipsec_actvec_free(actp, nact);
10292 
10293 	/*
10294 	 * File the v4 policies.
10295 	 */
10296 	fam = IPSEC_AF_V4;
10297 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10298 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10299 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10300 
10301 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10302 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10303 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10304 
10305 	/*
10306 	 * If the requests need security, set enforce_policy.
10307 	 * If the requests are IPSEC_PREF_NEVER, one should
10308 	 * still set conn_out_enforce_policy so that an ipsec_out
10309 	 * gets attached in ip_wput. This is needed so that
10310 	 * for connections that we don't cache policy in ip_bind,
10311 	 * if global policy matches in ip_wput_attach_policy, we
10312 	 * don't wrongly inherit global policy. Similarly, we need
10313 	 * to set conn_in_enforce_policy also so that we don't verify
10314 	 * policy wrongly.
10315 	 */
10316 	if ((ah_req & REQ_MASK) != 0 ||
10317 	    (esp_req & REQ_MASK) != 0 ||
10318 	    (se_req & REQ_MASK) != 0) {
10319 		connp->conn_in_enforce_policy = B_TRUE;
10320 		connp->conn_out_enforce_policy = B_TRUE;
10321 		connp->conn_flags |= IPCL_CHECK_POLICY;
10322 	}
10323 
10324 	mutex_exit(&connp->conn_lock);
10325 	return (error);
10326 #undef REQ_MASK
10327 
10328 	/*
10329 	 * Common memory-allocation-failure exit path.
10330 	 */
10331 enomem:
10332 	mutex_exit(&connp->conn_lock);
10333 	if (actp != NULL)
10334 		ipsec_actvec_free(actp, nact);
10335 	if (pin4 != NULL)
10336 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10337 	if (pout4 != NULL)
10338 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10339 	if (pin6 != NULL)
10340 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10341 	if (pout6 != NULL)
10342 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10343 	return (ENOMEM);
10344 }
10345 
10346 /*
10347  * Only for options that pass in an IP addr. Currently only V4 options
10348  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10349  * So this function assumes level is IPPROTO_IP
10350  */
10351 int
10352 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10353     mblk_t *first_mp)
10354 {
10355 	ipif_t *ipif = NULL;
10356 	int error;
10357 	ill_t *ill;
10358 	int zoneid;
10359 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10360 
10361 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10362 
10363 	if (addr != INADDR_ANY || checkonly) {
10364 		ASSERT(connp != NULL);
10365 		zoneid = IPCL_ZONEID(connp);
10366 		if (option == IP_NEXTHOP) {
10367 			ipif = ipif_lookup_onlink_addr(addr,
10368 			    connp->conn_zoneid, ipst);
10369 		} else {
10370 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10371 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10372 			    &error, ipst);
10373 		}
10374 		if (ipif == NULL) {
10375 			if (error == EINPROGRESS)
10376 				return (error);
10377 			if ((option == IP_MULTICAST_IF) ||
10378 			    (option == IP_NEXTHOP))
10379 				return (EHOSTUNREACH);
10380 			else
10381 				return (EINVAL);
10382 		} else if (checkonly) {
10383 			if (option == IP_MULTICAST_IF) {
10384 				ill = ipif->ipif_ill;
10385 				/* not supported by the virtual network iface */
10386 				if (IS_VNI(ill)) {
10387 					ipif_refrele(ipif);
10388 					return (EINVAL);
10389 				}
10390 			}
10391 			ipif_refrele(ipif);
10392 			return (0);
10393 		}
10394 		ill = ipif->ipif_ill;
10395 		mutex_enter(&connp->conn_lock);
10396 		mutex_enter(&ill->ill_lock);
10397 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10398 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10399 			mutex_exit(&ill->ill_lock);
10400 			mutex_exit(&connp->conn_lock);
10401 			ipif_refrele(ipif);
10402 			return (option == IP_MULTICAST_IF ?
10403 			    EHOSTUNREACH : EINVAL);
10404 		}
10405 	} else {
10406 		mutex_enter(&connp->conn_lock);
10407 	}
10408 
10409 	/* None of the options below are supported on the VNI */
10410 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10411 		mutex_exit(&ill->ill_lock);
10412 		mutex_exit(&connp->conn_lock);
10413 		ipif_refrele(ipif);
10414 		return (EINVAL);
10415 	}
10416 
10417 	switch (option) {
10418 	case IP_MULTICAST_IF:
10419 		connp->conn_multicast_ipif = ipif;
10420 		break;
10421 	case IP_NEXTHOP:
10422 		connp->conn_nexthop_v4 = addr;
10423 		connp->conn_nexthop_set = B_TRUE;
10424 		break;
10425 	}
10426 
10427 	if (ipif != NULL) {
10428 		mutex_exit(&ill->ill_lock);
10429 		mutex_exit(&connp->conn_lock);
10430 		ipif_refrele(ipif);
10431 		return (0);
10432 	}
10433 	mutex_exit(&connp->conn_lock);
10434 	/* We succeded in cleared the option */
10435 	return (0);
10436 }
10437 
10438 /*
10439  * For options that pass in an ifindex specifying the ill. V6 options always
10440  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10441  */
10442 int
10443 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10444     int level, int option, mblk_t *first_mp)
10445 {
10446 	ill_t *ill = NULL;
10447 	int error = 0;
10448 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10449 
10450 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10451 	if (ifindex != 0) {
10452 		ASSERT(connp != NULL);
10453 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10454 		    first_mp, ip_restart_optmgmt, &error, ipst);
10455 		if (ill != NULL) {
10456 			if (checkonly) {
10457 				/* not supported by the virtual network iface */
10458 				if (IS_VNI(ill)) {
10459 					ill_refrele(ill);
10460 					return (EINVAL);
10461 				}
10462 				ill_refrele(ill);
10463 				return (0);
10464 			}
10465 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10466 			    0, NULL)) {
10467 				ill_refrele(ill);
10468 				ill = NULL;
10469 				mutex_enter(&connp->conn_lock);
10470 				goto setit;
10471 			}
10472 			mutex_enter(&connp->conn_lock);
10473 			mutex_enter(&ill->ill_lock);
10474 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10475 				mutex_exit(&ill->ill_lock);
10476 				mutex_exit(&connp->conn_lock);
10477 				ill_refrele(ill);
10478 				ill = NULL;
10479 				mutex_enter(&connp->conn_lock);
10480 			}
10481 			goto setit;
10482 		} else if (error == EINPROGRESS) {
10483 			return (error);
10484 		} else {
10485 			error = 0;
10486 		}
10487 	}
10488 	mutex_enter(&connp->conn_lock);
10489 setit:
10490 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10491 
10492 	/*
10493 	 * The options below assume that the ILL (if any) transmits and/or
10494 	 * receives traffic. Neither of which is true for the virtual network
10495 	 * interface, so fail setting these on a VNI.
10496 	 */
10497 	if (IS_VNI(ill)) {
10498 		ASSERT(ill != NULL);
10499 		mutex_exit(&ill->ill_lock);
10500 		mutex_exit(&connp->conn_lock);
10501 		ill_refrele(ill);
10502 		return (EINVAL);
10503 	}
10504 
10505 	if (level == IPPROTO_IP) {
10506 		switch (option) {
10507 		case IP_BOUND_IF:
10508 			connp->conn_incoming_ill = ill;
10509 			connp->conn_outgoing_ill = ill;
10510 			break;
10511 
10512 		case IP_MULTICAST_IF:
10513 			/*
10514 			 * This option is an internal special. The socket
10515 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10516 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10517 			 * specifies an ifindex and we try first on V6 ill's.
10518 			 * If we don't find one, we they try using on v4 ill's
10519 			 * intenally and we come here.
10520 			 */
10521 			if (!checkonly && ill != NULL) {
10522 				ipif_t	*ipif;
10523 				ipif = ill->ill_ipif;
10524 
10525 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10526 					mutex_exit(&ill->ill_lock);
10527 					mutex_exit(&connp->conn_lock);
10528 					ill_refrele(ill);
10529 					ill = NULL;
10530 					mutex_enter(&connp->conn_lock);
10531 				} else {
10532 					connp->conn_multicast_ipif = ipif;
10533 				}
10534 			}
10535 			break;
10536 
10537 		case IP_DHCPINIT_IF:
10538 			if (connp->conn_dhcpinit_ill != NULL) {
10539 				/*
10540 				 * We've locked the conn so conn_cleanup_ill()
10541 				 * cannot clear conn_dhcpinit_ill -- so it's
10542 				 * safe to access the ill.
10543 				 */
10544 				ill_t *oill = connp->conn_dhcpinit_ill;
10545 
10546 				ASSERT(oill->ill_dhcpinit != 0);
10547 				atomic_dec_32(&oill->ill_dhcpinit);
10548 				connp->conn_dhcpinit_ill = NULL;
10549 			}
10550 
10551 			if (ill != NULL) {
10552 				connp->conn_dhcpinit_ill = ill;
10553 				atomic_inc_32(&ill->ill_dhcpinit);
10554 			}
10555 			break;
10556 		}
10557 	} else {
10558 		switch (option) {
10559 		case IPV6_BOUND_IF:
10560 			connp->conn_incoming_ill = ill;
10561 			connp->conn_outgoing_ill = ill;
10562 			break;
10563 
10564 		case IPV6_MULTICAST_IF:
10565 			/*
10566 			 * Set conn_multicast_ill to be the IPv6 ill.
10567 			 * Set conn_multicast_ipif to be an IPv4 ipif
10568 			 * for ifindex to make IPv4 mapped addresses
10569 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10570 			 * Even if no IPv6 ill exists for the ifindex
10571 			 * we need to check for an IPv4 ifindex in order
10572 			 * for this to work with mapped addresses. In that
10573 			 * case only set conn_multicast_ipif.
10574 			 */
10575 			if (!checkonly) {
10576 				if (ifindex == 0) {
10577 					connp->conn_multicast_ill = NULL;
10578 					connp->conn_multicast_ipif = NULL;
10579 				} else if (ill != NULL) {
10580 					connp->conn_multicast_ill = ill;
10581 				}
10582 			}
10583 			break;
10584 		}
10585 	}
10586 
10587 	if (ill != NULL) {
10588 		mutex_exit(&ill->ill_lock);
10589 		mutex_exit(&connp->conn_lock);
10590 		ill_refrele(ill);
10591 		return (0);
10592 	}
10593 	mutex_exit(&connp->conn_lock);
10594 	/*
10595 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10596 	 * locate the ill and could not set the option (ifindex != 0)
10597 	 */
10598 	return (ifindex == 0 ? 0 : EINVAL);
10599 }
10600 
10601 /* This routine sets socket options. */
10602 /* ARGSUSED */
10603 int
10604 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10605     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10606     void *dummy, cred_t *cr, mblk_t *first_mp)
10607 {
10608 	int		*i1 = (int *)invalp;
10609 	conn_t		*connp = Q_TO_CONN(q);
10610 	int		error = 0;
10611 	boolean_t	checkonly;
10612 	ire_t		*ire;
10613 	boolean_t	found;
10614 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10615 
10616 	switch (optset_context) {
10617 
10618 	case SETFN_OPTCOM_CHECKONLY:
10619 		checkonly = B_TRUE;
10620 		/*
10621 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10622 		 * inlen != 0 implies value supplied and
10623 		 * 	we have to "pretend" to set it.
10624 		 * inlen == 0 implies that there is no
10625 		 * 	value part in T_CHECK request and just validation
10626 		 * done elsewhere should be enough, we just return here.
10627 		 */
10628 		if (inlen == 0) {
10629 			*outlenp = 0;
10630 			return (0);
10631 		}
10632 		break;
10633 	case SETFN_OPTCOM_NEGOTIATE:
10634 	case SETFN_UD_NEGOTIATE:
10635 	case SETFN_CONN_NEGOTIATE:
10636 		checkonly = B_FALSE;
10637 		break;
10638 	default:
10639 		/*
10640 		 * We should never get here
10641 		 */
10642 		*outlenp = 0;
10643 		return (EINVAL);
10644 	}
10645 
10646 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10647 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10648 
10649 	/*
10650 	 * For fixed length options, no sanity check
10651 	 * of passed in length is done. It is assumed *_optcom_req()
10652 	 * routines do the right thing.
10653 	 */
10654 
10655 	switch (level) {
10656 	case SOL_SOCKET:
10657 		/*
10658 		 * conn_lock protects the bitfields, and is used to
10659 		 * set the fields atomically.
10660 		 */
10661 		switch (name) {
10662 		case SO_BROADCAST:
10663 			if (!checkonly) {
10664 				/* TODO: use value someplace? */
10665 				mutex_enter(&connp->conn_lock);
10666 				connp->conn_broadcast = *i1 ? 1 : 0;
10667 				mutex_exit(&connp->conn_lock);
10668 			}
10669 			break;	/* goto sizeof (int) option return */
10670 		case SO_USELOOPBACK:
10671 			if (!checkonly) {
10672 				/* TODO: use value someplace? */
10673 				mutex_enter(&connp->conn_lock);
10674 				connp->conn_loopback = *i1 ? 1 : 0;
10675 				mutex_exit(&connp->conn_lock);
10676 			}
10677 			break;	/* goto sizeof (int) option return */
10678 		case SO_DONTROUTE:
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_dontroute = *i1 ? 1 : 0;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			break;	/* goto sizeof (int) option return */
10685 		case SO_REUSEADDR:
10686 			if (!checkonly) {
10687 				mutex_enter(&connp->conn_lock);
10688 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10689 				mutex_exit(&connp->conn_lock);
10690 			}
10691 			break;	/* goto sizeof (int) option return */
10692 		case SO_PROTOTYPE:
10693 			if (!checkonly) {
10694 				mutex_enter(&connp->conn_lock);
10695 				connp->conn_proto = *i1;
10696 				mutex_exit(&connp->conn_lock);
10697 			}
10698 			break;	/* goto sizeof (int) option return */
10699 		case SO_ALLZONES:
10700 			if (!checkonly) {
10701 				mutex_enter(&connp->conn_lock);
10702 				if (IPCL_IS_BOUND(connp)) {
10703 					mutex_exit(&connp->conn_lock);
10704 					return (EINVAL);
10705 				}
10706 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10707 				mutex_exit(&connp->conn_lock);
10708 			}
10709 			break;	/* goto sizeof (int) option return */
10710 		case SO_ANON_MLP:
10711 			if (!checkonly) {
10712 				mutex_enter(&connp->conn_lock);
10713 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10714 				mutex_exit(&connp->conn_lock);
10715 			}
10716 			break;	/* goto sizeof (int) option return */
10717 		case SO_MAC_EXEMPT:
10718 			if (secpolicy_net_mac_aware(cr) != 0 ||
10719 			    IPCL_IS_BOUND(connp))
10720 				return (EACCES);
10721 			if (!checkonly) {
10722 				mutex_enter(&connp->conn_lock);
10723 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10724 				mutex_exit(&connp->conn_lock);
10725 			}
10726 			break;	/* goto sizeof (int) option return */
10727 		default:
10728 			/*
10729 			 * "soft" error (negative)
10730 			 * option not handled at this level
10731 			 * Note: Do not modify *outlenp
10732 			 */
10733 			return (-EINVAL);
10734 		}
10735 		break;
10736 	case IPPROTO_IP:
10737 		switch (name) {
10738 		case IP_NEXTHOP:
10739 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10740 				return (EPERM);
10741 			/* FALLTHRU */
10742 		case IP_MULTICAST_IF: {
10743 			ipaddr_t addr = *i1;
10744 
10745 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10746 			    first_mp);
10747 			if (error != 0)
10748 				return (error);
10749 			break;	/* goto sizeof (int) option return */
10750 		}
10751 
10752 		case IP_MULTICAST_TTL:
10753 			/* Recorded in transport above IP */
10754 			*outvalp = *invalp;
10755 			*outlenp = sizeof (uchar_t);
10756 			return (0);
10757 		case IP_MULTICAST_LOOP:
10758 			if (!checkonly) {
10759 				mutex_enter(&connp->conn_lock);
10760 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10761 				mutex_exit(&connp->conn_lock);
10762 			}
10763 			*outvalp = *invalp;
10764 			*outlenp = sizeof (uchar_t);
10765 			return (0);
10766 		case IP_ADD_MEMBERSHIP:
10767 		case MCAST_JOIN_GROUP:
10768 		case IP_DROP_MEMBERSHIP:
10769 		case MCAST_LEAVE_GROUP: {
10770 			struct ip_mreq *mreqp;
10771 			struct group_req *greqp;
10772 			ire_t *ire;
10773 			boolean_t done = B_FALSE;
10774 			ipaddr_t group, ifaddr;
10775 			struct sockaddr_in *sin;
10776 			uint32_t *ifindexp;
10777 			boolean_t mcast_opt = B_TRUE;
10778 			mcast_record_t fmode;
10779 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10780 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10781 
10782 			switch (name) {
10783 			case IP_ADD_MEMBERSHIP:
10784 				mcast_opt = B_FALSE;
10785 				/* FALLTHRU */
10786 			case MCAST_JOIN_GROUP:
10787 				fmode = MODE_IS_EXCLUDE;
10788 				optfn = ip_opt_add_group;
10789 				break;
10790 
10791 			case IP_DROP_MEMBERSHIP:
10792 				mcast_opt = B_FALSE;
10793 				/* FALLTHRU */
10794 			case MCAST_LEAVE_GROUP:
10795 				fmode = MODE_IS_INCLUDE;
10796 				optfn = ip_opt_delete_group;
10797 				break;
10798 			}
10799 
10800 			if (mcast_opt) {
10801 				greqp = (struct group_req *)i1;
10802 				sin = (struct sockaddr_in *)&greqp->gr_group;
10803 				if (sin->sin_family != AF_INET) {
10804 					*outlenp = 0;
10805 					return (ENOPROTOOPT);
10806 				}
10807 				group = (ipaddr_t)sin->sin_addr.s_addr;
10808 				ifaddr = INADDR_ANY;
10809 				ifindexp = &greqp->gr_interface;
10810 			} else {
10811 				mreqp = (struct ip_mreq *)i1;
10812 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10813 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10814 				ifindexp = NULL;
10815 			}
10816 
10817 			/*
10818 			 * In the multirouting case, we need to replicate
10819 			 * the request on all interfaces that will take part
10820 			 * in replication.  We do so because multirouting is
10821 			 * reflective, thus we will probably receive multi-
10822 			 * casts on those interfaces.
10823 			 * The ip_multirt_apply_membership() succeeds if the
10824 			 * operation succeeds on at least one interface.
10825 			 */
10826 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10827 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10828 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10829 			if (ire != NULL) {
10830 				if (ire->ire_flags & RTF_MULTIRT) {
10831 					error = ip_multirt_apply_membership(
10832 					    optfn, ire, connp, checkonly, group,
10833 					    fmode, INADDR_ANY, first_mp);
10834 					done = B_TRUE;
10835 				}
10836 				ire_refrele(ire);
10837 			}
10838 			if (!done) {
10839 				error = optfn(connp, checkonly, group, ifaddr,
10840 				    ifindexp, fmode, INADDR_ANY, first_mp);
10841 			}
10842 			if (error) {
10843 				/*
10844 				 * EINPROGRESS is a soft error, needs retry
10845 				 * so don't make *outlenp zero.
10846 				 */
10847 				if (error != EINPROGRESS)
10848 					*outlenp = 0;
10849 				return (error);
10850 			}
10851 			/* OK return - copy input buffer into output buffer */
10852 			if (invalp != outvalp) {
10853 				/* don't trust bcopy for identical src/dst */
10854 				bcopy(invalp, outvalp, inlen);
10855 			}
10856 			*outlenp = inlen;
10857 			return (0);
10858 		}
10859 		case IP_BLOCK_SOURCE:
10860 		case IP_UNBLOCK_SOURCE:
10861 		case IP_ADD_SOURCE_MEMBERSHIP:
10862 		case IP_DROP_SOURCE_MEMBERSHIP:
10863 		case MCAST_BLOCK_SOURCE:
10864 		case MCAST_UNBLOCK_SOURCE:
10865 		case MCAST_JOIN_SOURCE_GROUP:
10866 		case MCAST_LEAVE_SOURCE_GROUP: {
10867 			struct ip_mreq_source *imreqp;
10868 			struct group_source_req *gsreqp;
10869 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10870 			uint32_t ifindex = 0;
10871 			mcast_record_t fmode;
10872 			struct sockaddr_in *sin;
10873 			ire_t *ire;
10874 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10875 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10876 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10877 
10878 			switch (name) {
10879 			case IP_BLOCK_SOURCE:
10880 				mcast_opt = B_FALSE;
10881 				/* FALLTHRU */
10882 			case MCAST_BLOCK_SOURCE:
10883 				fmode = MODE_IS_EXCLUDE;
10884 				optfn = ip_opt_add_group;
10885 				break;
10886 
10887 			case IP_UNBLOCK_SOURCE:
10888 				mcast_opt = B_FALSE;
10889 				/* FALLTHRU */
10890 			case MCAST_UNBLOCK_SOURCE:
10891 				fmode = MODE_IS_EXCLUDE;
10892 				optfn = ip_opt_delete_group;
10893 				break;
10894 
10895 			case IP_ADD_SOURCE_MEMBERSHIP:
10896 				mcast_opt = B_FALSE;
10897 				/* FALLTHRU */
10898 			case MCAST_JOIN_SOURCE_GROUP:
10899 				fmode = MODE_IS_INCLUDE;
10900 				optfn = ip_opt_add_group;
10901 				break;
10902 
10903 			case IP_DROP_SOURCE_MEMBERSHIP:
10904 				mcast_opt = B_FALSE;
10905 				/* FALLTHRU */
10906 			case MCAST_LEAVE_SOURCE_GROUP:
10907 				fmode = MODE_IS_INCLUDE;
10908 				optfn = ip_opt_delete_group;
10909 				break;
10910 			}
10911 
10912 			if (mcast_opt) {
10913 				gsreqp = (struct group_source_req *)i1;
10914 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10915 					*outlenp = 0;
10916 					return (ENOPROTOOPT);
10917 				}
10918 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10919 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10920 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10921 				src = (ipaddr_t)sin->sin_addr.s_addr;
10922 				ifindex = gsreqp->gsr_interface;
10923 			} else {
10924 				imreqp = (struct ip_mreq_source *)i1;
10925 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10926 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10927 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10928 			}
10929 
10930 			/*
10931 			 * In the multirouting case, we need to replicate
10932 			 * the request as noted in the mcast cases above.
10933 			 */
10934 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10935 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10936 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10937 			if (ire != NULL) {
10938 				if (ire->ire_flags & RTF_MULTIRT) {
10939 					error = ip_multirt_apply_membership(
10940 					    optfn, ire, connp, checkonly, grp,
10941 					    fmode, src, first_mp);
10942 					done = B_TRUE;
10943 				}
10944 				ire_refrele(ire);
10945 			}
10946 			if (!done) {
10947 				error = optfn(connp, checkonly, grp, ifaddr,
10948 				    &ifindex, fmode, src, first_mp);
10949 			}
10950 			if (error != 0) {
10951 				/*
10952 				 * EINPROGRESS is a soft error, needs retry
10953 				 * so don't make *outlenp zero.
10954 				 */
10955 				if (error != EINPROGRESS)
10956 					*outlenp = 0;
10957 				return (error);
10958 			}
10959 			/* OK return - copy input buffer into output buffer */
10960 			if (invalp != outvalp) {
10961 				bcopy(invalp, outvalp, inlen);
10962 			}
10963 			*outlenp = inlen;
10964 			return (0);
10965 		}
10966 		case IP_SEC_OPT:
10967 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10968 			if (error != 0) {
10969 				*outlenp = 0;
10970 				return (error);
10971 			}
10972 			break;
10973 		case IP_HDRINCL:
10974 		case IP_OPTIONS:
10975 		case T_IP_OPTIONS:
10976 		case IP_TOS:
10977 		case T_IP_TOS:
10978 		case IP_TTL:
10979 		case IP_RECVDSTADDR:
10980 		case IP_RECVOPTS:
10981 			/* OK return - copy input buffer into output buffer */
10982 			if (invalp != outvalp) {
10983 				/* don't trust bcopy for identical src/dst */
10984 				bcopy(invalp, outvalp, inlen);
10985 			}
10986 			*outlenp = inlen;
10987 			return (0);
10988 		case IP_RECVIF:
10989 			/* Retrieve the inbound interface index */
10990 			if (!checkonly) {
10991 				mutex_enter(&connp->conn_lock);
10992 				connp->conn_recvif = *i1 ? 1 : 0;
10993 				mutex_exit(&connp->conn_lock);
10994 			}
10995 			break;	/* goto sizeof (int) option return */
10996 		case IP_RECVPKTINFO:
10997 			if (!checkonly) {
10998 				mutex_enter(&connp->conn_lock);
10999 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11000 				mutex_exit(&connp->conn_lock);
11001 			}
11002 			break;	/* goto sizeof (int) option return */
11003 		case IP_RECVSLLA:
11004 			/* Retrieve the source link layer address */
11005 			if (!checkonly) {
11006 				mutex_enter(&connp->conn_lock);
11007 				connp->conn_recvslla = *i1 ? 1 : 0;
11008 				mutex_exit(&connp->conn_lock);
11009 			}
11010 			break;	/* goto sizeof (int) option return */
11011 		case MRT_INIT:
11012 		case MRT_DONE:
11013 		case MRT_ADD_VIF:
11014 		case MRT_DEL_VIF:
11015 		case MRT_ADD_MFC:
11016 		case MRT_DEL_MFC:
11017 		case MRT_ASSERT:
11018 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11019 				*outlenp = 0;
11020 				return (error);
11021 			}
11022 			error = ip_mrouter_set((int)name, q, checkonly,
11023 			    (uchar_t *)invalp, inlen, first_mp);
11024 			if (error) {
11025 				*outlenp = 0;
11026 				return (error);
11027 			}
11028 			/* OK return - copy input buffer into output buffer */
11029 			if (invalp != outvalp) {
11030 				/* don't trust bcopy for identical src/dst */
11031 				bcopy(invalp, outvalp, inlen);
11032 			}
11033 			*outlenp = inlen;
11034 			return (0);
11035 		case IP_BOUND_IF:
11036 		case IP_DHCPINIT_IF:
11037 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11038 			    level, name, first_mp);
11039 			if (error != 0)
11040 				return (error);
11041 			break; 		/* goto sizeof (int) option return */
11042 
11043 		case IP_UNSPEC_SRC:
11044 			/* Allow sending with a zero source address */
11045 			if (!checkonly) {
11046 				mutex_enter(&connp->conn_lock);
11047 				connp->conn_unspec_src = *i1 ? 1 : 0;
11048 				mutex_exit(&connp->conn_lock);
11049 			}
11050 			break;	/* goto sizeof (int) option return */
11051 		default:
11052 			/*
11053 			 * "soft" error (negative)
11054 			 * option not handled at this level
11055 			 * Note: Do not modify *outlenp
11056 			 */
11057 			return (-EINVAL);
11058 		}
11059 		break;
11060 	case IPPROTO_IPV6:
11061 		switch (name) {
11062 		case IPV6_BOUND_IF:
11063 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11064 			    level, name, first_mp);
11065 			if (error != 0)
11066 				return (error);
11067 			break; 		/* goto sizeof (int) option return */
11068 
11069 		case IPV6_MULTICAST_IF:
11070 			/*
11071 			 * The only possible errors are EINPROGRESS and
11072 			 * EINVAL. EINPROGRESS will be restarted and is not
11073 			 * a hard error. We call this option on both V4 and V6
11074 			 * If both return EINVAL, then this call returns
11075 			 * EINVAL. If at least one of them succeeds we
11076 			 * return success.
11077 			 */
11078 			found = B_FALSE;
11079 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11080 			    level, name, first_mp);
11081 			if (error == EINPROGRESS)
11082 				return (error);
11083 			if (error == 0)
11084 				found = B_TRUE;
11085 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11086 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11087 			if (error == 0)
11088 				found = B_TRUE;
11089 			if (!found)
11090 				return (error);
11091 			break; 		/* goto sizeof (int) option return */
11092 
11093 		case IPV6_MULTICAST_HOPS:
11094 			/* Recorded in transport above IP */
11095 			break;	/* goto sizeof (int) option return */
11096 		case IPV6_MULTICAST_LOOP:
11097 			if (!checkonly) {
11098 				mutex_enter(&connp->conn_lock);
11099 				connp->conn_multicast_loop = *i1;
11100 				mutex_exit(&connp->conn_lock);
11101 			}
11102 			break;	/* goto sizeof (int) option return */
11103 		case IPV6_JOIN_GROUP:
11104 		case MCAST_JOIN_GROUP:
11105 		case IPV6_LEAVE_GROUP:
11106 		case MCAST_LEAVE_GROUP: {
11107 			struct ipv6_mreq *ip_mreqp;
11108 			struct group_req *greqp;
11109 			ire_t *ire;
11110 			boolean_t done = B_FALSE;
11111 			in6_addr_t groupv6;
11112 			uint32_t ifindex;
11113 			boolean_t mcast_opt = B_TRUE;
11114 			mcast_record_t fmode;
11115 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11116 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11117 
11118 			switch (name) {
11119 			case IPV6_JOIN_GROUP:
11120 				mcast_opt = B_FALSE;
11121 				/* FALLTHRU */
11122 			case MCAST_JOIN_GROUP:
11123 				fmode = MODE_IS_EXCLUDE;
11124 				optfn = ip_opt_add_group_v6;
11125 				break;
11126 
11127 			case IPV6_LEAVE_GROUP:
11128 				mcast_opt = B_FALSE;
11129 				/* FALLTHRU */
11130 			case MCAST_LEAVE_GROUP:
11131 				fmode = MODE_IS_INCLUDE;
11132 				optfn = ip_opt_delete_group_v6;
11133 				break;
11134 			}
11135 
11136 			if (mcast_opt) {
11137 				struct sockaddr_in *sin;
11138 				struct sockaddr_in6 *sin6;
11139 				greqp = (struct group_req *)i1;
11140 				if (greqp->gr_group.ss_family == AF_INET) {
11141 					sin = (struct sockaddr_in *)
11142 					    &(greqp->gr_group);
11143 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11144 					    &groupv6);
11145 				} else {
11146 					sin6 = (struct sockaddr_in6 *)
11147 					    &(greqp->gr_group);
11148 					groupv6 = sin6->sin6_addr;
11149 				}
11150 				ifindex = greqp->gr_interface;
11151 			} else {
11152 				ip_mreqp = (struct ipv6_mreq *)i1;
11153 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11154 				ifindex = ip_mreqp->ipv6mr_interface;
11155 			}
11156 			/*
11157 			 * In the multirouting case, we need to replicate
11158 			 * the request on all interfaces that will take part
11159 			 * in replication.  We do so because multirouting is
11160 			 * reflective, thus we will probably receive multi-
11161 			 * casts on those interfaces.
11162 			 * The ip_multirt_apply_membership_v6() succeeds if
11163 			 * the operation succeeds on at least one interface.
11164 			 */
11165 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11166 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11167 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11168 			if (ire != NULL) {
11169 				if (ire->ire_flags & RTF_MULTIRT) {
11170 					error = ip_multirt_apply_membership_v6(
11171 					    optfn, ire, connp, checkonly,
11172 					    &groupv6, fmode, &ipv6_all_zeros,
11173 					    first_mp);
11174 					done = B_TRUE;
11175 				}
11176 				ire_refrele(ire);
11177 			}
11178 			if (!done) {
11179 				error = optfn(connp, checkonly, &groupv6,
11180 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11181 			}
11182 			if (error) {
11183 				/*
11184 				 * EINPROGRESS is a soft error, needs retry
11185 				 * so don't make *outlenp zero.
11186 				 */
11187 				if (error != EINPROGRESS)
11188 					*outlenp = 0;
11189 				return (error);
11190 			}
11191 			/* OK return - copy input buffer into output buffer */
11192 			if (invalp != outvalp) {
11193 				/* don't trust bcopy for identical src/dst */
11194 				bcopy(invalp, outvalp, inlen);
11195 			}
11196 			*outlenp = inlen;
11197 			return (0);
11198 		}
11199 		case MCAST_BLOCK_SOURCE:
11200 		case MCAST_UNBLOCK_SOURCE:
11201 		case MCAST_JOIN_SOURCE_GROUP:
11202 		case MCAST_LEAVE_SOURCE_GROUP: {
11203 			struct group_source_req *gsreqp;
11204 			in6_addr_t v6grp, v6src;
11205 			uint32_t ifindex;
11206 			mcast_record_t fmode;
11207 			ire_t *ire;
11208 			boolean_t done = B_FALSE;
11209 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11210 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11211 
11212 			switch (name) {
11213 			case MCAST_BLOCK_SOURCE:
11214 				fmode = MODE_IS_EXCLUDE;
11215 				optfn = ip_opt_add_group_v6;
11216 				break;
11217 			case MCAST_UNBLOCK_SOURCE:
11218 				fmode = MODE_IS_EXCLUDE;
11219 				optfn = ip_opt_delete_group_v6;
11220 				break;
11221 			case MCAST_JOIN_SOURCE_GROUP:
11222 				fmode = MODE_IS_INCLUDE;
11223 				optfn = ip_opt_add_group_v6;
11224 				break;
11225 			case MCAST_LEAVE_SOURCE_GROUP:
11226 				fmode = MODE_IS_INCLUDE;
11227 				optfn = ip_opt_delete_group_v6;
11228 				break;
11229 			}
11230 
11231 			gsreqp = (struct group_source_req *)i1;
11232 			ifindex = gsreqp->gsr_interface;
11233 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11234 				struct sockaddr_in *s;
11235 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11236 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11237 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11238 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11239 			} else {
11240 				struct sockaddr_in6 *s6;
11241 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11242 				v6grp = s6->sin6_addr;
11243 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11244 				v6src = s6->sin6_addr;
11245 			}
11246 
11247 			/*
11248 			 * In the multirouting case, we need to replicate
11249 			 * the request as noted in the mcast cases above.
11250 			 */
11251 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11252 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11253 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11254 			if (ire != NULL) {
11255 				if (ire->ire_flags & RTF_MULTIRT) {
11256 					error = ip_multirt_apply_membership_v6(
11257 					    optfn, ire, connp, checkonly,
11258 					    &v6grp, fmode, &v6src, first_mp);
11259 					done = B_TRUE;
11260 				}
11261 				ire_refrele(ire);
11262 			}
11263 			if (!done) {
11264 				error = optfn(connp, checkonly, &v6grp,
11265 				    ifindex, fmode, &v6src, first_mp);
11266 			}
11267 			if (error != 0) {
11268 				/*
11269 				 * EINPROGRESS is a soft error, needs retry
11270 				 * so don't make *outlenp zero.
11271 				 */
11272 				if (error != EINPROGRESS)
11273 					*outlenp = 0;
11274 				return (error);
11275 			}
11276 			/* OK return - copy input buffer into output buffer */
11277 			if (invalp != outvalp) {
11278 				bcopy(invalp, outvalp, inlen);
11279 			}
11280 			*outlenp = inlen;
11281 			return (0);
11282 		}
11283 		case IPV6_UNICAST_HOPS:
11284 			/* Recorded in transport above IP */
11285 			break;	/* goto sizeof (int) option return */
11286 		case IPV6_UNSPEC_SRC:
11287 			/* Allow sending with a zero source address */
11288 			if (!checkonly) {
11289 				mutex_enter(&connp->conn_lock);
11290 				connp->conn_unspec_src = *i1 ? 1 : 0;
11291 				mutex_exit(&connp->conn_lock);
11292 			}
11293 			break;	/* goto sizeof (int) option return */
11294 		case IPV6_RECVPKTINFO:
11295 			if (!checkonly) {
11296 				mutex_enter(&connp->conn_lock);
11297 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11298 				mutex_exit(&connp->conn_lock);
11299 			}
11300 			break;	/* goto sizeof (int) option return */
11301 		case IPV6_RECVTCLASS:
11302 			if (!checkonly) {
11303 				if (*i1 < 0 || *i1 > 1) {
11304 					return (EINVAL);
11305 				}
11306 				mutex_enter(&connp->conn_lock);
11307 				connp->conn_ipv6_recvtclass = *i1;
11308 				mutex_exit(&connp->conn_lock);
11309 			}
11310 			break;
11311 		case IPV6_RECVPATHMTU:
11312 			if (!checkonly) {
11313 				if (*i1 < 0 || *i1 > 1) {
11314 					return (EINVAL);
11315 				}
11316 				mutex_enter(&connp->conn_lock);
11317 				connp->conn_ipv6_recvpathmtu = *i1;
11318 				mutex_exit(&connp->conn_lock);
11319 			}
11320 			break;
11321 		case IPV6_RECVHOPLIMIT:
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		case IPV6_RECVHOPOPTS:
11329 			if (!checkonly) {
11330 				mutex_enter(&connp->conn_lock);
11331 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11332 				mutex_exit(&connp->conn_lock);
11333 			}
11334 			break;	/* goto sizeof (int) option return */
11335 		case IPV6_RECVDSTOPTS:
11336 			if (!checkonly) {
11337 				mutex_enter(&connp->conn_lock);
11338 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11339 				mutex_exit(&connp->conn_lock);
11340 			}
11341 			break;	/* goto sizeof (int) option return */
11342 		case IPV6_RECVRTHDR:
11343 			if (!checkonly) {
11344 				mutex_enter(&connp->conn_lock);
11345 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11346 				mutex_exit(&connp->conn_lock);
11347 			}
11348 			break;	/* goto sizeof (int) option return */
11349 		case IPV6_RECVRTHDRDSTOPTS:
11350 			if (!checkonly) {
11351 				mutex_enter(&connp->conn_lock);
11352 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11353 				mutex_exit(&connp->conn_lock);
11354 			}
11355 			break;	/* goto sizeof (int) option return */
11356 		case IPV6_PKTINFO:
11357 			if (inlen == 0)
11358 				return (-EINVAL);	/* clearing option */
11359 			error = ip6_set_pktinfo(cr, connp,
11360 			    (struct in6_pktinfo *)invalp);
11361 			if (error != 0)
11362 				*outlenp = 0;
11363 			else
11364 				*outlenp = inlen;
11365 			return (error);
11366 		case IPV6_NEXTHOP: {
11367 			struct sockaddr_in6 *sin6;
11368 
11369 			/* Verify that the nexthop is reachable */
11370 			if (inlen == 0)
11371 				return (-EINVAL);	/* clearing option */
11372 
11373 			sin6 = (struct sockaddr_in6 *)invalp;
11374 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11375 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11376 			    NULL, MATCH_IRE_DEFAULT, ipst);
11377 
11378 			if (ire == NULL) {
11379 				*outlenp = 0;
11380 				return (EHOSTUNREACH);
11381 			}
11382 			ire_refrele(ire);
11383 			return (-EINVAL);
11384 		}
11385 		case IPV6_SEC_OPT:
11386 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11387 			if (error != 0) {
11388 				*outlenp = 0;
11389 				return (error);
11390 			}
11391 			break;
11392 		case IPV6_SRC_PREFERENCES: {
11393 			/*
11394 			 * This is implemented strictly in the ip module
11395 			 * (here and in tcp_opt_*() to accomodate tcp
11396 			 * sockets).  Modules above ip pass this option
11397 			 * down here since ip is the only one that needs to
11398 			 * be aware of source address preferences.
11399 			 *
11400 			 * This socket option only affects connected
11401 			 * sockets that haven't already bound to a specific
11402 			 * IPv6 address.  In other words, sockets that
11403 			 * don't call bind() with an address other than the
11404 			 * unspecified address and that call connect().
11405 			 * ip_bind_connected_v6() passes these preferences
11406 			 * to the ipif_select_source_v6() function.
11407 			 */
11408 			if (inlen != sizeof (uint32_t))
11409 				return (EINVAL);
11410 			error = ip6_set_src_preferences(connp,
11411 			    *(uint32_t *)invalp);
11412 			if (error != 0) {
11413 				*outlenp = 0;
11414 				return (error);
11415 			} else {
11416 				*outlenp = sizeof (uint32_t);
11417 			}
11418 			break;
11419 		}
11420 		case IPV6_V6ONLY:
11421 			if (*i1 < 0 || *i1 > 1) {
11422 				return (EINVAL);
11423 			}
11424 			mutex_enter(&connp->conn_lock);
11425 			connp->conn_ipv6_v6only = *i1;
11426 			mutex_exit(&connp->conn_lock);
11427 			break;
11428 		default:
11429 			return (-EINVAL);
11430 		}
11431 		break;
11432 	default:
11433 		/*
11434 		 * "soft" error (negative)
11435 		 * option not handled at this level
11436 		 * Note: Do not modify *outlenp
11437 		 */
11438 		return (-EINVAL);
11439 	}
11440 	/*
11441 	 * Common case of return from an option that is sizeof (int)
11442 	 */
11443 	*(int *)outvalp = *i1;
11444 	*outlenp = sizeof (int);
11445 	return (0);
11446 }
11447 
11448 /*
11449  * This routine gets default values of certain options whose default
11450  * values are maintained by protocol specific code
11451  */
11452 /* ARGSUSED */
11453 int
11454 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11455 {
11456 	int *i1 = (int *)ptr;
11457 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11458 
11459 	switch (level) {
11460 	case IPPROTO_IP:
11461 		switch (name) {
11462 		case IP_MULTICAST_TTL:
11463 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11464 			return (sizeof (uchar_t));
11465 		case IP_MULTICAST_LOOP:
11466 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11467 			return (sizeof (uchar_t));
11468 		default:
11469 			return (-1);
11470 		}
11471 	case IPPROTO_IPV6:
11472 		switch (name) {
11473 		case IPV6_UNICAST_HOPS:
11474 			*i1 = ipst->ips_ipv6_def_hops;
11475 			return (sizeof (int));
11476 		case IPV6_MULTICAST_HOPS:
11477 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11478 			return (sizeof (int));
11479 		case IPV6_MULTICAST_LOOP:
11480 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11481 			return (sizeof (int));
11482 		case IPV6_V6ONLY:
11483 			*i1 = 1;
11484 			return (sizeof (int));
11485 		default:
11486 			return (-1);
11487 		}
11488 	default:
11489 		return (-1);
11490 	}
11491 	/* NOTREACHED */
11492 }
11493 
11494 /*
11495  * Given a destination address and a pointer to where to put the information
11496  * this routine fills in the mtuinfo.
11497  */
11498 int
11499 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11500     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11501 {
11502 	ire_t *ire;
11503 	ip_stack_t	*ipst = ns->netstack_ip;
11504 
11505 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11506 		return (-1);
11507 
11508 	bzero(mtuinfo, sizeof (*mtuinfo));
11509 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11510 	mtuinfo->ip6m_addr.sin6_port = port;
11511 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11512 
11513 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11514 	if (ire != NULL) {
11515 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11516 		ire_refrele(ire);
11517 	} else {
11518 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11519 	}
11520 	return (sizeof (struct ip6_mtuinfo));
11521 }
11522 
11523 /*
11524  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11525  * checking of cred and that ip_g_mrouter is set should be done and
11526  * isn't.  This doesn't matter as the error checking is done properly for the
11527  * other MRT options coming in through ip_opt_set.
11528  */
11529 int
11530 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11531 {
11532 	conn_t		*connp = Q_TO_CONN(q);
11533 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11534 
11535 	switch (level) {
11536 	case IPPROTO_IP:
11537 		switch (name) {
11538 		case MRT_VERSION:
11539 		case MRT_ASSERT:
11540 			(void) ip_mrouter_get(name, q, ptr);
11541 			return (sizeof (int));
11542 		case IP_SEC_OPT:
11543 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11544 		case IP_NEXTHOP:
11545 			if (connp->conn_nexthop_set) {
11546 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11547 				return (sizeof (ipaddr_t));
11548 			} else
11549 				return (0);
11550 		case IP_RECVPKTINFO:
11551 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11552 			return (sizeof (int));
11553 		default:
11554 			break;
11555 		}
11556 		break;
11557 	case IPPROTO_IPV6:
11558 		switch (name) {
11559 		case IPV6_SEC_OPT:
11560 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11561 		case IPV6_SRC_PREFERENCES: {
11562 			return (ip6_get_src_preferences(connp,
11563 			    (uint32_t *)ptr));
11564 		}
11565 		case IPV6_V6ONLY:
11566 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11567 			return (sizeof (int));
11568 		case IPV6_PATHMTU:
11569 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11570 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11571 		default:
11572 			break;
11573 		}
11574 		break;
11575 	default:
11576 		break;
11577 	}
11578 	return (-1);
11579 }
11580 /* Named Dispatch routine to get a current value out of our parameter table. */
11581 /* ARGSUSED */
11582 static int
11583 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11584 {
11585 	ipparam_t *ippa = (ipparam_t *)cp;
11586 
11587 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11588 	return (0);
11589 }
11590 
11591 /* ARGSUSED */
11592 static int
11593 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11594 {
11595 
11596 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11597 	return (0);
11598 }
11599 
11600 /*
11601  * Set ip{,6}_forwarding values.  This means walking through all of the
11602  * ill's and toggling their forwarding values.
11603  */
11604 /* ARGSUSED */
11605 static int
11606 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11607 {
11608 	long new_value;
11609 	int *forwarding_value = (int *)cp;
11610 	ill_t *ill;
11611 	boolean_t isv6;
11612 	ill_walk_context_t ctx;
11613 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11614 
11615 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11616 
11617 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11618 	    new_value < 0 || new_value > 1) {
11619 		return (EINVAL);
11620 	}
11621 
11622 	*forwarding_value = new_value;
11623 
11624 	/*
11625 	 * Regardless of the current value of ip_forwarding, set all per-ill
11626 	 * values of ip_forwarding to the value being set.
11627 	 *
11628 	 * Bring all the ill's up to date with the new global value.
11629 	 */
11630 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11631 
11632 	if (isv6)
11633 		ill = ILL_START_WALK_V6(&ctx, ipst);
11634 	else
11635 		ill = ILL_START_WALK_V4(&ctx, ipst);
11636 
11637 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11638 		(void) ill_forward_set(ill, new_value != 0);
11639 
11640 	rw_exit(&ipst->ips_ill_g_lock);
11641 	return (0);
11642 }
11643 
11644 /*
11645  * Walk through the param array specified registering each element with the
11646  * Named Dispatch handler. This is called only during init. So it is ok
11647  * not to acquire any locks
11648  */
11649 static boolean_t
11650 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11651     ipndp_t *ipnd, size_t ipnd_cnt)
11652 {
11653 	for (; ippa_cnt-- > 0; ippa++) {
11654 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11655 			if (!nd_load(ndp, ippa->ip_param_name,
11656 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11657 				nd_free(ndp);
11658 				return (B_FALSE);
11659 			}
11660 		}
11661 	}
11662 
11663 	for (; ipnd_cnt-- > 0; ipnd++) {
11664 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11665 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11666 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11667 			    ipnd->ip_ndp_data)) {
11668 				nd_free(ndp);
11669 				return (B_FALSE);
11670 			}
11671 		}
11672 	}
11673 
11674 	return (B_TRUE);
11675 }
11676 
11677 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11678 /* ARGSUSED */
11679 static int
11680 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11681 {
11682 	long		new_value;
11683 	ipparam_t	*ippa = (ipparam_t *)cp;
11684 
11685 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11686 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11687 		return (EINVAL);
11688 	}
11689 	ippa->ip_param_value = new_value;
11690 	return (0);
11691 }
11692 
11693 /*
11694  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11695  * When an ipf is passed here for the first time, if
11696  * we already have in-order fragments on the queue, we convert from the fast-
11697  * path reassembly scheme to the hard-case scheme.  From then on, additional
11698  * fragments are reassembled here.  We keep track of the start and end offsets
11699  * of each piece, and the number of holes in the chain.  When the hole count
11700  * goes to zero, we are done!
11701  *
11702  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11703  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11704  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11705  * after the call to ip_reassemble().
11706  */
11707 int
11708 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11709     size_t msg_len)
11710 {
11711 	uint_t	end;
11712 	mblk_t	*next_mp;
11713 	mblk_t	*mp1;
11714 	uint_t	offset;
11715 	boolean_t incr_dups = B_TRUE;
11716 	boolean_t offset_zero_seen = B_FALSE;
11717 	boolean_t pkt_boundary_checked = B_FALSE;
11718 
11719 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11720 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11721 
11722 	/* Add in byte count */
11723 	ipf->ipf_count += msg_len;
11724 	if (ipf->ipf_end) {
11725 		/*
11726 		 * We were part way through in-order reassembly, but now there
11727 		 * is a hole.  We walk through messages already queued, and
11728 		 * mark them for hard case reassembly.  We know that up till
11729 		 * now they were in order starting from offset zero.
11730 		 */
11731 		offset = 0;
11732 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11733 			IP_REASS_SET_START(mp1, offset);
11734 			if (offset == 0) {
11735 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11736 				offset = -ipf->ipf_nf_hdr_len;
11737 			}
11738 			offset += mp1->b_wptr - mp1->b_rptr;
11739 			IP_REASS_SET_END(mp1, offset);
11740 		}
11741 		/* One hole at the end. */
11742 		ipf->ipf_hole_cnt = 1;
11743 		/* Brand it as a hard case, forever. */
11744 		ipf->ipf_end = 0;
11745 	}
11746 	/* Walk through all the new pieces. */
11747 	do {
11748 		end = start + (mp->b_wptr - mp->b_rptr);
11749 		/*
11750 		 * If start is 0, decrease 'end' only for the first mblk of
11751 		 * the fragment. Otherwise 'end' can get wrong value in the
11752 		 * second pass of the loop if first mblk is exactly the
11753 		 * size of ipf_nf_hdr_len.
11754 		 */
11755 		if (start == 0 && !offset_zero_seen) {
11756 			/* First segment */
11757 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11758 			end -= ipf->ipf_nf_hdr_len;
11759 			offset_zero_seen = B_TRUE;
11760 		}
11761 		next_mp = mp->b_cont;
11762 		/*
11763 		 * We are checking to see if there is any interesing data
11764 		 * to process.  If there isn't and the mblk isn't the
11765 		 * one which carries the unfragmentable header then we
11766 		 * drop it.  It's possible to have just the unfragmentable
11767 		 * header come through without any data.  That needs to be
11768 		 * saved.
11769 		 *
11770 		 * If the assert at the top of this function holds then the
11771 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11772 		 * is infrequently traveled enough that the test is left in
11773 		 * to protect against future code changes which break that
11774 		 * invariant.
11775 		 */
11776 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11777 			/* Empty.  Blast it. */
11778 			IP_REASS_SET_START(mp, 0);
11779 			IP_REASS_SET_END(mp, 0);
11780 			/*
11781 			 * If the ipf points to the mblk we are about to free,
11782 			 * update ipf to point to the next mblk (or NULL
11783 			 * if none).
11784 			 */
11785 			if (ipf->ipf_mp->b_cont == mp)
11786 				ipf->ipf_mp->b_cont = next_mp;
11787 			freeb(mp);
11788 			continue;
11789 		}
11790 		mp->b_cont = NULL;
11791 		IP_REASS_SET_START(mp, start);
11792 		IP_REASS_SET_END(mp, end);
11793 		if (!ipf->ipf_tail_mp) {
11794 			ipf->ipf_tail_mp = mp;
11795 			ipf->ipf_mp->b_cont = mp;
11796 			if (start == 0 || !more) {
11797 				ipf->ipf_hole_cnt = 1;
11798 				/*
11799 				 * if the first fragment comes in more than one
11800 				 * mblk, this loop will be executed for each
11801 				 * mblk. Need to adjust hole count so exiting
11802 				 * this routine will leave hole count at 1.
11803 				 */
11804 				if (next_mp)
11805 					ipf->ipf_hole_cnt++;
11806 			} else
11807 				ipf->ipf_hole_cnt = 2;
11808 			continue;
11809 		} else if (ipf->ipf_last_frag_seen && !more &&
11810 		    !pkt_boundary_checked) {
11811 			/*
11812 			 * We check datagram boundary only if this fragment
11813 			 * claims to be the last fragment and we have seen a
11814 			 * last fragment in the past too. We do this only
11815 			 * once for a given fragment.
11816 			 *
11817 			 * start cannot be 0 here as fragments with start=0
11818 			 * and MF=0 gets handled as a complete packet. These
11819 			 * fragments should not reach here.
11820 			 */
11821 
11822 			if (start + msgdsize(mp) !=
11823 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11824 				/*
11825 				 * We have two fragments both of which claim
11826 				 * to be the last fragment but gives conflicting
11827 				 * information about the whole datagram size.
11828 				 * Something fishy is going on. Drop the
11829 				 * fragment and free up the reassembly list.
11830 				 */
11831 				return (IP_REASS_FAILED);
11832 			}
11833 
11834 			/*
11835 			 * We shouldn't come to this code block again for this
11836 			 * particular fragment.
11837 			 */
11838 			pkt_boundary_checked = B_TRUE;
11839 		}
11840 
11841 		/* New stuff at or beyond tail? */
11842 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11843 		if (start >= offset) {
11844 			if (ipf->ipf_last_frag_seen) {
11845 				/* current fragment is beyond last fragment */
11846 				return (IP_REASS_FAILED);
11847 			}
11848 			/* Link it on end. */
11849 			ipf->ipf_tail_mp->b_cont = mp;
11850 			ipf->ipf_tail_mp = mp;
11851 			if (more) {
11852 				if (start != offset)
11853 					ipf->ipf_hole_cnt++;
11854 			} else if (start == offset && next_mp == NULL)
11855 					ipf->ipf_hole_cnt--;
11856 			continue;
11857 		}
11858 		mp1 = ipf->ipf_mp->b_cont;
11859 		offset = IP_REASS_START(mp1);
11860 		/* New stuff at the front? */
11861 		if (start < offset) {
11862 			if (start == 0) {
11863 				if (end >= offset) {
11864 					/* Nailed the hole at the begining. */
11865 					ipf->ipf_hole_cnt--;
11866 				}
11867 			} else if (end < offset) {
11868 				/*
11869 				 * A hole, stuff, and a hole where there used
11870 				 * to be just a hole.
11871 				 */
11872 				ipf->ipf_hole_cnt++;
11873 			}
11874 			mp->b_cont = mp1;
11875 			/* Check for overlap. */
11876 			while (end > offset) {
11877 				if (end < IP_REASS_END(mp1)) {
11878 					mp->b_wptr -= end - offset;
11879 					IP_REASS_SET_END(mp, offset);
11880 					BUMP_MIB(ill->ill_ip_mib,
11881 					    ipIfStatsReasmPartDups);
11882 					break;
11883 				}
11884 				/* Did we cover another hole? */
11885 				if ((mp1->b_cont &&
11886 				    IP_REASS_END(mp1) !=
11887 				    IP_REASS_START(mp1->b_cont) &&
11888 				    end >= IP_REASS_START(mp1->b_cont)) ||
11889 				    (!ipf->ipf_last_frag_seen && !more)) {
11890 					ipf->ipf_hole_cnt--;
11891 				}
11892 				/* Clip out mp1. */
11893 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11894 					/*
11895 					 * After clipping out mp1, this guy
11896 					 * is now hanging off the end.
11897 					 */
11898 					ipf->ipf_tail_mp = mp;
11899 				}
11900 				IP_REASS_SET_START(mp1, 0);
11901 				IP_REASS_SET_END(mp1, 0);
11902 				/* Subtract byte count */
11903 				ipf->ipf_count -= mp1->b_datap->db_lim -
11904 				    mp1->b_datap->db_base;
11905 				freeb(mp1);
11906 				BUMP_MIB(ill->ill_ip_mib,
11907 				    ipIfStatsReasmPartDups);
11908 				mp1 = mp->b_cont;
11909 				if (!mp1)
11910 					break;
11911 				offset = IP_REASS_START(mp1);
11912 			}
11913 			ipf->ipf_mp->b_cont = mp;
11914 			continue;
11915 		}
11916 		/*
11917 		 * The new piece starts somewhere between the start of the head
11918 		 * and before the end of the tail.
11919 		 */
11920 		for (; mp1; mp1 = mp1->b_cont) {
11921 			offset = IP_REASS_END(mp1);
11922 			if (start < offset) {
11923 				if (end <= offset) {
11924 					/* Nothing new. */
11925 					IP_REASS_SET_START(mp, 0);
11926 					IP_REASS_SET_END(mp, 0);
11927 					/* Subtract byte count */
11928 					ipf->ipf_count -= mp->b_datap->db_lim -
11929 					    mp->b_datap->db_base;
11930 					if (incr_dups) {
11931 						ipf->ipf_num_dups++;
11932 						incr_dups = B_FALSE;
11933 					}
11934 					freeb(mp);
11935 					BUMP_MIB(ill->ill_ip_mib,
11936 					    ipIfStatsReasmDuplicates);
11937 					break;
11938 				}
11939 				/*
11940 				 * Trim redundant stuff off beginning of new
11941 				 * piece.
11942 				 */
11943 				IP_REASS_SET_START(mp, offset);
11944 				mp->b_rptr += offset - start;
11945 				BUMP_MIB(ill->ill_ip_mib,
11946 				    ipIfStatsReasmPartDups);
11947 				start = offset;
11948 				if (!mp1->b_cont) {
11949 					/*
11950 					 * After trimming, this guy is now
11951 					 * hanging off the end.
11952 					 */
11953 					mp1->b_cont = mp;
11954 					ipf->ipf_tail_mp = mp;
11955 					if (!more) {
11956 						ipf->ipf_hole_cnt--;
11957 					}
11958 					break;
11959 				}
11960 			}
11961 			if (start >= IP_REASS_START(mp1->b_cont))
11962 				continue;
11963 			/* Fill a hole */
11964 			if (start > offset)
11965 				ipf->ipf_hole_cnt++;
11966 			mp->b_cont = mp1->b_cont;
11967 			mp1->b_cont = mp;
11968 			mp1 = mp->b_cont;
11969 			offset = IP_REASS_START(mp1);
11970 			if (end >= offset) {
11971 				ipf->ipf_hole_cnt--;
11972 				/* Check for overlap. */
11973 				while (end > offset) {
11974 					if (end < IP_REASS_END(mp1)) {
11975 						mp->b_wptr -= end - offset;
11976 						IP_REASS_SET_END(mp, offset);
11977 						/*
11978 						 * TODO we might bump
11979 						 * this up twice if there is
11980 						 * overlap at both ends.
11981 						 */
11982 						BUMP_MIB(ill->ill_ip_mib,
11983 						    ipIfStatsReasmPartDups);
11984 						break;
11985 					}
11986 					/* Did we cover another hole? */
11987 					if ((mp1->b_cont &&
11988 					    IP_REASS_END(mp1)
11989 					    != IP_REASS_START(mp1->b_cont) &&
11990 					    end >=
11991 					    IP_REASS_START(mp1->b_cont)) ||
11992 					    (!ipf->ipf_last_frag_seen &&
11993 					    !more)) {
11994 						ipf->ipf_hole_cnt--;
11995 					}
11996 					/* Clip out mp1. */
11997 					if ((mp->b_cont = mp1->b_cont) ==
11998 					    NULL) {
11999 						/*
12000 						 * After clipping out mp1,
12001 						 * this guy is now hanging
12002 						 * off the end.
12003 						 */
12004 						ipf->ipf_tail_mp = mp;
12005 					}
12006 					IP_REASS_SET_START(mp1, 0);
12007 					IP_REASS_SET_END(mp1, 0);
12008 					/* Subtract byte count */
12009 					ipf->ipf_count -=
12010 					    mp1->b_datap->db_lim -
12011 					    mp1->b_datap->db_base;
12012 					freeb(mp1);
12013 					BUMP_MIB(ill->ill_ip_mib,
12014 					    ipIfStatsReasmPartDups);
12015 					mp1 = mp->b_cont;
12016 					if (!mp1)
12017 						break;
12018 					offset = IP_REASS_START(mp1);
12019 				}
12020 			}
12021 			break;
12022 		}
12023 	} while (start = end, mp = next_mp);
12024 
12025 	/* Fragment just processed could be the last one. Remember this fact */
12026 	if (!more)
12027 		ipf->ipf_last_frag_seen = B_TRUE;
12028 
12029 	/* Still got holes? */
12030 	if (ipf->ipf_hole_cnt)
12031 		return (IP_REASS_PARTIAL);
12032 	/* Clean up overloaded fields to avoid upstream disasters. */
12033 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12034 		IP_REASS_SET_START(mp1, 0);
12035 		IP_REASS_SET_END(mp1, 0);
12036 	}
12037 	return (IP_REASS_COMPLETE);
12038 }
12039 
12040 /*
12041  * ipsec processing for the fast path, used for input UDP Packets
12042  * Returns true if ready for passup to UDP.
12043  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12044  * was an ESP-in-UDP packet, etc.).
12045  */
12046 static boolean_t
12047 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12048     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12049 {
12050 	uint32_t	ill_index;
12051 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12052 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12053 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12054 	udp_t		*udp = connp->conn_udp;
12055 
12056 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12057 	/* The ill_index of the incoming ILL */
12058 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12059 
12060 	/* pass packet up to the transport */
12061 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12062 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12063 		    NULL, mctl_present);
12064 		if (*first_mpp == NULL) {
12065 			return (B_FALSE);
12066 		}
12067 	}
12068 
12069 	/* Initiate IPPF processing for fastpath UDP */
12070 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12071 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12072 		if (*mpp == NULL) {
12073 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12074 			    "deferred/dropped during IPPF processing\n"));
12075 			return (B_FALSE);
12076 		}
12077 	}
12078 	/*
12079 	 * Remove 0-spi if it's 0, or move everything behind
12080 	 * the UDP header over it and forward to ESP via
12081 	 * ip_proto_input().
12082 	 */
12083 	if (udp->udp_nat_t_endpoint) {
12084 		if (mctl_present) {
12085 			/* mctl_present *shouldn't* happen. */
12086 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12087 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12088 			    &ipss->ipsec_dropper);
12089 			*first_mpp = NULL;
12090 			return (B_FALSE);
12091 		}
12092 
12093 		/* "ill" is "recv_ill" in actuality. */
12094 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12095 			return (B_FALSE);
12096 
12097 		/* Else continue like a normal UDP packet. */
12098 	}
12099 
12100 	/*
12101 	 * We make the checks as below since we are in the fast path
12102 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12103 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12104 	 */
12105 	if (connp->conn_recvif || connp->conn_recvslla ||
12106 	    connp->conn_ip_recvpktinfo) {
12107 		if (connp->conn_recvif) {
12108 			in_flags = IPF_RECVIF;
12109 		}
12110 		/*
12111 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12112 		 * so the flag passed to ip_add_info is based on IP version
12113 		 * of connp.
12114 		 */
12115 		if (connp->conn_ip_recvpktinfo) {
12116 			if (connp->conn_af_isv6) {
12117 				/*
12118 				 * V6 only needs index
12119 				 */
12120 				in_flags |= IPF_RECVIF;
12121 			} else {
12122 				/*
12123 				 * V4 needs index + matching address.
12124 				 */
12125 				in_flags |= IPF_RECVADDR;
12126 			}
12127 		}
12128 		if (connp->conn_recvslla) {
12129 			in_flags |= IPF_RECVSLLA;
12130 		}
12131 		/*
12132 		 * since in_flags are being set ill will be
12133 		 * referenced in ip_add_info, so it better not
12134 		 * be NULL.
12135 		 */
12136 		/*
12137 		 * the actual data will be contained in b_cont
12138 		 * upon successful return of the following call.
12139 		 * If the call fails then the original mblk is
12140 		 * returned.
12141 		 */
12142 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12143 		    ipst);
12144 	}
12145 
12146 	return (B_TRUE);
12147 }
12148 
12149 /*
12150  * Fragmentation reassembly.  Each ILL has a hash table for
12151  * queuing packets undergoing reassembly for all IPIFs
12152  * associated with the ILL.  The hash is based on the packet
12153  * IP ident field.  The ILL frag hash table was allocated
12154  * as a timer block at the time the ILL was created.  Whenever
12155  * there is anything on the reassembly queue, the timer will
12156  * be running.  Returns B_TRUE if successful else B_FALSE;
12157  * frees mp on failure.
12158  */
12159 static boolean_t
12160 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12161     uint32_t *cksum_val, uint16_t *cksum_flags)
12162 {
12163 	uint32_t	frag_offset_flags;
12164 	mblk_t		*mp = *mpp;
12165 	mblk_t		*t_mp;
12166 	ipaddr_t	dst;
12167 	uint8_t		proto = ipha->ipha_protocol;
12168 	uint32_t	sum_val;
12169 	uint16_t	sum_flags;
12170 	ipf_t		*ipf;
12171 	ipf_t		**ipfp;
12172 	ipfb_t		*ipfb;
12173 	uint16_t	ident;
12174 	uint32_t	offset;
12175 	ipaddr_t	src;
12176 	uint_t		hdr_length;
12177 	uint32_t	end;
12178 	mblk_t		*mp1;
12179 	mblk_t		*tail_mp;
12180 	size_t		count;
12181 	size_t		msg_len;
12182 	uint8_t		ecn_info = 0;
12183 	uint32_t	packet_size;
12184 	boolean_t	pruned = B_FALSE;
12185 	ip_stack_t *ipst = ill->ill_ipst;
12186 
12187 	if (cksum_val != NULL)
12188 		*cksum_val = 0;
12189 	if (cksum_flags != NULL)
12190 		*cksum_flags = 0;
12191 
12192 	/*
12193 	 * Drop the fragmented as early as possible, if
12194 	 * we don't have resource(s) to re-assemble.
12195 	 */
12196 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12197 		freemsg(mp);
12198 		return (B_FALSE);
12199 	}
12200 
12201 	/* Check for fragmentation offset; return if there's none */
12202 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12203 	    (IPH_MF | IPH_OFFSET)) == 0)
12204 		return (B_TRUE);
12205 
12206 	/*
12207 	 * We utilize hardware computed checksum info only for UDP since
12208 	 * IP fragmentation is a normal occurrence for the protocol.  In
12209 	 * addition, checksum offload support for IP fragments carrying
12210 	 * UDP payload is commonly implemented across network adapters.
12211 	 */
12212 	ASSERT(recv_ill != NULL);
12213 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12214 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12215 		mblk_t *mp1 = mp->b_cont;
12216 		int32_t len;
12217 
12218 		/* Record checksum information from the packet */
12219 		sum_val = (uint32_t)DB_CKSUM16(mp);
12220 		sum_flags = DB_CKSUMFLAGS(mp);
12221 
12222 		/* IP payload offset from beginning of mblk */
12223 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12224 
12225 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12226 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12227 		    offset >= DB_CKSUMSTART(mp) &&
12228 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12229 			uint32_t adj;
12230 			/*
12231 			 * Partial checksum has been calculated by hardware
12232 			 * and attached to the packet; in addition, any
12233 			 * prepended extraneous data is even byte aligned.
12234 			 * If any such data exists, we adjust the checksum;
12235 			 * this would also handle any postpended data.
12236 			 */
12237 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12238 			    mp, mp1, len, adj);
12239 
12240 			/* One's complement subtract extraneous checksum */
12241 			if (adj >= sum_val)
12242 				sum_val = ~(adj - sum_val) & 0xFFFF;
12243 			else
12244 				sum_val -= adj;
12245 		}
12246 	} else {
12247 		sum_val = 0;
12248 		sum_flags = 0;
12249 	}
12250 
12251 	/* Clear hardware checksumming flag */
12252 	DB_CKSUMFLAGS(mp) = 0;
12253 
12254 	ident = ipha->ipha_ident;
12255 	offset = (frag_offset_flags << 3) & 0xFFFF;
12256 	src = ipha->ipha_src;
12257 	dst = ipha->ipha_dst;
12258 	hdr_length = IPH_HDR_LENGTH(ipha);
12259 	end = ntohs(ipha->ipha_length) - hdr_length;
12260 
12261 	/* If end == 0 then we have a packet with no data, so just free it */
12262 	if (end == 0) {
12263 		freemsg(mp);
12264 		return (B_FALSE);
12265 	}
12266 
12267 	/* Record the ECN field info. */
12268 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12269 	if (offset != 0) {
12270 		/*
12271 		 * If this isn't the first piece, strip the header, and
12272 		 * add the offset to the end value.
12273 		 */
12274 		mp->b_rptr += hdr_length;
12275 		end += offset;
12276 	}
12277 
12278 	msg_len = MBLKSIZE(mp);
12279 	tail_mp = mp;
12280 	while (tail_mp->b_cont != NULL) {
12281 		tail_mp = tail_mp->b_cont;
12282 		msg_len += MBLKSIZE(tail_mp);
12283 	}
12284 
12285 	/* If the reassembly list for this ILL will get too big, prune it */
12286 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12287 	    ipst->ips_ip_reass_queue_bytes) {
12288 		ill_frag_prune(ill,
12289 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12290 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12291 		pruned = B_TRUE;
12292 	}
12293 
12294 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12295 	mutex_enter(&ipfb->ipfb_lock);
12296 
12297 	ipfp = &ipfb->ipfb_ipf;
12298 	/* Try to find an existing fragment queue for this packet. */
12299 	for (;;) {
12300 		ipf = ipfp[0];
12301 		if (ipf != NULL) {
12302 			/*
12303 			 * It has to match on ident and src/dst address.
12304 			 */
12305 			if (ipf->ipf_ident == ident &&
12306 			    ipf->ipf_src == src &&
12307 			    ipf->ipf_dst == dst &&
12308 			    ipf->ipf_protocol == proto) {
12309 				/*
12310 				 * If we have received too many
12311 				 * duplicate fragments for this packet
12312 				 * free it.
12313 				 */
12314 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12315 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12316 					freemsg(mp);
12317 					mutex_exit(&ipfb->ipfb_lock);
12318 					return (B_FALSE);
12319 				}
12320 				/* Found it. */
12321 				break;
12322 			}
12323 			ipfp = &ipf->ipf_hash_next;
12324 			continue;
12325 		}
12326 
12327 		/*
12328 		 * If we pruned the list, do we want to store this new
12329 		 * fragment?. We apply an optimization here based on the
12330 		 * fact that most fragments will be received in order.
12331 		 * So if the offset of this incoming fragment is zero,
12332 		 * it is the first fragment of a new packet. We will
12333 		 * keep it.  Otherwise drop the fragment, as we have
12334 		 * probably pruned the packet already (since the
12335 		 * packet cannot be found).
12336 		 */
12337 		if (pruned && offset != 0) {
12338 			mutex_exit(&ipfb->ipfb_lock);
12339 			freemsg(mp);
12340 			return (B_FALSE);
12341 		}
12342 
12343 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12344 			/*
12345 			 * Too many fragmented packets in this hash
12346 			 * bucket. Free the oldest.
12347 			 */
12348 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12349 		}
12350 
12351 		/* New guy.  Allocate a frag message. */
12352 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12353 		if (mp1 == NULL) {
12354 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12355 			freemsg(mp);
12356 reass_done:
12357 			mutex_exit(&ipfb->ipfb_lock);
12358 			return (B_FALSE);
12359 		}
12360 
12361 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12362 		mp1->b_cont = mp;
12363 
12364 		/* Initialize the fragment header. */
12365 		ipf = (ipf_t *)mp1->b_rptr;
12366 		ipf->ipf_mp = mp1;
12367 		ipf->ipf_ptphn = ipfp;
12368 		ipfp[0] = ipf;
12369 		ipf->ipf_hash_next = NULL;
12370 		ipf->ipf_ident = ident;
12371 		ipf->ipf_protocol = proto;
12372 		ipf->ipf_src = src;
12373 		ipf->ipf_dst = dst;
12374 		ipf->ipf_nf_hdr_len = 0;
12375 		/* Record reassembly start time. */
12376 		ipf->ipf_timestamp = gethrestime_sec();
12377 		/* Record ipf generation and account for frag header */
12378 		ipf->ipf_gen = ill->ill_ipf_gen++;
12379 		ipf->ipf_count = MBLKSIZE(mp1);
12380 		ipf->ipf_last_frag_seen = B_FALSE;
12381 		ipf->ipf_ecn = ecn_info;
12382 		ipf->ipf_num_dups = 0;
12383 		ipfb->ipfb_frag_pkts++;
12384 		ipf->ipf_checksum = 0;
12385 		ipf->ipf_checksum_flags = 0;
12386 
12387 		/* Store checksum value in fragment header */
12388 		if (sum_flags != 0) {
12389 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12390 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12391 			ipf->ipf_checksum = sum_val;
12392 			ipf->ipf_checksum_flags = sum_flags;
12393 		}
12394 
12395 		/*
12396 		 * We handle reassembly two ways.  In the easy case,
12397 		 * where all the fragments show up in order, we do
12398 		 * minimal bookkeeping, and just clip new pieces on
12399 		 * the end.  If we ever see a hole, then we go off
12400 		 * to ip_reassemble which has to mark the pieces and
12401 		 * keep track of the number of holes, etc.  Obviously,
12402 		 * the point of having both mechanisms is so we can
12403 		 * handle the easy case as efficiently as possible.
12404 		 */
12405 		if (offset == 0) {
12406 			/* Easy case, in-order reassembly so far. */
12407 			ipf->ipf_count += msg_len;
12408 			ipf->ipf_tail_mp = tail_mp;
12409 			/*
12410 			 * Keep track of next expected offset in
12411 			 * ipf_end.
12412 			 */
12413 			ipf->ipf_end = end;
12414 			ipf->ipf_nf_hdr_len = hdr_length;
12415 		} else {
12416 			/* Hard case, hole at the beginning. */
12417 			ipf->ipf_tail_mp = NULL;
12418 			/*
12419 			 * ipf_end == 0 means that we have given up
12420 			 * on easy reassembly.
12421 			 */
12422 			ipf->ipf_end = 0;
12423 
12424 			/* Forget checksum offload from now on */
12425 			ipf->ipf_checksum_flags = 0;
12426 
12427 			/*
12428 			 * ipf_hole_cnt is set by ip_reassemble.
12429 			 * ipf_count is updated by ip_reassemble.
12430 			 * No need to check for return value here
12431 			 * as we don't expect reassembly to complete
12432 			 * or fail for the first fragment itself.
12433 			 */
12434 			(void) ip_reassemble(mp, ipf,
12435 			    (frag_offset_flags & IPH_OFFSET) << 3,
12436 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12437 		}
12438 		/* Update per ipfb and ill byte counts */
12439 		ipfb->ipfb_count += ipf->ipf_count;
12440 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12441 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12442 		/* If the frag timer wasn't already going, start it. */
12443 		mutex_enter(&ill->ill_lock);
12444 		ill_frag_timer_start(ill);
12445 		mutex_exit(&ill->ill_lock);
12446 		goto reass_done;
12447 	}
12448 
12449 	/*
12450 	 * If the packet's flag has changed (it could be coming up
12451 	 * from an interface different than the previous, therefore
12452 	 * possibly different checksum capability), then forget about
12453 	 * any stored checksum states.  Otherwise add the value to
12454 	 * the existing one stored in the fragment header.
12455 	 */
12456 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12457 		sum_val += ipf->ipf_checksum;
12458 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12459 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12460 		ipf->ipf_checksum = sum_val;
12461 	} else if (ipf->ipf_checksum_flags != 0) {
12462 		/* Forget checksum offload from now on */
12463 		ipf->ipf_checksum_flags = 0;
12464 	}
12465 
12466 	/*
12467 	 * We have a new piece of a datagram which is already being
12468 	 * reassembled.  Update the ECN info if all IP fragments
12469 	 * are ECN capable.  If there is one which is not, clear
12470 	 * all the info.  If there is at least one which has CE
12471 	 * code point, IP needs to report that up to transport.
12472 	 */
12473 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12474 		if (ecn_info == IPH_ECN_CE)
12475 			ipf->ipf_ecn = IPH_ECN_CE;
12476 	} else {
12477 		ipf->ipf_ecn = IPH_ECN_NECT;
12478 	}
12479 	if (offset && ipf->ipf_end == offset) {
12480 		/* The new fragment fits at the end */
12481 		ipf->ipf_tail_mp->b_cont = mp;
12482 		/* Update the byte count */
12483 		ipf->ipf_count += msg_len;
12484 		/* Update per ipfb and ill byte counts */
12485 		ipfb->ipfb_count += msg_len;
12486 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12487 		atomic_add_32(&ill->ill_frag_count, msg_len);
12488 		if (frag_offset_flags & IPH_MF) {
12489 			/* More to come. */
12490 			ipf->ipf_end = end;
12491 			ipf->ipf_tail_mp = tail_mp;
12492 			goto reass_done;
12493 		}
12494 	} else {
12495 		/* Go do the hard cases. */
12496 		int ret;
12497 
12498 		if (offset == 0)
12499 			ipf->ipf_nf_hdr_len = hdr_length;
12500 
12501 		/* Save current byte count */
12502 		count = ipf->ipf_count;
12503 		ret = ip_reassemble(mp, ipf,
12504 		    (frag_offset_flags & IPH_OFFSET) << 3,
12505 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12506 		/* Count of bytes added and subtracted (freeb()ed) */
12507 		count = ipf->ipf_count - count;
12508 		if (count) {
12509 			/* Update per ipfb and ill byte counts */
12510 			ipfb->ipfb_count += count;
12511 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12512 			atomic_add_32(&ill->ill_frag_count, count);
12513 		}
12514 		if (ret == IP_REASS_PARTIAL) {
12515 			goto reass_done;
12516 		} else if (ret == IP_REASS_FAILED) {
12517 			/* Reassembly failed. Free up all resources */
12518 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12519 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12520 				IP_REASS_SET_START(t_mp, 0);
12521 				IP_REASS_SET_END(t_mp, 0);
12522 			}
12523 			freemsg(mp);
12524 			goto reass_done;
12525 		}
12526 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12527 	}
12528 	/*
12529 	 * We have completed reassembly.  Unhook the frag header from
12530 	 * the reassembly list.
12531 	 *
12532 	 * Before we free the frag header, record the ECN info
12533 	 * to report back to the transport.
12534 	 */
12535 	ecn_info = ipf->ipf_ecn;
12536 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12537 	ipfp = ipf->ipf_ptphn;
12538 
12539 	/* We need to supply these to caller */
12540 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12541 		sum_val = ipf->ipf_checksum;
12542 	else
12543 		sum_val = 0;
12544 
12545 	mp1 = ipf->ipf_mp;
12546 	count = ipf->ipf_count;
12547 	ipf = ipf->ipf_hash_next;
12548 	if (ipf != NULL)
12549 		ipf->ipf_ptphn = ipfp;
12550 	ipfp[0] = ipf;
12551 	atomic_add_32(&ill->ill_frag_count, -count);
12552 	ASSERT(ipfb->ipfb_count >= count);
12553 	ipfb->ipfb_count -= count;
12554 	ipfb->ipfb_frag_pkts--;
12555 	mutex_exit(&ipfb->ipfb_lock);
12556 	/* Ditch the frag header. */
12557 	mp = mp1->b_cont;
12558 
12559 	freeb(mp1);
12560 
12561 	/* Restore original IP length in header. */
12562 	packet_size = (uint32_t)msgdsize(mp);
12563 	if (packet_size > IP_MAXPACKET) {
12564 		freemsg(mp);
12565 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12566 		return (B_FALSE);
12567 	}
12568 
12569 	if (DB_REF(mp) > 1) {
12570 		mblk_t *mp2 = copymsg(mp);
12571 
12572 		freemsg(mp);
12573 		if (mp2 == NULL) {
12574 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12575 			return (B_FALSE);
12576 		}
12577 		mp = mp2;
12578 	}
12579 	ipha = (ipha_t *)mp->b_rptr;
12580 
12581 	ipha->ipha_length = htons((uint16_t)packet_size);
12582 	/* We're now complete, zip the frag state */
12583 	ipha->ipha_fragment_offset_and_flags = 0;
12584 	/* Record the ECN info. */
12585 	ipha->ipha_type_of_service &= 0xFC;
12586 	ipha->ipha_type_of_service |= ecn_info;
12587 	*mpp = mp;
12588 
12589 	/* Reassembly is successful; return checksum information if needed */
12590 	if (cksum_val != NULL)
12591 		*cksum_val = sum_val;
12592 	if (cksum_flags != NULL)
12593 		*cksum_flags = sum_flags;
12594 
12595 	return (B_TRUE);
12596 }
12597 
12598 /*
12599  * Perform ip header check sum update local options.
12600  * return B_TRUE if all is well, else return B_FALSE and release
12601  * the mp. caller is responsible for decrementing ire ref cnt.
12602  */
12603 static boolean_t
12604 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12605     ip_stack_t *ipst)
12606 {
12607 	mblk_t		*first_mp;
12608 	boolean_t	mctl_present;
12609 	uint16_t	sum;
12610 
12611 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12612 	/*
12613 	 * Don't do the checksum if it has gone through AH/ESP
12614 	 * processing.
12615 	 */
12616 	if (!mctl_present) {
12617 		sum = ip_csum_hdr(ipha);
12618 		if (sum != 0) {
12619 			if (ill != NULL) {
12620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12621 			} else {
12622 				BUMP_MIB(&ipst->ips_ip_mib,
12623 				    ipIfStatsInCksumErrs);
12624 			}
12625 			freemsg(first_mp);
12626 			return (B_FALSE);
12627 		}
12628 	}
12629 
12630 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12631 		if (mctl_present)
12632 			freeb(first_mp);
12633 		return (B_FALSE);
12634 	}
12635 
12636 	return (B_TRUE);
12637 }
12638 
12639 /*
12640  * All udp packet are delivered to the local host via this routine.
12641  */
12642 void
12643 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12644     ill_t *recv_ill)
12645 {
12646 	uint32_t	sum;
12647 	uint32_t	u1;
12648 	boolean_t	mctl_present;
12649 	conn_t		*connp;
12650 	mblk_t		*first_mp;
12651 	uint16_t	*up;
12652 	ill_t		*ill = (ill_t *)q->q_ptr;
12653 	uint16_t	reass_hck_flags = 0;
12654 	ip_stack_t	*ipst;
12655 
12656 	ASSERT(recv_ill != NULL);
12657 	ipst = recv_ill->ill_ipst;
12658 
12659 #define	rptr    ((uchar_t *)ipha)
12660 
12661 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12662 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12663 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12664 	ASSERT(ill != NULL);
12665 
12666 	/*
12667 	 * FAST PATH for udp packets
12668 	 */
12669 
12670 	/* u1 is # words of IP options */
12671 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12672 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12673 
12674 	/* IP options present */
12675 	if (u1 != 0)
12676 		goto ipoptions;
12677 
12678 	/* Check the IP header checksum.  */
12679 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12680 		/* Clear the IP header h/w cksum flag */
12681 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12682 	} else if (!mctl_present) {
12683 		/*
12684 		 * Don't verify header checksum if this packet is coming
12685 		 * back from AH/ESP as we already did it.
12686 		 */
12687 #define	uph	((uint16_t *)ipha)
12688 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12689 		    uph[6] + uph[7] + uph[8] + uph[9];
12690 #undef	uph
12691 		/* finish doing IP checksum */
12692 		sum = (sum & 0xFFFF) + (sum >> 16);
12693 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12694 		if (sum != 0 && sum != 0xFFFF) {
12695 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12696 			freemsg(first_mp);
12697 			return;
12698 		}
12699 	}
12700 
12701 	/*
12702 	 * Count for SNMP of inbound packets for ire.
12703 	 * if mctl is present this might be a secure packet and
12704 	 * has already been counted for in ip_proto_input().
12705 	 */
12706 	if (!mctl_present) {
12707 		UPDATE_IB_PKT_COUNT(ire);
12708 		ire->ire_last_used_time = lbolt;
12709 	}
12710 
12711 	/* packet part of fragmented IP packet? */
12712 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12713 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12714 		goto fragmented;
12715 	}
12716 
12717 	/* u1 = IP header length (20 bytes) */
12718 	u1 = IP_SIMPLE_HDR_LENGTH;
12719 
12720 	/* packet does not contain complete IP & UDP headers */
12721 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12722 		goto udppullup;
12723 
12724 	/* up points to UDP header */
12725 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12726 #define	iphs    ((uint16_t *)ipha)
12727 
12728 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12729 	if (up[3] != 0) {
12730 		mblk_t *mp1 = mp->b_cont;
12731 		boolean_t cksum_err;
12732 		uint16_t hck_flags = 0;
12733 
12734 		/* Pseudo-header checksum */
12735 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12736 		    iphs[9] + up[2];
12737 
12738 		/*
12739 		 * Revert to software checksum calculation if the interface
12740 		 * isn't capable of checksum offload or if IPsec is present.
12741 		 */
12742 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12743 			hck_flags = DB_CKSUMFLAGS(mp);
12744 
12745 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12746 			IP_STAT(ipst, ip_in_sw_cksum);
12747 
12748 		IP_CKSUM_RECV(hck_flags, u1,
12749 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12750 		    (int32_t)((uchar_t *)up - rptr),
12751 		    mp, mp1, cksum_err);
12752 
12753 		if (cksum_err) {
12754 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12755 			if (hck_flags & HCK_FULLCKSUM)
12756 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12757 			else if (hck_flags & HCK_PARTIALCKSUM)
12758 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12759 			else
12760 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12761 
12762 			freemsg(first_mp);
12763 			return;
12764 		}
12765 	}
12766 
12767 	/* Non-fragmented broadcast or multicast packet? */
12768 	if (ire->ire_type == IRE_BROADCAST)
12769 		goto udpslowpath;
12770 
12771 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12772 	    ire->ire_zoneid, ipst)) != NULL) {
12773 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12774 		IP_STAT(ipst, ip_udp_fast_path);
12775 
12776 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12777 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12778 			freemsg(mp);
12779 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12780 		} else {
12781 			if (!mctl_present) {
12782 				BUMP_MIB(ill->ill_ip_mib,
12783 				    ipIfStatsHCInDelivers);
12784 			}
12785 			/*
12786 			 * mp and first_mp can change.
12787 			 */
12788 			if (ip_udp_check(q, connp, recv_ill,
12789 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12790 				/* Send it upstream */
12791 				(connp->conn_recv)(connp, mp, NULL);
12792 			}
12793 		}
12794 		/*
12795 		 * freeb() cannot deal with null mblk being passed
12796 		 * in and first_mp can be set to null in the call
12797 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12798 		 */
12799 		if (mctl_present && first_mp != NULL) {
12800 			freeb(first_mp);
12801 		}
12802 		CONN_DEC_REF(connp);
12803 		return;
12804 	}
12805 
12806 	/*
12807 	 * if we got here we know the packet is not fragmented and
12808 	 * has no options. The classifier could not find a conn_t and
12809 	 * most likely its an icmp packet so send it through slow path.
12810 	 */
12811 
12812 	goto udpslowpath;
12813 
12814 ipoptions:
12815 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12816 		goto slow_done;
12817 	}
12818 
12819 	UPDATE_IB_PKT_COUNT(ire);
12820 	ire->ire_last_used_time = lbolt;
12821 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12822 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12823 fragmented:
12824 		/*
12825 		 * "sum" and "reass_hck_flags" are non-zero if the
12826 		 * reassembled packet has a valid hardware computed
12827 		 * checksum information associated with it.
12828 		 */
12829 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12830 		    &reass_hck_flags)) {
12831 			goto slow_done;
12832 		}
12833 
12834 		/*
12835 		 * Make sure that first_mp points back to mp as
12836 		 * the mp we came in with could have changed in
12837 		 * ip_rput_fragment().
12838 		 */
12839 		ASSERT(!mctl_present);
12840 		ipha = (ipha_t *)mp->b_rptr;
12841 		first_mp = mp;
12842 	}
12843 
12844 	/* Now we have a complete datagram, destined for this machine. */
12845 	u1 = IPH_HDR_LENGTH(ipha);
12846 	/* Pull up the UDP header, if necessary. */
12847 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12848 udppullup:
12849 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12850 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12851 			freemsg(first_mp);
12852 			goto slow_done;
12853 		}
12854 		ipha = (ipha_t *)mp->b_rptr;
12855 	}
12856 
12857 	/*
12858 	 * Validate the checksum for the reassembled packet; for the
12859 	 * pullup case we calculate the payload checksum in software.
12860 	 */
12861 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12862 	if (up[3] != 0) {
12863 		boolean_t cksum_err;
12864 
12865 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12866 			IP_STAT(ipst, ip_in_sw_cksum);
12867 
12868 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12869 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12870 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12871 		    iphs[9] + up[2], sum, cksum_err);
12872 
12873 		if (cksum_err) {
12874 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12875 
12876 			if (reass_hck_flags & HCK_FULLCKSUM)
12877 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12878 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12879 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12880 			else
12881 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12882 
12883 			freemsg(first_mp);
12884 			goto slow_done;
12885 		}
12886 	}
12887 udpslowpath:
12888 
12889 	/* Clear hardware checksum flag to be safe */
12890 	DB_CKSUMFLAGS(mp) = 0;
12891 
12892 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12893 	    (ire->ire_type == IRE_BROADCAST),
12894 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12895 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12896 
12897 slow_done:
12898 	IP_STAT(ipst, ip_udp_slow_path);
12899 	return;
12900 
12901 #undef  iphs
12902 #undef  rptr
12903 }
12904 
12905 /* ARGSUSED */
12906 static mblk_t *
12907 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12908     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12909     ill_rx_ring_t *ill_ring)
12910 {
12911 	conn_t		*connp;
12912 	uint32_t	sum;
12913 	uint32_t	u1;
12914 	uint16_t	*up;
12915 	int		offset;
12916 	ssize_t		len;
12917 	mblk_t		*mp1;
12918 	boolean_t	syn_present = B_FALSE;
12919 	tcph_t		*tcph;
12920 	uint_t		tcph_flags;
12921 	uint_t		ip_hdr_len;
12922 	ill_t		*ill = (ill_t *)q->q_ptr;
12923 	zoneid_t	zoneid = ire->ire_zoneid;
12924 	boolean_t	cksum_err;
12925 	uint16_t	hck_flags = 0;
12926 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12927 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12928 
12929 #define	rptr	((uchar_t *)ipha)
12930 
12931 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12932 	ASSERT(ill != NULL);
12933 
12934 	/*
12935 	 * FAST PATH for tcp packets
12936 	 */
12937 
12938 	/* u1 is # words of IP options */
12939 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12940 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12941 
12942 	/* IP options present */
12943 	if (u1) {
12944 		goto ipoptions;
12945 	} else if (!mctl_present) {
12946 		/* Check the IP header checksum.  */
12947 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12948 			/* Clear the IP header h/w cksum flag */
12949 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12950 		} else if (!mctl_present) {
12951 			/*
12952 			 * Don't verify header checksum if this packet
12953 			 * is coming back from AH/ESP as we already did it.
12954 			 */
12955 #define	uph	((uint16_t *)ipha)
12956 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12957 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12958 #undef	uph
12959 			/* finish doing IP checksum */
12960 			sum = (sum & 0xFFFF) + (sum >> 16);
12961 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12962 			if (sum != 0 && sum != 0xFFFF) {
12963 				BUMP_MIB(ill->ill_ip_mib,
12964 				    ipIfStatsInCksumErrs);
12965 				goto error;
12966 			}
12967 		}
12968 	}
12969 
12970 	if (!mctl_present) {
12971 		UPDATE_IB_PKT_COUNT(ire);
12972 		ire->ire_last_used_time = lbolt;
12973 	}
12974 
12975 	/* packet part of fragmented IP packet? */
12976 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12977 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12978 		goto fragmented;
12979 	}
12980 
12981 	/* u1 = IP header length (20 bytes) */
12982 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12983 
12984 	/* does packet contain IP+TCP headers? */
12985 	len = mp->b_wptr - rptr;
12986 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12987 		IP_STAT(ipst, ip_tcppullup);
12988 		goto tcppullup;
12989 	}
12990 
12991 	/* TCP options present? */
12992 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12993 
12994 	/*
12995 	 * If options need to be pulled up, then goto tcpoptions.
12996 	 * otherwise we are still in the fast path
12997 	 */
12998 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12999 		IP_STAT(ipst, ip_tcpoptions);
13000 		goto tcpoptions;
13001 	}
13002 
13003 	/* multiple mblks of tcp data? */
13004 	if ((mp1 = mp->b_cont) != NULL) {
13005 		/* more then two? */
13006 		if (mp1->b_cont != NULL) {
13007 			IP_STAT(ipst, ip_multipkttcp);
13008 			goto multipkttcp;
13009 		}
13010 		len += mp1->b_wptr - mp1->b_rptr;
13011 	}
13012 
13013 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13014 
13015 	/* part of pseudo checksum */
13016 
13017 	/* TCP datagram length */
13018 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13019 
13020 #define	iphs    ((uint16_t *)ipha)
13021 
13022 #ifdef	_BIG_ENDIAN
13023 	u1 += IPPROTO_TCP;
13024 #else
13025 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13026 #endif
13027 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13028 
13029 	/*
13030 	 * Revert to software checksum calculation if the interface
13031 	 * isn't capable of checksum offload or if IPsec is present.
13032 	 */
13033 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13034 		hck_flags = DB_CKSUMFLAGS(mp);
13035 
13036 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13037 		IP_STAT(ipst, ip_in_sw_cksum);
13038 
13039 	IP_CKSUM_RECV(hck_flags, u1,
13040 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13041 	    (int32_t)((uchar_t *)up - rptr),
13042 	    mp, mp1, cksum_err);
13043 
13044 	if (cksum_err) {
13045 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13046 
13047 		if (hck_flags & HCK_FULLCKSUM)
13048 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13049 		else if (hck_flags & HCK_PARTIALCKSUM)
13050 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13051 		else
13052 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13053 
13054 		goto error;
13055 	}
13056 
13057 try_again:
13058 
13059 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13060 	    zoneid, ipst)) == NULL) {
13061 		/* Send the TH_RST */
13062 		goto no_conn;
13063 	}
13064 
13065 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13066 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13067 
13068 	/*
13069 	 * TCP FAST PATH for AF_INET socket.
13070 	 *
13071 	 * TCP fast path to avoid extra work. An AF_INET socket type
13072 	 * does not have facility to receive extra information via
13073 	 * ip_process or ip_add_info. Also, when the connection was
13074 	 * established, we made a check if this connection is impacted
13075 	 * by any global IPsec policy or per connection policy (a
13076 	 * policy that comes in effect later will not apply to this
13077 	 * connection). Since all this can be determined at the
13078 	 * connection establishment time, a quick check of flags
13079 	 * can avoid extra work.
13080 	 */
13081 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13082 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13083 		ASSERT(first_mp == mp);
13084 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13085 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13086 			SET_SQUEUE(mp, tcp_rput_data, connp);
13087 			return (mp);
13088 		}
13089 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13090 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13091 		SET_SQUEUE(mp, tcp_input, connp);
13092 		return (mp);
13093 	}
13094 
13095 	if (tcph_flags == TH_SYN) {
13096 		if (IPCL_IS_TCP(connp)) {
13097 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13098 			DB_CKSUMSTART(mp) =
13099 			    (intptr_t)ip_squeue_get(ill_ring);
13100 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13101 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13102 				BUMP_MIB(ill->ill_ip_mib,
13103 				    ipIfStatsHCInDelivers);
13104 				SET_SQUEUE(mp, connp->conn_recv, connp);
13105 				return (mp);
13106 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13107 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13108 				BUMP_MIB(ill->ill_ip_mib,
13109 				    ipIfStatsHCInDelivers);
13110 				ip_squeue_enter_unbound++;
13111 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13112 				    connp);
13113 				return (mp);
13114 			}
13115 			syn_present = B_TRUE;
13116 		}
13117 	}
13118 
13119 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13120 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13121 
13122 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13123 		/* No need to send this packet to TCP */
13124 		if ((flags & TH_RST) || (flags & TH_URG)) {
13125 			CONN_DEC_REF(connp);
13126 			freemsg(first_mp);
13127 			return (NULL);
13128 		}
13129 		if (flags & TH_ACK) {
13130 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13131 			    ipst->ips_netstack->netstack_tcp, connp);
13132 			CONN_DEC_REF(connp);
13133 			return (NULL);
13134 		}
13135 
13136 		CONN_DEC_REF(connp);
13137 		freemsg(first_mp);
13138 		return (NULL);
13139 	}
13140 
13141 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13142 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13143 		    ipha, NULL, mctl_present);
13144 		if (first_mp == NULL) {
13145 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13146 			CONN_DEC_REF(connp);
13147 			return (NULL);
13148 		}
13149 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13150 			ASSERT(syn_present);
13151 			if (mctl_present) {
13152 				ASSERT(first_mp != mp);
13153 				first_mp->b_datap->db_struioflag |=
13154 				    STRUIO_POLICY;
13155 			} else {
13156 				ASSERT(first_mp == mp);
13157 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13158 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13159 			}
13160 		} else {
13161 			/*
13162 			 * Discard first_mp early since we're dealing with a
13163 			 * fully-connected conn_t and tcp doesn't do policy in
13164 			 * this case.
13165 			 */
13166 			if (mctl_present) {
13167 				freeb(first_mp);
13168 				mctl_present = B_FALSE;
13169 			}
13170 			first_mp = mp;
13171 		}
13172 	}
13173 
13174 	/* Initiate IPPF processing for fastpath */
13175 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13176 		uint32_t	ill_index;
13177 
13178 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13179 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13180 		if (mp == NULL) {
13181 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13182 			    "deferred/dropped during IPPF processing\n"));
13183 			CONN_DEC_REF(connp);
13184 			if (mctl_present)
13185 				freeb(first_mp);
13186 			return (NULL);
13187 		} else if (mctl_present) {
13188 			/*
13189 			 * ip_process might return a new mp.
13190 			 */
13191 			ASSERT(first_mp != mp);
13192 			first_mp->b_cont = mp;
13193 		} else {
13194 			first_mp = mp;
13195 		}
13196 
13197 	}
13198 
13199 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13200 		/*
13201 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13202 		 * make sure IPF_RECVIF is passed to ip_add_info.
13203 		 */
13204 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13205 		    IPCL_ZONEID(connp), ipst);
13206 		if (mp == NULL) {
13207 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13208 			CONN_DEC_REF(connp);
13209 			if (mctl_present)
13210 				freeb(first_mp);
13211 			return (NULL);
13212 		} else if (mctl_present) {
13213 			/*
13214 			 * ip_add_info might return a new mp.
13215 			 */
13216 			ASSERT(first_mp != mp);
13217 			first_mp->b_cont = mp;
13218 		} else {
13219 			first_mp = mp;
13220 		}
13221 	}
13222 
13223 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13224 	if (IPCL_IS_TCP(connp)) {
13225 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13226 		return (first_mp);
13227 	} else {
13228 		/* SOCK_RAW, IPPROTO_TCP case */
13229 		(connp->conn_recv)(connp, first_mp, NULL);
13230 		CONN_DEC_REF(connp);
13231 		return (NULL);
13232 	}
13233 
13234 no_conn:
13235 	/* Initiate IPPf processing, if needed. */
13236 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13237 		uint32_t ill_index;
13238 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13239 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13240 		if (first_mp == NULL) {
13241 			return (NULL);
13242 		}
13243 	}
13244 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13245 
13246 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13247 	    ipst->ips_netstack->netstack_tcp, NULL);
13248 	return (NULL);
13249 ipoptions:
13250 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13251 		goto slow_done;
13252 	}
13253 
13254 	UPDATE_IB_PKT_COUNT(ire);
13255 	ire->ire_last_used_time = lbolt;
13256 
13257 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13258 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13259 fragmented:
13260 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13261 			if (mctl_present)
13262 				freeb(first_mp);
13263 			goto slow_done;
13264 		}
13265 		/*
13266 		 * Make sure that first_mp points back to mp as
13267 		 * the mp we came in with could have changed in
13268 		 * ip_rput_fragment().
13269 		 */
13270 		ASSERT(!mctl_present);
13271 		ipha = (ipha_t *)mp->b_rptr;
13272 		first_mp = mp;
13273 	}
13274 
13275 	/* Now we have a complete datagram, destined for this machine. */
13276 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13277 
13278 	len = mp->b_wptr - mp->b_rptr;
13279 	/* Pull up a minimal TCP header, if necessary. */
13280 	if (len < (u1 + 20)) {
13281 tcppullup:
13282 		if (!pullupmsg(mp, u1 + 20)) {
13283 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13284 			goto error;
13285 		}
13286 		ipha = (ipha_t *)mp->b_rptr;
13287 		len = mp->b_wptr - mp->b_rptr;
13288 	}
13289 
13290 	/*
13291 	 * Extract the offset field from the TCP header.  As usual, we
13292 	 * try to help the compiler more than the reader.
13293 	 */
13294 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13295 	if (offset != 5) {
13296 tcpoptions:
13297 		if (offset < 5) {
13298 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13299 			goto error;
13300 		}
13301 		/*
13302 		 * There must be TCP options.
13303 		 * Make sure we can grab them.
13304 		 */
13305 		offset <<= 2;
13306 		offset += u1;
13307 		if (len < offset) {
13308 			if (!pullupmsg(mp, offset)) {
13309 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13310 				goto error;
13311 			}
13312 			ipha = (ipha_t *)mp->b_rptr;
13313 			len = mp->b_wptr - rptr;
13314 		}
13315 	}
13316 
13317 	/* Get the total packet length in len, including headers. */
13318 	if (mp->b_cont) {
13319 multipkttcp:
13320 		len = msgdsize(mp);
13321 	}
13322 
13323 	/*
13324 	 * Check the TCP checksum by pulling together the pseudo-
13325 	 * header checksum, and passing it to ip_csum to be added in
13326 	 * with the TCP datagram.
13327 	 *
13328 	 * Since we are not using the hwcksum if available we must
13329 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13330 	 * If either of these fails along the way the mblk is freed.
13331 	 * If this logic ever changes and mblk is reused to say send
13332 	 * ICMP's back, then this flag may need to be cleared in
13333 	 * other places as well.
13334 	 */
13335 	DB_CKSUMFLAGS(mp) = 0;
13336 
13337 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13338 
13339 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13340 #ifdef	_BIG_ENDIAN
13341 	u1 += IPPROTO_TCP;
13342 #else
13343 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13344 #endif
13345 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13346 	/*
13347 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13348 	 */
13349 	IP_STAT(ipst, ip_in_sw_cksum);
13350 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13351 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13352 		goto error;
13353 	}
13354 
13355 	IP_STAT(ipst, ip_tcp_slow_path);
13356 	goto try_again;
13357 #undef  iphs
13358 #undef  rptr
13359 
13360 error:
13361 	freemsg(first_mp);
13362 slow_done:
13363 	return (NULL);
13364 }
13365 
13366 /* ARGSUSED */
13367 static void
13368 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13369     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13370 {
13371 	conn_t		*connp;
13372 	uint32_t	sum;
13373 	uint32_t	u1;
13374 	ssize_t		len;
13375 	sctp_hdr_t	*sctph;
13376 	zoneid_t	zoneid = ire->ire_zoneid;
13377 	uint32_t	pktsum;
13378 	uint32_t	calcsum;
13379 	uint32_t	ports;
13380 	in6_addr_t	map_src, map_dst;
13381 	ill_t		*ill = (ill_t *)q->q_ptr;
13382 	ip_stack_t	*ipst;
13383 	sctp_stack_t	*sctps;
13384 	boolean_t	sctp_csum_err = B_FALSE;
13385 
13386 	ASSERT(recv_ill != NULL);
13387 	ipst = recv_ill->ill_ipst;
13388 	sctps = ipst->ips_netstack->netstack_sctp;
13389 
13390 #define	rptr	((uchar_t *)ipha)
13391 
13392 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13393 	ASSERT(ill != NULL);
13394 
13395 	/* u1 is # words of IP options */
13396 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13397 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13398 
13399 	/* IP options present */
13400 	if (u1 > 0) {
13401 		goto ipoptions;
13402 	} else {
13403 		/* Check the IP header checksum.  */
13404 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13405 		    !mctl_present) {
13406 #define	uph	((uint16_t *)ipha)
13407 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13408 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13409 #undef	uph
13410 			/* finish doing IP checksum */
13411 			sum = (sum & 0xFFFF) + (sum >> 16);
13412 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13413 			/*
13414 			 * Don't verify header checksum if this packet
13415 			 * is coming back from AH/ESP as we already did it.
13416 			 */
13417 			if (sum != 0 && sum != 0xFFFF) {
13418 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13419 				goto error;
13420 			}
13421 		}
13422 		/*
13423 		 * Since there is no SCTP h/w cksum support yet, just
13424 		 * clear the flag.
13425 		 */
13426 		DB_CKSUMFLAGS(mp) = 0;
13427 	}
13428 
13429 	/*
13430 	 * Don't verify header checksum if this packet is coming
13431 	 * back from AH/ESP as we already did it.
13432 	 */
13433 	if (!mctl_present) {
13434 		UPDATE_IB_PKT_COUNT(ire);
13435 		ire->ire_last_used_time = lbolt;
13436 	}
13437 
13438 	/* packet part of fragmented IP packet? */
13439 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13440 	if (u1 & (IPH_MF | IPH_OFFSET))
13441 		goto fragmented;
13442 
13443 	/* u1 = IP header length (20 bytes) */
13444 	u1 = IP_SIMPLE_HDR_LENGTH;
13445 
13446 find_sctp_client:
13447 	/* Pullup if we don't have the sctp common header. */
13448 	len = MBLKL(mp);
13449 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13450 		if (mp->b_cont == NULL ||
13451 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13452 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13453 			goto error;
13454 		}
13455 		ipha = (ipha_t *)mp->b_rptr;
13456 		len = MBLKL(mp);
13457 	}
13458 
13459 	sctph = (sctp_hdr_t *)(rptr + u1);
13460 #ifdef	DEBUG
13461 	if (!skip_sctp_cksum) {
13462 #endif
13463 		pktsum = sctph->sh_chksum;
13464 		sctph->sh_chksum = 0;
13465 		calcsum = sctp_cksum(mp, u1);
13466 		sctph->sh_chksum = pktsum;
13467 		if (calcsum != pktsum)
13468 			sctp_csum_err = B_TRUE;
13469 #ifdef	DEBUG	/* skip_sctp_cksum */
13470 	}
13471 #endif
13472 	/* get the ports */
13473 	ports = *(uint32_t *)&sctph->sh_sport;
13474 
13475 	IRE_REFRELE(ire);
13476 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13477 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13478 	if (sctp_csum_err) {
13479 		/*
13480 		 * No potential sctp checksum errors go to the Sun
13481 		 * sctp stack however they might be Adler-32 summed
13482 		 * packets a userland stack bound to a raw IP socket
13483 		 * could reasonably use. Note though that Adler-32 is
13484 		 * a long deprecated algorithm and customer sctp
13485 		 * networks should eventually migrate to CRC-32 at
13486 		 * which time this facility should be removed.
13487 		 */
13488 		flags |= IP_FF_SCTP_CSUM_ERR;
13489 		goto no_conn;
13490 	}
13491 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13492 	    sctps)) == NULL) {
13493 		/* Check for raw socket or OOTB handling */
13494 		goto no_conn;
13495 	}
13496 
13497 	/* Found a client; up it goes */
13498 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13499 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13500 	return;
13501 
13502 no_conn:
13503 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13504 	    ports, mctl_present, flags, B_TRUE, zoneid);
13505 	return;
13506 
13507 ipoptions:
13508 	DB_CKSUMFLAGS(mp) = 0;
13509 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13510 		goto slow_done;
13511 
13512 	UPDATE_IB_PKT_COUNT(ire);
13513 	ire->ire_last_used_time = lbolt;
13514 
13515 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13516 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13517 fragmented:
13518 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13519 			goto slow_done;
13520 		/*
13521 		 * Make sure that first_mp points back to mp as
13522 		 * the mp we came in with could have changed in
13523 		 * ip_rput_fragment().
13524 		 */
13525 		ASSERT(!mctl_present);
13526 		ipha = (ipha_t *)mp->b_rptr;
13527 		first_mp = mp;
13528 	}
13529 
13530 	/* Now we have a complete datagram, destined for this machine. */
13531 	u1 = IPH_HDR_LENGTH(ipha);
13532 	goto find_sctp_client;
13533 #undef  iphs
13534 #undef  rptr
13535 
13536 error:
13537 	freemsg(first_mp);
13538 slow_done:
13539 	IRE_REFRELE(ire);
13540 }
13541 
13542 #define	VER_BITS	0xF0
13543 #define	VERSION_6	0x60
13544 
13545 static boolean_t
13546 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13547     ipaddr_t *dstp, ip_stack_t *ipst)
13548 {
13549 	uint_t	opt_len;
13550 	ipha_t *ipha;
13551 	ssize_t len;
13552 	uint_t	pkt_len;
13553 
13554 	ASSERT(ill != NULL);
13555 	IP_STAT(ipst, ip_ipoptions);
13556 	ipha = *iphapp;
13557 
13558 #define	rptr    ((uchar_t *)ipha)
13559 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13560 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13561 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13562 		freemsg(mp);
13563 		return (B_FALSE);
13564 	}
13565 
13566 	/* multiple mblk or too short */
13567 	pkt_len = ntohs(ipha->ipha_length);
13568 
13569 	/* Get the number of words of IP options in the IP header. */
13570 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13571 	if (opt_len) {
13572 		/* IP Options present!  Validate and process. */
13573 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13574 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13575 			goto done;
13576 		}
13577 		/*
13578 		 * Recompute complete header length and make sure we
13579 		 * have access to all of it.
13580 		 */
13581 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13582 		if (len > (mp->b_wptr - rptr)) {
13583 			if (len > pkt_len) {
13584 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13585 				goto done;
13586 			}
13587 			if (!pullupmsg(mp, len)) {
13588 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13589 				goto done;
13590 			}
13591 			ipha = (ipha_t *)mp->b_rptr;
13592 		}
13593 		/*
13594 		 * Go off to ip_rput_options which returns the next hop
13595 		 * destination address, which may have been affected
13596 		 * by source routing.
13597 		 */
13598 		IP_STAT(ipst, ip_opt);
13599 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13600 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13601 			return (B_FALSE);
13602 		}
13603 	}
13604 	*iphapp = ipha;
13605 	return (B_TRUE);
13606 done:
13607 	/* clear b_prev - used by ip_mroute_decap */
13608 	mp->b_prev = NULL;
13609 	freemsg(mp);
13610 	return (B_FALSE);
13611 #undef  rptr
13612 }
13613 
13614 /*
13615  * Deal with the fact that there is no ire for the destination.
13616  */
13617 static ire_t *
13618 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13619 {
13620 	ipha_t	*ipha;
13621 	ill_t	*ill;
13622 	ire_t	*ire;
13623 	ip_stack_t *ipst;
13624 	enum	ire_forward_action ret_action;
13625 
13626 	ipha = (ipha_t *)mp->b_rptr;
13627 	ill = (ill_t *)q->q_ptr;
13628 
13629 	ASSERT(ill != NULL);
13630 	ipst = ill->ill_ipst;
13631 
13632 	/*
13633 	 * No IRE for this destination, so it can't be for us.
13634 	 * Unless we are forwarding, drop the packet.
13635 	 * We have to let source routed packets through
13636 	 * since we don't yet know if they are 'ping -l'
13637 	 * packets i.e. if they will go out over the
13638 	 * same interface as they came in on.
13639 	 */
13640 	if (ll_multicast) {
13641 		freemsg(mp);
13642 		return (NULL);
13643 	}
13644 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13645 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13646 		freemsg(mp);
13647 		return (NULL);
13648 	}
13649 
13650 	/*
13651 	 * Mark this packet as having originated externally.
13652 	 *
13653 	 * For non-forwarding code path, ire_send later double
13654 	 * checks this interface to see if it is still exists
13655 	 * post-ARP resolution.
13656 	 *
13657 	 * Also, IPQOS uses this to differentiate between
13658 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13659 	 * QOS packet processing in ip_wput_attach_llhdr().
13660 	 * The QoS module can mark the b_band for a fastpath message
13661 	 * or the dl_priority field in a unitdata_req header for
13662 	 * CoS marking. This info can only be found in
13663 	 * ip_wput_attach_llhdr().
13664 	 */
13665 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13666 	/*
13667 	 * Clear the indication that this may have a hardware checksum
13668 	 * as we are not using it
13669 	 */
13670 	DB_CKSUMFLAGS(mp) = 0;
13671 
13672 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13673 	    msg_getlabel(mp), ipst);
13674 
13675 	if (ire == NULL && ret_action == Forward_check_multirt) {
13676 		/* Let ip_newroute handle CGTP  */
13677 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13678 		return (NULL);
13679 	}
13680 
13681 	if (ire != NULL)
13682 		return (ire);
13683 
13684 	mp->b_prev = mp->b_next = 0;
13685 
13686 	if (ret_action == Forward_blackhole) {
13687 		freemsg(mp);
13688 		return (NULL);
13689 	}
13690 	/* send icmp unreachable */
13691 	q = WR(q);
13692 	/* Sent by forwarding path, and router is global zone */
13693 	if (ip_source_routed(ipha, ipst)) {
13694 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13695 		    GLOBAL_ZONEID, ipst);
13696 	} else {
13697 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13698 		    ipst);
13699 	}
13700 
13701 	return (NULL);
13702 
13703 }
13704 
13705 /*
13706  * check ip header length and align it.
13707  */
13708 static boolean_t
13709 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13710 {
13711 	ssize_t len;
13712 	ill_t *ill;
13713 	ipha_t	*ipha;
13714 
13715 	len = MBLKL(mp);
13716 
13717 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13718 		ill = (ill_t *)q->q_ptr;
13719 
13720 		if (!OK_32PTR(mp->b_rptr))
13721 			IP_STAT(ipst, ip_notaligned1);
13722 		else
13723 			IP_STAT(ipst, ip_notaligned2);
13724 		/* Guard against bogus device drivers */
13725 		if (len < 0) {
13726 			/* clear b_prev - used by ip_mroute_decap */
13727 			mp->b_prev = NULL;
13728 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13729 			freemsg(mp);
13730 			return (B_FALSE);
13731 		}
13732 
13733 		if (ip_rput_pullups++ == 0) {
13734 			ipha = (ipha_t *)mp->b_rptr;
13735 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13736 			    "ip_check_and_align_header: %s forced us to "
13737 			    " pullup pkt, hdr len %ld, hdr addr %p",
13738 			    ill->ill_name, len, (void *)ipha);
13739 		}
13740 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13741 			/* clear b_prev - used by ip_mroute_decap */
13742 			mp->b_prev = NULL;
13743 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13744 			freemsg(mp);
13745 			return (B_FALSE);
13746 		}
13747 	}
13748 	return (B_TRUE);
13749 }
13750 
13751 /*
13752  * Handle the situation where a packet came in on `ill' but matched an IRE
13753  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13754  * for interface statistics.
13755  */
13756 ire_t *
13757 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13758 {
13759 	ire_t		*new_ire;
13760 	ill_t		*ire_ill;
13761 	uint_t		ifindex;
13762 	ip_stack_t	*ipst = ill->ill_ipst;
13763 	boolean_t	strict_check = B_FALSE;
13764 
13765 	/*
13766 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13767 	 * issue (e.g. packet received on an underlying interface matched an
13768 	 * IRE_LOCAL on its associated group interface).
13769 	 */
13770 	if (ire->ire_rfq != NULL &&
13771 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13772 		return (ire);
13773 	}
13774 
13775 	/*
13776 	 * Do another ire lookup here, using the ingress ill, to see if the
13777 	 * interface is in a usesrc group.
13778 	 * As long as the ills belong to the same group, we don't consider
13779 	 * them to be arriving on the wrong interface. Thus, if the switch
13780 	 * is doing inbound load spreading, we won't drop packets when the
13781 	 * ip*_strict_dst_multihoming switch is on.
13782 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13783 	 * where the local address may not be unique. In this case we were
13784 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13785 	 * actually returned. The new lookup, which is more specific, should
13786 	 * only find the IRE_LOCAL associated with the ingress ill if one
13787 	 * exists.
13788 	 */
13789 
13790 	if (ire->ire_ipversion == IPV4_VERSION) {
13791 		if (ipst->ips_ip_strict_dst_multihoming)
13792 			strict_check = B_TRUE;
13793 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13794 		    ill->ill_ipif, ALL_ZONES, NULL,
13795 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13796 	} else {
13797 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13798 		if (ipst->ips_ipv6_strict_dst_multihoming)
13799 			strict_check = B_TRUE;
13800 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13801 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13802 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13803 	}
13804 	/*
13805 	 * If the same ire that was returned in ip_input() is found then this
13806 	 * is an indication that usesrc groups are in use. The packet
13807 	 * arrived on a different ill in the group than the one associated with
13808 	 * the destination address.  If a different ire was found then the same
13809 	 * IP address must be hosted on multiple ills. This is possible with
13810 	 * unnumbered point2point interfaces. We switch to use this new ire in
13811 	 * order to have accurate interface statistics.
13812 	 */
13813 	if (new_ire != NULL) {
13814 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13815 			ire_refrele(ire);
13816 			ire = new_ire;
13817 		} else {
13818 			ire_refrele(new_ire);
13819 		}
13820 		return (ire);
13821 	} else if ((ire->ire_rfq == NULL) &&
13822 	    (ire->ire_ipversion == IPV4_VERSION)) {
13823 		/*
13824 		 * The best match could have been the original ire which
13825 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13826 		 * the strict multihoming checks are irrelevant as we consider
13827 		 * local addresses hosted on lo0 to be interface agnostic. We
13828 		 * only expect a null ire_rfq on IREs which are associated with
13829 		 * lo0 hence we can return now.
13830 		 */
13831 		return (ire);
13832 	}
13833 
13834 	/*
13835 	 * Chase pointers once and store locally.
13836 	 */
13837 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13838 	    (ill_t *)(ire->ire_rfq->q_ptr);
13839 	ifindex = ill->ill_usesrc_ifindex;
13840 
13841 	/*
13842 	 * Check if it's a legal address on the 'usesrc' interface.
13843 	 */
13844 	if ((ifindex != 0) && (ire_ill != NULL) &&
13845 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13846 		return (ire);
13847 	}
13848 
13849 	/*
13850 	 * If the ip*_strict_dst_multihoming switch is on then we can
13851 	 * only accept this packet if the interface is marked as routing.
13852 	 */
13853 	if (!(strict_check))
13854 		return (ire);
13855 
13856 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13857 	    ILLF_ROUTER) != 0) {
13858 		return (ire);
13859 	}
13860 
13861 	ire_refrele(ire);
13862 	return (NULL);
13863 }
13864 
13865 /*
13866  *
13867  * This is the fast forward path. If we are here, we dont need to
13868  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13869  * needed to find the nexthop in this case is much simpler
13870  */
13871 ire_t *
13872 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13873 {
13874 	ipha_t	*ipha;
13875 	ire_t	*src_ire;
13876 	ill_t	*stq_ill;
13877 	uint_t	hlen;
13878 	uint_t	pkt_len;
13879 	uint32_t sum;
13880 	queue_t	*dev_q;
13881 	ip_stack_t *ipst = ill->ill_ipst;
13882 	mblk_t *fpmp;
13883 	enum	ire_forward_action ret_action;
13884 
13885 	ipha = (ipha_t *)mp->b_rptr;
13886 
13887 	if (ire != NULL &&
13888 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13889 	    ire->ire_zoneid != ALL_ZONES) {
13890 		/*
13891 		 * Should only use IREs that are visible to the global
13892 		 * zone for forwarding.
13893 		 */
13894 		ire_refrele(ire);
13895 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13896 		/*
13897 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13898 		 * transient cases. In such case, just drop the packet
13899 		 */
13900 		if (ire->ire_type != IRE_CACHE)
13901 			goto drop;
13902 	}
13903 
13904 	/*
13905 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13906 	 * The loopback address check for both src and dst has already
13907 	 * been checked in ip_input
13908 	 */
13909 
13910 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13911 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13912 		goto drop;
13913 	}
13914 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13915 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13916 
13917 	if (src_ire != NULL) {
13918 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13919 		ire_refrele(src_ire);
13920 		goto drop;
13921 	}
13922 
13923 	/* No ire cache of nexthop. So first create one  */
13924 	if (ire == NULL) {
13925 
13926 		ire = ire_forward_simple(dst, &ret_action, ipst);
13927 
13928 		/*
13929 		 * We only come to ip_fast_forward if ip_cgtp_filter
13930 		 * is not set. So ire_forward() should not return with
13931 		 * Forward_check_multirt as the next action.
13932 		 */
13933 		ASSERT(ret_action != Forward_check_multirt);
13934 		if (ire == NULL) {
13935 			/* An attempt was made to forward the packet */
13936 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13937 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13938 			mp->b_prev = mp->b_next = 0;
13939 			/* send icmp unreachable */
13940 			/* Sent by forwarding path, and router is global zone */
13941 			if (ret_action == Forward_ret_icmp_err) {
13942 				if (ip_source_routed(ipha, ipst)) {
13943 					icmp_unreachable(ill->ill_wq, mp,
13944 					    ICMP_SOURCE_ROUTE_FAILED,
13945 					    GLOBAL_ZONEID, ipst);
13946 				} else {
13947 					icmp_unreachable(ill->ill_wq, mp,
13948 					    ICMP_HOST_UNREACHABLE,
13949 					    GLOBAL_ZONEID, ipst);
13950 				}
13951 			} else {
13952 				freemsg(mp);
13953 			}
13954 			return (NULL);
13955 		}
13956 	}
13957 
13958 	/*
13959 	 * Forwarding fastpath exception case:
13960 	 * If any of the following are true, we take the slowpath:
13961 	 *	o forwarding is not enabled
13962 	 *	o incoming and outgoing interface are the same, or in the same
13963 	 *	  IPMP group.
13964 	 *	o corresponding ire is in incomplete state
13965 	 *	o packet needs fragmentation
13966 	 *	o ARP cache is not resolved
13967 	 *
13968 	 * The codeflow from here on is thus:
13969 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13970 	 */
13971 	pkt_len = ntohs(ipha->ipha_length);
13972 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13973 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13974 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13975 	    (ire->ire_nce == NULL) ||
13976 	    (pkt_len > ire->ire_max_frag) ||
13977 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13978 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13979 	    ipha->ipha_ttl <= 1) {
13980 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13981 		    ipha, ill, B_FALSE, B_TRUE);
13982 		return (ire);
13983 	}
13984 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13985 
13986 	DTRACE_PROBE4(ip4__forwarding__start,
13987 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13988 
13989 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13990 	    ipst->ips_ipv4firewall_forwarding,
13991 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13992 
13993 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13994 
13995 	if (mp == NULL)
13996 		goto drop;
13997 
13998 	mp->b_datap->db_struioun.cksum.flags = 0;
13999 	/* Adjust the checksum to reflect the ttl decrement. */
14000 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14001 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14002 	ipha->ipha_ttl--;
14003 
14004 	/*
14005 	 * Write the link layer header.  We can do this safely here,
14006 	 * because we have already tested to make sure that the IP
14007 	 * policy is not set, and that we have a fast path destination
14008 	 * header.
14009 	 */
14010 	mp->b_rptr -= hlen;
14011 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14012 
14013 	UPDATE_IB_PKT_COUNT(ire);
14014 	ire->ire_last_used_time = lbolt;
14015 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14016 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14017 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14018 
14019 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14020 		dev_q = ire->ire_stq->q_next;
14021 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14022 			goto indiscard;
14023 	}
14024 
14025 	DTRACE_PROBE4(ip4__physical__out__start,
14026 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14027 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14028 	    ipst->ips_ipv4firewall_physical_out,
14029 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14030 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14031 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14032 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14033 	    ip6_t *, NULL, int, 0);
14034 
14035 	if (mp != NULL) {
14036 		if (ipst->ips_ipobs_enabled) {
14037 			zoneid_t szone;
14038 
14039 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14040 			    ipst, ALL_ZONES);
14041 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14042 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14043 		}
14044 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14045 	}
14046 	return (ire);
14047 
14048 indiscard:
14049 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14050 drop:
14051 	if (mp != NULL)
14052 		freemsg(mp);
14053 	return (ire);
14054 
14055 }
14056 
14057 /*
14058  * This function is called in the forwarding slowpath, when
14059  * either the ire lacks the link-layer address, or the packet needs
14060  * further processing(eg. fragmentation), before transmission.
14061  */
14062 
14063 static void
14064 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14065     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14066 {
14067 	queue_t		*dev_q;
14068 	ire_t		*src_ire;
14069 	ip_stack_t	*ipst = ill->ill_ipst;
14070 	boolean_t	same_illgrp = B_FALSE;
14071 
14072 	ASSERT(ire->ire_stq != NULL);
14073 
14074 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14075 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14076 
14077 	/*
14078 	 * If the caller of this function is ip_fast_forward() skip the
14079 	 * next three checks as it does not apply.
14080 	 */
14081 	if (from_ip_fast_forward)
14082 		goto skip;
14083 
14084 	if (ll_multicast != 0) {
14085 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14086 		goto drop_pkt;
14087 	}
14088 
14089 	/*
14090 	 * check if ipha_src is a broadcast address. Note that this
14091 	 * check is redundant when we get here from ip_fast_forward()
14092 	 * which has already done this check. However, since we can
14093 	 * also get here from ip_rput_process_broadcast() or, for
14094 	 * for the slow path through ip_fast_forward(), we perform
14095 	 * the check again for code-reusability
14096 	 */
14097 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14098 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14099 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14100 		if (src_ire != NULL)
14101 			ire_refrele(src_ire);
14102 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14103 		ip2dbg(("ip_rput_process_forward: Received packet with"
14104 		    " bad src/dst address on %s\n", ill->ill_name));
14105 		goto drop_pkt;
14106 	}
14107 
14108 	/*
14109 	 * Check if we want to forward this one at this time.
14110 	 * We allow source routed packets on a host provided that
14111 	 * they go out the same ill or illgrp as they came in on.
14112 	 *
14113 	 * XXX To be quicker, we may wish to not chase pointers to
14114 	 * get the ILLF_ROUTER flag and instead store the
14115 	 * forwarding policy in the ire.  An unfortunate
14116 	 * side-effect of that would be requiring an ire flush
14117 	 * whenever the ILLF_ROUTER flag changes.
14118 	 */
14119 skip:
14120 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14121 
14122 	if (((ill->ill_flags &
14123 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14124 	    !(ip_source_routed(ipha, ipst) &&
14125 	    (ire->ire_rfq == q || same_illgrp))) {
14126 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14127 		if (ip_source_routed(ipha, ipst)) {
14128 			q = WR(q);
14129 			/*
14130 			 * Clear the indication that this may have
14131 			 * hardware checksum as we are not using it.
14132 			 */
14133 			DB_CKSUMFLAGS(mp) = 0;
14134 			/* Sent by forwarding path, and router is global zone */
14135 			icmp_unreachable(q, mp,
14136 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14137 			return;
14138 		}
14139 		goto drop_pkt;
14140 	}
14141 
14142 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14143 
14144 	/* Packet is being forwarded. Turning off hwcksum flag. */
14145 	DB_CKSUMFLAGS(mp) = 0;
14146 	if (ipst->ips_ip_g_send_redirects) {
14147 		/*
14148 		 * Check whether the incoming interface and outgoing
14149 		 * interface is part of the same group. If so,
14150 		 * send redirects.
14151 		 *
14152 		 * Check the source address to see if it originated
14153 		 * on the same logical subnet it is going back out on.
14154 		 * If so, we should be able to send it a redirect.
14155 		 * Avoid sending a redirect if the destination
14156 		 * is directly connected (i.e., ipha_dst is the same
14157 		 * as ire_gateway_addr or the ire_addr of the
14158 		 * nexthop IRE_CACHE ), or if the packet was source
14159 		 * routed out this interface.
14160 		 */
14161 		ipaddr_t src, nhop;
14162 		mblk_t	*mp1;
14163 		ire_t	*nhop_ire = NULL;
14164 
14165 		/*
14166 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14167 		 * If so, send redirects.
14168 		 */
14169 		if ((ire->ire_rfq == q || same_illgrp) &&
14170 		    !ip_source_routed(ipha, ipst)) {
14171 
14172 			nhop = (ire->ire_gateway_addr != 0 ?
14173 			    ire->ire_gateway_addr : ire->ire_addr);
14174 
14175 			if (ipha->ipha_dst == nhop) {
14176 				/*
14177 				 * We avoid sending a redirect if the
14178 				 * destination is directly connected
14179 				 * because it is possible that multiple
14180 				 * IP subnets may have been configured on
14181 				 * the link, and the source may not
14182 				 * be on the same subnet as ip destination,
14183 				 * even though they are on the same
14184 				 * physical link.
14185 				 */
14186 				goto sendit;
14187 			}
14188 
14189 			src = ipha->ipha_src;
14190 
14191 			/*
14192 			 * We look up the interface ire for the nexthop,
14193 			 * to see if ipha_src is in the same subnet
14194 			 * as the nexthop.
14195 			 *
14196 			 * Note that, if, in the future, IRE_CACHE entries
14197 			 * are obsoleted,  this lookup will not be needed,
14198 			 * as the ire passed to this function will be the
14199 			 * same as the nhop_ire computed below.
14200 			 */
14201 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14202 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14203 			    0, NULL, MATCH_IRE_TYPE, ipst);
14204 
14205 			if (nhop_ire != NULL) {
14206 				if ((src & nhop_ire->ire_mask) ==
14207 				    (nhop & nhop_ire->ire_mask)) {
14208 					/*
14209 					 * The source is directly connected.
14210 					 * Just copy the ip header (which is
14211 					 * in the first mblk)
14212 					 */
14213 					mp1 = copyb(mp);
14214 					if (mp1 != NULL) {
14215 						icmp_send_redirect(WR(q), mp1,
14216 						    nhop, ipst);
14217 					}
14218 				}
14219 				ire_refrele(nhop_ire);
14220 			}
14221 		}
14222 	}
14223 sendit:
14224 	dev_q = ire->ire_stq->q_next;
14225 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14226 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14227 		freemsg(mp);
14228 		return;
14229 	}
14230 
14231 	ip_rput_forward(ire, ipha, mp, ill);
14232 	return;
14233 
14234 drop_pkt:
14235 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14236 	freemsg(mp);
14237 }
14238 
14239 ire_t *
14240 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14241     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14242 {
14243 	queue_t		*q;
14244 	uint16_t	hcksumflags;
14245 	ip_stack_t	*ipst = ill->ill_ipst;
14246 
14247 	q = *qp;
14248 
14249 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14250 
14251 	/*
14252 	 * Clear the indication that this may have hardware
14253 	 * checksum as we are not using it for forwarding.
14254 	 */
14255 	hcksumflags = DB_CKSUMFLAGS(mp);
14256 	DB_CKSUMFLAGS(mp) = 0;
14257 
14258 	/*
14259 	 * Directed broadcast forwarding: if the packet came in over a
14260 	 * different interface then it is routed out over we can forward it.
14261 	 */
14262 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14263 		ire_refrele(ire);
14264 		freemsg(mp);
14265 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14266 		return (NULL);
14267 	}
14268 	/*
14269 	 * For multicast we have set dst to be INADDR_BROADCAST
14270 	 * for delivering to all STREAMS.
14271 	 */
14272 	if (!CLASSD(ipha->ipha_dst)) {
14273 		ire_t *new_ire;
14274 		ipif_t *ipif;
14275 
14276 		ipif = ipif_get_next_ipif(NULL, ill);
14277 		if (ipif == NULL) {
14278 discard:		ire_refrele(ire);
14279 			freemsg(mp);
14280 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14281 			return (NULL);
14282 		}
14283 		new_ire = ire_ctable_lookup(dst, 0, 0,
14284 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14285 		ipif_refrele(ipif);
14286 
14287 		if (new_ire != NULL) {
14288 			/*
14289 			 * If the matching IRE_BROADCAST is part of an IPMP
14290 			 * group, then drop the packet unless our ill has been
14291 			 * nominated to receive for the group.
14292 			 */
14293 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14294 			    new_ire->ire_rfq != q) {
14295 				ire_refrele(new_ire);
14296 				goto discard;
14297 			}
14298 
14299 			/*
14300 			 * In the special case of multirouted broadcast
14301 			 * packets, we unconditionally need to "gateway"
14302 			 * them to the appropriate interface here.
14303 			 * In the normal case, this cannot happen, because
14304 			 * there is no broadcast IRE tagged with the
14305 			 * RTF_MULTIRT flag.
14306 			 */
14307 			if (new_ire->ire_flags & RTF_MULTIRT) {
14308 				ire_refrele(new_ire);
14309 				if (ire->ire_rfq != NULL) {
14310 					q = ire->ire_rfq;
14311 					*qp = q;
14312 				}
14313 			} else {
14314 				ire_refrele(ire);
14315 				ire = new_ire;
14316 			}
14317 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14318 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14319 				/*
14320 				 * Free the message if
14321 				 * ip_g_forward_directed_bcast is turned
14322 				 * off for non-local broadcast.
14323 				 */
14324 				ire_refrele(ire);
14325 				freemsg(mp);
14326 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14327 				return (NULL);
14328 			}
14329 		} else {
14330 			/*
14331 			 * This CGTP packet successfully passed the
14332 			 * CGTP filter, but the related CGTP
14333 			 * broadcast IRE has not been found,
14334 			 * meaning that the redundant ipif is
14335 			 * probably down. However, if we discarded
14336 			 * this packet, its duplicate would be
14337 			 * filtered out by the CGTP filter so none
14338 			 * of them would get through. So we keep
14339 			 * going with this one.
14340 			 */
14341 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14342 			if (ire->ire_rfq != NULL) {
14343 				q = ire->ire_rfq;
14344 				*qp = q;
14345 			}
14346 		}
14347 	}
14348 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14349 		/*
14350 		 * Verify that there are not more then one
14351 		 * IRE_BROADCAST with this broadcast address which
14352 		 * has ire_stq set.
14353 		 * TODO: simplify, loop over all IRE's
14354 		 */
14355 		ire_t	*ire1;
14356 		int	num_stq = 0;
14357 		mblk_t	*mp1;
14358 
14359 		/* Find the first one with ire_stq set */
14360 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14361 		for (ire1 = ire; ire1 &&
14362 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14363 		    ire1 = ire1->ire_next)
14364 			;
14365 		if (ire1) {
14366 			ire_refrele(ire);
14367 			ire = ire1;
14368 			IRE_REFHOLD(ire);
14369 		}
14370 
14371 		/* Check if there are additional ones with stq set */
14372 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14373 			if (ire->ire_addr != ire1->ire_addr)
14374 				break;
14375 			if (ire1->ire_stq) {
14376 				num_stq++;
14377 				break;
14378 			}
14379 		}
14380 		rw_exit(&ire->ire_bucket->irb_lock);
14381 		if (num_stq == 1 && ire->ire_stq != NULL) {
14382 			ip1dbg(("ip_rput_process_broadcast: directed "
14383 			    "broadcast to 0x%x\n",
14384 			    ntohl(ire->ire_addr)));
14385 			mp1 = copymsg(mp);
14386 			if (mp1) {
14387 				switch (ipha->ipha_protocol) {
14388 				case IPPROTO_UDP:
14389 					ip_udp_input(q, mp1, ipha, ire, ill);
14390 					break;
14391 				default:
14392 					ip_proto_input(q, mp1, ipha, ire, ill,
14393 					    0);
14394 					break;
14395 				}
14396 			}
14397 			/*
14398 			 * Adjust ttl to 2 (1+1 - the forward engine
14399 			 * will decrement it by one.
14400 			 */
14401 			if (ip_csum_hdr(ipha)) {
14402 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14403 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14404 				freemsg(mp);
14405 				ire_refrele(ire);
14406 				return (NULL);
14407 			}
14408 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14409 			ipha->ipha_hdr_checksum = 0;
14410 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14411 			ip_rput_process_forward(q, mp, ire, ipha,
14412 			    ill, ll_multicast, B_FALSE);
14413 			ire_refrele(ire);
14414 			return (NULL);
14415 		}
14416 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14417 		    ntohl(ire->ire_addr)));
14418 	}
14419 
14420 	/* Restore any hardware checksum flags */
14421 	DB_CKSUMFLAGS(mp) = hcksumflags;
14422 	return (ire);
14423 }
14424 
14425 /* ARGSUSED */
14426 static boolean_t
14427 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14428     int *ll_multicast, ipaddr_t *dstp)
14429 {
14430 	ip_stack_t	*ipst = ill->ill_ipst;
14431 
14432 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14433 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14434 	    ntohs(ipha->ipha_length));
14435 
14436 	/*
14437 	 * So that we don't end up with dups, only one ill in an IPMP group is
14438 	 * nominated to receive multicast traffic.
14439 	 */
14440 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14441 		goto drop_pkt;
14442 
14443 	/*
14444 	 * Forward packets only if we have joined the allmulti
14445 	 * group on this interface.
14446 	 */
14447 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14448 		int retval;
14449 
14450 		/*
14451 		 * Clear the indication that this may have hardware
14452 		 * checksum as we are not using it.
14453 		 */
14454 		DB_CKSUMFLAGS(mp) = 0;
14455 		retval = ip_mforward(ill, ipha, mp);
14456 		/* ip_mforward updates mib variables if needed */
14457 		/* clear b_prev - used by ip_mroute_decap */
14458 		mp->b_prev = NULL;
14459 
14460 		switch (retval) {
14461 		case 0:
14462 			/*
14463 			 * pkt is okay and arrived on phyint.
14464 			 *
14465 			 * If we are running as a multicast router
14466 			 * we need to see all IGMP and/or PIM packets.
14467 			 */
14468 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14469 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14470 				goto done;
14471 			}
14472 			break;
14473 		case -1:
14474 			/* pkt is mal-formed, toss it */
14475 			goto drop_pkt;
14476 		case 1:
14477 			/* pkt is okay and arrived on a tunnel */
14478 			/*
14479 			 * If we are running a multicast router
14480 			 *  we need to see all igmp packets.
14481 			 */
14482 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14483 				*dstp = INADDR_BROADCAST;
14484 				*ll_multicast = 1;
14485 				return (B_FALSE);
14486 			}
14487 
14488 			goto drop_pkt;
14489 		}
14490 	}
14491 
14492 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14493 		/*
14494 		 * This might just be caused by the fact that
14495 		 * multiple IP Multicast addresses map to the same
14496 		 * link layer multicast - no need to increment counter!
14497 		 */
14498 		freemsg(mp);
14499 		return (B_TRUE);
14500 	}
14501 done:
14502 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14503 	/*
14504 	 * This assumes the we deliver to all streams for multicast
14505 	 * and broadcast packets.
14506 	 */
14507 	*dstp = INADDR_BROADCAST;
14508 	*ll_multicast = 1;
14509 	return (B_FALSE);
14510 drop_pkt:
14511 	ip2dbg(("ip_rput: drop pkt\n"));
14512 	freemsg(mp);
14513 	return (B_TRUE);
14514 }
14515 
14516 /*
14517  * This function is used to both return an indication of whether or not
14518  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14519  * and in doing so, determine whether or not it is broadcast vs multicast.
14520  * For it to be a broadcast packet, we must have the appropriate mblk_t
14521  * hanging off the ill_t.  If this is either not present or doesn't match
14522  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14523  * to be multicast.  Thus NICs that have no broadcast address (or no
14524  * capability for one, such as point to point links) cannot return as
14525  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14526  * the return values simplifies the current use of the return value of this
14527  * function, which is to pass through the multicast/broadcast characteristic
14528  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14529  * changing the return value to some other symbol demands the appropriate
14530  * "translation" when hpe_flags is set prior to calling hook_run() for
14531  * packet events.
14532  */
14533 int
14534 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14535 {
14536 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14537 	mblk_t *bmp;
14538 
14539 	if (ind->dl_group_address) {
14540 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14541 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14542 		    MBLKL(mb) &&
14543 		    (bmp = ill->ill_bcast_mp) != NULL) {
14544 			dl_unitdata_req_t *dlur;
14545 			uint8_t *bphys_addr;
14546 
14547 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14548 			if (ill->ill_sap_length < 0)
14549 				bphys_addr = (uchar_t *)dlur +
14550 				    dlur->dl_dest_addr_offset;
14551 			else
14552 				bphys_addr = (uchar_t *)dlur +
14553 				    dlur->dl_dest_addr_offset +
14554 				    ill->ill_sap_length;
14555 
14556 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14557 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14558 				return (HPE_BROADCAST);
14559 			}
14560 			return (HPE_MULTICAST);
14561 		}
14562 		return (HPE_MULTICAST);
14563 	}
14564 	return (0);
14565 }
14566 
14567 static boolean_t
14568 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14569     int *ll_multicast, mblk_t **mpp)
14570 {
14571 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14572 	boolean_t must_copy = B_FALSE;
14573 	struct iocblk   *iocp;
14574 	ipha_t		*ipha;
14575 	ip_stack_t	*ipst = ill->ill_ipst;
14576 
14577 #define	rptr    ((uchar_t *)ipha)
14578 
14579 	first_mp = *first_mpp;
14580 	mp = *mpp;
14581 
14582 	ASSERT(first_mp == mp);
14583 
14584 	/*
14585 	 * if db_ref > 1 then copymsg and free original. Packet may be
14586 	 * changed and do not want other entity who has a reference to this
14587 	 * message to trip over the changes. This is a blind change because
14588 	 * trying to catch all places that might change packet is too
14589 	 * difficult (since it may be a module above this one)
14590 	 *
14591 	 * This corresponds to the non-fast path case. We walk down the full
14592 	 * chain in this case, and check the db_ref count of all the dblks,
14593 	 * and do a copymsg if required. It is possible that the db_ref counts
14594 	 * of the data blocks in the mblk chain can be different.
14595 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14596 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14597 	 * 'snoop' is running.
14598 	 */
14599 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14600 		if (mp1->b_datap->db_ref > 1) {
14601 			must_copy = B_TRUE;
14602 			break;
14603 		}
14604 	}
14605 
14606 	if (must_copy) {
14607 		mp1 = copymsg(mp);
14608 		if (mp1 == NULL) {
14609 			for (mp1 = mp; mp1 != NULL;
14610 			    mp1 = mp1->b_cont) {
14611 				mp1->b_next = NULL;
14612 				mp1->b_prev = NULL;
14613 			}
14614 			freemsg(mp);
14615 			if (ill != NULL) {
14616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14617 			} else {
14618 				BUMP_MIB(&ipst->ips_ip_mib,
14619 				    ipIfStatsInDiscards);
14620 			}
14621 			return (B_TRUE);
14622 		}
14623 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14624 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14625 			/* Copy b_prev - used by ip_mroute_decap */
14626 			to_mp->b_prev = from_mp->b_prev;
14627 			from_mp->b_prev = NULL;
14628 		}
14629 		*first_mpp = first_mp = mp1;
14630 		freemsg(mp);
14631 		mp = mp1;
14632 		*mpp = mp1;
14633 	}
14634 
14635 	ipha = (ipha_t *)mp->b_rptr;
14636 
14637 	/*
14638 	 * previous code has a case for M_DATA.
14639 	 * We want to check how that happens.
14640 	 */
14641 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14642 	switch (first_mp->b_datap->db_type) {
14643 	case M_PROTO:
14644 	case M_PCPROTO:
14645 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14646 		    DL_UNITDATA_IND) {
14647 			/* Go handle anything other than data elsewhere. */
14648 			ip_rput_dlpi(q, mp);
14649 			return (B_TRUE);
14650 		}
14651 
14652 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14653 		/* Ditch the DLPI header. */
14654 		mp1 = mp->b_cont;
14655 		ASSERT(first_mp == mp);
14656 		*first_mpp = mp1;
14657 		freeb(mp);
14658 		*mpp = mp1;
14659 		return (B_FALSE);
14660 	case M_IOCACK:
14661 		ip1dbg(("got iocack "));
14662 		iocp = (struct iocblk *)mp->b_rptr;
14663 		switch (iocp->ioc_cmd) {
14664 		case DL_IOC_HDR_INFO:
14665 			ill = (ill_t *)q->q_ptr;
14666 			ill_fastpath_ack(ill, mp);
14667 			return (B_TRUE);
14668 		case SIOCSTUNPARAM:
14669 		case OSIOCSTUNPARAM:
14670 			/* Go through qwriter_ip */
14671 			break;
14672 		case SIOCGTUNPARAM:
14673 		case OSIOCGTUNPARAM:
14674 			ip_rput_other(NULL, q, mp, NULL);
14675 			return (B_TRUE);
14676 		default:
14677 			putnext(q, mp);
14678 			return (B_TRUE);
14679 		}
14680 		/* FALLTHRU */
14681 	case M_ERROR:
14682 	case M_HANGUP:
14683 		/*
14684 		 * Since this is on the ill stream we unconditionally
14685 		 * bump up the refcount
14686 		 */
14687 		ill_refhold(ill);
14688 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14689 		return (B_TRUE);
14690 	case M_CTL:
14691 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14692 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14693 		    IPHADA_M_CTL)) {
14694 			/*
14695 			 * It's an IPsec accelerated packet.
14696 			 * Make sure that the ill from which we received the
14697 			 * packet has enabled IPsec hardware acceleration.
14698 			 */
14699 			if (!(ill->ill_capabilities &
14700 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14701 				/* IPsec kstats: bean counter */
14702 				freemsg(mp);
14703 				return (B_TRUE);
14704 			}
14705 
14706 			/*
14707 			 * Make mp point to the mblk following the M_CTL,
14708 			 * then process according to type of mp.
14709 			 * After this processing, first_mp will point to
14710 			 * the data-attributes and mp to the pkt following
14711 			 * the M_CTL.
14712 			 */
14713 			mp = first_mp->b_cont;
14714 			if (mp == NULL) {
14715 				freemsg(first_mp);
14716 				return (B_TRUE);
14717 			}
14718 			/*
14719 			 * A Hardware Accelerated packet can only be M_DATA
14720 			 * ESP or AH packet.
14721 			 */
14722 			if (mp->b_datap->db_type != M_DATA) {
14723 				/* non-M_DATA IPsec accelerated packet */
14724 				IPSECHW_DEBUG(IPSECHW_PKT,
14725 				    ("non-M_DATA IPsec accelerated pkt\n"));
14726 				freemsg(first_mp);
14727 				return (B_TRUE);
14728 			}
14729 			ipha = (ipha_t *)mp->b_rptr;
14730 			if (ipha->ipha_protocol != IPPROTO_AH &&
14731 			    ipha->ipha_protocol != IPPROTO_ESP) {
14732 				IPSECHW_DEBUG(IPSECHW_PKT,
14733 				    ("non-M_DATA IPsec accelerated pkt\n"));
14734 				freemsg(first_mp);
14735 				return (B_TRUE);
14736 			}
14737 			*mpp = mp;
14738 			return (B_FALSE);
14739 		}
14740 		putnext(q, mp);
14741 		return (B_TRUE);
14742 	case M_IOCNAK:
14743 		ip1dbg(("got iocnak "));
14744 		iocp = (struct iocblk *)mp->b_rptr;
14745 		switch (iocp->ioc_cmd) {
14746 		case SIOCSTUNPARAM:
14747 		case OSIOCSTUNPARAM:
14748 			/*
14749 			 * Since this is on the ill stream we unconditionally
14750 			 * bump up the refcount
14751 			 */
14752 			ill_refhold(ill);
14753 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14754 			return (B_TRUE);
14755 		case DL_IOC_HDR_INFO:
14756 		case SIOCGTUNPARAM:
14757 		case OSIOCGTUNPARAM:
14758 			ip_rput_other(NULL, q, mp, NULL);
14759 			return (B_TRUE);
14760 		default:
14761 			break;
14762 		}
14763 		/* FALLTHRU */
14764 	default:
14765 		putnext(q, mp);
14766 		return (B_TRUE);
14767 	}
14768 }
14769 
14770 /* Read side put procedure.  Packets coming from the wire arrive here. */
14771 void
14772 ip_rput(queue_t *q, mblk_t *mp)
14773 {
14774 	ill_t	*ill;
14775 	union DL_primitives *dl;
14776 
14777 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14778 
14779 	ill = (ill_t *)q->q_ptr;
14780 
14781 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14782 		/*
14783 		 * If things are opening or closing, only accept high-priority
14784 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14785 		 * created; on close, things hanging off the ill may have been
14786 		 * freed already.)
14787 		 */
14788 		dl = (union DL_primitives *)mp->b_rptr;
14789 		if (DB_TYPE(mp) != M_PCPROTO ||
14790 		    dl->dl_primitive == DL_UNITDATA_IND) {
14791 			/*
14792 			 * SIOC[GS]TUNPARAM ioctls can come here.
14793 			 */
14794 			inet_freemsg(mp);
14795 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14796 			    "ip_rput_end: q %p (%S)", q, "uninit");
14797 			return;
14798 		}
14799 	}
14800 
14801 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14802 	    "ip_rput_end: q %p (%S)", q, "end");
14803 
14804 	ip_input(ill, NULL, mp, NULL);
14805 }
14806 
14807 static mblk_t *
14808 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14809 {
14810 	mblk_t *mp1;
14811 	boolean_t adjusted = B_FALSE;
14812 	ip_stack_t *ipst = ill->ill_ipst;
14813 
14814 	IP_STAT(ipst, ip_db_ref);
14815 	/*
14816 	 * The IP_RECVSLLA option depends on having the
14817 	 * link layer header. First check that:
14818 	 * a> the underlying device is of type ether,
14819 	 * since this option is currently supported only
14820 	 * over ethernet.
14821 	 * b> there is enough room to copy over the link
14822 	 * layer header.
14823 	 *
14824 	 * Once the checks are done, adjust rptr so that
14825 	 * the link layer header will be copied via
14826 	 * copymsg. Note that, IFT_ETHER may be returned
14827 	 * by some non-ethernet drivers but in this case
14828 	 * the second check will fail.
14829 	 */
14830 	if (ill->ill_type == IFT_ETHER &&
14831 	    (mp->b_rptr - mp->b_datap->db_base) >=
14832 	    sizeof (struct ether_header)) {
14833 		mp->b_rptr -= sizeof (struct ether_header);
14834 		adjusted = B_TRUE;
14835 	}
14836 	mp1 = copymsg(mp);
14837 
14838 	if (mp1 == NULL) {
14839 		mp->b_next = NULL;
14840 		/* clear b_prev - used by ip_mroute_decap */
14841 		mp->b_prev = NULL;
14842 		freemsg(mp);
14843 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14844 		return (NULL);
14845 	}
14846 
14847 	if (adjusted) {
14848 		/*
14849 		 * Copy is done. Restore the pointer in
14850 		 * the _new_ mblk
14851 		 */
14852 		mp1->b_rptr += sizeof (struct ether_header);
14853 	}
14854 
14855 	/* Copy b_prev - used by ip_mroute_decap */
14856 	mp1->b_prev = mp->b_prev;
14857 	mp->b_prev = NULL;
14858 
14859 	/* preserve the hardware checksum flags and data, if present */
14860 	if (DB_CKSUMFLAGS(mp) != 0) {
14861 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14862 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14863 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14864 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14865 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14866 	}
14867 
14868 	freemsg(mp);
14869 	return (mp1);
14870 }
14871 
14872 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14873 	if (tail != NULL)					\
14874 		tail->b_next = mp;				\
14875 	else							\
14876 		head = mp;					\
14877 	tail = mp;						\
14878 	cnt++;							\
14879 }
14880 
14881 /*
14882  * Direct read side procedure capable of dealing with chains. GLDv3 based
14883  * drivers call this function directly with mblk chains while STREAMS
14884  * read side procedure ip_rput() calls this for single packet with ip_ring
14885  * set to NULL to process one packet at a time.
14886  *
14887  * The ill will always be valid if this function is called directly from
14888  * the driver.
14889  *
14890  * If ip_input() is called from GLDv3:
14891  *
14892  *   - This must be a non-VLAN IP stream.
14893  *   - 'mp' is either an untagged or a special priority-tagged packet.
14894  *   - Any VLAN tag that was in the MAC header has been stripped.
14895  *
14896  * If the IP header in packet is not 32-bit aligned, every message in the
14897  * chain will be aligned before further operations. This is required on SPARC
14898  * platform.
14899  */
14900 /* ARGSUSED */
14901 void
14902 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14903     struct mac_header_info_s *mhip)
14904 {
14905 	ipaddr_t		dst = NULL;
14906 	ipaddr_t		prev_dst;
14907 	ire_t			*ire = NULL;
14908 	ipha_t			*ipha;
14909 	uint_t			pkt_len;
14910 	ssize_t			len;
14911 	uint_t			opt_len;
14912 	int			ll_multicast;
14913 	int			cgtp_flt_pkt;
14914 	queue_t			*q = ill->ill_rq;
14915 	squeue_t		*curr_sqp = NULL;
14916 	mblk_t 			*head = NULL;
14917 	mblk_t			*tail = NULL;
14918 	mblk_t			*first_mp;
14919 	int			cnt = 0;
14920 	ip_stack_t		*ipst = ill->ill_ipst;
14921 	mblk_t			*mp;
14922 	mblk_t			*dmp;
14923 	uint8_t			tag;
14924 
14925 	ASSERT(mp_chain != NULL);
14926 	ASSERT(ill != NULL);
14927 
14928 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14929 
14930 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14931 
14932 #define	rptr	((uchar_t *)ipha)
14933 
14934 	while (mp_chain != NULL) {
14935 		mp = mp_chain;
14936 		mp_chain = mp_chain->b_next;
14937 		mp->b_next = NULL;
14938 		ll_multicast = 0;
14939 
14940 		/*
14941 		 * We do ire caching from one iteration to
14942 		 * another. In the event the packet chain contains
14943 		 * all packets from the same dst, this caching saves
14944 		 * an ire_cache_lookup for each of the succeeding
14945 		 * packets in a packet chain.
14946 		 */
14947 		prev_dst = dst;
14948 
14949 		/*
14950 		 * if db_ref > 1 then copymsg and free original. Packet
14951 		 * may be changed and we do not want the other entity
14952 		 * who has a reference to this message to trip over the
14953 		 * changes. This is a blind change because trying to
14954 		 * catch all places that might change the packet is too
14955 		 * difficult.
14956 		 *
14957 		 * This corresponds to the fast path case, where we have
14958 		 * a chain of M_DATA mblks.  We check the db_ref count
14959 		 * of only the 1st data block in the mblk chain. There
14960 		 * doesn't seem to be a reason why a device driver would
14961 		 * send up data with varying db_ref counts in the mblk
14962 		 * chain. In any case the Fast path is a private
14963 		 * interface, and our drivers don't do such a thing.
14964 		 * Given the above assumption, there is no need to walk
14965 		 * down the entire mblk chain (which could have a
14966 		 * potential performance problem)
14967 		 *
14968 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14969 		 * to here because of exclusive ip stacks and vnics.
14970 		 * Packets transmitted from exclusive stack over vnic
14971 		 * can have db_ref > 1 and when it gets looped back to
14972 		 * another vnic in a different zone, you have ip_input()
14973 		 * getting dblks with db_ref > 1. So if someone
14974 		 * complains of TCP performance under this scenario,
14975 		 * take a serious look here on the impact of copymsg().
14976 		 */
14977 
14978 		if (DB_REF(mp) > 1) {
14979 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14980 				continue;
14981 		}
14982 
14983 		/*
14984 		 * Check and align the IP header.
14985 		 */
14986 		first_mp = mp;
14987 		if (DB_TYPE(mp) == M_DATA) {
14988 			dmp = mp;
14989 		} else if (DB_TYPE(mp) == M_PROTO &&
14990 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14991 			dmp = mp->b_cont;
14992 		} else {
14993 			dmp = NULL;
14994 		}
14995 		if (dmp != NULL) {
14996 			/*
14997 			 * IP header ptr not aligned?
14998 			 * OR IP header not complete in first mblk
14999 			 */
15000 			if (!OK_32PTR(dmp->b_rptr) ||
15001 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15002 				if (!ip_check_and_align_header(q, dmp, ipst))
15003 					continue;
15004 			}
15005 		}
15006 
15007 		/*
15008 		 * ip_input fast path
15009 		 */
15010 
15011 		/* mblk type is not M_DATA */
15012 		if (DB_TYPE(mp) != M_DATA) {
15013 			if (ip_rput_process_notdata(q, &first_mp, ill,
15014 			    &ll_multicast, &mp))
15015 				continue;
15016 
15017 			/*
15018 			 * The only way we can get here is if we had a
15019 			 * packet that was either a DL_UNITDATA_IND or
15020 			 * an M_CTL for an IPsec accelerated packet.
15021 			 *
15022 			 * In either case, the first_mp will point to
15023 			 * the leading M_PROTO or M_CTL.
15024 			 */
15025 			ASSERT(first_mp != NULL);
15026 		} else if (mhip != NULL) {
15027 			/*
15028 			 * ll_multicast is set here so that it is ready
15029 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15030 			 * manipulates ll_multicast in the same fashion when
15031 			 * called from ip_rput_process_notdata.
15032 			 */
15033 			switch (mhip->mhi_dsttype) {
15034 			case MAC_ADDRTYPE_MULTICAST :
15035 				ll_multicast = HPE_MULTICAST;
15036 				break;
15037 			case MAC_ADDRTYPE_BROADCAST :
15038 				ll_multicast = HPE_BROADCAST;
15039 				break;
15040 			default :
15041 				break;
15042 			}
15043 		}
15044 
15045 		/* Only M_DATA can come here and it is always aligned */
15046 		ASSERT(DB_TYPE(mp) == M_DATA);
15047 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15048 
15049 		ipha = (ipha_t *)mp->b_rptr;
15050 		len = mp->b_wptr - rptr;
15051 		pkt_len = ntohs(ipha->ipha_length);
15052 
15053 		/*
15054 		 * We must count all incoming packets, even if they end
15055 		 * up being dropped later on.
15056 		 */
15057 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15058 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15059 
15060 		/* multiple mblk or too short */
15061 		len -= pkt_len;
15062 		if (len != 0) {
15063 			/*
15064 			 * Make sure we have data length consistent
15065 			 * with the IP header.
15066 			 */
15067 			if (mp->b_cont == NULL) {
15068 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15069 					BUMP_MIB(ill->ill_ip_mib,
15070 					    ipIfStatsInHdrErrors);
15071 					ip2dbg(("ip_input: drop pkt\n"));
15072 					freemsg(mp);
15073 					continue;
15074 				}
15075 				mp->b_wptr = rptr + pkt_len;
15076 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15077 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15078 					BUMP_MIB(ill->ill_ip_mib,
15079 					    ipIfStatsInHdrErrors);
15080 					ip2dbg(("ip_input: drop pkt\n"));
15081 					freemsg(mp);
15082 					continue;
15083 				}
15084 				(void) adjmsg(mp, -len);
15085 				IP_STAT(ipst, ip_multimblk3);
15086 			}
15087 		}
15088 
15089 		/* Obtain the dst of the current packet */
15090 		dst = ipha->ipha_dst;
15091 
15092 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15093 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15094 		    ipha, ip6_t *, NULL, int, 0);
15095 
15096 		/*
15097 		 * The following test for loopback is faster than
15098 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15099 		 * operations.
15100 		 * Note that these addresses are always in network byte order
15101 		 */
15102 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15103 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15104 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15105 			freemsg(mp);
15106 			continue;
15107 		}
15108 
15109 		/*
15110 		 * The event for packets being received from a 'physical'
15111 		 * interface is placed after validation of the source and/or
15112 		 * destination address as being local so that packets can be
15113 		 * redirected to loopback addresses using ipnat.
15114 		 */
15115 		DTRACE_PROBE4(ip4__physical__in__start,
15116 		    ill_t *, ill, ill_t *, NULL,
15117 		    ipha_t *, ipha, mblk_t *, first_mp);
15118 
15119 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15120 		    ipst->ips_ipv4firewall_physical_in,
15121 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15122 
15123 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15124 
15125 		if (first_mp == NULL) {
15126 			continue;
15127 		}
15128 		dst = ipha->ipha_dst;
15129 		/*
15130 		 * Attach any necessary label information to
15131 		 * this packet
15132 		 */
15133 		if (is_system_labeled() &&
15134 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15135 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15136 			freemsg(mp);
15137 			continue;
15138 		}
15139 
15140 		if (ipst->ips_ipobs_enabled) {
15141 			zoneid_t dzone;
15142 
15143 			/*
15144 			 * On the inbound path the src zone will be unknown as
15145 			 * this packet has come from the wire.
15146 			 */
15147 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15148 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15149 			    ill, IPV4_VERSION, 0, ipst);
15150 		}
15151 
15152 		/*
15153 		 * Reuse the cached ire only if the ipha_dst of the previous
15154 		 * packet is the same as the current packet AND it is not
15155 		 * INADDR_ANY.
15156 		 */
15157 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15158 		    (ire != NULL)) {
15159 			ire_refrele(ire);
15160 			ire = NULL;
15161 		}
15162 
15163 		opt_len = ipha->ipha_version_and_hdr_length -
15164 		    IP_SIMPLE_HDR_VERSION;
15165 
15166 		/*
15167 		 * Check to see if we can take the fastpath.
15168 		 * That is possible if the following conditions are met
15169 		 *	o Tsol disabled
15170 		 *	o CGTP disabled
15171 		 *	o ipp_action_count is 0
15172 		 *	o no options in the packet
15173 		 *	o not a RSVP packet
15174 		 * 	o not a multicast packet
15175 		 *	o ill not in IP_DHCPINIT_IF mode
15176 		 */
15177 		if (!is_system_labeled() &&
15178 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15179 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15180 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15181 			if (ire == NULL)
15182 				ire = ire_cache_lookup_simple(dst, ipst);
15183 			/*
15184 			 * Unless forwarding is enabled, dont call
15185 			 * ip_fast_forward(). Incoming packet is for forwarding
15186 			 */
15187 			if ((ill->ill_flags & ILLF_ROUTER) &&
15188 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15189 				ire = ip_fast_forward(ire, dst, ill, mp);
15190 				continue;
15191 			}
15192 			/* incoming packet is for local consumption */
15193 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15194 				goto local;
15195 		}
15196 
15197 		/*
15198 		 * Disable ire caching for anything more complex
15199 		 * than the simple fast path case we checked for above.
15200 		 */
15201 		if (ire != NULL) {
15202 			ire_refrele(ire);
15203 			ire = NULL;
15204 		}
15205 
15206 		/*
15207 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15208 		 * server to unicast DHCP packets to a DHCP client using the
15209 		 * IP address it is offering to the client.  This can be
15210 		 * disabled through the "broadcast bit", but not all DHCP
15211 		 * servers honor that bit.  Therefore, to interoperate with as
15212 		 * many DHCP servers as possible, the DHCP client allows the
15213 		 * server to unicast, but we treat those packets as broadcast
15214 		 * here.  Note that we don't rewrite the packet itself since
15215 		 * (a) that would mess up the checksums and (b) the DHCP
15216 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15217 		 * hand it the packet regardless.
15218 		 */
15219 		if (ill->ill_dhcpinit != 0 &&
15220 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15221 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15222 			udpha_t *udpha;
15223 
15224 			/*
15225 			 * Reload ipha since pullupmsg() can change b_rptr.
15226 			 */
15227 			ipha = (ipha_t *)mp->b_rptr;
15228 			udpha = (udpha_t *)&ipha[1];
15229 
15230 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15231 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15232 				    mblk_t *, mp);
15233 				dst = INADDR_BROADCAST;
15234 			}
15235 		}
15236 
15237 		/* Full-blown slow path */
15238 		if (opt_len != 0) {
15239 			if (len != 0)
15240 				IP_STAT(ipst, ip_multimblk4);
15241 			else
15242 				IP_STAT(ipst, ip_ipoptions);
15243 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15244 			    &dst, ipst))
15245 				continue;
15246 		}
15247 
15248 		/*
15249 		 * Invoke the CGTP (multirouting) filtering module to process
15250 		 * the incoming packet. Packets identified as duplicates
15251 		 * must be discarded. Filtering is active only if the
15252 		 * the ip_cgtp_filter ndd variable is non-zero.
15253 		 */
15254 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15255 		if (ipst->ips_ip_cgtp_filter &&
15256 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15257 			netstackid_t stackid;
15258 
15259 			stackid = ipst->ips_netstack->netstack_stackid;
15260 			cgtp_flt_pkt =
15261 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15262 			    ill->ill_phyint->phyint_ifindex, mp);
15263 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15264 				freemsg(first_mp);
15265 				continue;
15266 			}
15267 		}
15268 
15269 		/*
15270 		 * If rsvpd is running, let RSVP daemon handle its processing
15271 		 * and forwarding of RSVP multicast/unicast packets.
15272 		 * If rsvpd is not running but mrouted is running, RSVP
15273 		 * multicast packets are forwarded as multicast traffic
15274 		 * and RSVP unicast packets are forwarded by unicast router.
15275 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15276 		 * packets are not forwarded, but the unicast packets are
15277 		 * forwarded like unicast traffic.
15278 		 */
15279 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15280 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15281 		    NULL) {
15282 			/* RSVP packet and rsvpd running. Treat as ours */
15283 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15284 			/*
15285 			 * This assumes that we deliver to all streams for
15286 			 * multicast and broadcast packets.
15287 			 * We have to force ll_multicast to 1 to handle the
15288 			 * M_DATA messages passed in from ip_mroute_decap.
15289 			 */
15290 			dst = INADDR_BROADCAST;
15291 			ll_multicast = 1;
15292 		} else if (CLASSD(dst)) {
15293 			/* packet is multicast */
15294 			mp->b_next = NULL;
15295 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15296 			    &ll_multicast, &dst))
15297 				continue;
15298 		}
15299 
15300 		if (ire == NULL) {
15301 			ire = ire_cache_lookup(dst, ALL_ZONES,
15302 			    msg_getlabel(mp), ipst);
15303 		}
15304 
15305 		if (ire != NULL && ire->ire_stq != NULL &&
15306 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15307 		    ire->ire_zoneid != ALL_ZONES) {
15308 			/*
15309 			 * Should only use IREs that are visible from the
15310 			 * global zone for forwarding.
15311 			 */
15312 			ire_refrele(ire);
15313 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15314 			    msg_getlabel(mp), ipst);
15315 		}
15316 
15317 		if (ire == NULL) {
15318 			/*
15319 			 * No IRE for this destination, so it can't be for us.
15320 			 * Unless we are forwarding, drop the packet.
15321 			 * We have to let source routed packets through
15322 			 * since we don't yet know if they are 'ping -l'
15323 			 * packets i.e. if they will go out over the
15324 			 * same interface as they came in on.
15325 			 */
15326 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15327 			if (ire == NULL)
15328 				continue;
15329 		}
15330 
15331 		/*
15332 		 * Broadcast IRE may indicate either broadcast or
15333 		 * multicast packet
15334 		 */
15335 		if (ire->ire_type == IRE_BROADCAST) {
15336 			/*
15337 			 * Skip broadcast checks if packet is UDP multicast;
15338 			 * we'd rather not enter ip_rput_process_broadcast()
15339 			 * unless the packet is broadcast for real, since
15340 			 * that routine is a no-op for multicast.
15341 			 */
15342 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15343 			    !CLASSD(ipha->ipha_dst)) {
15344 				ire = ip_rput_process_broadcast(&q, mp,
15345 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15346 				    ll_multicast);
15347 				if (ire == NULL)
15348 					continue;
15349 			}
15350 		} else if (ire->ire_stq != NULL) {
15351 			/* fowarding? */
15352 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15353 			    ll_multicast, B_FALSE);
15354 			/* ip_rput_process_forward consumed the packet */
15355 			continue;
15356 		}
15357 
15358 local:
15359 		/*
15360 		 * If the queue in the ire is different to the ingress queue
15361 		 * then we need to check to see if we can accept the packet.
15362 		 * Note that for multicast packets and broadcast packets sent
15363 		 * to a broadcast address which is shared between multiple
15364 		 * interfaces we should not do this since we just got a random
15365 		 * broadcast ire.
15366 		 */
15367 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15368 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15369 			if (ire == NULL) {
15370 				/* Drop packet */
15371 				BUMP_MIB(ill->ill_ip_mib,
15372 				    ipIfStatsForwProhibits);
15373 				freemsg(mp);
15374 				continue;
15375 			}
15376 			if (ire->ire_rfq != NULL)
15377 				q = ire->ire_rfq;
15378 		}
15379 
15380 		switch (ipha->ipha_protocol) {
15381 		case IPPROTO_TCP:
15382 			ASSERT(first_mp == mp);
15383 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15384 			    mp, 0, q, ip_ring)) != NULL) {
15385 				if (curr_sqp == NULL) {
15386 					curr_sqp = GET_SQUEUE(mp);
15387 					ASSERT(cnt == 0);
15388 					cnt++;
15389 					head = tail = mp;
15390 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15391 					ASSERT(tail != NULL);
15392 					cnt++;
15393 					tail->b_next = mp;
15394 					tail = mp;
15395 				} else {
15396 					/*
15397 					 * A different squeue. Send the
15398 					 * chain for the previous squeue on
15399 					 * its way. This shouldn't happen
15400 					 * often unless interrupt binding
15401 					 * changes.
15402 					 */
15403 					IP_STAT(ipst, ip_input_multi_squeue);
15404 					SQUEUE_ENTER(curr_sqp, head,
15405 					    tail, cnt, SQ_PROCESS, tag);
15406 					curr_sqp = GET_SQUEUE(mp);
15407 					head = mp;
15408 					tail = mp;
15409 					cnt = 1;
15410 				}
15411 			}
15412 			continue;
15413 		case IPPROTO_UDP:
15414 			ASSERT(first_mp == mp);
15415 			ip_udp_input(q, mp, ipha, ire, ill);
15416 			continue;
15417 		case IPPROTO_SCTP:
15418 			ASSERT(first_mp == mp);
15419 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15420 			    q, dst);
15421 			/* ire has been released by ip_sctp_input */
15422 			ire = NULL;
15423 			continue;
15424 		default:
15425 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15426 			continue;
15427 		}
15428 	}
15429 
15430 	if (ire != NULL)
15431 		ire_refrele(ire);
15432 
15433 	if (head != NULL)
15434 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15435 
15436 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15437 	    "ip_input_end: q %p (%S)", q, "end");
15438 #undef  rptr
15439 }
15440 
15441 /*
15442  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15443  * a chain of packets in the poll mode. The packets have gone through the
15444  * data link processing but not IP processing. For performance and latency
15445  * reasons, the squeue wants to process the chain in line instead of feeding
15446  * it back via ip_input path.
15447  *
15448  * So this is a light weight function which checks to see if the packets
15449  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15450  * but we still do the paranoid check) meant for local machine and we don't
15451  * have labels etc enabled. Packets that meet the criterion are returned to
15452  * the squeue and processed inline while the rest go via ip_input path.
15453  */
15454 /*ARGSUSED*/
15455 mblk_t *
15456 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15457     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15458 {
15459 	mblk_t 		*mp;
15460 	ipaddr_t	dst = NULL;
15461 	ipaddr_t	prev_dst;
15462 	ire_t		*ire = NULL;
15463 	ipha_t		*ipha;
15464 	uint_t		pkt_len;
15465 	ssize_t		len;
15466 	uint_t		opt_len;
15467 	queue_t		*q = ill->ill_rq;
15468 	squeue_t	*curr_sqp;
15469 	mblk_t 		*ahead = NULL;	/* Accepted head */
15470 	mblk_t		*atail = NULL;	/* Accepted tail */
15471 	uint_t		acnt = 0;	/* Accepted count */
15472 	mblk_t		*utail = NULL;	/* Unaccepted head */
15473 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15474 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15475 	ip_stack_t	*ipst = ill->ill_ipst;
15476 
15477 	*cnt = 0;
15478 
15479 	ASSERT(ill != NULL);
15480 	ASSERT(ip_ring != NULL);
15481 
15482 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15483 
15484 #define	rptr	((uchar_t *)ipha)
15485 
15486 	while (mp_chain != NULL) {
15487 		mp = mp_chain;
15488 		mp_chain = mp_chain->b_next;
15489 		mp->b_next = NULL;
15490 
15491 		/*
15492 		 * We do ire caching from one iteration to
15493 		 * another. In the event the packet chain contains
15494 		 * all packets from the same dst, this caching saves
15495 		 * an ire_cache_lookup for each of the succeeding
15496 		 * packets in a packet chain.
15497 		 */
15498 		prev_dst = dst;
15499 
15500 		ipha = (ipha_t *)mp->b_rptr;
15501 		len = mp->b_wptr - rptr;
15502 
15503 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15504 
15505 		/*
15506 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15507 		 * or doesn't have min len, reject.
15508 		 */
15509 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15510 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15511 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15512 			continue;
15513 		}
15514 
15515 		pkt_len = ntohs(ipha->ipha_length);
15516 		if (len != pkt_len) {
15517 			if (len > pkt_len) {
15518 				mp->b_wptr = rptr + pkt_len;
15519 			} else {
15520 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15521 				continue;
15522 			}
15523 		}
15524 
15525 		opt_len = ipha->ipha_version_and_hdr_length -
15526 		    IP_SIMPLE_HDR_VERSION;
15527 		dst = ipha->ipha_dst;
15528 
15529 		/* IP version bad or there are IP options */
15530 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15531 		    mp, &ipha, &dst, ipst)))
15532 			continue;
15533 
15534 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15535 		    (ipst->ips_ip_cgtp_filter &&
15536 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15537 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15538 			continue;
15539 		}
15540 
15541 		/*
15542 		 * Reuse the cached ire only if the ipha_dst of the previous
15543 		 * packet is the same as the current packet AND it is not
15544 		 * INADDR_ANY.
15545 		 */
15546 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15547 		    (ire != NULL)) {
15548 			ire_refrele(ire);
15549 			ire = NULL;
15550 		}
15551 
15552 		if (ire == NULL)
15553 			ire = ire_cache_lookup_simple(dst, ipst);
15554 
15555 		/*
15556 		 * Unless forwarding is enabled, dont call
15557 		 * ip_fast_forward(). Incoming packet is for forwarding
15558 		 */
15559 		if ((ill->ill_flags & ILLF_ROUTER) &&
15560 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15561 
15562 			DTRACE_PROBE4(ip4__physical__in__start,
15563 			    ill_t *, ill, ill_t *, NULL,
15564 			    ipha_t *, ipha, mblk_t *, mp);
15565 
15566 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15567 			    ipst->ips_ipv4firewall_physical_in,
15568 			    ill, NULL, ipha, mp, mp, 0, ipst);
15569 
15570 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15571 
15572 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15573 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15574 			    pkt_len);
15575 
15576 			if (mp != NULL)
15577 				ire = ip_fast_forward(ire, dst, ill, mp);
15578 			continue;
15579 		}
15580 
15581 		/* incoming packet is for local consumption */
15582 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15583 			goto local_accept;
15584 
15585 		/*
15586 		 * Disable ire caching for anything more complex
15587 		 * than the simple fast path case we checked for above.
15588 		 */
15589 		if (ire != NULL) {
15590 			ire_refrele(ire);
15591 			ire = NULL;
15592 		}
15593 
15594 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15595 		    ipst);
15596 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15597 		    ire->ire_stq != NULL) {
15598 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15599 			if (ire != NULL) {
15600 				ire_refrele(ire);
15601 				ire = NULL;
15602 			}
15603 			continue;
15604 		}
15605 
15606 local_accept:
15607 
15608 		if (ire->ire_rfq != q) {
15609 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15610 			if (ire != NULL) {
15611 				ire_refrele(ire);
15612 				ire = NULL;
15613 			}
15614 			continue;
15615 		}
15616 
15617 		/*
15618 		 * The event for packets being received from a 'physical'
15619 		 * interface is placed after validation of the source and/or
15620 		 * destination address as being local so that packets can be
15621 		 * redirected to loopback addresses using ipnat.
15622 		 */
15623 		DTRACE_PROBE4(ip4__physical__in__start,
15624 		    ill_t *, ill, ill_t *, NULL,
15625 		    ipha_t *, ipha, mblk_t *, mp);
15626 
15627 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15628 		    ipst->ips_ipv4firewall_physical_in,
15629 		    ill, NULL, ipha, mp, mp, 0, ipst);
15630 
15631 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15632 
15633 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15634 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15635 
15636 		if (mp != NULL &&
15637 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15638 		    0, q, ip_ring)) != NULL) {
15639 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15640 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15641 			} else {
15642 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15643 				    SQ_FILL, SQTAG_IP_INPUT);
15644 			}
15645 		}
15646 	}
15647 
15648 	if (ire != NULL)
15649 		ire_refrele(ire);
15650 
15651 	if (uhead != NULL)
15652 		ip_input(ill, ip_ring, uhead, NULL);
15653 
15654 	if (ahead != NULL) {
15655 		*last = atail;
15656 		*cnt = acnt;
15657 		return (ahead);
15658 	}
15659 
15660 	return (NULL);
15661 #undef  rptr
15662 }
15663 
15664 static void
15665 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15666     t_uscalar_t err)
15667 {
15668 	if (dl_err == DL_SYSERR) {
15669 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15670 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15671 		    ill->ill_name, dl_primstr(prim), err);
15672 		return;
15673 	}
15674 
15675 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15676 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15677 	    dl_errstr(dl_err));
15678 }
15679 
15680 /*
15681  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15682  * than DL_UNITDATA_IND messages. If we need to process this message
15683  * exclusively, we call qwriter_ip, in which case we also need to call
15684  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15685  */
15686 void
15687 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15688 {
15689 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15690 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15691 	ill_t		*ill = q->q_ptr;
15692 	t_uscalar_t	prim = dloa->dl_primitive;
15693 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15694 
15695 	ip1dbg(("ip_rput_dlpi"));
15696 
15697 	/*
15698 	 * If we received an ACK but didn't send a request for it, then it
15699 	 * can't be part of any pending operation; discard up-front.
15700 	 */
15701 	switch (prim) {
15702 	case DL_ERROR_ACK:
15703 		reqprim = dlea->dl_error_primitive;
15704 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15705 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15706 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15707 		    dlea->dl_unix_errno));
15708 		break;
15709 	case DL_OK_ACK:
15710 		reqprim = dloa->dl_correct_primitive;
15711 		break;
15712 	case DL_INFO_ACK:
15713 		reqprim = DL_INFO_REQ;
15714 		break;
15715 	case DL_BIND_ACK:
15716 		reqprim = DL_BIND_REQ;
15717 		break;
15718 	case DL_PHYS_ADDR_ACK:
15719 		reqprim = DL_PHYS_ADDR_REQ;
15720 		break;
15721 	case DL_NOTIFY_ACK:
15722 		reqprim = DL_NOTIFY_REQ;
15723 		break;
15724 	case DL_CONTROL_ACK:
15725 		reqprim = DL_CONTROL_REQ;
15726 		break;
15727 	case DL_CAPABILITY_ACK:
15728 		reqprim = DL_CAPABILITY_REQ;
15729 		break;
15730 	}
15731 
15732 	if (prim != DL_NOTIFY_IND) {
15733 		if (reqprim == DL_PRIM_INVAL ||
15734 		    !ill_dlpi_pending(ill, reqprim)) {
15735 			/* Not a DLPI message we support or expected */
15736 			freemsg(mp);
15737 			return;
15738 		}
15739 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15740 		    dl_primstr(reqprim)));
15741 	}
15742 
15743 	switch (reqprim) {
15744 	case DL_UNBIND_REQ:
15745 		/*
15746 		 * NOTE: we mark the unbind as complete even if we got a
15747 		 * DL_ERROR_ACK, since there's not much else we can do.
15748 		 */
15749 		mutex_enter(&ill->ill_lock);
15750 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15751 		cv_signal(&ill->ill_cv);
15752 		mutex_exit(&ill->ill_lock);
15753 		break;
15754 
15755 	case DL_ENABMULTI_REQ:
15756 		if (prim == DL_OK_ACK) {
15757 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15758 				ill->ill_dlpi_multicast_state = IDS_OK;
15759 		}
15760 		break;
15761 	}
15762 
15763 	/*
15764 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15765 	 * need to become writer to continue to process it.  Because an
15766 	 * exclusive operation doesn't complete until replies to all queued
15767 	 * DLPI messages have been received, we know we're in the middle of an
15768 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15769 	 *
15770 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15771 	 * Since this is on the ill stream we unconditionally bump up the
15772 	 * refcount without doing ILL_CAN_LOOKUP().
15773 	 */
15774 	ill_refhold(ill);
15775 	if (prim == DL_NOTIFY_IND)
15776 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15777 	else
15778 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15779 }
15780 
15781 /*
15782  * Handling of DLPI messages that require exclusive access to the ipsq.
15783  *
15784  * Need to do ill_pending_mp_release on ioctl completion, which could
15785  * happen here. (along with mi_copy_done)
15786  */
15787 /* ARGSUSED */
15788 static void
15789 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15790 {
15791 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15792 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15793 	int		err = 0;
15794 	ill_t		*ill;
15795 	ipif_t		*ipif = NULL;
15796 	mblk_t		*mp1 = NULL;
15797 	conn_t		*connp = NULL;
15798 	t_uscalar_t	paddrreq;
15799 	mblk_t		*mp_hw;
15800 	boolean_t	success;
15801 	boolean_t	ioctl_aborted = B_FALSE;
15802 	boolean_t	log = B_TRUE;
15803 	ip_stack_t		*ipst;
15804 
15805 	ip1dbg(("ip_rput_dlpi_writer .."));
15806 	ill = (ill_t *)q->q_ptr;
15807 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15808 	ASSERT(IAM_WRITER_ILL(ill));
15809 
15810 	ipst = ill->ill_ipst;
15811 
15812 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15813 	/*
15814 	 * The current ioctl could have been aborted by the user and a new
15815 	 * ioctl to bring up another ill could have started. We could still
15816 	 * get a response from the driver later.
15817 	 */
15818 	if (ipif != NULL && ipif->ipif_ill != ill)
15819 		ioctl_aborted = B_TRUE;
15820 
15821 	switch (dloa->dl_primitive) {
15822 	case DL_ERROR_ACK:
15823 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15824 		    dl_primstr(dlea->dl_error_primitive)));
15825 
15826 		switch (dlea->dl_error_primitive) {
15827 		case DL_DISABMULTI_REQ:
15828 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15829 			break;
15830 		case DL_PROMISCON_REQ:
15831 		case DL_PROMISCOFF_REQ:
15832 		case DL_UNBIND_REQ:
15833 		case DL_ATTACH_REQ:
15834 		case DL_INFO_REQ:
15835 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15836 			break;
15837 		case DL_NOTIFY_REQ:
15838 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15839 			log = B_FALSE;
15840 			break;
15841 		case DL_PHYS_ADDR_REQ:
15842 			/*
15843 			 * For IPv6 only, there are two additional
15844 			 * phys_addr_req's sent to the driver to get the
15845 			 * IPv6 token and lla. This allows IP to acquire
15846 			 * the hardware address format for a given interface
15847 			 * without having built in knowledge of the hardware
15848 			 * address. ill_phys_addr_pend keeps track of the last
15849 			 * DL_PAR sent so we know which response we are
15850 			 * dealing with. ill_dlpi_done will update
15851 			 * ill_phys_addr_pend when it sends the next req.
15852 			 * We don't complete the IOCTL until all three DL_PARs
15853 			 * have been attempted, so set *_len to 0 and break.
15854 			 */
15855 			paddrreq = ill->ill_phys_addr_pend;
15856 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15857 			if (paddrreq == DL_IPV6_TOKEN) {
15858 				ill->ill_token_length = 0;
15859 				log = B_FALSE;
15860 				break;
15861 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15862 				ill->ill_nd_lla_len = 0;
15863 				log = B_FALSE;
15864 				break;
15865 			}
15866 			/*
15867 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15868 			 * We presumably have an IOCTL hanging out waiting
15869 			 * for completion. Find it and complete the IOCTL
15870 			 * with the error noted.
15871 			 * However, ill_dl_phys was called on an ill queue
15872 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15873 			 * set. But the ioctl is known to be pending on ill_wq.
15874 			 */
15875 			if (!ill->ill_ifname_pending)
15876 				break;
15877 			ill->ill_ifname_pending = 0;
15878 			if (!ioctl_aborted)
15879 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15880 			if (mp1 != NULL) {
15881 				/*
15882 				 * This operation (SIOCSLIFNAME) must have
15883 				 * happened on the ill. Assert there is no conn
15884 				 */
15885 				ASSERT(connp == NULL);
15886 				q = ill->ill_wq;
15887 			}
15888 			break;
15889 		case DL_BIND_REQ:
15890 			ill_dlpi_done(ill, DL_BIND_REQ);
15891 			if (ill->ill_ifname_pending)
15892 				break;
15893 			/*
15894 			 * Something went wrong with the bind.  We presumably
15895 			 * have an IOCTL hanging out waiting for completion.
15896 			 * Find it, take down the interface that was coming
15897 			 * up, and complete the IOCTL with the error noted.
15898 			 */
15899 			if (!ioctl_aborted)
15900 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15901 			if (mp1 != NULL) {
15902 				/*
15903 				 * This might be a result of a DL_NOTE_REPLUMB
15904 				 * notification. In that case, connp is NULL.
15905 				 */
15906 				if (connp != NULL)
15907 					q = CONNP_TO_WQ(connp);
15908 
15909 				(void) ipif_down(ipif, NULL, NULL);
15910 				/* error is set below the switch */
15911 			}
15912 			break;
15913 		case DL_ENABMULTI_REQ:
15914 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15915 
15916 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15917 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15918 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15919 				ipif_t *ipif;
15920 
15921 				printf("ip: joining multicasts failed (%d)"
15922 				    " on %s - will use link layer "
15923 				    "broadcasts for multicast\n",
15924 				    dlea->dl_errno, ill->ill_name);
15925 
15926 				/*
15927 				 * Set up the multicast mapping alone.
15928 				 * writer, so ok to access ill->ill_ipif
15929 				 * without any lock.
15930 				 */
15931 				ipif = ill->ill_ipif;
15932 				mutex_enter(&ill->ill_phyint->phyint_lock);
15933 				ill->ill_phyint->phyint_flags |=
15934 				    PHYI_MULTI_BCAST;
15935 				mutex_exit(&ill->ill_phyint->phyint_lock);
15936 
15937 				if (!ill->ill_isv6) {
15938 					(void) ipif_arp_setup_multicast(ipif,
15939 					    NULL);
15940 				} else {
15941 					(void) ipif_ndp_setup_multicast(ipif,
15942 					    NULL);
15943 				}
15944 			}
15945 			freemsg(mp);	/* Don't want to pass this up */
15946 			return;
15947 		case DL_CONTROL_REQ:
15948 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15949 			    "DL_CONTROL_REQ\n"));
15950 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15951 			freemsg(mp);
15952 			return;
15953 		case DL_CAPABILITY_REQ:
15954 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15955 			    "DL_CAPABILITY REQ\n"));
15956 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15957 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15958 			ill_capability_done(ill);
15959 			freemsg(mp);
15960 			return;
15961 		}
15962 		/*
15963 		 * Note the error for IOCTL completion (mp1 is set when
15964 		 * ready to complete ioctl). If ill_ifname_pending_err is
15965 		 * set, an error occured during plumbing (ill_ifname_pending),
15966 		 * so we want to report that error.
15967 		 *
15968 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15969 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15970 		 * expected to get errack'd if the driver doesn't support
15971 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15972 		 * if these error conditions are encountered.
15973 		 */
15974 		if (mp1 != NULL) {
15975 			if (ill->ill_ifname_pending_err != 0)  {
15976 				err = ill->ill_ifname_pending_err;
15977 				ill->ill_ifname_pending_err = 0;
15978 			} else {
15979 				err = dlea->dl_unix_errno ?
15980 				    dlea->dl_unix_errno : ENXIO;
15981 			}
15982 		/*
15983 		 * If we're plumbing an interface and an error hasn't already
15984 		 * been saved, set ill_ifname_pending_err to the error passed
15985 		 * up. Ignore the error if log is B_FALSE (see comment above).
15986 		 */
15987 		} else if (log && ill->ill_ifname_pending &&
15988 		    ill->ill_ifname_pending_err == 0) {
15989 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15990 			    dlea->dl_unix_errno : ENXIO;
15991 		}
15992 
15993 		if (log)
15994 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15995 			    dlea->dl_errno, dlea->dl_unix_errno);
15996 		break;
15997 	case DL_CAPABILITY_ACK:
15998 		ill_capability_ack(ill, mp);
15999 		/*
16000 		 * The message has been handed off to ill_capability_ack
16001 		 * and must not be freed below
16002 		 */
16003 		mp = NULL;
16004 		break;
16005 
16006 	case DL_CONTROL_ACK:
16007 		/* We treat all of these as "fire and forget" */
16008 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16009 		break;
16010 	case DL_INFO_ACK:
16011 		/* Call a routine to handle this one. */
16012 		ill_dlpi_done(ill, DL_INFO_REQ);
16013 		ip_ll_subnet_defaults(ill, mp);
16014 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16015 		return;
16016 	case DL_BIND_ACK:
16017 		/*
16018 		 * We should have an IOCTL waiting on this unless
16019 		 * sent by ill_dl_phys, in which case just return
16020 		 */
16021 		ill_dlpi_done(ill, DL_BIND_REQ);
16022 		if (ill->ill_ifname_pending)
16023 			break;
16024 
16025 		if (!ioctl_aborted)
16026 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16027 		if (mp1 == NULL)
16028 			break;
16029 		/*
16030 		 * mp1 was added by ill_dl_up(). if that is a result of
16031 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16032 		 */
16033 		if (connp != NULL)
16034 			q = CONNP_TO_WQ(connp);
16035 
16036 		/*
16037 		 * We are exclusive. So nothing can change even after
16038 		 * we get the pending mp. If need be we can put it back
16039 		 * and restart, as in calling ipif_arp_up()  below.
16040 		 */
16041 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16042 
16043 		mutex_enter(&ill->ill_lock);
16044 		ill->ill_dl_up = 1;
16045 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16046 		mutex_exit(&ill->ill_lock);
16047 
16048 		/*
16049 		 * Now bring up the resolver; when that is complete, we'll
16050 		 * create IREs.  Note that we intentionally mirror what
16051 		 * ipif_up() would have done, because we got here by way of
16052 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16053 		 */
16054 		if (ill->ill_isv6) {
16055 			if (ill->ill_flags & ILLF_XRESOLV) {
16056 				if (connp != NULL)
16057 					mutex_enter(&connp->conn_lock);
16058 				mutex_enter(&ill->ill_lock);
16059 				success = ipsq_pending_mp_add(connp, ipif, q,
16060 				    mp1, 0);
16061 				mutex_exit(&ill->ill_lock);
16062 				if (connp != NULL)
16063 					mutex_exit(&connp->conn_lock);
16064 				if (success) {
16065 					err = ipif_resolver_up(ipif,
16066 					    Res_act_initial);
16067 					if (err == EINPROGRESS) {
16068 						freemsg(mp);
16069 						return;
16070 					}
16071 					ASSERT(err != 0);
16072 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16073 					ASSERT(mp1 != NULL);
16074 				} else {
16075 					/* conn has started closing */
16076 					err = EINTR;
16077 				}
16078 			} else { /* Non XRESOLV interface */
16079 				(void) ipif_resolver_up(ipif, Res_act_initial);
16080 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16081 					err = ipif_up_done_v6(ipif);
16082 			}
16083 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16084 			/*
16085 			 * ARP and other v4 external resolvers.
16086 			 * Leave the pending mblk intact so that
16087 			 * the ioctl completes in ip_rput().
16088 			 */
16089 			if (connp != NULL)
16090 				mutex_enter(&connp->conn_lock);
16091 			mutex_enter(&ill->ill_lock);
16092 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16093 			mutex_exit(&ill->ill_lock);
16094 			if (connp != NULL)
16095 				mutex_exit(&connp->conn_lock);
16096 			if (success) {
16097 				err = ipif_resolver_up(ipif, Res_act_initial);
16098 				if (err == EINPROGRESS) {
16099 					freemsg(mp);
16100 					return;
16101 				}
16102 				ASSERT(err != 0);
16103 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16104 			} else {
16105 				/* The conn has started closing */
16106 				err = EINTR;
16107 			}
16108 		} else {
16109 			/*
16110 			 * This one is complete. Reply to pending ioctl.
16111 			 */
16112 			(void) ipif_resolver_up(ipif, Res_act_initial);
16113 			err = ipif_up_done(ipif);
16114 		}
16115 
16116 		if ((err == 0) && (ill->ill_up_ipifs)) {
16117 			err = ill_up_ipifs(ill, q, mp1);
16118 			if (err == EINPROGRESS) {
16119 				freemsg(mp);
16120 				return;
16121 			}
16122 		}
16123 
16124 		/*
16125 		 * If we have a moved ipif to bring up, and everything has
16126 		 * succeeded to this point, bring it up on the IPMP ill.
16127 		 * Otherwise, leave it down -- the admin can try to bring it
16128 		 * up by hand if need be.
16129 		 */
16130 		if (ill->ill_move_ipif != NULL) {
16131 			if (err != 0) {
16132 				ill->ill_move_ipif = NULL;
16133 			} else {
16134 				ipif = ill->ill_move_ipif;
16135 				ill->ill_move_ipif = NULL;
16136 				err = ipif_up(ipif, q, mp1);
16137 				if (err == EINPROGRESS) {
16138 					freemsg(mp);
16139 					return;
16140 				}
16141 			}
16142 		}
16143 		break;
16144 
16145 	case DL_NOTIFY_IND: {
16146 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16147 		ire_t *ire;
16148 		uint_t orig_mtu;
16149 		boolean_t need_ire_walk_v4 = B_FALSE;
16150 		boolean_t need_ire_walk_v6 = B_FALSE;
16151 
16152 		switch (notify->dl_notification) {
16153 		case DL_NOTE_PHYS_ADDR:
16154 			err = ill_set_phys_addr(ill, mp);
16155 			break;
16156 
16157 		case DL_NOTE_REPLUMB:
16158 			/*
16159 			 * Directly return after calling ill_replumb().
16160 			 * Note that we should not free mp as it is reused
16161 			 * in the ill_replumb() function.
16162 			 */
16163 			err = ill_replumb(ill, mp);
16164 			return;
16165 
16166 		case DL_NOTE_FASTPATH_FLUSH:
16167 			ill_fastpath_flush(ill);
16168 			break;
16169 
16170 		case DL_NOTE_SDU_SIZE:
16171 			/*
16172 			 * Change the MTU size of the interface, of all
16173 			 * attached ipif's, and of all relevant ire's.  The
16174 			 * new value's a uint32_t at notify->dl_data.
16175 			 * Mtu change Vs. new ire creation - protocol below.
16176 			 *
16177 			 * a Mark the ipif as IPIF_CHANGING.
16178 			 * b Set the new mtu in the ipif.
16179 			 * c Change the ire_max_frag on all affected ires
16180 			 * d Unmark the IPIF_CHANGING
16181 			 *
16182 			 * To see how the protocol works, assume an interface
16183 			 * route is also being added simultaneously by
16184 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16185 			 * the ire. If the ire is created before step a,
16186 			 * it will be cleaned up by step c. If the ire is
16187 			 * created after step d, it will see the new value of
16188 			 * ipif_mtu. Any attempt to create the ire between
16189 			 * steps a to d will fail because of the IPIF_CHANGING
16190 			 * flag. Note that ire_create() is passed a pointer to
16191 			 * the ipif_mtu, and not the value. During ire_add
16192 			 * under the bucket lock, the ire_max_frag of the
16193 			 * new ire being created is set from the ipif/ire from
16194 			 * which it is being derived.
16195 			 */
16196 			mutex_enter(&ill->ill_lock);
16197 
16198 			orig_mtu = ill->ill_max_mtu;
16199 			ill->ill_max_frag = (uint_t)notify->dl_data;
16200 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16201 
16202 			/*
16203 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16204 			 * clamp ill_max_mtu at it.
16205 			 */
16206 			if (ill->ill_user_mtu != 0 &&
16207 			    ill->ill_user_mtu < ill->ill_max_mtu)
16208 				ill->ill_max_mtu = ill->ill_user_mtu;
16209 
16210 			/*
16211 			 * If the MTU is unchanged, we're done.
16212 			 */
16213 			if (orig_mtu == ill->ill_max_mtu) {
16214 				mutex_exit(&ill->ill_lock);
16215 				break;
16216 			}
16217 
16218 			if (ill->ill_isv6) {
16219 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16220 					ill->ill_max_mtu = IPV6_MIN_MTU;
16221 			} else {
16222 				if (ill->ill_max_mtu < IP_MIN_MTU)
16223 					ill->ill_max_mtu = IP_MIN_MTU;
16224 			}
16225 			for (ipif = ill->ill_ipif; ipif != NULL;
16226 			    ipif = ipif->ipif_next) {
16227 				/*
16228 				 * Don't override the mtu if the user
16229 				 * has explicitly set it.
16230 				 */
16231 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16232 					continue;
16233 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16234 				if (ipif->ipif_isv6)
16235 					ire = ipif_to_ire_v6(ipif);
16236 				else
16237 					ire = ipif_to_ire(ipif);
16238 				if (ire != NULL) {
16239 					ire->ire_max_frag = ipif->ipif_mtu;
16240 					ire_refrele(ire);
16241 				}
16242 				if (ipif->ipif_flags & IPIF_UP) {
16243 					if (ill->ill_isv6)
16244 						need_ire_walk_v6 = B_TRUE;
16245 					else
16246 						need_ire_walk_v4 = B_TRUE;
16247 				}
16248 			}
16249 			mutex_exit(&ill->ill_lock);
16250 			if (need_ire_walk_v4)
16251 				ire_walk_v4(ill_mtu_change, (char *)ill,
16252 				    ALL_ZONES, ipst);
16253 			if (need_ire_walk_v6)
16254 				ire_walk_v6(ill_mtu_change, (char *)ill,
16255 				    ALL_ZONES, ipst);
16256 
16257 			/*
16258 			 * Refresh IPMP meta-interface MTU if necessary.
16259 			 */
16260 			if (IS_UNDER_IPMP(ill))
16261 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16262 			break;
16263 
16264 		case DL_NOTE_LINK_UP:
16265 		case DL_NOTE_LINK_DOWN: {
16266 			/*
16267 			 * We are writer. ill / phyint / ipsq assocs stable.
16268 			 * The RUNNING flag reflects the state of the link.
16269 			 */
16270 			phyint_t *phyint = ill->ill_phyint;
16271 			uint64_t new_phyint_flags;
16272 			boolean_t changed = B_FALSE;
16273 			boolean_t went_up;
16274 
16275 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16276 			mutex_enter(&phyint->phyint_lock);
16277 
16278 			new_phyint_flags = went_up ?
16279 			    phyint->phyint_flags | PHYI_RUNNING :
16280 			    phyint->phyint_flags & ~PHYI_RUNNING;
16281 
16282 			if (IS_IPMP(ill)) {
16283 				new_phyint_flags = went_up ?
16284 				    new_phyint_flags & ~PHYI_FAILED :
16285 				    new_phyint_flags | PHYI_FAILED;
16286 			}
16287 
16288 			if (new_phyint_flags != phyint->phyint_flags) {
16289 				phyint->phyint_flags = new_phyint_flags;
16290 				changed = B_TRUE;
16291 			}
16292 			mutex_exit(&phyint->phyint_lock);
16293 			/*
16294 			 * ill_restart_dad handles the DAD restart and routing
16295 			 * socket notification logic.
16296 			 */
16297 			if (changed) {
16298 				ill_restart_dad(phyint->phyint_illv4, went_up);
16299 				ill_restart_dad(phyint->phyint_illv6, went_up);
16300 			}
16301 			break;
16302 		}
16303 		case DL_NOTE_PROMISC_ON_PHYS:
16304 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16305 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16306 			mutex_enter(&ill->ill_lock);
16307 			ill->ill_promisc_on_phys = B_TRUE;
16308 			mutex_exit(&ill->ill_lock);
16309 			break;
16310 		case DL_NOTE_PROMISC_OFF_PHYS:
16311 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16312 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16313 			mutex_enter(&ill->ill_lock);
16314 			ill->ill_promisc_on_phys = B_FALSE;
16315 			mutex_exit(&ill->ill_lock);
16316 			break;
16317 		case DL_NOTE_CAPAB_RENEG:
16318 			/*
16319 			 * Something changed on the driver side.
16320 			 * It wants us to renegotiate the capabilities
16321 			 * on this ill. One possible cause is the aggregation
16322 			 * interface under us where a port got added or
16323 			 * went away.
16324 			 *
16325 			 * If the capability negotiation is already done
16326 			 * or is in progress, reset the capabilities and
16327 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16328 			 * so that when the ack comes back, we can start
16329 			 * the renegotiation process.
16330 			 *
16331 			 * Note that if ill_capab_reneg is already B_TRUE
16332 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16333 			 * the capability resetting request has been sent
16334 			 * and the renegotiation has not been started yet;
16335 			 * nothing needs to be done in this case.
16336 			 */
16337 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16338 			ill_capability_reset(ill, B_TRUE);
16339 			ipsq_current_finish(ipsq);
16340 			break;
16341 		default:
16342 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16343 			    "type 0x%x for DL_NOTIFY_IND\n",
16344 			    notify->dl_notification));
16345 			break;
16346 		}
16347 
16348 		/*
16349 		 * As this is an asynchronous operation, we
16350 		 * should not call ill_dlpi_done
16351 		 */
16352 		break;
16353 	}
16354 	case DL_NOTIFY_ACK: {
16355 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16356 
16357 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16358 			ill->ill_note_link = 1;
16359 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16360 		break;
16361 	}
16362 	case DL_PHYS_ADDR_ACK: {
16363 		/*
16364 		 * As part of plumbing the interface via SIOCSLIFNAME,
16365 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16366 		 * whose answers we receive here.  As each answer is received,
16367 		 * we call ill_dlpi_done() to dispatch the next request as
16368 		 * we're processing the current one.  Once all answers have
16369 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16370 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16371 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16372 		 * available, but we know the ioctl is pending on ill_wq.)
16373 		 */
16374 		uint_t	paddrlen, paddroff;
16375 
16376 		paddrreq = ill->ill_phys_addr_pend;
16377 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16378 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16379 
16380 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16381 		if (paddrreq == DL_IPV6_TOKEN) {
16382 			/*
16383 			 * bcopy to low-order bits of ill_token
16384 			 *
16385 			 * XXX Temporary hack - currently, all known tokens
16386 			 * are 64 bits, so I'll cheat for the moment.
16387 			 */
16388 			bcopy(mp->b_rptr + paddroff,
16389 			    &ill->ill_token.s6_addr32[2], paddrlen);
16390 			ill->ill_token_length = paddrlen;
16391 			break;
16392 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16393 			ASSERT(ill->ill_nd_lla_mp == NULL);
16394 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16395 			mp = NULL;
16396 			break;
16397 		}
16398 
16399 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16400 		ASSERT(ill->ill_phys_addr_mp == NULL);
16401 		if (!ill->ill_ifname_pending)
16402 			break;
16403 		ill->ill_ifname_pending = 0;
16404 		if (!ioctl_aborted)
16405 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16406 		if (mp1 != NULL) {
16407 			ASSERT(connp == NULL);
16408 			q = ill->ill_wq;
16409 		}
16410 		/*
16411 		 * If any error acks received during the plumbing sequence,
16412 		 * ill_ifname_pending_err will be set. Break out and send up
16413 		 * the error to the pending ioctl.
16414 		 */
16415 		if (ill->ill_ifname_pending_err != 0) {
16416 			err = ill->ill_ifname_pending_err;
16417 			ill->ill_ifname_pending_err = 0;
16418 			break;
16419 		}
16420 
16421 		ill->ill_phys_addr_mp = mp;
16422 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16423 		mp = NULL;
16424 
16425 		/*
16426 		 * If paddrlen is zero, the DLPI provider doesn't support
16427 		 * physical addresses.  The other two tests were historical
16428 		 * workarounds for bugs in our former PPP implementation, but
16429 		 * now other things have grown dependencies on them -- e.g.,
16430 		 * the tun module specifies a dl_addr_length of zero in its
16431 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16432 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16433 		 * but only after careful testing ensures that all dependent
16434 		 * broken DLPI providers have been fixed.
16435 		 */
16436 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16437 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16438 			ill->ill_phys_addr = NULL;
16439 		} else if (paddrlen != ill->ill_phys_addr_length) {
16440 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16441 			    paddrlen, ill->ill_phys_addr_length));
16442 			err = EINVAL;
16443 			break;
16444 		}
16445 
16446 		if (ill->ill_nd_lla_mp == NULL) {
16447 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16448 				err = ENOMEM;
16449 				break;
16450 			}
16451 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16452 		}
16453 
16454 		/*
16455 		 * Set the interface token.  If the zeroth interface address
16456 		 * is unspecified, then set it to the link local address.
16457 		 */
16458 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16459 			(void) ill_setdefaulttoken(ill);
16460 
16461 		ASSERT(ill->ill_ipif->ipif_id == 0);
16462 		if (ipif != NULL &&
16463 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16464 			(void) ipif_setlinklocal(ipif);
16465 		}
16466 		break;
16467 	}
16468 	case DL_OK_ACK:
16469 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16470 		    dl_primstr((int)dloa->dl_correct_primitive),
16471 		    dloa->dl_correct_primitive));
16472 		switch (dloa->dl_correct_primitive) {
16473 		case DL_ENABMULTI_REQ:
16474 		case DL_DISABMULTI_REQ:
16475 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16476 			break;
16477 		case DL_PROMISCON_REQ:
16478 		case DL_PROMISCOFF_REQ:
16479 		case DL_UNBIND_REQ:
16480 		case DL_ATTACH_REQ:
16481 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16482 			break;
16483 		}
16484 		break;
16485 	default:
16486 		break;
16487 	}
16488 
16489 	freemsg(mp);
16490 	if (mp1 == NULL)
16491 		return;
16492 
16493 	/*
16494 	 * The operation must complete without EINPROGRESS since
16495 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16496 	 * the operation will be stuck forever inside the IPSQ.
16497 	 */
16498 	ASSERT(err != EINPROGRESS);
16499 
16500 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16501 	case 0:
16502 		ipsq_current_finish(ipsq);
16503 		break;
16504 
16505 	case SIOCSLIFNAME:
16506 	case IF_UNITSEL: {
16507 		ill_t *ill_other = ILL_OTHER(ill);
16508 
16509 		/*
16510 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16511 		 * ill has a peer which is in an IPMP group, then place ill
16512 		 * into the same group.  One catch: although ifconfig plumbs
16513 		 * the appropriate IPMP meta-interface prior to plumbing this
16514 		 * ill, it is possible for multiple ifconfig applications to
16515 		 * race (or for another application to adjust plumbing), in
16516 		 * which case the IPMP meta-interface we need will be missing.
16517 		 * If so, kick the phyint out of the group.
16518 		 */
16519 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16520 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16521 			ipmp_illgrp_t	*illg;
16522 
16523 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16524 			if (illg == NULL)
16525 				ipmp_phyint_leave_grp(ill->ill_phyint);
16526 			else
16527 				ipmp_ill_join_illgrp(ill, illg);
16528 		}
16529 
16530 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16531 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16532 		else
16533 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16534 		break;
16535 	}
16536 	case SIOCLIFADDIF:
16537 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16538 		break;
16539 
16540 	default:
16541 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16542 		break;
16543 	}
16544 }
16545 
16546 /*
16547  * ip_rput_other is called by ip_rput to handle messages modifying the global
16548  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16549  */
16550 /* ARGSUSED */
16551 void
16552 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16553 {
16554 	ill_t		*ill = q->q_ptr;
16555 	struct iocblk	*iocp;
16556 	mblk_t		*mp1;
16557 	conn_t		*connp = NULL;
16558 
16559 	ip1dbg(("ip_rput_other "));
16560 	if (ipsq != NULL) {
16561 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16562 		ASSERT(ipsq->ipsq_xop ==
16563 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16564 	}
16565 
16566 	switch (mp->b_datap->db_type) {
16567 	case M_ERROR:
16568 	case M_HANGUP:
16569 		/*
16570 		 * The device has a problem.  We force the ILL down.  It can
16571 		 * be brought up again manually using SIOCSIFFLAGS (via
16572 		 * ifconfig or equivalent).
16573 		 */
16574 		ASSERT(ipsq != NULL);
16575 		if (mp->b_rptr < mp->b_wptr)
16576 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16577 		if (ill->ill_error == 0)
16578 			ill->ill_error = ENXIO;
16579 		if (!ill_down_start(q, mp))
16580 			return;
16581 		ipif_all_down_tail(ipsq, q, mp, NULL);
16582 		break;
16583 	case M_IOCACK:
16584 		iocp = (struct iocblk *)mp->b_rptr;
16585 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16586 		switch (iocp->ioc_cmd) {
16587 		case SIOCSTUNPARAM:
16588 		case OSIOCSTUNPARAM:
16589 			ASSERT(ipsq != NULL);
16590 			/*
16591 			 * Finish socket ioctl passed through to tun.
16592 			 * We should have an IOCTL waiting on this.
16593 			 */
16594 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16595 			if (ill->ill_isv6) {
16596 				struct iftun_req *ta;
16597 
16598 				/*
16599 				 * if a source or destination is
16600 				 * being set, try and set the link
16601 				 * local address for the tunnel
16602 				 */
16603 				ta = (struct iftun_req *)mp->b_cont->
16604 				    b_cont->b_rptr;
16605 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16606 					ipif_set_tun_llink(ill, ta);
16607 				}
16608 
16609 			}
16610 			if (mp1 != NULL) {
16611 				/*
16612 				 * Now copy back the b_next/b_prev used by
16613 				 * mi code for the mi_copy* functions.
16614 				 * See ip_sioctl_tunparam() for the reason.
16615 				 * Also protect against missing b_cont.
16616 				 */
16617 				if (mp->b_cont != NULL) {
16618 					mp->b_cont->b_next =
16619 					    mp1->b_cont->b_next;
16620 					mp->b_cont->b_prev =
16621 					    mp1->b_cont->b_prev;
16622 				}
16623 				inet_freemsg(mp1);
16624 				ASSERT(connp != NULL);
16625 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16626 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16627 			} else {
16628 				ASSERT(connp == NULL);
16629 				putnext(q, mp);
16630 			}
16631 			break;
16632 		case SIOCGTUNPARAM:
16633 		case OSIOCGTUNPARAM:
16634 			/*
16635 			 * This is really M_IOCDATA from the tunnel driver.
16636 			 * convert back and complete the ioctl.
16637 			 * We should have an IOCTL waiting on this.
16638 			 */
16639 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16640 			if (mp1) {
16641 				/*
16642 				 * Now copy back the b_next/b_prev used by
16643 				 * mi code for the mi_copy* functions.
16644 				 * See ip_sioctl_tunparam() for the reason.
16645 				 * Also protect against missing b_cont.
16646 				 */
16647 				if (mp->b_cont != NULL) {
16648 					mp->b_cont->b_next =
16649 					    mp1->b_cont->b_next;
16650 					mp->b_cont->b_prev =
16651 					    mp1->b_cont->b_prev;
16652 				}
16653 				inet_freemsg(mp1);
16654 				if (iocp->ioc_error == 0)
16655 					mp->b_datap->db_type = M_IOCDATA;
16656 				ASSERT(connp != NULL);
16657 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16658 				    iocp->ioc_error, COPYOUT, NULL);
16659 			} else {
16660 				ASSERT(connp == NULL);
16661 				putnext(q, mp);
16662 			}
16663 			break;
16664 		default:
16665 			break;
16666 		}
16667 		break;
16668 	case M_IOCNAK:
16669 		iocp = (struct iocblk *)mp->b_rptr;
16670 
16671 		switch (iocp->ioc_cmd) {
16672 			int mode;
16673 
16674 		case DL_IOC_HDR_INFO:
16675 			/*
16676 			 * If this was the first attempt, turn off the
16677 			 * fastpath probing.
16678 			 */
16679 			mutex_enter(&ill->ill_lock);
16680 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16681 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16682 				mutex_exit(&ill->ill_lock);
16683 				ill_fastpath_nack(ill);
16684 				ip1dbg(("ip_rput: DLPI fastpath off on "
16685 				    "interface %s\n",
16686 				    ill->ill_name));
16687 			} else {
16688 				mutex_exit(&ill->ill_lock);
16689 			}
16690 			freemsg(mp);
16691 			break;
16692 			case SIOCSTUNPARAM:
16693 		case OSIOCSTUNPARAM:
16694 			ASSERT(ipsq != NULL);
16695 			/*
16696 			 * Finish socket ioctl passed through to tun
16697 			 * We should have an IOCTL waiting on this.
16698 			 */
16699 			/* FALLTHRU */
16700 		case SIOCGTUNPARAM:
16701 		case OSIOCGTUNPARAM:
16702 			/*
16703 			 * This is really M_IOCDATA from the tunnel driver.
16704 			 * convert back and complete the ioctl.
16705 			 * We should have an IOCTL waiting on this.
16706 			 */
16707 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16708 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16709 				mp1 = ill_pending_mp_get(ill, &connp,
16710 				    iocp->ioc_id);
16711 				mode = COPYOUT;
16712 				ipsq = NULL;
16713 			} else {
16714 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16715 				mode = NO_COPYOUT;
16716 			}
16717 			if (mp1 != NULL) {
16718 				/*
16719 				 * Now copy back the b_next/b_prev used by
16720 				 * mi code for the mi_copy* functions.
16721 				 * See ip_sioctl_tunparam() for the reason.
16722 				 * Also protect against missing b_cont.
16723 				 */
16724 				if (mp->b_cont != NULL) {
16725 					mp->b_cont->b_next =
16726 					    mp1->b_cont->b_next;
16727 					mp->b_cont->b_prev =
16728 					    mp1->b_cont->b_prev;
16729 				}
16730 				inet_freemsg(mp1);
16731 				if (iocp->ioc_error == 0)
16732 					iocp->ioc_error = EINVAL;
16733 				ASSERT(connp != NULL);
16734 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16735 				    iocp->ioc_error, mode, ipsq);
16736 			} else {
16737 				ASSERT(connp == NULL);
16738 				putnext(q, mp);
16739 			}
16740 			break;
16741 		default:
16742 			break;
16743 		}
16744 	default:
16745 		break;
16746 	}
16747 }
16748 
16749 /*
16750  * NOTE : This function does not ire_refrele the ire argument passed in.
16751  *
16752  * IPQoS notes
16753  * IP policy is invoked twice for a forwarded packet, once on the read side
16754  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16755  * enabled. An additional parameter, in_ill, has been added for this purpose.
16756  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16757  * because ip_mroute drops this information.
16758  *
16759  */
16760 void
16761 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16762 {
16763 	uint32_t	old_pkt_len;
16764 	uint32_t	pkt_len;
16765 	queue_t	*q;
16766 	uint32_t	sum;
16767 #define	rptr	((uchar_t *)ipha)
16768 	uint32_t	max_frag;
16769 	uint32_t	ill_index;
16770 	ill_t		*out_ill;
16771 	mib2_ipIfStatsEntry_t *mibptr;
16772 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16773 
16774 	/* Get the ill_index of the incoming ILL */
16775 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16776 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16777 
16778 	/* Initiate Read side IPPF processing */
16779 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16780 		ip_process(IPP_FWD_IN, &mp, ill_index);
16781 		if (mp == NULL) {
16782 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16783 			    "during IPPF processing\n"));
16784 			return;
16785 		}
16786 	}
16787 
16788 	/* Adjust the checksum to reflect the ttl decrement. */
16789 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16790 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16791 
16792 	if (ipha->ipha_ttl-- <= 1) {
16793 		if (ip_csum_hdr(ipha)) {
16794 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16795 			goto drop_pkt;
16796 		}
16797 		/*
16798 		 * Note: ire_stq this will be NULL for multicast
16799 		 * datagrams using the long path through arp (the IRE
16800 		 * is not an IRE_CACHE). This should not cause
16801 		 * problems since we don't generate ICMP errors for
16802 		 * multicast packets.
16803 		 */
16804 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16805 		q = ire->ire_stq;
16806 		if (q != NULL) {
16807 			/* Sent by forwarding path, and router is global zone */
16808 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16809 			    GLOBAL_ZONEID, ipst);
16810 		} else
16811 			freemsg(mp);
16812 		return;
16813 	}
16814 
16815 	/*
16816 	 * Don't forward if the interface is down
16817 	 */
16818 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16819 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16820 		ip2dbg(("ip_rput_forward:interface is down\n"));
16821 		goto drop_pkt;
16822 	}
16823 
16824 	/* Get the ill_index of the outgoing ILL */
16825 	out_ill = ire_to_ill(ire);
16826 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16827 
16828 	DTRACE_PROBE4(ip4__forwarding__start,
16829 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16830 
16831 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16832 	    ipst->ips_ipv4firewall_forwarding,
16833 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16834 
16835 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16836 
16837 	if (mp == NULL)
16838 		return;
16839 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16840 
16841 	if (is_system_labeled()) {
16842 		mblk_t *mp1;
16843 
16844 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16845 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16846 			goto drop_pkt;
16847 		}
16848 		/* Size may have changed */
16849 		mp = mp1;
16850 		ipha = (ipha_t *)mp->b_rptr;
16851 		pkt_len = ntohs(ipha->ipha_length);
16852 	}
16853 
16854 	/* Check if there are options to update */
16855 	if (!IS_SIMPLE_IPH(ipha)) {
16856 		if (ip_csum_hdr(ipha)) {
16857 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16858 			goto drop_pkt;
16859 		}
16860 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16861 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16862 			return;
16863 		}
16864 
16865 		ipha->ipha_hdr_checksum = 0;
16866 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16867 	}
16868 	max_frag = ire->ire_max_frag;
16869 	if (pkt_len > max_frag) {
16870 		/*
16871 		 * It needs fragging on its way out.  We haven't
16872 		 * verified the header checksum yet.  Since we
16873 		 * are going to put a surely good checksum in the
16874 		 * outgoing header, we have to make sure that it
16875 		 * was good coming in.
16876 		 */
16877 		if (ip_csum_hdr(ipha)) {
16878 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16879 			goto drop_pkt;
16880 		}
16881 		/* Initiate Write side IPPF processing */
16882 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16883 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16884 			if (mp == NULL) {
16885 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16886 				    " during IPPF processing\n"));
16887 				return;
16888 			}
16889 		}
16890 		/*
16891 		 * Handle labeled packet resizing.
16892 		 *
16893 		 * If we have added a label, inform ip_wput_frag() of its
16894 		 * effect on the MTU for ICMP messages.
16895 		 */
16896 		if (pkt_len > old_pkt_len) {
16897 			uint32_t secopt_size;
16898 
16899 			secopt_size = pkt_len - old_pkt_len;
16900 			if (secopt_size < max_frag)
16901 				max_frag -= secopt_size;
16902 		}
16903 
16904 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16905 		    GLOBAL_ZONEID, ipst, NULL);
16906 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16907 		return;
16908 	}
16909 
16910 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16911 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16912 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16913 	    ipst->ips_ipv4firewall_physical_out,
16914 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16915 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16916 	if (mp == NULL)
16917 		return;
16918 
16919 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16920 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16921 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16922 	/* ip_xmit_v4 always consumes the packet */
16923 	return;
16924 
16925 drop_pkt:;
16926 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16927 	freemsg(mp);
16928 #undef	rptr
16929 }
16930 
16931 void
16932 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16933 {
16934 	ire_t	*ire;
16935 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16936 
16937 	ASSERT(!ipif->ipif_isv6);
16938 	/*
16939 	 * Find an IRE which matches the destination and the outgoing
16940 	 * queue in the cache table. All we need is an IRE_CACHE which
16941 	 * is pointing at ipif->ipif_ill.
16942 	 */
16943 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16944 		dst = ipif->ipif_pp_dst_addr;
16945 
16946 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16947 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16948 	if (ire == NULL) {
16949 		/*
16950 		 * Mark this packet to make it be delivered to
16951 		 * ip_rput_forward after the new ire has been
16952 		 * created.
16953 		 */
16954 		mp->b_prev = NULL;
16955 		mp->b_next = mp;
16956 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16957 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16958 	} else {
16959 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16960 		IRE_REFRELE(ire);
16961 	}
16962 }
16963 
16964 /* Update any source route, record route or timestamp options */
16965 static int
16966 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16967 {
16968 	ipoptp_t	opts;
16969 	uchar_t		*opt;
16970 	uint8_t		optval;
16971 	uint8_t		optlen;
16972 	ipaddr_t	dst;
16973 	uint32_t	ts;
16974 	ire_t		*dst_ire = NULL;
16975 	ire_t		*tmp_ire = NULL;
16976 	timestruc_t	now;
16977 
16978 	ip2dbg(("ip_rput_forward_options\n"));
16979 	dst = ipha->ipha_dst;
16980 	for (optval = ipoptp_first(&opts, ipha);
16981 	    optval != IPOPT_EOL;
16982 	    optval = ipoptp_next(&opts)) {
16983 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16984 		opt = opts.ipoptp_cur;
16985 		optlen = opts.ipoptp_len;
16986 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16987 		    optval, opts.ipoptp_len));
16988 		switch (optval) {
16989 			uint32_t off;
16990 		case IPOPT_SSRR:
16991 		case IPOPT_LSRR:
16992 			/* Check if adminstratively disabled */
16993 			if (!ipst->ips_ip_forward_src_routed) {
16994 				if (ire->ire_stq != NULL) {
16995 					/*
16996 					 * Sent by forwarding path, and router
16997 					 * is global zone
16998 					 */
16999 					icmp_unreachable(ire->ire_stq, mp,
17000 					    ICMP_SOURCE_ROUTE_FAILED,
17001 					    GLOBAL_ZONEID, ipst);
17002 				} else {
17003 					ip0dbg(("ip_rput_forward_options: "
17004 					    "unable to send unreach\n"));
17005 					freemsg(mp);
17006 				}
17007 				return (-1);
17008 			}
17009 
17010 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17011 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17012 			if (dst_ire == NULL) {
17013 				/*
17014 				 * Must be partial since ip_rput_options
17015 				 * checked for strict.
17016 				 */
17017 				break;
17018 			}
17019 			off = opt[IPOPT_OFFSET];
17020 			off--;
17021 		redo_srr:
17022 			if (optlen < IP_ADDR_LEN ||
17023 			    off > optlen - IP_ADDR_LEN) {
17024 				/* End of source route */
17025 				ip1dbg((
17026 				    "ip_rput_forward_options: end of SR\n"));
17027 				ire_refrele(dst_ire);
17028 				break;
17029 			}
17030 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17031 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17032 			    IP_ADDR_LEN);
17033 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17034 			    ntohl(dst)));
17035 
17036 			/*
17037 			 * Check if our address is present more than
17038 			 * once as consecutive hops in source route.
17039 			 */
17040 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17041 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17042 			if (tmp_ire != NULL) {
17043 				ire_refrele(tmp_ire);
17044 				off += IP_ADDR_LEN;
17045 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17046 				goto redo_srr;
17047 			}
17048 			ipha->ipha_dst = dst;
17049 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17050 			ire_refrele(dst_ire);
17051 			break;
17052 		case IPOPT_RR:
17053 			off = opt[IPOPT_OFFSET];
17054 			off--;
17055 			if (optlen < IP_ADDR_LEN ||
17056 			    off > optlen - IP_ADDR_LEN) {
17057 				/* No more room - ignore */
17058 				ip1dbg((
17059 				    "ip_rput_forward_options: end of RR\n"));
17060 				break;
17061 			}
17062 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17063 			    IP_ADDR_LEN);
17064 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17065 			break;
17066 		case IPOPT_TS:
17067 			/* Insert timestamp if there is room */
17068 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17069 			case IPOPT_TS_TSONLY:
17070 				off = IPOPT_TS_TIMELEN;
17071 				break;
17072 			case IPOPT_TS_PRESPEC:
17073 			case IPOPT_TS_PRESPEC_RFC791:
17074 				/* Verify that the address matched */
17075 				off = opt[IPOPT_OFFSET] - 1;
17076 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17077 				dst_ire = ire_ctable_lookup(dst, 0,
17078 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17079 				    MATCH_IRE_TYPE, ipst);
17080 				if (dst_ire == NULL) {
17081 					/* Not for us */
17082 					break;
17083 				}
17084 				ire_refrele(dst_ire);
17085 				/* FALLTHRU */
17086 			case IPOPT_TS_TSANDADDR:
17087 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17088 				break;
17089 			default:
17090 				/*
17091 				 * ip_*put_options should have already
17092 				 * dropped this packet.
17093 				 */
17094 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17095 				    "unknown IT - bug in ip_rput_options?\n");
17096 				return (0);	/* Keep "lint" happy */
17097 			}
17098 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17099 				/* Increase overflow counter */
17100 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17101 				opt[IPOPT_POS_OV_FLG] =
17102 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17103 				    (off << 4));
17104 				break;
17105 			}
17106 			off = opt[IPOPT_OFFSET] - 1;
17107 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17108 			case IPOPT_TS_PRESPEC:
17109 			case IPOPT_TS_PRESPEC_RFC791:
17110 			case IPOPT_TS_TSANDADDR:
17111 				bcopy(&ire->ire_src_addr,
17112 				    (char *)opt + off, IP_ADDR_LEN);
17113 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17114 				/* FALLTHRU */
17115 			case IPOPT_TS_TSONLY:
17116 				off = opt[IPOPT_OFFSET] - 1;
17117 				/* Compute # of milliseconds since midnight */
17118 				gethrestime(&now);
17119 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17120 				    now.tv_nsec / (NANOSEC / MILLISEC);
17121 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17122 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17123 				break;
17124 			}
17125 			break;
17126 		}
17127 	}
17128 	return (0);
17129 }
17130 
17131 /*
17132  * This is called after processing at least one of AH/ESP headers.
17133  *
17134  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17135  * the actual, physical interface on which the packet was received,
17136  * but, when ip_strict_dst_multihoming is set to 1, could be the
17137  * interface which had the ipha_dst configured when the packet went
17138  * through ip_rput. The ill_index corresponding to the recv_ill
17139  * is saved in ipsec_in_rill_index
17140  *
17141  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17142  * cannot assume "ire" points to valid data for any IPv6 cases.
17143  */
17144 void
17145 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17146 {
17147 	mblk_t *mp;
17148 	ipaddr_t dst;
17149 	in6_addr_t *v6dstp;
17150 	ipha_t *ipha;
17151 	ip6_t *ip6h;
17152 	ipsec_in_t *ii;
17153 	boolean_t ill_need_rele = B_FALSE;
17154 	boolean_t rill_need_rele = B_FALSE;
17155 	boolean_t ire_need_rele = B_FALSE;
17156 	netstack_t	*ns;
17157 	ip_stack_t	*ipst;
17158 
17159 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17160 	ASSERT(ii->ipsec_in_ill_index != 0);
17161 	ns = ii->ipsec_in_ns;
17162 	ASSERT(ii->ipsec_in_ns != NULL);
17163 	ipst = ns->netstack_ip;
17164 
17165 	mp = ipsec_mp->b_cont;
17166 	ASSERT(mp != NULL);
17167 
17168 	if (ill == NULL) {
17169 		ASSERT(recv_ill == NULL);
17170 		/*
17171 		 * We need to get the original queue on which ip_rput_local
17172 		 * or ip_rput_data_v6 was called.
17173 		 */
17174 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17175 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17176 		ill_need_rele = B_TRUE;
17177 
17178 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17179 			recv_ill = ill_lookup_on_ifindex(
17180 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17181 			    NULL, NULL, NULL, NULL, ipst);
17182 			rill_need_rele = B_TRUE;
17183 		} else {
17184 			recv_ill = ill;
17185 		}
17186 
17187 		if ((ill == NULL) || (recv_ill == NULL)) {
17188 			ip0dbg(("ip_fanout_proto_again: interface "
17189 			    "disappeared\n"));
17190 			if (ill != NULL)
17191 				ill_refrele(ill);
17192 			if (recv_ill != NULL)
17193 				ill_refrele(recv_ill);
17194 			freemsg(ipsec_mp);
17195 			return;
17196 		}
17197 	}
17198 
17199 	ASSERT(ill != NULL && recv_ill != NULL);
17200 
17201 	if (mp->b_datap->db_type == M_CTL) {
17202 		/*
17203 		 * AH/ESP is returning the ICMP message after
17204 		 * removing their headers. Fanout again till
17205 		 * it gets to the right protocol.
17206 		 */
17207 		if (ii->ipsec_in_v4) {
17208 			icmph_t *icmph;
17209 			int iph_hdr_length;
17210 			int hdr_length;
17211 
17212 			ipha = (ipha_t *)mp->b_rptr;
17213 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17214 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17215 			ipha = (ipha_t *)&icmph[1];
17216 			hdr_length = IPH_HDR_LENGTH(ipha);
17217 			/*
17218 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17219 			 * Reset the type to M_DATA.
17220 			 */
17221 			mp->b_datap->db_type = M_DATA;
17222 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17223 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17224 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17225 		} else {
17226 			icmp6_t *icmp6;
17227 			int hdr_length;
17228 
17229 			ip6h = (ip6_t *)mp->b_rptr;
17230 			/* Don't call hdr_length_v6() unless you have to. */
17231 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17232 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17233 			else
17234 				hdr_length = IPV6_HDR_LEN;
17235 
17236 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17237 			/*
17238 			 * icmp_inbound_error_fanout_v6 may need to do
17239 			 * pullupmsg.  Reset the type to M_DATA.
17240 			 */
17241 			mp->b_datap->db_type = M_DATA;
17242 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17243 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17244 			    ii->ipsec_in_zoneid);
17245 		}
17246 		if (ill_need_rele)
17247 			ill_refrele(ill);
17248 		if (rill_need_rele)
17249 			ill_refrele(recv_ill);
17250 		return;
17251 	}
17252 
17253 	if (ii->ipsec_in_v4) {
17254 		ipha = (ipha_t *)mp->b_rptr;
17255 		dst = ipha->ipha_dst;
17256 		if (CLASSD(dst)) {
17257 			/*
17258 			 * Multicast has to be delivered to all streams.
17259 			 */
17260 			dst = INADDR_BROADCAST;
17261 		}
17262 
17263 		if (ire == NULL) {
17264 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17265 			    msg_getlabel(mp), ipst);
17266 			if (ire == NULL) {
17267 				if (ill_need_rele)
17268 					ill_refrele(ill);
17269 				if (rill_need_rele)
17270 					ill_refrele(recv_ill);
17271 				ip1dbg(("ip_fanout_proto_again: "
17272 				    "IRE not found"));
17273 				freemsg(ipsec_mp);
17274 				return;
17275 			}
17276 			ire_need_rele = B_TRUE;
17277 		}
17278 
17279 		switch (ipha->ipha_protocol) {
17280 		case IPPROTO_UDP:
17281 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17282 			    recv_ill);
17283 			if (ire_need_rele)
17284 				ire_refrele(ire);
17285 			break;
17286 		case IPPROTO_TCP:
17287 			if (!ire_need_rele)
17288 				IRE_REFHOLD(ire);
17289 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17290 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17291 			IRE_REFRELE(ire);
17292 			if (mp != NULL) {
17293 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17294 				    mp, 1, SQ_PROCESS,
17295 				    SQTAG_IP_PROTO_AGAIN);
17296 			}
17297 			break;
17298 		case IPPROTO_SCTP:
17299 			if (!ire_need_rele)
17300 				IRE_REFHOLD(ire);
17301 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17302 			    ipsec_mp, 0, ill->ill_rq, dst);
17303 			break;
17304 		default:
17305 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17306 			    recv_ill, 0);
17307 			if (ire_need_rele)
17308 				ire_refrele(ire);
17309 			break;
17310 		}
17311 	} else {
17312 		uint32_t rput_flags = 0;
17313 
17314 		ip6h = (ip6_t *)mp->b_rptr;
17315 		v6dstp = &ip6h->ip6_dst;
17316 		/*
17317 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17318 		 * address.
17319 		 *
17320 		 * Currently, we don't store that state in the IPSEC_IN
17321 		 * message, and we may need to.
17322 		 */
17323 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17324 		    IP6_IN_LLMCAST : 0);
17325 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17326 		    NULL, NULL);
17327 	}
17328 	if (ill_need_rele)
17329 		ill_refrele(ill);
17330 	if (rill_need_rele)
17331 		ill_refrele(recv_ill);
17332 }
17333 
17334 /*
17335  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17336  * returns 'true' if there are still fragments left on the queue, in
17337  * which case we restart the timer.
17338  */
17339 void
17340 ill_frag_timer(void *arg)
17341 {
17342 	ill_t	*ill = (ill_t *)arg;
17343 	boolean_t frag_pending;
17344 	ip_stack_t	*ipst = ill->ill_ipst;
17345 
17346 	mutex_enter(&ill->ill_lock);
17347 	ASSERT(!ill->ill_fragtimer_executing);
17348 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17349 		ill->ill_frag_timer_id = 0;
17350 		mutex_exit(&ill->ill_lock);
17351 		return;
17352 	}
17353 	ill->ill_fragtimer_executing = 1;
17354 	mutex_exit(&ill->ill_lock);
17355 
17356 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17357 
17358 	/*
17359 	 * Restart the timer, if we have fragments pending or if someone
17360 	 * wanted us to be scheduled again.
17361 	 */
17362 	mutex_enter(&ill->ill_lock);
17363 	ill->ill_fragtimer_executing = 0;
17364 	ill->ill_frag_timer_id = 0;
17365 	if (frag_pending || ill->ill_fragtimer_needrestart)
17366 		ill_frag_timer_start(ill);
17367 	mutex_exit(&ill->ill_lock);
17368 }
17369 
17370 void
17371 ill_frag_timer_start(ill_t *ill)
17372 {
17373 	ip_stack_t	*ipst = ill->ill_ipst;
17374 
17375 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17376 
17377 	/* If the ill is closing or opening don't proceed */
17378 	if (ill->ill_state_flags & ILL_CONDEMNED)
17379 		return;
17380 
17381 	if (ill->ill_fragtimer_executing) {
17382 		/*
17383 		 * ill_frag_timer is currently executing. Just record the
17384 		 * the fact that we want the timer to be restarted.
17385 		 * ill_frag_timer will post a timeout before it returns,
17386 		 * ensuring it will be called again.
17387 		 */
17388 		ill->ill_fragtimer_needrestart = 1;
17389 		return;
17390 	}
17391 
17392 	if (ill->ill_frag_timer_id == 0) {
17393 		/*
17394 		 * The timer is neither running nor is the timeout handler
17395 		 * executing. Post a timeout so that ill_frag_timer will be
17396 		 * called
17397 		 */
17398 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17399 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17400 		ill->ill_fragtimer_needrestart = 0;
17401 	}
17402 }
17403 
17404 /*
17405  * This routine is needed for loopback when forwarding multicasts.
17406  *
17407  * IPQoS Notes:
17408  * IPPF processing is done in fanout routines.
17409  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17410  * processing for IPsec packets is done when it comes back in clear.
17411  * NOTE : The callers of this function need to do the ire_refrele for the
17412  *	  ire that is being passed in.
17413  */
17414 void
17415 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17416     ill_t *recv_ill, uint32_t esp_udp_ports)
17417 {
17418 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17419 	ill_t	*ill = (ill_t *)q->q_ptr;
17420 	uint32_t	sum;
17421 	uint32_t	u1;
17422 	uint32_t	u2;
17423 	int		hdr_length;
17424 	boolean_t	mctl_present;
17425 	mblk_t		*first_mp = mp;
17426 	mblk_t		*hada_mp = NULL;
17427 	ipha_t		*inner_ipha;
17428 	ip_stack_t	*ipst;
17429 
17430 	ASSERT(recv_ill != NULL);
17431 	ipst = recv_ill->ill_ipst;
17432 
17433 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17434 	    "ip_rput_locl_start: q %p", q);
17435 
17436 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17437 	ASSERT(ill != NULL);
17438 
17439 #define	rptr	((uchar_t *)ipha)
17440 #define	iphs	((uint16_t *)ipha)
17441 
17442 	/*
17443 	 * no UDP or TCP packet should come here anymore.
17444 	 */
17445 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17446 	    ipha->ipha_protocol != IPPROTO_UDP);
17447 
17448 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17449 	if (mctl_present &&
17450 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17451 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17452 
17453 		/*
17454 		 * It's an IPsec accelerated packet.
17455 		 * Keep a pointer to the data attributes around until
17456 		 * we allocate the ipsec_info_t.
17457 		 */
17458 		IPSECHW_DEBUG(IPSECHW_PKT,
17459 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17460 		hada_mp = first_mp;
17461 		hada_mp->b_cont = NULL;
17462 		/*
17463 		 * Since it is accelerated, it comes directly from
17464 		 * the ill and the data attributes is followed by
17465 		 * the packet data.
17466 		 */
17467 		ASSERT(mp->b_datap->db_type != M_CTL);
17468 		first_mp = mp;
17469 		mctl_present = B_FALSE;
17470 	}
17471 
17472 	/*
17473 	 * IF M_CTL is not present, then ipsec_in_is_secure
17474 	 * should return B_TRUE. There is a case where loopback
17475 	 * packets has an M_CTL in the front with all the
17476 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17477 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17478 	 * packets never comes here, it is safe to ASSERT the
17479 	 * following.
17480 	 */
17481 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17482 
17483 	/*
17484 	 * Also, we should never have an mctl_present if this is an
17485 	 * ESP-in-UDP packet.
17486 	 */
17487 	ASSERT(!mctl_present || !esp_in_udp_packet);
17488 
17489 	/* u1 is # words of IP options */
17490 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17491 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17492 
17493 	/*
17494 	 * Don't verify header checksum if we just removed UDP header or
17495 	 * packet is coming back from AH/ESP.
17496 	 */
17497 	if (!esp_in_udp_packet && !mctl_present) {
17498 		if (u1) {
17499 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17500 				if (hada_mp != NULL)
17501 					freemsg(hada_mp);
17502 				return;
17503 			}
17504 		} else {
17505 			/* Check the IP header checksum.  */
17506 #define	uph	((uint16_t *)ipha)
17507 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17508 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17509 #undef  uph
17510 			/* finish doing IP checksum */
17511 			sum = (sum & 0xFFFF) + (sum >> 16);
17512 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17513 			if (sum && sum != 0xFFFF) {
17514 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17515 				goto drop_pkt;
17516 			}
17517 		}
17518 	}
17519 
17520 	/*
17521 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17522 	 * might be called more than once for secure packets, count only
17523 	 * the first time.
17524 	 */
17525 	if (!mctl_present) {
17526 		UPDATE_IB_PKT_COUNT(ire);
17527 		ire->ire_last_used_time = lbolt;
17528 	}
17529 
17530 	/* Check for fragmentation offset. */
17531 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17532 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17533 	if (u1) {
17534 		/*
17535 		 * We re-assemble fragments before we do the AH/ESP
17536 		 * processing. Thus, M_CTL should not be present
17537 		 * while we are re-assembling.
17538 		 */
17539 		ASSERT(!mctl_present);
17540 		ASSERT(first_mp == mp);
17541 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17542 			return;
17543 
17544 		/*
17545 		 * Make sure that first_mp points back to mp as
17546 		 * the mp we came in with could have changed in
17547 		 * ip_rput_fragment().
17548 		 */
17549 		ipha = (ipha_t *)mp->b_rptr;
17550 		first_mp = mp;
17551 	}
17552 
17553 	/*
17554 	 * Clear hardware checksumming flag as it is currently only
17555 	 * used by TCP and UDP.
17556 	 */
17557 	DB_CKSUMFLAGS(mp) = 0;
17558 
17559 	/* Now we have a complete datagram, destined for this machine. */
17560 	u1 = IPH_HDR_LENGTH(ipha);
17561 	switch (ipha->ipha_protocol) {
17562 	case IPPROTO_ICMP: {
17563 		ire_t		*ire_zone;
17564 		ilm_t		*ilm;
17565 		mblk_t		*mp1;
17566 		zoneid_t	last_zoneid;
17567 		ilm_walker_t	ilw;
17568 
17569 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17570 			ASSERT(ire->ire_type == IRE_BROADCAST);
17571 
17572 			/*
17573 			 * In the multicast case, applications may have joined
17574 			 * the group from different zones, so we need to deliver
17575 			 * the packet to each of them. Loop through the
17576 			 * multicast memberships structures (ilm) on the receive
17577 			 * ill and send a copy of the packet up each matching
17578 			 * one. However, we don't do this for multicasts sent on
17579 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17580 			 * they must stay in the sender's zone.
17581 			 *
17582 			 * ilm_add_v6() ensures that ilms in the same zone are
17583 			 * contiguous in the ill_ilm list. We use this property
17584 			 * to avoid sending duplicates needed when two
17585 			 * applications in the same zone join the same group on
17586 			 * different logical interfaces: we ignore the ilm if
17587 			 * its zoneid is the same as the last matching one.
17588 			 * In addition, the sending of the packet for
17589 			 * ire_zoneid is delayed until all of the other ilms
17590 			 * have been exhausted.
17591 			 */
17592 			last_zoneid = -1;
17593 			ilm = ilm_walker_start(&ilw, recv_ill);
17594 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17595 				if (ipha->ipha_dst != ilm->ilm_addr ||
17596 				    ilm->ilm_zoneid == last_zoneid ||
17597 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17598 				    ilm->ilm_zoneid == ALL_ZONES ||
17599 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17600 					continue;
17601 				mp1 = ip_copymsg(first_mp);
17602 				if (mp1 == NULL)
17603 					continue;
17604 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17605 				    0, sum, mctl_present, B_TRUE,
17606 				    recv_ill, ilm->ilm_zoneid);
17607 				last_zoneid = ilm->ilm_zoneid;
17608 			}
17609 			ilm_walker_finish(&ilw);
17610 		} else if (ire->ire_type == IRE_BROADCAST) {
17611 			/*
17612 			 * In the broadcast case, there may be many zones
17613 			 * which need a copy of the packet delivered to them.
17614 			 * There is one IRE_BROADCAST per broadcast address
17615 			 * and per zone; we walk those using a helper function.
17616 			 * In addition, the sending of the packet for ire is
17617 			 * delayed until all of the other ires have been
17618 			 * processed.
17619 			 */
17620 			IRB_REFHOLD(ire->ire_bucket);
17621 			ire_zone = NULL;
17622 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17623 			    ire)) != NULL) {
17624 				mp1 = ip_copymsg(first_mp);
17625 				if (mp1 == NULL)
17626 					continue;
17627 
17628 				UPDATE_IB_PKT_COUNT(ire_zone);
17629 				ire_zone->ire_last_used_time = lbolt;
17630 				icmp_inbound(q, mp1, B_TRUE, ill,
17631 				    0, sum, mctl_present, B_TRUE,
17632 				    recv_ill, ire_zone->ire_zoneid);
17633 			}
17634 			IRB_REFRELE(ire->ire_bucket);
17635 		}
17636 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17637 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17638 		    ire->ire_zoneid);
17639 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17640 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17641 		return;
17642 	}
17643 	case IPPROTO_IGMP:
17644 		/*
17645 		 * If we are not willing to accept IGMP packets in clear,
17646 		 * then check with global policy.
17647 		 */
17648 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17649 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17650 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17651 			if (first_mp == NULL)
17652 				return;
17653 		}
17654 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17655 			freemsg(first_mp);
17656 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17657 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17658 			return;
17659 		}
17660 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17661 			/* Bad packet - discarded by igmp_input */
17662 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17663 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17664 			if (mctl_present)
17665 				freeb(first_mp);
17666 			return;
17667 		}
17668 		/*
17669 		 * igmp_input() may have returned the pulled up message.
17670 		 * So first_mp and ipha need to be reinitialized.
17671 		 */
17672 		ipha = (ipha_t *)mp->b_rptr;
17673 		if (mctl_present)
17674 			first_mp->b_cont = mp;
17675 		else
17676 			first_mp = mp;
17677 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17678 		    connf_head != NULL) {
17679 			/* No user-level listener for IGMP packets */
17680 			goto drop_pkt;
17681 		}
17682 		/* deliver to local raw users */
17683 		break;
17684 	case IPPROTO_PIM:
17685 		/*
17686 		 * If we are not willing to accept PIM packets in clear,
17687 		 * then check with global policy.
17688 		 */
17689 		if (ipst->ips_pim_accept_clear_messages == 0) {
17690 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17691 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17692 			if (first_mp == NULL)
17693 				return;
17694 		}
17695 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17696 			freemsg(first_mp);
17697 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17698 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17699 			return;
17700 		}
17701 		if (pim_input(q, mp, ill) != 0) {
17702 			/* Bad packet - discarded by pim_input */
17703 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17704 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17705 			if (mctl_present)
17706 				freeb(first_mp);
17707 			return;
17708 		}
17709 
17710 		/*
17711 		 * pim_input() may have pulled up the message so ipha needs to
17712 		 * be reinitialized.
17713 		 */
17714 		ipha = (ipha_t *)mp->b_rptr;
17715 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17716 		    connf_head != NULL) {
17717 			/* No user-level listener for PIM packets */
17718 			goto drop_pkt;
17719 		}
17720 		/* deliver to local raw users */
17721 		break;
17722 	case IPPROTO_ENCAP:
17723 		/*
17724 		 * Handle self-encapsulated packets (IP-in-IP where
17725 		 * the inner addresses == the outer addresses).
17726 		 */
17727 		hdr_length = IPH_HDR_LENGTH(ipha);
17728 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17729 		    mp->b_wptr) {
17730 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17731 			    sizeof (ipha_t) - mp->b_rptr)) {
17732 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17733 				freemsg(first_mp);
17734 				return;
17735 			}
17736 			ipha = (ipha_t *)mp->b_rptr;
17737 		}
17738 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17739 		/*
17740 		 * Check the sanity of the inner IP header.
17741 		 */
17742 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17743 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17744 			freemsg(first_mp);
17745 			return;
17746 		}
17747 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17748 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17749 			freemsg(first_mp);
17750 			return;
17751 		}
17752 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17753 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17754 			ipsec_in_t *ii;
17755 
17756 			/*
17757 			 * Self-encapsulated tunnel packet. Remove
17758 			 * the outer IP header and fanout again.
17759 			 * We also need to make sure that the inner
17760 			 * header is pulled up until options.
17761 			 */
17762 			mp->b_rptr = (uchar_t *)inner_ipha;
17763 			ipha = inner_ipha;
17764 			hdr_length = IPH_HDR_LENGTH(ipha);
17765 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17766 				if (!pullupmsg(mp, (uchar_t *)ipha +
17767 				    + hdr_length - mp->b_rptr)) {
17768 					freemsg(first_mp);
17769 					return;
17770 				}
17771 				ipha = (ipha_t *)mp->b_rptr;
17772 			}
17773 			if (hdr_length > sizeof (ipha_t)) {
17774 				/* We got options on the inner packet. */
17775 				ipaddr_t dst = ipha->ipha_dst;
17776 
17777 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17778 				    -1) {
17779 					/* Bad options! */
17780 					return;
17781 				}
17782 				if (dst != ipha->ipha_dst) {
17783 					/*
17784 					 * Someone put a source-route in
17785 					 * the inside header of a self-
17786 					 * encapsulated packet.  Drop it
17787 					 * with extreme prejudice and let
17788 					 * the sender know.
17789 					 */
17790 					icmp_unreachable(q, first_mp,
17791 					    ICMP_SOURCE_ROUTE_FAILED,
17792 					    recv_ill->ill_zoneid, ipst);
17793 					return;
17794 				}
17795 			}
17796 			if (!mctl_present) {
17797 				ASSERT(first_mp == mp);
17798 				/*
17799 				 * This means that somebody is sending
17800 				 * Self-encapsualted packets without AH/ESP.
17801 				 * If AH/ESP was present, we would have already
17802 				 * allocated the first_mp.
17803 				 *
17804 				 * Send this packet to find a tunnel endpoint.
17805 				 * if I can't find one, an ICMP
17806 				 * PROTOCOL_UNREACHABLE will get sent.
17807 				 */
17808 				goto fanout;
17809 			}
17810 			/*
17811 			 * We generally store the ill_index if we need to
17812 			 * do IPsec processing as we lose the ill queue when
17813 			 * we come back. But in this case, we never should
17814 			 * have to store the ill_index here as it should have
17815 			 * been stored previously when we processed the
17816 			 * AH/ESP header in this routine or for non-ipsec
17817 			 * cases, we still have the queue. But for some bad
17818 			 * packets from the wire, we can get to IPsec after
17819 			 * this and we better store the index for that case.
17820 			 */
17821 			ill = (ill_t *)q->q_ptr;
17822 			ii = (ipsec_in_t *)first_mp->b_rptr;
17823 			ii->ipsec_in_ill_index =
17824 			    ill->ill_phyint->phyint_ifindex;
17825 			ii->ipsec_in_rill_index =
17826 			    recv_ill->ill_phyint->phyint_ifindex;
17827 			if (ii->ipsec_in_decaps) {
17828 				/*
17829 				 * This packet is self-encapsulated multiple
17830 				 * times. We don't want to recurse infinitely.
17831 				 * To keep it simple, drop the packet.
17832 				 */
17833 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17834 				freemsg(first_mp);
17835 				return;
17836 			}
17837 			ii->ipsec_in_decaps = B_TRUE;
17838 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17839 			    ire);
17840 			return;
17841 		}
17842 		break;
17843 	case IPPROTO_AH:
17844 	case IPPROTO_ESP: {
17845 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17846 
17847 		/*
17848 		 * Fast path for AH/ESP. If this is the first time
17849 		 * we are sending a datagram to AH/ESP, allocate
17850 		 * a IPSEC_IN message and prepend it. Otherwise,
17851 		 * just fanout.
17852 		 */
17853 
17854 		int ipsec_rc;
17855 		ipsec_in_t *ii;
17856 		netstack_t *ns = ipst->ips_netstack;
17857 
17858 		IP_STAT(ipst, ipsec_proto_ahesp);
17859 		if (!mctl_present) {
17860 			ASSERT(first_mp == mp);
17861 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17862 			if (first_mp == NULL) {
17863 				ip1dbg(("ip_proto_input: IPSEC_IN "
17864 				    "allocation failure.\n"));
17865 				freemsg(hada_mp); /* okay ifnull */
17866 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17867 				freemsg(mp);
17868 				return;
17869 			}
17870 			/*
17871 			 * Store the ill_index so that when we come back
17872 			 * from IPsec we ride on the same queue.
17873 			 */
17874 			ill = (ill_t *)q->q_ptr;
17875 			ii = (ipsec_in_t *)first_mp->b_rptr;
17876 			ii->ipsec_in_ill_index =
17877 			    ill->ill_phyint->phyint_ifindex;
17878 			ii->ipsec_in_rill_index =
17879 			    recv_ill->ill_phyint->phyint_ifindex;
17880 			first_mp->b_cont = mp;
17881 			/*
17882 			 * Cache hardware acceleration info.
17883 			 */
17884 			if (hada_mp != NULL) {
17885 				IPSECHW_DEBUG(IPSECHW_PKT,
17886 				    ("ip_rput_local: caching data attr.\n"));
17887 				ii->ipsec_in_accelerated = B_TRUE;
17888 				ii->ipsec_in_da = hada_mp;
17889 				hada_mp = NULL;
17890 			}
17891 		} else {
17892 			ii = (ipsec_in_t *)first_mp->b_rptr;
17893 		}
17894 
17895 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17896 
17897 		if (!ipsec_loaded(ipss)) {
17898 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17899 			    ire->ire_zoneid, ipst);
17900 			return;
17901 		}
17902 
17903 		ns = ipst->ips_netstack;
17904 		/* select inbound SA and have IPsec process the pkt */
17905 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17906 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17907 			boolean_t esp_in_udp_sa;
17908 			if (esph == NULL)
17909 				return;
17910 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17911 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17912 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17913 			    IPSA_F_NATT) != 0);
17914 			/*
17915 			 * The following is a fancy, but quick, way of saying:
17916 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17917 			 *    OR
17918 			 * ESP SA and ESP-in-UDP packet --> drop
17919 			 */
17920 			if (esp_in_udp_sa != esp_in_udp_packet) {
17921 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17922 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17923 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17924 				    &ns->netstack_ipsec->ipsec_dropper);
17925 				return;
17926 			}
17927 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17928 			    first_mp, esph);
17929 		} else {
17930 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17931 			if (ah == NULL)
17932 				return;
17933 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17934 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17935 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17936 			    first_mp, ah);
17937 		}
17938 
17939 		switch (ipsec_rc) {
17940 		case IPSEC_STATUS_SUCCESS:
17941 			break;
17942 		case IPSEC_STATUS_FAILED:
17943 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17944 			/* FALLTHRU */
17945 		case IPSEC_STATUS_PENDING:
17946 			return;
17947 		}
17948 		/* we're done with IPsec processing, send it up */
17949 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17950 		return;
17951 	}
17952 	default:
17953 		break;
17954 	}
17955 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17956 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17957 		    ire->ire_zoneid));
17958 		goto drop_pkt;
17959 	}
17960 	/*
17961 	 * Handle protocols with which IP is less intimate.  There
17962 	 * can be more than one stream bound to a particular
17963 	 * protocol.  When this is the case, each one gets a copy
17964 	 * of any incoming packets.
17965 	 */
17966 fanout:
17967 	ip_fanout_proto(q, first_mp, ill, ipha,
17968 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17969 	    B_TRUE, recv_ill, ire->ire_zoneid);
17970 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17971 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17972 	return;
17973 
17974 drop_pkt:
17975 	freemsg(first_mp);
17976 	if (hada_mp != NULL)
17977 		freeb(hada_mp);
17978 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17979 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17980 #undef	rptr
17981 #undef  iphs
17982 
17983 }
17984 
17985 /*
17986  * Update any source route, record route or timestamp options.
17987  * Check that we are at end of strict source route.
17988  * The options have already been checked for sanity in ip_rput_options().
17989  */
17990 static boolean_t
17991 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17992     ip_stack_t *ipst)
17993 {
17994 	ipoptp_t	opts;
17995 	uchar_t		*opt;
17996 	uint8_t		optval;
17997 	uint8_t		optlen;
17998 	ipaddr_t	dst;
17999 	uint32_t	ts;
18000 	ire_t		*dst_ire;
18001 	timestruc_t	now;
18002 	zoneid_t	zoneid;
18003 	ill_t		*ill;
18004 
18005 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18006 
18007 	ip2dbg(("ip_rput_local_options\n"));
18008 
18009 	for (optval = ipoptp_first(&opts, ipha);
18010 	    optval != IPOPT_EOL;
18011 	    optval = ipoptp_next(&opts)) {
18012 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18013 		opt = opts.ipoptp_cur;
18014 		optlen = opts.ipoptp_len;
18015 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18016 		    optval, optlen));
18017 		switch (optval) {
18018 			uint32_t off;
18019 		case IPOPT_SSRR:
18020 		case IPOPT_LSRR:
18021 			off = opt[IPOPT_OFFSET];
18022 			off--;
18023 			if (optlen < IP_ADDR_LEN ||
18024 			    off > optlen - IP_ADDR_LEN) {
18025 				/* End of source route */
18026 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18027 				break;
18028 			}
18029 			/*
18030 			 * This will only happen if two consecutive entries
18031 			 * in the source route contains our address or if
18032 			 * it is a packet with a loose source route which
18033 			 * reaches us before consuming the whole source route
18034 			 */
18035 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18036 			if (optval == IPOPT_SSRR) {
18037 				goto bad_src_route;
18038 			}
18039 			/*
18040 			 * Hack: instead of dropping the packet truncate the
18041 			 * source route to what has been used by filling the
18042 			 * rest with IPOPT_NOP.
18043 			 */
18044 			opt[IPOPT_OLEN] = (uint8_t)off;
18045 			while (off < optlen) {
18046 				opt[off++] = IPOPT_NOP;
18047 			}
18048 			break;
18049 		case IPOPT_RR:
18050 			off = opt[IPOPT_OFFSET];
18051 			off--;
18052 			if (optlen < IP_ADDR_LEN ||
18053 			    off > optlen - IP_ADDR_LEN) {
18054 				/* No more room - ignore */
18055 				ip1dbg((
18056 				    "ip_rput_local_options: end of RR\n"));
18057 				break;
18058 			}
18059 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18060 			    IP_ADDR_LEN);
18061 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18062 			break;
18063 		case IPOPT_TS:
18064 			/* Insert timestamp if there is romm */
18065 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18066 			case IPOPT_TS_TSONLY:
18067 				off = IPOPT_TS_TIMELEN;
18068 				break;
18069 			case IPOPT_TS_PRESPEC:
18070 			case IPOPT_TS_PRESPEC_RFC791:
18071 				/* Verify that the address matched */
18072 				off = opt[IPOPT_OFFSET] - 1;
18073 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18074 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18075 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18076 				    ipst);
18077 				if (dst_ire == NULL) {
18078 					/* Not for us */
18079 					break;
18080 				}
18081 				ire_refrele(dst_ire);
18082 				/* FALLTHRU */
18083 			case IPOPT_TS_TSANDADDR:
18084 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18085 				break;
18086 			default:
18087 				/*
18088 				 * ip_*put_options should have already
18089 				 * dropped this packet.
18090 				 */
18091 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18092 				    "unknown IT - bug in ip_rput_options?\n");
18093 				return (B_TRUE);	/* Keep "lint" happy */
18094 			}
18095 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18096 				/* Increase overflow counter */
18097 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18098 				opt[IPOPT_POS_OV_FLG] =
18099 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18100 				    (off << 4));
18101 				break;
18102 			}
18103 			off = opt[IPOPT_OFFSET] - 1;
18104 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18105 			case IPOPT_TS_PRESPEC:
18106 			case IPOPT_TS_PRESPEC_RFC791:
18107 			case IPOPT_TS_TSANDADDR:
18108 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18109 				    IP_ADDR_LEN);
18110 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18111 				/* FALLTHRU */
18112 			case IPOPT_TS_TSONLY:
18113 				off = opt[IPOPT_OFFSET] - 1;
18114 				/* Compute # of milliseconds since midnight */
18115 				gethrestime(&now);
18116 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18117 				    now.tv_nsec / (NANOSEC / MILLISEC);
18118 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18119 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18120 				break;
18121 			}
18122 			break;
18123 		}
18124 	}
18125 	return (B_TRUE);
18126 
18127 bad_src_route:
18128 	q = WR(q);
18129 	if (q->q_next != NULL)
18130 		ill = q->q_ptr;
18131 	else
18132 		ill = NULL;
18133 
18134 	/* make sure we clear any indication of a hardware checksum */
18135 	DB_CKSUMFLAGS(mp) = 0;
18136 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18137 	if (zoneid == ALL_ZONES)
18138 		freemsg(mp);
18139 	else
18140 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18141 	return (B_FALSE);
18142 
18143 }
18144 
18145 /*
18146  * Process IP options in an inbound packet.  If an option affects the
18147  * effective destination address, return the next hop address via dstp.
18148  * Returns -1 if something fails in which case an ICMP error has been sent
18149  * and mp freed.
18150  */
18151 static int
18152 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18153     ip_stack_t *ipst)
18154 {
18155 	ipoptp_t	opts;
18156 	uchar_t		*opt;
18157 	uint8_t		optval;
18158 	uint8_t		optlen;
18159 	ipaddr_t	dst;
18160 	intptr_t	code = 0;
18161 	ire_t		*ire = NULL;
18162 	zoneid_t	zoneid;
18163 	ill_t		*ill;
18164 
18165 	ip2dbg(("ip_rput_options\n"));
18166 	dst = ipha->ipha_dst;
18167 	for (optval = ipoptp_first(&opts, ipha);
18168 	    optval != IPOPT_EOL;
18169 	    optval = ipoptp_next(&opts)) {
18170 		opt = opts.ipoptp_cur;
18171 		optlen = opts.ipoptp_len;
18172 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18173 		    optval, optlen));
18174 		/*
18175 		 * Note: we need to verify the checksum before we
18176 		 * modify anything thus this routine only extracts the next
18177 		 * hop dst from any source route.
18178 		 */
18179 		switch (optval) {
18180 			uint32_t off;
18181 		case IPOPT_SSRR:
18182 		case IPOPT_LSRR:
18183 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18184 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18185 			if (ire == NULL) {
18186 				if (optval == IPOPT_SSRR) {
18187 					ip1dbg(("ip_rput_options: not next"
18188 					    " strict source route 0x%x\n",
18189 					    ntohl(dst)));
18190 					code = (char *)&ipha->ipha_dst -
18191 					    (char *)ipha;
18192 					goto param_prob; /* RouterReq's */
18193 				}
18194 				ip2dbg(("ip_rput_options: "
18195 				    "not next source route 0x%x\n",
18196 				    ntohl(dst)));
18197 				break;
18198 			}
18199 			ire_refrele(ire);
18200 
18201 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18202 				ip1dbg((
18203 				    "ip_rput_options: bad option offset\n"));
18204 				code = (char *)&opt[IPOPT_OLEN] -
18205 				    (char *)ipha;
18206 				goto param_prob;
18207 			}
18208 			off = opt[IPOPT_OFFSET];
18209 			off--;
18210 		redo_srr:
18211 			if (optlen < IP_ADDR_LEN ||
18212 			    off > optlen - IP_ADDR_LEN) {
18213 				/* End of source route */
18214 				ip1dbg(("ip_rput_options: end of SR\n"));
18215 				break;
18216 			}
18217 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18218 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18219 			    ntohl(dst)));
18220 
18221 			/*
18222 			 * Check if our address is present more than
18223 			 * once as consecutive hops in source route.
18224 			 * XXX verify per-interface ip_forwarding
18225 			 * for source route?
18226 			 */
18227 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18228 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18229 
18230 			if (ire != NULL) {
18231 				ire_refrele(ire);
18232 				off += IP_ADDR_LEN;
18233 				goto redo_srr;
18234 			}
18235 
18236 			if (dst == htonl(INADDR_LOOPBACK)) {
18237 				ip1dbg(("ip_rput_options: loopback addr in "
18238 				    "source route!\n"));
18239 				goto bad_src_route;
18240 			}
18241 			/*
18242 			 * For strict: verify that dst is directly
18243 			 * reachable.
18244 			 */
18245 			if (optval == IPOPT_SSRR) {
18246 				ire = ire_ftable_lookup(dst, 0, 0,
18247 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18248 				    msg_getlabel(mp),
18249 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18250 				if (ire == NULL) {
18251 					ip1dbg(("ip_rput_options: SSRR not "
18252 					    "directly reachable: 0x%x\n",
18253 					    ntohl(dst)));
18254 					goto bad_src_route;
18255 				}
18256 				ire_refrele(ire);
18257 			}
18258 			/*
18259 			 * Defer update of the offset and the record route
18260 			 * until the packet is forwarded.
18261 			 */
18262 			break;
18263 		case IPOPT_RR:
18264 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18265 				ip1dbg((
18266 				    "ip_rput_options: bad option offset\n"));
18267 				code = (char *)&opt[IPOPT_OLEN] -
18268 				    (char *)ipha;
18269 				goto param_prob;
18270 			}
18271 			break;
18272 		case IPOPT_TS:
18273 			/*
18274 			 * Verify that length >= 5 and that there is either
18275 			 * room for another timestamp or that the overflow
18276 			 * counter is not maxed out.
18277 			 */
18278 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18279 			if (optlen < IPOPT_MINLEN_IT) {
18280 				goto param_prob;
18281 			}
18282 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18283 				ip1dbg((
18284 				    "ip_rput_options: bad option offset\n"));
18285 				code = (char *)&opt[IPOPT_OFFSET] -
18286 				    (char *)ipha;
18287 				goto param_prob;
18288 			}
18289 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18290 			case IPOPT_TS_TSONLY:
18291 				off = IPOPT_TS_TIMELEN;
18292 				break;
18293 			case IPOPT_TS_TSANDADDR:
18294 			case IPOPT_TS_PRESPEC:
18295 			case IPOPT_TS_PRESPEC_RFC791:
18296 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18297 				break;
18298 			default:
18299 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18300 				    (char *)ipha;
18301 				goto param_prob;
18302 			}
18303 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18304 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18305 				/*
18306 				 * No room and the overflow counter is 15
18307 				 * already.
18308 				 */
18309 				goto param_prob;
18310 			}
18311 			break;
18312 		}
18313 	}
18314 
18315 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18316 		*dstp = dst;
18317 		return (0);
18318 	}
18319 
18320 	ip1dbg(("ip_rput_options: error processing IP options."));
18321 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18322 
18323 param_prob:
18324 	q = WR(q);
18325 	if (q->q_next != NULL)
18326 		ill = q->q_ptr;
18327 	else
18328 		ill = NULL;
18329 
18330 	/* make sure we clear any indication of a hardware checksum */
18331 	DB_CKSUMFLAGS(mp) = 0;
18332 	/* Don't know whether this is for non-global or global/forwarding */
18333 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18334 	if (zoneid == ALL_ZONES)
18335 		freemsg(mp);
18336 	else
18337 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18338 	return (-1);
18339 
18340 bad_src_route:
18341 	q = WR(q);
18342 	if (q->q_next != NULL)
18343 		ill = q->q_ptr;
18344 	else
18345 		ill = NULL;
18346 
18347 	/* make sure we clear any indication of a hardware checksum */
18348 	DB_CKSUMFLAGS(mp) = 0;
18349 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18350 	if (zoneid == ALL_ZONES)
18351 		freemsg(mp);
18352 	else
18353 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18354 	return (-1);
18355 }
18356 
18357 /*
18358  * IP & ICMP info in >=14 msg's ...
18359  *  - ip fixed part (mib2_ip_t)
18360  *  - icmp fixed part (mib2_icmp_t)
18361  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18362  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18363  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18364  *  - ipRouteAttributeTable (ip 102)	labeled routes
18365  *  - ip multicast membership (ip_member_t)
18366  *  - ip multicast source filtering (ip_grpsrc_t)
18367  *  - igmp fixed part (struct igmpstat)
18368  *  - multicast routing stats (struct mrtstat)
18369  *  - multicast routing vifs (array of struct vifctl)
18370  *  - multicast routing routes (array of struct mfcctl)
18371  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18372  *					One per ill plus one generic
18373  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18374  *					One per ill plus one generic
18375  *  - ipv6RouteEntry			all IPv6 IREs
18376  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18377  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18378  *  - ipv6AddrEntry			all IPv6 ipifs
18379  *  - ipv6 multicast membership (ipv6_member_t)
18380  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18381  *
18382  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18383  *
18384  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18385  * already filled in by the caller.
18386  * Return value of 0 indicates that no messages were sent and caller
18387  * should free mpctl.
18388  */
18389 int
18390 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18391 {
18392 	ip_stack_t *ipst;
18393 	sctp_stack_t *sctps;
18394 
18395 	if (q->q_next != NULL) {
18396 		ipst = ILLQ_TO_IPST(q);
18397 	} else {
18398 		ipst = CONNQ_TO_IPST(q);
18399 	}
18400 	ASSERT(ipst != NULL);
18401 	sctps = ipst->ips_netstack->netstack_sctp;
18402 
18403 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18404 		return (0);
18405 	}
18406 
18407 	/*
18408 	 * For the purposes of the (broken) packet shell use
18409 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18410 	 * to make TCP and UDP appear first in the list of mib items.
18411 	 * TBD: We could expand this and use it in netstat so that
18412 	 * the kernel doesn't have to produce large tables (connections,
18413 	 * routes, etc) when netstat only wants the statistics or a particular
18414 	 * table.
18415 	 */
18416 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18417 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18418 			return (1);
18419 		}
18420 	}
18421 
18422 	if (level != MIB2_TCP) {
18423 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18424 			return (1);
18425 		}
18426 	}
18427 
18428 	if (level != MIB2_UDP) {
18429 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18430 			return (1);
18431 		}
18432 	}
18433 
18434 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18435 	    ipst)) == NULL) {
18436 		return (1);
18437 	}
18438 
18439 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18440 		return (1);
18441 	}
18442 
18443 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18444 		return (1);
18445 	}
18446 
18447 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18448 		return (1);
18449 	}
18450 
18451 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18452 		return (1);
18453 	}
18454 
18455 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18456 		return (1);
18457 	}
18458 
18459 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18460 		return (1);
18461 	}
18462 
18463 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18464 		return (1);
18465 	}
18466 
18467 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18468 		return (1);
18469 	}
18470 
18471 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18472 		return (1);
18473 	}
18474 
18475 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18476 		return (1);
18477 	}
18478 
18479 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18480 		return (1);
18481 	}
18482 
18483 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18484 		return (1);
18485 	}
18486 
18487 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18488 		return (1);
18489 	}
18490 
18491 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18492 	if (mpctl == NULL)
18493 		return (1);
18494 
18495 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18496 	if (mpctl == NULL)
18497 		return (1);
18498 
18499 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18500 		return (1);
18501 	}
18502 	freemsg(mpctl);
18503 	return (1);
18504 }
18505 
18506 /* Get global (legacy) IPv4 statistics */
18507 static mblk_t *
18508 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18509     ip_stack_t *ipst)
18510 {
18511 	mib2_ip_t		old_ip_mib;
18512 	struct opthdr		*optp;
18513 	mblk_t			*mp2ctl;
18514 
18515 	/*
18516 	 * make a copy of the original message
18517 	 */
18518 	mp2ctl = copymsg(mpctl);
18519 
18520 	/* fixed length IP structure... */
18521 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18522 	optp->level = MIB2_IP;
18523 	optp->name = 0;
18524 	SET_MIB(old_ip_mib.ipForwarding,
18525 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18526 	SET_MIB(old_ip_mib.ipDefaultTTL,
18527 	    (uint32_t)ipst->ips_ip_def_ttl);
18528 	SET_MIB(old_ip_mib.ipReasmTimeout,
18529 	    ipst->ips_ip_g_frag_timeout);
18530 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18531 	    sizeof (mib2_ipAddrEntry_t));
18532 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18533 	    sizeof (mib2_ipRouteEntry_t));
18534 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18535 	    sizeof (mib2_ipNetToMediaEntry_t));
18536 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18537 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18538 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18539 	    sizeof (mib2_ipAttributeEntry_t));
18540 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18541 
18542 	/*
18543 	 * Grab the statistics from the new IP MIB
18544 	 */
18545 	SET_MIB(old_ip_mib.ipInReceives,
18546 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18547 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18548 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18549 	SET_MIB(old_ip_mib.ipForwDatagrams,
18550 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18551 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18552 	    ipmib->ipIfStatsInUnknownProtos);
18553 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18554 	SET_MIB(old_ip_mib.ipInDelivers,
18555 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18556 	SET_MIB(old_ip_mib.ipOutRequests,
18557 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18558 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18559 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18560 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18561 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18562 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18563 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18564 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18565 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18566 
18567 	/* ipRoutingDiscards is not being used */
18568 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18569 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18570 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18571 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18572 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18573 	    ipmib->ipIfStatsReasmDuplicates);
18574 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18575 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18576 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18577 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18578 	SET_MIB(old_ip_mib.rawipInOverflows,
18579 	    ipmib->rawipIfStatsInOverflows);
18580 
18581 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18582 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18583 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18584 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18585 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18586 	    ipmib->ipIfStatsOutSwitchIPVersion);
18587 
18588 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18589 	    (int)sizeof (old_ip_mib))) {
18590 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18591 		    (uint_t)sizeof (old_ip_mib)));
18592 	}
18593 
18594 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18595 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18596 	    (int)optp->level, (int)optp->name, (int)optp->len));
18597 	qreply(q, mpctl);
18598 	return (mp2ctl);
18599 }
18600 
18601 /* Per interface IPv4 statistics */
18602 static mblk_t *
18603 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18604 {
18605 	struct opthdr		*optp;
18606 	mblk_t			*mp2ctl;
18607 	ill_t			*ill;
18608 	ill_walk_context_t	ctx;
18609 	mblk_t			*mp_tail = NULL;
18610 	mib2_ipIfStatsEntry_t	global_ip_mib;
18611 
18612 	/*
18613 	 * Make a copy of the original message
18614 	 */
18615 	mp2ctl = copymsg(mpctl);
18616 
18617 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18618 	optp->level = MIB2_IP;
18619 	optp->name = MIB2_IP_TRAFFIC_STATS;
18620 	/* Include "unknown interface" ip_mib */
18621 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18622 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18623 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18624 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18625 	    (ipst->ips_ip_g_forward ? 1 : 2));
18626 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18627 	    (uint32_t)ipst->ips_ip_def_ttl);
18628 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18629 	    sizeof (mib2_ipIfStatsEntry_t));
18630 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18631 	    sizeof (mib2_ipAddrEntry_t));
18632 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18633 	    sizeof (mib2_ipRouteEntry_t));
18634 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18635 	    sizeof (mib2_ipNetToMediaEntry_t));
18636 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18637 	    sizeof (ip_member_t));
18638 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18639 	    sizeof (ip_grpsrc_t));
18640 
18641 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18642 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18643 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18644 		    "failed to allocate %u bytes\n",
18645 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18646 	}
18647 
18648 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18649 
18650 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18651 	ill = ILL_START_WALK_V4(&ctx, ipst);
18652 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18653 		ill->ill_ip_mib->ipIfStatsIfIndex =
18654 		    ill->ill_phyint->phyint_ifindex;
18655 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18656 		    (ipst->ips_ip_g_forward ? 1 : 2));
18657 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18658 		    (uint32_t)ipst->ips_ip_def_ttl);
18659 
18660 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18661 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18662 		    (char *)ill->ill_ip_mib,
18663 		    (int)sizeof (*ill->ill_ip_mib))) {
18664 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18665 			    "failed to allocate %u bytes\n",
18666 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18667 		}
18668 	}
18669 	rw_exit(&ipst->ips_ill_g_lock);
18670 
18671 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18672 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18673 	    "level %d, name %d, len %d\n",
18674 	    (int)optp->level, (int)optp->name, (int)optp->len));
18675 	qreply(q, mpctl);
18676 
18677 	if (mp2ctl == NULL)
18678 		return (NULL);
18679 
18680 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18681 }
18682 
18683 /* Global IPv4 ICMP statistics */
18684 static mblk_t *
18685 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18686 {
18687 	struct opthdr		*optp;
18688 	mblk_t			*mp2ctl;
18689 
18690 	/*
18691 	 * Make a copy of the original message
18692 	 */
18693 	mp2ctl = copymsg(mpctl);
18694 
18695 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18696 	optp->level = MIB2_ICMP;
18697 	optp->name = 0;
18698 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18699 	    (int)sizeof (ipst->ips_icmp_mib))) {
18700 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18701 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18702 	}
18703 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18704 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18705 	    (int)optp->level, (int)optp->name, (int)optp->len));
18706 	qreply(q, mpctl);
18707 	return (mp2ctl);
18708 }
18709 
18710 /* Global IPv4 IGMP statistics */
18711 static mblk_t *
18712 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18713 {
18714 	struct opthdr		*optp;
18715 	mblk_t			*mp2ctl;
18716 
18717 	/*
18718 	 * make a copy of the original message
18719 	 */
18720 	mp2ctl = copymsg(mpctl);
18721 
18722 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18723 	optp->level = EXPER_IGMP;
18724 	optp->name = 0;
18725 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18726 	    (int)sizeof (ipst->ips_igmpstat))) {
18727 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18728 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18729 	}
18730 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18731 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18732 	    (int)optp->level, (int)optp->name, (int)optp->len));
18733 	qreply(q, mpctl);
18734 	return (mp2ctl);
18735 }
18736 
18737 /* Global IPv4 Multicast Routing statistics */
18738 static mblk_t *
18739 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18740 {
18741 	struct opthdr		*optp;
18742 	mblk_t			*mp2ctl;
18743 
18744 	/*
18745 	 * make a copy of the original message
18746 	 */
18747 	mp2ctl = copymsg(mpctl);
18748 
18749 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18750 	optp->level = EXPER_DVMRP;
18751 	optp->name = 0;
18752 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18753 		ip0dbg(("ip_mroute_stats: failed\n"));
18754 	}
18755 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18756 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18757 	    (int)optp->level, (int)optp->name, (int)optp->len));
18758 	qreply(q, mpctl);
18759 	return (mp2ctl);
18760 }
18761 
18762 /* IPv4 address information */
18763 static mblk_t *
18764 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18765 {
18766 	struct opthdr		*optp;
18767 	mblk_t			*mp2ctl;
18768 	mblk_t			*mp_tail = NULL;
18769 	ill_t			*ill;
18770 	ipif_t			*ipif;
18771 	uint_t			bitval;
18772 	mib2_ipAddrEntry_t	mae;
18773 	zoneid_t		zoneid;
18774 	ill_walk_context_t ctx;
18775 
18776 	/*
18777 	 * make a copy of the original message
18778 	 */
18779 	mp2ctl = copymsg(mpctl);
18780 
18781 	/* ipAddrEntryTable */
18782 
18783 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18784 	optp->level = MIB2_IP;
18785 	optp->name = MIB2_IP_ADDR;
18786 	zoneid = Q_TO_CONN(q)->conn_zoneid;
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 		for (ipif = ill->ill_ipif; ipif != NULL;
18792 		    ipif = ipif->ipif_next) {
18793 			if (ipif->ipif_zoneid != zoneid &&
18794 			    ipif->ipif_zoneid != ALL_ZONES)
18795 				continue;
18796 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18797 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18798 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18799 
18800 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18801 			    OCTET_LENGTH);
18802 			mae.ipAdEntIfIndex.o_length =
18803 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18804 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18805 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18806 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18807 			mae.ipAdEntInfo.ae_subnet_len =
18808 			    ip_mask_to_plen(ipif->ipif_net_mask);
18809 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18810 			for (bitval = 1;
18811 			    bitval &&
18812 			    !(bitval & ipif->ipif_brd_addr);
18813 			    bitval <<= 1)
18814 				noop;
18815 			mae.ipAdEntBcastAddr = bitval;
18816 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18817 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18818 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18819 			mae.ipAdEntInfo.ae_broadcast_addr =
18820 			    ipif->ipif_brd_addr;
18821 			mae.ipAdEntInfo.ae_pp_dst_addr =
18822 			    ipif->ipif_pp_dst_addr;
18823 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18824 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18825 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18826 
18827 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18828 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18829 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18830 				    "allocate %u bytes\n",
18831 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18832 			}
18833 		}
18834 	}
18835 	rw_exit(&ipst->ips_ill_g_lock);
18836 
18837 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18838 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18839 	    (int)optp->level, (int)optp->name, (int)optp->len));
18840 	qreply(q, mpctl);
18841 	return (mp2ctl);
18842 }
18843 
18844 /* IPv6 address information */
18845 static mblk_t *
18846 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18847 {
18848 	struct opthdr		*optp;
18849 	mblk_t			*mp2ctl;
18850 	mblk_t			*mp_tail = NULL;
18851 	ill_t			*ill;
18852 	ipif_t			*ipif;
18853 	mib2_ipv6AddrEntry_t	mae6;
18854 	zoneid_t		zoneid;
18855 	ill_walk_context_t	ctx;
18856 
18857 	/*
18858 	 * make a copy of the original message
18859 	 */
18860 	mp2ctl = copymsg(mpctl);
18861 
18862 	/* ipv6AddrEntryTable */
18863 
18864 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18865 	optp->level = MIB2_IP6;
18866 	optp->name = MIB2_IP6_ADDR;
18867 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18868 
18869 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18870 	ill = ILL_START_WALK_V6(&ctx, ipst);
18871 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18872 		for (ipif = ill->ill_ipif; ipif != NULL;
18873 		    ipif = ipif->ipif_next) {
18874 			if (ipif->ipif_zoneid != zoneid &&
18875 			    ipif->ipif_zoneid != ALL_ZONES)
18876 				continue;
18877 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18878 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18879 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18880 
18881 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18882 			    OCTET_LENGTH);
18883 			mae6.ipv6AddrIfIndex.o_length =
18884 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18885 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18886 			mae6.ipv6AddrPfxLength =
18887 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18888 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18889 			mae6.ipv6AddrInfo.ae_subnet_len =
18890 			    mae6.ipv6AddrPfxLength;
18891 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18892 
18893 			/* Type: stateless(1), stateful(2), unknown(3) */
18894 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18895 				mae6.ipv6AddrType = 1;
18896 			else
18897 				mae6.ipv6AddrType = 2;
18898 			/* Anycast: true(1), false(2) */
18899 			if (ipif->ipif_flags & IPIF_ANYCAST)
18900 				mae6.ipv6AddrAnycastFlag = 1;
18901 			else
18902 				mae6.ipv6AddrAnycastFlag = 2;
18903 
18904 			/*
18905 			 * Address status: preferred(1), deprecated(2),
18906 			 * invalid(3), inaccessible(4), unknown(5)
18907 			 */
18908 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18909 				mae6.ipv6AddrStatus = 3;
18910 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18911 				mae6.ipv6AddrStatus = 2;
18912 			else
18913 				mae6.ipv6AddrStatus = 1;
18914 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18915 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18916 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18917 			    ipif->ipif_v6pp_dst_addr;
18918 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18919 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18920 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18921 			mae6.ipv6AddrIdentifier = ill->ill_token;
18922 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18923 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18924 			mae6.ipv6AddrRetransmitTime =
18925 			    ill->ill_reachable_retrans_time;
18926 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18927 			    (char *)&mae6,
18928 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18929 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18930 				    "allocate %u bytes\n",
18931 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18932 			}
18933 		}
18934 	}
18935 	rw_exit(&ipst->ips_ill_g_lock);
18936 
18937 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18938 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18939 	    (int)optp->level, (int)optp->name, (int)optp->len));
18940 	qreply(q, mpctl);
18941 	return (mp2ctl);
18942 }
18943 
18944 /* IPv4 multicast group membership. */
18945 static mblk_t *
18946 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18947 {
18948 	struct opthdr		*optp;
18949 	mblk_t			*mp2ctl;
18950 	ill_t			*ill;
18951 	ipif_t			*ipif;
18952 	ilm_t			*ilm;
18953 	ip_member_t		ipm;
18954 	mblk_t			*mp_tail = NULL;
18955 	ill_walk_context_t	ctx;
18956 	zoneid_t		zoneid;
18957 	ilm_walker_t		ilw;
18958 
18959 	/*
18960 	 * make a copy of the original message
18961 	 */
18962 	mp2ctl = copymsg(mpctl);
18963 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18964 
18965 	/* ipGroupMember table */
18966 	optp = (struct opthdr *)&mpctl->b_rptr[
18967 	    sizeof (struct T_optmgmt_ack)];
18968 	optp->level = MIB2_IP;
18969 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18970 
18971 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18972 	ill = ILL_START_WALK_V4(&ctx, ipst);
18973 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18974 		if (IS_UNDER_IPMP(ill))
18975 			continue;
18976 
18977 		ilm = ilm_walker_start(&ilw, ill);
18978 		for (ipif = ill->ill_ipif; ipif != NULL;
18979 		    ipif = ipif->ipif_next) {
18980 			if (ipif->ipif_zoneid != zoneid &&
18981 			    ipif->ipif_zoneid != ALL_ZONES)
18982 				continue;	/* not this zone */
18983 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18984 			    OCTET_LENGTH);
18985 			ipm.ipGroupMemberIfIndex.o_length =
18986 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18987 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18988 				ASSERT(ilm->ilm_ipif != NULL);
18989 				ASSERT(ilm->ilm_ill == NULL);
18990 				if (ilm->ilm_ipif != ipif)
18991 					continue;
18992 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18993 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18994 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18995 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18996 				    (char *)&ipm, (int)sizeof (ipm))) {
18997 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18998 					    "failed to allocate %u bytes\n",
18999 					    (uint_t)sizeof (ipm)));
19000 				}
19001 			}
19002 		}
19003 		ilm_walker_finish(&ilw);
19004 	}
19005 	rw_exit(&ipst->ips_ill_g_lock);
19006 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19007 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19008 	    (int)optp->level, (int)optp->name, (int)optp->len));
19009 	qreply(q, mpctl);
19010 	return (mp2ctl);
19011 }
19012 
19013 /* IPv6 multicast group membership. */
19014 static mblk_t *
19015 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19016 {
19017 	struct opthdr		*optp;
19018 	mblk_t			*mp2ctl;
19019 	ill_t			*ill;
19020 	ilm_t			*ilm;
19021 	ipv6_member_t		ipm6;
19022 	mblk_t			*mp_tail = NULL;
19023 	ill_walk_context_t	ctx;
19024 	zoneid_t		zoneid;
19025 	ilm_walker_t		ilw;
19026 
19027 	/*
19028 	 * make a copy of the original message
19029 	 */
19030 	mp2ctl = copymsg(mpctl);
19031 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19032 
19033 	/* ip6GroupMember table */
19034 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19035 	optp->level = MIB2_IP6;
19036 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19037 
19038 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19039 	ill = ILL_START_WALK_V6(&ctx, ipst);
19040 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19041 		if (IS_UNDER_IPMP(ill))
19042 			continue;
19043 
19044 		ilm = ilm_walker_start(&ilw, ill);
19045 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19046 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19047 			ASSERT(ilm->ilm_ipif == NULL);
19048 			ASSERT(ilm->ilm_ill != NULL);
19049 			if (ilm->ilm_zoneid != zoneid)
19050 				continue;	/* not this zone */
19051 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19052 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19053 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19054 			if (!snmp_append_data2(mpctl->b_cont,
19055 			    &mp_tail,
19056 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19057 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19058 				    "failed to allocate %u bytes\n",
19059 				    (uint_t)sizeof (ipm6)));
19060 			}
19061 		}
19062 		ilm_walker_finish(&ilw);
19063 	}
19064 	rw_exit(&ipst->ips_ill_g_lock);
19065 
19066 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19067 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19068 	    (int)optp->level, (int)optp->name, (int)optp->len));
19069 	qreply(q, mpctl);
19070 	return (mp2ctl);
19071 }
19072 
19073 /* IP multicast filtered sources */
19074 static mblk_t *
19075 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19076 {
19077 	struct opthdr		*optp;
19078 	mblk_t			*mp2ctl;
19079 	ill_t			*ill;
19080 	ipif_t			*ipif;
19081 	ilm_t			*ilm;
19082 	ip_grpsrc_t		ips;
19083 	mblk_t			*mp_tail = NULL;
19084 	ill_walk_context_t	ctx;
19085 	zoneid_t		zoneid;
19086 	int			i;
19087 	slist_t			*sl;
19088 	ilm_walker_t		ilw;
19089 
19090 	/*
19091 	 * make a copy of the original message
19092 	 */
19093 	mp2ctl = copymsg(mpctl);
19094 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19095 
19096 	/* ipGroupSource table */
19097 	optp = (struct opthdr *)&mpctl->b_rptr[
19098 	    sizeof (struct T_optmgmt_ack)];
19099 	optp->level = MIB2_IP;
19100 	optp->name = EXPER_IP_GROUP_SOURCES;
19101 
19102 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19103 	ill = ILL_START_WALK_V4(&ctx, ipst);
19104 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19105 		if (IS_UNDER_IPMP(ill))
19106 			continue;
19107 
19108 		ilm = ilm_walker_start(&ilw, ill);
19109 		for (ipif = ill->ill_ipif; ipif != NULL;
19110 		    ipif = ipif->ipif_next) {
19111 			if (ipif->ipif_zoneid != zoneid)
19112 				continue;	/* not this zone */
19113 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19114 			    OCTET_LENGTH);
19115 			ips.ipGroupSourceIfIndex.o_length =
19116 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19117 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19118 				ASSERT(ilm->ilm_ipif != NULL);
19119 				ASSERT(ilm->ilm_ill == NULL);
19120 				sl = ilm->ilm_filter;
19121 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19122 					continue;
19123 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19124 				for (i = 0; i < sl->sl_numsrc; i++) {
19125 					if (!IN6_IS_ADDR_V4MAPPED(
19126 					    &sl->sl_addr[i]))
19127 						continue;
19128 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19129 					    ips.ipGroupSourceAddress);
19130 					if (snmp_append_data2(mpctl->b_cont,
19131 					    &mp_tail, (char *)&ips,
19132 					    (int)sizeof (ips)) == 0) {
19133 						ip1dbg(("ip_snmp_get_mib2_"
19134 						    "ip_group_src: failed to "
19135 						    "allocate %u bytes\n",
19136 						    (uint_t)sizeof (ips)));
19137 					}
19138 				}
19139 			}
19140 		}
19141 		ilm_walker_finish(&ilw);
19142 	}
19143 	rw_exit(&ipst->ips_ill_g_lock);
19144 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19145 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19146 	    (int)optp->level, (int)optp->name, (int)optp->len));
19147 	qreply(q, mpctl);
19148 	return (mp2ctl);
19149 }
19150 
19151 /* IPv6 multicast filtered sources. */
19152 static mblk_t *
19153 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19154 {
19155 	struct opthdr		*optp;
19156 	mblk_t			*mp2ctl;
19157 	ill_t			*ill;
19158 	ilm_t			*ilm;
19159 	ipv6_grpsrc_t		ips6;
19160 	mblk_t			*mp_tail = NULL;
19161 	ill_walk_context_t	ctx;
19162 	zoneid_t		zoneid;
19163 	int			i;
19164 	slist_t			*sl;
19165 	ilm_walker_t		ilw;
19166 
19167 	/*
19168 	 * make a copy of the original message
19169 	 */
19170 	mp2ctl = copymsg(mpctl);
19171 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19172 
19173 	/* ip6GroupMember table */
19174 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19175 	optp->level = MIB2_IP6;
19176 	optp->name = EXPER_IP6_GROUP_SOURCES;
19177 
19178 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19179 	ill = ILL_START_WALK_V6(&ctx, ipst);
19180 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19181 		if (IS_UNDER_IPMP(ill))
19182 			continue;
19183 
19184 		ilm = ilm_walker_start(&ilw, ill);
19185 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19186 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19187 			ASSERT(ilm->ilm_ipif == NULL);
19188 			ASSERT(ilm->ilm_ill != NULL);
19189 			sl = ilm->ilm_filter;
19190 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19191 				continue;
19192 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19193 			for (i = 0; i < sl->sl_numsrc; i++) {
19194 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19195 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19196 				    (char *)&ips6, (int)sizeof (ips6))) {
19197 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19198 					    "group_src: failed to allocate "
19199 					    "%u bytes\n",
19200 					    (uint_t)sizeof (ips6)));
19201 				}
19202 			}
19203 		}
19204 		ilm_walker_finish(&ilw);
19205 	}
19206 	rw_exit(&ipst->ips_ill_g_lock);
19207 
19208 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19209 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19210 	    (int)optp->level, (int)optp->name, (int)optp->len));
19211 	qreply(q, mpctl);
19212 	return (mp2ctl);
19213 }
19214 
19215 /* Multicast routing virtual interface table. */
19216 static mblk_t *
19217 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19218 {
19219 	struct opthdr		*optp;
19220 	mblk_t			*mp2ctl;
19221 
19222 	/*
19223 	 * make a copy of the original message
19224 	 */
19225 	mp2ctl = copymsg(mpctl);
19226 
19227 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19228 	optp->level = EXPER_DVMRP;
19229 	optp->name = EXPER_DVMRP_VIF;
19230 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19231 		ip0dbg(("ip_mroute_vif: failed\n"));
19232 	}
19233 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19234 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19235 	    (int)optp->level, (int)optp->name, (int)optp->len));
19236 	qreply(q, mpctl);
19237 	return (mp2ctl);
19238 }
19239 
19240 /* Multicast routing table. */
19241 static mblk_t *
19242 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19243 {
19244 	struct opthdr		*optp;
19245 	mblk_t			*mp2ctl;
19246 
19247 	/*
19248 	 * make a copy of the original message
19249 	 */
19250 	mp2ctl = copymsg(mpctl);
19251 
19252 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19253 	optp->level = EXPER_DVMRP;
19254 	optp->name = EXPER_DVMRP_MRT;
19255 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19256 		ip0dbg(("ip_mroute_mrt: failed\n"));
19257 	}
19258 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19259 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19260 	    (int)optp->level, (int)optp->name, (int)optp->len));
19261 	qreply(q, mpctl);
19262 	return (mp2ctl);
19263 }
19264 
19265 /*
19266  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19267  * in one IRE walk.
19268  */
19269 static mblk_t *
19270 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19271     ip_stack_t *ipst)
19272 {
19273 	struct opthdr	*optp;
19274 	mblk_t		*mp2ctl;	/* Returned */
19275 	mblk_t		*mp3ctl;	/* nettomedia */
19276 	mblk_t		*mp4ctl;	/* routeattrs */
19277 	iproutedata_t	ird;
19278 	zoneid_t	zoneid;
19279 
19280 	/*
19281 	 * make copies of the original message
19282 	 *	- mp2ctl is returned unchanged to the caller for his use
19283 	 *	- mpctl is sent upstream as ipRouteEntryTable
19284 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19285 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19286 	 */
19287 	mp2ctl = copymsg(mpctl);
19288 	mp3ctl = copymsg(mpctl);
19289 	mp4ctl = copymsg(mpctl);
19290 	if (mp3ctl == NULL || mp4ctl == NULL) {
19291 		freemsg(mp4ctl);
19292 		freemsg(mp3ctl);
19293 		freemsg(mp2ctl);
19294 		freemsg(mpctl);
19295 		return (NULL);
19296 	}
19297 
19298 	bzero(&ird, sizeof (ird));
19299 
19300 	ird.ird_route.lp_head = mpctl->b_cont;
19301 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19302 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19303 	/*
19304 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19305 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19306 	 * intended a temporary solution until a proper MIB API is provided
19307 	 * that provides complete filtering/caller-opt-in.
19308 	 */
19309 	if (level == EXPER_IP_AND_TESTHIDDEN)
19310 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19311 
19312 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19313 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19314 
19315 	/* ipRouteEntryTable in mpctl */
19316 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19317 	optp->level = MIB2_IP;
19318 	optp->name = MIB2_IP_ROUTE;
19319 	optp->len = msgdsize(ird.ird_route.lp_head);
19320 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19321 	    (int)optp->level, (int)optp->name, (int)optp->len));
19322 	qreply(q, mpctl);
19323 
19324 	/* ipNetToMediaEntryTable in mp3ctl */
19325 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19326 	optp->level = MIB2_IP;
19327 	optp->name = MIB2_IP_MEDIA;
19328 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19329 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19330 	    (int)optp->level, (int)optp->name, (int)optp->len));
19331 	qreply(q, mp3ctl);
19332 
19333 	/* ipRouteAttributeTable in mp4ctl */
19334 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19335 	optp->level = MIB2_IP;
19336 	optp->name = EXPER_IP_RTATTR;
19337 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19338 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19339 	    (int)optp->level, (int)optp->name, (int)optp->len));
19340 	if (optp->len == 0)
19341 		freemsg(mp4ctl);
19342 	else
19343 		qreply(q, mp4ctl);
19344 
19345 	return (mp2ctl);
19346 }
19347 
19348 /*
19349  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19350  * ipv6NetToMediaEntryTable in an NDP walk.
19351  */
19352 static mblk_t *
19353 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19354     ip_stack_t *ipst)
19355 {
19356 	struct opthdr	*optp;
19357 	mblk_t		*mp2ctl;	/* Returned */
19358 	mblk_t		*mp3ctl;	/* nettomedia */
19359 	mblk_t		*mp4ctl;	/* routeattrs */
19360 	iproutedata_t	ird;
19361 	zoneid_t	zoneid;
19362 
19363 	/*
19364 	 * make copies of the original message
19365 	 *	- mp2ctl is returned unchanged to the caller for his use
19366 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19367 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19368 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19369 	 */
19370 	mp2ctl = copymsg(mpctl);
19371 	mp3ctl = copymsg(mpctl);
19372 	mp4ctl = copymsg(mpctl);
19373 	if (mp3ctl == NULL || mp4ctl == NULL) {
19374 		freemsg(mp4ctl);
19375 		freemsg(mp3ctl);
19376 		freemsg(mp2ctl);
19377 		freemsg(mpctl);
19378 		return (NULL);
19379 	}
19380 
19381 	bzero(&ird, sizeof (ird));
19382 
19383 	ird.ird_route.lp_head = mpctl->b_cont;
19384 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19385 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19386 	/*
19387 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19388 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19389 	 * intended a temporary solution until a proper MIB API is provided
19390 	 * that provides complete filtering/caller-opt-in.
19391 	 */
19392 	if (level == EXPER_IP_AND_TESTHIDDEN)
19393 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19394 
19395 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19396 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19397 
19398 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19399 	optp->level = MIB2_IP6;
19400 	optp->name = MIB2_IP6_ROUTE;
19401 	optp->len = msgdsize(ird.ird_route.lp_head);
19402 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19403 	    (int)optp->level, (int)optp->name, (int)optp->len));
19404 	qreply(q, mpctl);
19405 
19406 	/* ipv6NetToMediaEntryTable in mp3ctl */
19407 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19408 
19409 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19410 	optp->level = MIB2_IP6;
19411 	optp->name = MIB2_IP6_MEDIA;
19412 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19413 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19414 	    (int)optp->level, (int)optp->name, (int)optp->len));
19415 	qreply(q, mp3ctl);
19416 
19417 	/* ipv6RouteAttributeTable in mp4ctl */
19418 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19419 	optp->level = MIB2_IP6;
19420 	optp->name = EXPER_IP_RTATTR;
19421 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19422 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19423 	    (int)optp->level, (int)optp->name, (int)optp->len));
19424 	if (optp->len == 0)
19425 		freemsg(mp4ctl);
19426 	else
19427 		qreply(q, mp4ctl);
19428 
19429 	return (mp2ctl);
19430 }
19431 
19432 /*
19433  * IPv6 mib: One per ill
19434  */
19435 static mblk_t *
19436 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19437 {
19438 	struct opthdr		*optp;
19439 	mblk_t			*mp2ctl;
19440 	ill_t			*ill;
19441 	ill_walk_context_t	ctx;
19442 	mblk_t			*mp_tail = NULL;
19443 
19444 	/*
19445 	 * Make a copy of the original message
19446 	 */
19447 	mp2ctl = copymsg(mpctl);
19448 
19449 	/* fixed length IPv6 structure ... */
19450 
19451 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19452 	optp->level = MIB2_IP6;
19453 	optp->name = 0;
19454 	/* Include "unknown interface" ip6_mib */
19455 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19456 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19457 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19458 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19459 	    ipst->ips_ipv6_forward ? 1 : 2);
19460 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19461 	    ipst->ips_ipv6_def_hops);
19462 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19463 	    sizeof (mib2_ipIfStatsEntry_t));
19464 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19465 	    sizeof (mib2_ipv6AddrEntry_t));
19466 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19467 	    sizeof (mib2_ipv6RouteEntry_t));
19468 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19469 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19470 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19471 	    sizeof (ipv6_member_t));
19472 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19473 	    sizeof (ipv6_grpsrc_t));
19474 
19475 	/*
19476 	 * Synchronize 64- and 32-bit counters
19477 	 */
19478 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19479 	    ipIfStatsHCInReceives);
19480 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19481 	    ipIfStatsHCInDelivers);
19482 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19483 	    ipIfStatsHCOutRequests);
19484 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19485 	    ipIfStatsHCOutForwDatagrams);
19486 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19487 	    ipIfStatsHCOutMcastPkts);
19488 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19489 	    ipIfStatsHCInMcastPkts);
19490 
19491 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19492 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19493 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19494 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19495 	}
19496 
19497 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19498 	ill = ILL_START_WALK_V6(&ctx, ipst);
19499 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19500 		ill->ill_ip_mib->ipIfStatsIfIndex =
19501 		    ill->ill_phyint->phyint_ifindex;
19502 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19503 		    ipst->ips_ipv6_forward ? 1 : 2);
19504 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19505 		    ill->ill_max_hops);
19506 
19507 		/*
19508 		 * Synchronize 64- and 32-bit counters
19509 		 */
19510 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19511 		    ipIfStatsHCInReceives);
19512 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19513 		    ipIfStatsHCInDelivers);
19514 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19515 		    ipIfStatsHCOutRequests);
19516 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19517 		    ipIfStatsHCOutForwDatagrams);
19518 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19519 		    ipIfStatsHCOutMcastPkts);
19520 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19521 		    ipIfStatsHCInMcastPkts);
19522 
19523 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19524 		    (char *)ill->ill_ip_mib,
19525 		    (int)sizeof (*ill->ill_ip_mib))) {
19526 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19527 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19528 		}
19529 	}
19530 	rw_exit(&ipst->ips_ill_g_lock);
19531 
19532 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19533 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19534 	    (int)optp->level, (int)optp->name, (int)optp->len));
19535 	qreply(q, mpctl);
19536 	return (mp2ctl);
19537 }
19538 
19539 /*
19540  * ICMPv6 mib: One per ill
19541  */
19542 static mblk_t *
19543 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19544 {
19545 	struct opthdr		*optp;
19546 	mblk_t			*mp2ctl;
19547 	ill_t			*ill;
19548 	ill_walk_context_t	ctx;
19549 	mblk_t			*mp_tail = NULL;
19550 	/*
19551 	 * Make a copy of the original message
19552 	 */
19553 	mp2ctl = copymsg(mpctl);
19554 
19555 	/* fixed length ICMPv6 structure ... */
19556 
19557 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19558 	optp->level = MIB2_ICMP6;
19559 	optp->name = 0;
19560 	/* Include "unknown interface" icmp6_mib */
19561 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19562 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19563 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19564 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19565 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19566 	    (char *)&ipst->ips_icmp6_mib,
19567 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19568 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19569 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19570 	}
19571 
19572 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19573 	ill = ILL_START_WALK_V6(&ctx, ipst);
19574 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19575 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19576 		    ill->ill_phyint->phyint_ifindex;
19577 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19578 		    (char *)ill->ill_icmp6_mib,
19579 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19580 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19581 			    "%u bytes\n",
19582 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19583 		}
19584 	}
19585 	rw_exit(&ipst->ips_ill_g_lock);
19586 
19587 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19588 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19589 	    (int)optp->level, (int)optp->name, (int)optp->len));
19590 	qreply(q, mpctl);
19591 	return (mp2ctl);
19592 }
19593 
19594 /*
19595  * ire_walk routine to create both ipRouteEntryTable and
19596  * ipRouteAttributeTable in one IRE walk
19597  */
19598 static void
19599 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19600 {
19601 	ill_t				*ill;
19602 	ipif_t				*ipif;
19603 	mib2_ipRouteEntry_t		*re;
19604 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19605 	ipaddr_t			gw_addr;
19606 	tsol_ire_gw_secattr_t		*attrp;
19607 	tsol_gc_t			*gc = NULL;
19608 	tsol_gcgrp_t			*gcgrp = NULL;
19609 	uint_t				sacnt = 0;
19610 	int				i;
19611 
19612 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19613 
19614 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19615 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19616 		return;
19617 	}
19618 
19619 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19620 		return;
19621 
19622 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19623 		mutex_enter(&attrp->igsa_lock);
19624 		if ((gc = attrp->igsa_gc) != NULL) {
19625 			gcgrp = gc->gc_grp;
19626 			ASSERT(gcgrp != NULL);
19627 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19628 			sacnt = 1;
19629 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19630 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19631 			gc = gcgrp->gcgrp_head;
19632 			sacnt = gcgrp->gcgrp_count;
19633 		}
19634 		mutex_exit(&attrp->igsa_lock);
19635 
19636 		/* do nothing if there's no gc to report */
19637 		if (gc == NULL) {
19638 			ASSERT(sacnt == 0);
19639 			if (gcgrp != NULL) {
19640 				/* we might as well drop the lock now */
19641 				rw_exit(&gcgrp->gcgrp_rwlock);
19642 				gcgrp = NULL;
19643 			}
19644 			attrp = NULL;
19645 		}
19646 
19647 		ASSERT(gc == NULL || (gcgrp != NULL &&
19648 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19649 	}
19650 	ASSERT(sacnt == 0 || gc != NULL);
19651 
19652 	if (sacnt != 0 &&
19653 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19654 		kmem_free(re, sizeof (*re));
19655 		rw_exit(&gcgrp->gcgrp_rwlock);
19656 		return;
19657 	}
19658 
19659 	/*
19660 	 * Return all IRE types for route table... let caller pick and choose
19661 	 */
19662 	re->ipRouteDest = ire->ire_addr;
19663 	ipif = ire->ire_ipif;
19664 	re->ipRouteIfIndex.o_length = 0;
19665 	if (ire->ire_type == IRE_CACHE) {
19666 		ill = (ill_t *)ire->ire_stq->q_ptr;
19667 		re->ipRouteIfIndex.o_length =
19668 		    ill->ill_name_length == 0 ? 0 :
19669 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19670 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19671 		    re->ipRouteIfIndex.o_length);
19672 	} else if (ipif != NULL) {
19673 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19674 		re->ipRouteIfIndex.o_length =
19675 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19676 	}
19677 	re->ipRouteMetric1 = -1;
19678 	re->ipRouteMetric2 = -1;
19679 	re->ipRouteMetric3 = -1;
19680 	re->ipRouteMetric4 = -1;
19681 
19682 	gw_addr = ire->ire_gateway_addr;
19683 
19684 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19685 		re->ipRouteNextHop = ire->ire_src_addr;
19686 	else
19687 		re->ipRouteNextHop = gw_addr;
19688 	/* indirect(4), direct(3), or invalid(2) */
19689 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19690 		re->ipRouteType = 2;
19691 	else
19692 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19693 	re->ipRouteProto = -1;
19694 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19695 	re->ipRouteMask = ire->ire_mask;
19696 	re->ipRouteMetric5 = -1;
19697 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19698 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19699 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19700 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19701 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19702 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19703 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19704 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19705 
19706 	if (ire->ire_flags & RTF_DYNAMIC) {
19707 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19708 	} else {
19709 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19710 	}
19711 
19712 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19713 	    (char *)re, (int)sizeof (*re))) {
19714 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19715 		    (uint_t)sizeof (*re)));
19716 	}
19717 
19718 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19719 		iaeptr->iae_routeidx = ird->ird_idx;
19720 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19721 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19722 	}
19723 
19724 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19725 	    (char *)iae, sacnt * sizeof (*iae))) {
19726 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19727 		    (unsigned)(sacnt * sizeof (*iae))));
19728 	}
19729 
19730 	/* bump route index for next pass */
19731 	ird->ird_idx++;
19732 
19733 	kmem_free(re, sizeof (*re));
19734 	if (sacnt != 0)
19735 		kmem_free(iae, sacnt * sizeof (*iae));
19736 
19737 	if (gcgrp != NULL)
19738 		rw_exit(&gcgrp->gcgrp_rwlock);
19739 }
19740 
19741 /*
19742  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19743  */
19744 static void
19745 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19746 {
19747 	ill_t				*ill;
19748 	ipif_t				*ipif;
19749 	mib2_ipv6RouteEntry_t		*re;
19750 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19751 	in6_addr_t			gw_addr_v6;
19752 	tsol_ire_gw_secattr_t		*attrp;
19753 	tsol_gc_t			*gc = NULL;
19754 	tsol_gcgrp_t			*gcgrp = NULL;
19755 	uint_t				sacnt = 0;
19756 	int				i;
19757 
19758 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19759 
19760 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19761 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19762 		return;
19763 	}
19764 
19765 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19766 		return;
19767 
19768 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19769 		mutex_enter(&attrp->igsa_lock);
19770 		if ((gc = attrp->igsa_gc) != NULL) {
19771 			gcgrp = gc->gc_grp;
19772 			ASSERT(gcgrp != NULL);
19773 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19774 			sacnt = 1;
19775 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19776 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19777 			gc = gcgrp->gcgrp_head;
19778 			sacnt = gcgrp->gcgrp_count;
19779 		}
19780 		mutex_exit(&attrp->igsa_lock);
19781 
19782 		/* do nothing if there's no gc to report */
19783 		if (gc == NULL) {
19784 			ASSERT(sacnt == 0);
19785 			if (gcgrp != NULL) {
19786 				/* we might as well drop the lock now */
19787 				rw_exit(&gcgrp->gcgrp_rwlock);
19788 				gcgrp = NULL;
19789 			}
19790 			attrp = NULL;
19791 		}
19792 
19793 		ASSERT(gc == NULL || (gcgrp != NULL &&
19794 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19795 	}
19796 	ASSERT(sacnt == 0 || gc != NULL);
19797 
19798 	if (sacnt != 0 &&
19799 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19800 		kmem_free(re, sizeof (*re));
19801 		rw_exit(&gcgrp->gcgrp_rwlock);
19802 		return;
19803 	}
19804 
19805 	/*
19806 	 * Return all IRE types for route table... let caller pick and choose
19807 	 */
19808 	re->ipv6RouteDest = ire->ire_addr_v6;
19809 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19810 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19811 	re->ipv6RouteIfIndex.o_length = 0;
19812 	ipif = ire->ire_ipif;
19813 	if (ire->ire_type == IRE_CACHE) {
19814 		ill = (ill_t *)ire->ire_stq->q_ptr;
19815 		re->ipv6RouteIfIndex.o_length =
19816 		    ill->ill_name_length == 0 ? 0 :
19817 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19818 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19819 		    re->ipv6RouteIfIndex.o_length);
19820 	} else if (ipif != NULL) {
19821 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19822 		re->ipv6RouteIfIndex.o_length =
19823 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19824 	}
19825 
19826 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19827 
19828 	mutex_enter(&ire->ire_lock);
19829 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19830 	mutex_exit(&ire->ire_lock);
19831 
19832 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19833 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19834 	else
19835 		re->ipv6RouteNextHop = gw_addr_v6;
19836 
19837 	/* remote(4), local(3), or discard(2) */
19838 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19839 		re->ipv6RouteType = 2;
19840 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19841 		re->ipv6RouteType = 3;
19842 	else
19843 		re->ipv6RouteType = 4;
19844 
19845 	re->ipv6RouteProtocol	= -1;
19846 	re->ipv6RoutePolicy	= 0;
19847 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19848 	re->ipv6RouteNextHopRDI	= 0;
19849 	re->ipv6RouteWeight	= 0;
19850 	re->ipv6RouteMetric	= 0;
19851 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19852 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19853 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19854 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19855 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19856 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19857 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19858 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19859 
19860 	if (ire->ire_flags & RTF_DYNAMIC) {
19861 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19862 	} else {
19863 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19864 	}
19865 
19866 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19867 	    (char *)re, (int)sizeof (*re))) {
19868 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19869 		    (uint_t)sizeof (*re)));
19870 	}
19871 
19872 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19873 		iaeptr->iae_routeidx = ird->ird_idx;
19874 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19875 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19876 	}
19877 
19878 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19879 	    (char *)iae, sacnt * sizeof (*iae))) {
19880 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19881 		    (unsigned)(sacnt * sizeof (*iae))));
19882 	}
19883 
19884 	/* bump route index for next pass */
19885 	ird->ird_idx++;
19886 
19887 	kmem_free(re, sizeof (*re));
19888 	if (sacnt != 0)
19889 		kmem_free(iae, sacnt * sizeof (*iae));
19890 
19891 	if (gcgrp != NULL)
19892 		rw_exit(&gcgrp->gcgrp_rwlock);
19893 }
19894 
19895 /*
19896  * ndp_walk routine to create ipv6NetToMediaEntryTable
19897  */
19898 static int
19899 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19900 {
19901 	ill_t				*ill;
19902 	mib2_ipv6NetToMediaEntry_t	ntme;
19903 	dl_unitdata_req_t		*dl;
19904 
19905 	ill = nce->nce_ill;
19906 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19907 		return (0);
19908 
19909 	/*
19910 	 * Neighbor cache entry attached to IRE with on-link
19911 	 * destination.
19912 	 */
19913 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19914 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19915 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19916 	    (nce->nce_res_mp != NULL)) {
19917 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19918 		ntme.ipv6NetToMediaPhysAddress.o_length =
19919 		    dl->dl_dest_addr_length;
19920 	} else {
19921 		ntme.ipv6NetToMediaPhysAddress.o_length =
19922 		    ill->ill_phys_addr_length;
19923 	}
19924 	if (nce->nce_res_mp != NULL) {
19925 		bcopy((char *)nce->nce_res_mp->b_rptr +
19926 		    NCE_LL_ADDR_OFFSET(ill),
19927 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19928 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19929 	} else {
19930 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19931 		    ill->ill_phys_addr_length);
19932 	}
19933 	/*
19934 	 * Note: Returns ND_* states. Should be:
19935 	 * reachable(1), stale(2), delay(3), probe(4),
19936 	 * invalid(5), unknown(6)
19937 	 */
19938 	ntme.ipv6NetToMediaState = nce->nce_state;
19939 	ntme.ipv6NetToMediaLastUpdated = 0;
19940 
19941 	/* other(1), dynamic(2), static(3), local(4) */
19942 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19943 		ntme.ipv6NetToMediaType = 4;
19944 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19945 		ntme.ipv6NetToMediaType = 1;
19946 	} else {
19947 		ntme.ipv6NetToMediaType = 2;
19948 	}
19949 
19950 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19951 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19952 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19953 		    (uint_t)sizeof (ntme)));
19954 	}
19955 	return (0);
19956 }
19957 
19958 /*
19959  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19960  */
19961 /* ARGSUSED */
19962 int
19963 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19964 {
19965 	switch (level) {
19966 	case MIB2_IP:
19967 	case MIB2_ICMP:
19968 		switch (name) {
19969 		default:
19970 			break;
19971 		}
19972 		return (1);
19973 	default:
19974 		return (1);
19975 	}
19976 }
19977 
19978 /*
19979  * When there exists both a 64- and 32-bit counter of a particular type
19980  * (i.e., InReceives), only the 64-bit counters are added.
19981  */
19982 void
19983 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19984 {
19985 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19986 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19987 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19988 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19989 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19990 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19991 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19992 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19993 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19994 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19995 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19996 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19997 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19998 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19999 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20000 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20001 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20002 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20003 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20004 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20005 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20006 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20007 	    o2->ipIfStatsInWrongIPVersion);
20008 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20009 	    o2->ipIfStatsInWrongIPVersion);
20010 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20011 	    o2->ipIfStatsOutSwitchIPVersion);
20012 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20013 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20014 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20015 	    o2->ipIfStatsHCInForwDatagrams);
20016 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20017 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20018 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20019 	    o2->ipIfStatsHCOutForwDatagrams);
20020 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20021 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20022 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20023 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20024 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20025 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20026 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20027 	    o2->ipIfStatsHCOutMcastOctets);
20028 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20029 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20030 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20031 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20032 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20033 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20034 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20035 }
20036 
20037 void
20038 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20039 {
20040 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20041 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20042 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20043 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20044 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20045 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20046 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20047 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20048 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20049 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20050 	    o2->ipv6IfIcmpInRouterSolicits);
20051 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20052 	    o2->ipv6IfIcmpInRouterAdvertisements);
20053 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20054 	    o2->ipv6IfIcmpInNeighborSolicits);
20055 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20056 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20057 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20058 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20059 	    o2->ipv6IfIcmpInGroupMembQueries);
20060 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20061 	    o2->ipv6IfIcmpInGroupMembResponses);
20062 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20063 	    o2->ipv6IfIcmpInGroupMembReductions);
20064 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20065 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20066 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20067 	    o2->ipv6IfIcmpOutDestUnreachs);
20068 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20069 	    o2->ipv6IfIcmpOutAdminProhibs);
20070 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20071 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20072 	    o2->ipv6IfIcmpOutParmProblems);
20073 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20074 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20075 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20076 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20077 	    o2->ipv6IfIcmpOutRouterSolicits);
20078 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20079 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20080 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20081 	    o2->ipv6IfIcmpOutNeighborSolicits);
20082 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20083 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20084 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20085 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20086 	    o2->ipv6IfIcmpOutGroupMembQueries);
20087 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20088 	    o2->ipv6IfIcmpOutGroupMembResponses);
20089 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20090 	    o2->ipv6IfIcmpOutGroupMembReductions);
20091 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20092 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20093 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20094 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20095 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20096 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20097 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20098 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20099 	    o2->ipv6IfIcmpInGroupMembTotal);
20100 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20101 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20102 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20103 	    o2->ipv6IfIcmpInGroupMembBadReports);
20104 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20105 	    o2->ipv6IfIcmpInGroupMembOurReports);
20106 }
20107 
20108 /*
20109  * Called before the options are updated to check if this packet will
20110  * be source routed from here.
20111  * This routine assumes that the options are well formed i.e. that they
20112  * have already been checked.
20113  */
20114 static boolean_t
20115 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20116 {
20117 	ipoptp_t	opts;
20118 	uchar_t		*opt;
20119 	uint8_t		optval;
20120 	uint8_t		optlen;
20121 	ipaddr_t	dst;
20122 	ire_t		*ire;
20123 
20124 	if (IS_SIMPLE_IPH(ipha)) {
20125 		ip2dbg(("not source routed\n"));
20126 		return (B_FALSE);
20127 	}
20128 	dst = ipha->ipha_dst;
20129 	for (optval = ipoptp_first(&opts, ipha);
20130 	    optval != IPOPT_EOL;
20131 	    optval = ipoptp_next(&opts)) {
20132 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20133 		opt = opts.ipoptp_cur;
20134 		optlen = opts.ipoptp_len;
20135 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20136 		    optval, optlen));
20137 		switch (optval) {
20138 			uint32_t off;
20139 		case IPOPT_SSRR:
20140 		case IPOPT_LSRR:
20141 			/*
20142 			 * If dst is one of our addresses and there are some
20143 			 * entries left in the source route return (true).
20144 			 */
20145 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20146 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20147 			if (ire == NULL) {
20148 				ip2dbg(("ip_source_routed: not next"
20149 				    " source route 0x%x\n",
20150 				    ntohl(dst)));
20151 				return (B_FALSE);
20152 			}
20153 			ire_refrele(ire);
20154 			off = opt[IPOPT_OFFSET];
20155 			off--;
20156 			if (optlen < IP_ADDR_LEN ||
20157 			    off > optlen - IP_ADDR_LEN) {
20158 				/* End of source route */
20159 				ip1dbg(("ip_source_routed: end of SR\n"));
20160 				return (B_FALSE);
20161 			}
20162 			return (B_TRUE);
20163 		}
20164 	}
20165 	ip2dbg(("not source routed\n"));
20166 	return (B_FALSE);
20167 }
20168 
20169 /*
20170  * Check if the packet contains any source route.
20171  */
20172 static boolean_t
20173 ip_source_route_included(ipha_t *ipha)
20174 {
20175 	ipoptp_t	opts;
20176 	uint8_t		optval;
20177 
20178 	if (IS_SIMPLE_IPH(ipha))
20179 		return (B_FALSE);
20180 	for (optval = ipoptp_first(&opts, ipha);
20181 	    optval != IPOPT_EOL;
20182 	    optval = ipoptp_next(&opts)) {
20183 		switch (optval) {
20184 		case IPOPT_SSRR:
20185 		case IPOPT_LSRR:
20186 			return (B_TRUE);
20187 		}
20188 	}
20189 	return (B_FALSE);
20190 }
20191 
20192 /*
20193  * Called when the IRE expiration timer fires.
20194  */
20195 void
20196 ip_trash_timer_expire(void *args)
20197 {
20198 	int			flush_flag = 0;
20199 	ire_expire_arg_t	iea;
20200 	ip_stack_t		*ipst = (ip_stack_t *)args;
20201 
20202 	iea.iea_ipst = ipst;	/* No netstack_hold */
20203 
20204 	/*
20205 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20206 	 * This lock makes sure that a new invocation of this function
20207 	 * that occurs due to an almost immediate timer firing will not
20208 	 * progress beyond this point until the current invocation is done
20209 	 */
20210 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20211 	ipst->ips_ip_ire_expire_id = 0;
20212 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20213 
20214 	/* Periodic timer */
20215 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20216 	    ipst->ips_ip_ire_arp_interval) {
20217 		/*
20218 		 * Remove all IRE_CACHE entries since they might
20219 		 * contain arp information.
20220 		 */
20221 		flush_flag |= FLUSH_ARP_TIME;
20222 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20223 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20224 	}
20225 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20226 	    ipst->ips_ip_ire_redir_interval) {
20227 		/* Remove all redirects */
20228 		flush_flag |= FLUSH_REDIRECT_TIME;
20229 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20230 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20231 	}
20232 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20233 	    ipst->ips_ip_ire_pathmtu_interval) {
20234 		/* Increase path mtu */
20235 		flush_flag |= FLUSH_MTU_TIME;
20236 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20237 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20238 	}
20239 
20240 	/*
20241 	 * Optimize for the case when there are no redirects in the
20242 	 * ftable, that is, no need to walk the ftable in that case.
20243 	 */
20244 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20245 		iea.iea_flush_flag = flush_flag;
20246 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20247 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20248 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20249 		    NULL, ALL_ZONES, ipst);
20250 	}
20251 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20252 	    ipst->ips_ip_redirect_cnt > 0) {
20253 		iea.iea_flush_flag = flush_flag;
20254 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20255 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20256 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20257 	}
20258 	if (flush_flag & FLUSH_MTU_TIME) {
20259 		/*
20260 		 * Walk all IPv6 IRE's and update them
20261 		 * Note that ARP and redirect timers are not
20262 		 * needed since NUD handles stale entries.
20263 		 */
20264 		flush_flag = FLUSH_MTU_TIME;
20265 		iea.iea_flush_flag = flush_flag;
20266 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20267 		    ALL_ZONES, ipst);
20268 	}
20269 
20270 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20271 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20272 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20273 
20274 	/*
20275 	 * Hold the lock to serialize timeout calls and prevent
20276 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20277 	 * for the timer to fire and a new invocation of this function
20278 	 * to start before the return value of timeout has been stored
20279 	 * in ip_ire_expire_id by the current invocation.
20280 	 */
20281 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20282 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20283 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20284 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20285 }
20286 
20287 /*
20288  * Called by the memory allocator subsystem directly, when the system
20289  * is running low on memory.
20290  */
20291 /* ARGSUSED */
20292 void
20293 ip_trash_ire_reclaim(void *args)
20294 {
20295 	netstack_handle_t nh;
20296 	netstack_t *ns;
20297 
20298 	netstack_next_init(&nh);
20299 	while ((ns = netstack_next(&nh)) != NULL) {
20300 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20301 		netstack_rele(ns);
20302 	}
20303 	netstack_next_fini(&nh);
20304 }
20305 
20306 static void
20307 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20308 {
20309 	ire_cache_count_t icc;
20310 	ire_cache_reclaim_t icr;
20311 	ncc_cache_count_t ncc;
20312 	nce_cache_reclaim_t ncr;
20313 	uint_t delete_cnt;
20314 	/*
20315 	 * Memory reclaim call back.
20316 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20317 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20318 	 * entries, determine what fraction to free for
20319 	 * each category of IRE_CACHE entries giving absolute priority
20320 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20321 	 * entry will be freed unless all offlink entries are freed).
20322 	 */
20323 	icc.icc_total = 0;
20324 	icc.icc_unused = 0;
20325 	icc.icc_offlink = 0;
20326 	icc.icc_pmtu = 0;
20327 	icc.icc_onlink = 0;
20328 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20329 
20330 	/*
20331 	 * Free NCEs for IPv6 like the onlink ires.
20332 	 */
20333 	ncc.ncc_total = 0;
20334 	ncc.ncc_host = 0;
20335 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20336 
20337 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20338 	    icc.icc_pmtu + icc.icc_onlink);
20339 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20340 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20341 	if (delete_cnt == 0)
20342 		return;
20343 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20344 	/* Always delete all unused offlink entries */
20345 	icr.icr_ipst = ipst;
20346 	icr.icr_unused = 1;
20347 	if (delete_cnt <= icc.icc_unused) {
20348 		/*
20349 		 * Only need to free unused entries.  In other words,
20350 		 * there are enough unused entries to free to meet our
20351 		 * target number of freed ire cache entries.
20352 		 */
20353 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20354 		ncr.ncr_host = 0;
20355 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20356 		/*
20357 		 * Only need to free unused entries, plus a fraction of offlink
20358 		 * entries.  It follows from the first if statement that
20359 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20360 		 */
20361 		delete_cnt -= icc.icc_unused;
20362 		/* Round up # deleted by truncating fraction */
20363 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20364 		icr.icr_pmtu = icr.icr_onlink = 0;
20365 		ncr.ncr_host = 0;
20366 	} else if (delete_cnt <=
20367 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20368 		/*
20369 		 * Free all unused and offlink entries, plus a fraction of
20370 		 * pmtu entries.  It follows from the previous if statement
20371 		 * that icc_pmtu is non-zero, and that
20372 		 * delete_cnt != icc_unused + icc_offlink.
20373 		 */
20374 		icr.icr_offlink = 1;
20375 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20376 		/* Round up # deleted by truncating fraction */
20377 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20378 		icr.icr_onlink = 0;
20379 		ncr.ncr_host = 0;
20380 	} else {
20381 		/*
20382 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20383 		 * of onlink entries.  If we're here, then we know that
20384 		 * icc_onlink is non-zero, and that
20385 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20386 		 */
20387 		icr.icr_offlink = icr.icr_pmtu = 1;
20388 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20389 		    icc.icc_pmtu;
20390 		/* Round up # deleted by truncating fraction */
20391 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20392 		/* Using the same delete fraction as for onlink IREs */
20393 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20394 	}
20395 #ifdef DEBUG
20396 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20397 	    "fractions %d/%d/%d/%d\n",
20398 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20399 	    icc.icc_unused, icc.icc_offlink,
20400 	    icc.icc_pmtu, icc.icc_onlink,
20401 	    icr.icr_unused, icr.icr_offlink,
20402 	    icr.icr_pmtu, icr.icr_onlink));
20403 #endif
20404 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20405 	if (ncr.ncr_host != 0)
20406 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20407 		    (uchar_t *)&ncr, ipst);
20408 #ifdef DEBUG
20409 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20410 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20411 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20412 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20413 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20414 	    icc.icc_pmtu, icc.icc_onlink));
20415 #endif
20416 }
20417 
20418 /*
20419  * ip_unbind is called when a copy of an unbind request is received from the
20420  * upper level protocol.  We remove this conn from any fanout hash list it is
20421  * on, and zero out the bind information.  No reply is expected up above.
20422  */
20423 void
20424 ip_unbind(conn_t *connp)
20425 {
20426 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20427 
20428 	if (is_system_labeled() && connp->conn_anon_port) {
20429 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20430 		    connp->conn_mlp_type, connp->conn_ulp,
20431 		    ntohs(connp->conn_lport), B_FALSE);
20432 		connp->conn_anon_port = 0;
20433 	}
20434 	connp->conn_mlp_type = mlptSingle;
20435 
20436 	ipcl_hash_remove(connp);
20437 
20438 }
20439 
20440 /*
20441  * Write side put procedure.  Outbound data, IOCTLs, responses from
20442  * resolvers, etc, come down through here.
20443  *
20444  * arg2 is always a queue_t *.
20445  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20446  * the zoneid.
20447  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20448  */
20449 void
20450 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20451 {
20452 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20453 }
20454 
20455 void
20456 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20457     ip_opt_info_t *infop)
20458 {
20459 	conn_t		*connp = NULL;
20460 	queue_t		*q = (queue_t *)arg2;
20461 	ipha_t		*ipha;
20462 #define	rptr	((uchar_t *)ipha)
20463 	ire_t		*ire = NULL;
20464 	ire_t		*sctp_ire = NULL;
20465 	uint32_t	v_hlen_tos_len;
20466 	ipaddr_t	dst;
20467 	mblk_t		*first_mp = NULL;
20468 	boolean_t	mctl_present;
20469 	ipsec_out_t	*io;
20470 	int		match_flags;
20471 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20472 	ipif_t		*dst_ipif;
20473 	boolean_t	multirt_need_resolve = B_FALSE;
20474 	mblk_t		*copy_mp = NULL;
20475 	int		err;
20476 	zoneid_t	zoneid;
20477 	boolean_t	need_decref = B_FALSE;
20478 	boolean_t	ignore_dontroute = B_FALSE;
20479 	boolean_t	ignore_nexthop = B_FALSE;
20480 	boolean_t	ip_nexthop = B_FALSE;
20481 	ipaddr_t	nexthop_addr;
20482 	ip_stack_t	*ipst;
20483 
20484 #ifdef	_BIG_ENDIAN
20485 #define	V_HLEN	(v_hlen_tos_len >> 24)
20486 #else
20487 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20488 #endif
20489 
20490 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20491 	    "ip_wput_start: q %p", q);
20492 
20493 	/*
20494 	 * ip_wput fast path
20495 	 */
20496 
20497 	/* is packet from ARP ? */
20498 	if (q->q_next != NULL) {
20499 		zoneid = (zoneid_t)(uintptr_t)arg;
20500 		goto qnext;
20501 	}
20502 
20503 	connp = (conn_t *)arg;
20504 	ASSERT(connp != NULL);
20505 	zoneid = connp->conn_zoneid;
20506 	ipst = connp->conn_netstack->netstack_ip;
20507 	ASSERT(ipst != NULL);
20508 
20509 	/* is queue flow controlled? */
20510 	if ((q->q_first != NULL || connp->conn_draining) &&
20511 	    (caller == IP_WPUT)) {
20512 		ASSERT(!need_decref);
20513 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20514 		(void) putq(q, mp);
20515 		return;
20516 	}
20517 
20518 	/* Multidata transmit? */
20519 	if (DB_TYPE(mp) == M_MULTIDATA) {
20520 		/*
20521 		 * We should never get here, since all Multidata messages
20522 		 * originating from tcp should have been directed over to
20523 		 * tcp_multisend() in the first place.
20524 		 */
20525 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20526 		freemsg(mp);
20527 		return;
20528 	} else if (DB_TYPE(mp) != M_DATA)
20529 		goto notdata;
20530 
20531 	if (mp->b_flag & MSGHASREF) {
20532 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20533 		mp->b_flag &= ~MSGHASREF;
20534 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20535 		need_decref = B_TRUE;
20536 	}
20537 	ipha = (ipha_t *)mp->b_rptr;
20538 
20539 	/* is IP header non-aligned or mblk smaller than basic IP header */
20540 #ifndef SAFETY_BEFORE_SPEED
20541 	if (!OK_32PTR(rptr) ||
20542 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20543 		goto hdrtoosmall;
20544 #endif
20545 
20546 	ASSERT(OK_32PTR(ipha));
20547 
20548 	/*
20549 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20550 	 * wrong version, we'll catch it again in ip_output_v6.
20551 	 *
20552 	 * Note that this is *only* locally-generated output here, and never
20553 	 * forwarded data, and that we need to deal only with transports that
20554 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20555 	 * label.)
20556 	 */
20557 	if (is_system_labeled() &&
20558 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20559 	    !connp->conn_ulp_labeled) {
20560 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20561 		    connp->conn_mac_exempt, ipst);
20562 		ipha = (ipha_t *)mp->b_rptr;
20563 		if (err != 0) {
20564 			first_mp = mp;
20565 			if (err == EINVAL)
20566 				goto icmp_parameter_problem;
20567 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20568 			goto discard_pkt;
20569 		}
20570 	}
20571 
20572 	ASSERT(infop != NULL);
20573 
20574 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20575 		/*
20576 		 * IP_PKTINFO ancillary option is present.
20577 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20578 		 * allows using address of any zone as the source address.
20579 		 */
20580 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20581 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20582 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20583 		if (ire == NULL)
20584 			goto drop_pkt;
20585 		ire_refrele(ire);
20586 		ire = NULL;
20587 	}
20588 
20589 	/*
20590 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20591 	 */
20592 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20593 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20594 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20595 
20596 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20597 			goto drop_pkt;
20598 		/*
20599 		 * check that there is an ipif belonging
20600 		 * to our zone. IPCL_ZONEID is not used because
20601 		 * IP_ALLZONES option is valid only when the ill is
20602 		 * accessible from all zones i.e has a valid ipif in
20603 		 * all zones.
20604 		 */
20605 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20606 			goto drop_pkt;
20607 		}
20608 	}
20609 
20610 	/*
20611 	 * If there is a policy, try to attach an ipsec_out in
20612 	 * the front. At the end, first_mp either points to a
20613 	 * M_DATA message or IPSEC_OUT message linked to a
20614 	 * M_DATA message. We have to do it now as we might
20615 	 * lose the "conn" if we go through ip_newroute.
20616 	 */
20617 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20618 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20619 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20620 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20621 			if (need_decref)
20622 				CONN_DEC_REF(connp);
20623 			return;
20624 		} else {
20625 			ASSERT(mp->b_datap->db_type == M_CTL);
20626 			first_mp = mp;
20627 			mp = mp->b_cont;
20628 			mctl_present = B_TRUE;
20629 		}
20630 	} else {
20631 		first_mp = mp;
20632 		mctl_present = B_FALSE;
20633 	}
20634 
20635 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20636 
20637 	/* is wrong version or IP options present */
20638 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20639 		goto version_hdrlen_check;
20640 	dst = ipha->ipha_dst;
20641 
20642 	/* If IP_BOUND_IF has been set, use that ill. */
20643 	if (connp->conn_outgoing_ill != NULL) {
20644 		xmit_ill = conn_get_held_ill(connp,
20645 		    &connp->conn_outgoing_ill, &err);
20646 		if (err == ILL_LOOKUP_FAILED)
20647 			goto drop_pkt;
20648 
20649 		goto send_from_ill;
20650 	}
20651 
20652 	/* is packet multicast? */
20653 	if (CLASSD(dst))
20654 		goto multicast;
20655 
20656 	/*
20657 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20658 	 * takes precedence over conn_dontroute and conn_nexthop_set
20659 	 */
20660 	if (xmit_ill != NULL)
20661 		goto send_from_ill;
20662 
20663 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20664 		/*
20665 		 * If the destination is a broadcast, local, or loopback
20666 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20667 		 * standard path.
20668 		 */
20669 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20670 		if ((ire == NULL) || (ire->ire_type &
20671 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20672 			if (ire != NULL) {
20673 				ire_refrele(ire);
20674 				/* No more access to ire */
20675 				ire = NULL;
20676 			}
20677 			/*
20678 			 * bypass routing checks and go directly to interface.
20679 			 */
20680 			if (connp->conn_dontroute)
20681 				goto dontroute;
20682 
20683 			ASSERT(connp->conn_nexthop_set);
20684 			ip_nexthop = B_TRUE;
20685 			nexthop_addr = connp->conn_nexthop_v4;
20686 			goto send_from_ill;
20687 		}
20688 
20689 		/* Must be a broadcast, a loopback or a local ire */
20690 		ire_refrele(ire);
20691 		/* No more access to ire */
20692 		ire = NULL;
20693 	}
20694 
20695 	/*
20696 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20697 	 * this for the tcp global queue and listen end point
20698 	 * as it does not really have a real destination to
20699 	 * talk to.  This is also true for SCTP.
20700 	 */
20701 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20702 	    !connp->conn_fully_bound) {
20703 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20704 		if (ire == NULL)
20705 			goto noirefound;
20706 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20707 		    "ip_wput_end: q %p (%S)", q, "end");
20708 
20709 		/*
20710 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20711 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20712 		 */
20713 		if (ire->ire_flags & RTF_MULTIRT) {
20714 
20715 			/*
20716 			 * Force the TTL of multirouted packets if required.
20717 			 * The TTL of such packets is bounded by the
20718 			 * ip_multirt_ttl ndd variable.
20719 			 */
20720 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20721 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20722 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20723 				    "(was %d), dst 0x%08x\n",
20724 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20725 				    ntohl(ire->ire_addr)));
20726 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20727 			}
20728 			/*
20729 			 * We look at this point if there are pending
20730 			 * unresolved routes. ire_multirt_resolvable()
20731 			 * checks in O(n) that all IRE_OFFSUBNET ire
20732 			 * entries for the packet's destination and
20733 			 * flagged RTF_MULTIRT are currently resolved.
20734 			 * If some remain unresolved, we make a copy
20735 			 * of the current message. It will be used
20736 			 * to initiate additional route resolutions.
20737 			 */
20738 			multirt_need_resolve =
20739 			    ire_multirt_need_resolve(ire->ire_addr,
20740 			    msg_getlabel(first_mp), ipst);
20741 			ip2dbg(("ip_wput[TCP]: ire %p, "
20742 			    "multirt_need_resolve %d, first_mp %p\n",
20743 			    (void *)ire, multirt_need_resolve,
20744 			    (void *)first_mp));
20745 			if (multirt_need_resolve) {
20746 				copy_mp = copymsg(first_mp);
20747 				if (copy_mp != NULL) {
20748 					MULTIRT_DEBUG_TAG(copy_mp);
20749 				}
20750 			}
20751 		}
20752 
20753 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20754 
20755 		/*
20756 		 * Try to resolve another multiroute if
20757 		 * ire_multirt_need_resolve() deemed it necessary.
20758 		 */
20759 		if (copy_mp != NULL)
20760 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20761 		if (need_decref)
20762 			CONN_DEC_REF(connp);
20763 		return;
20764 	}
20765 
20766 	/*
20767 	 * Access to conn_ire_cache. (protected by conn_lock)
20768 	 *
20769 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20770 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20771 	 * send a packet or two with the IRE_CACHE that is going away.
20772 	 * Access to the ire requires an ire refhold on the ire prior to
20773 	 * its use since an interface unplumb thread may delete the cached
20774 	 * ire and release the refhold at any time.
20775 	 *
20776 	 * Caching an ire in the conn_ire_cache
20777 	 *
20778 	 * o Caching an ire pointer in the conn requires a strict check for
20779 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20780 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20781 	 * in the conn is done after making sure under the bucket lock that the
20782 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20783 	 * caching an ire after the unplumb thread has cleaned up the conn.
20784 	 * If the conn does not send a packet subsequently the unplumb thread
20785 	 * will be hanging waiting for the ire count to drop to zero.
20786 	 *
20787 	 * o We also need to atomically test for a null conn_ire_cache and
20788 	 * set the conn_ire_cache under the the protection of the conn_lock
20789 	 * to avoid races among concurrent threads trying to simultaneously
20790 	 * cache an ire in the conn_ire_cache.
20791 	 */
20792 	mutex_enter(&connp->conn_lock);
20793 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20794 
20795 	if (ire != NULL && ire->ire_addr == dst &&
20796 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20797 
20798 		IRE_REFHOLD(ire);
20799 		mutex_exit(&connp->conn_lock);
20800 
20801 	} else {
20802 		boolean_t cached = B_FALSE;
20803 		connp->conn_ire_cache = NULL;
20804 		mutex_exit(&connp->conn_lock);
20805 		/* Release the old ire */
20806 		if (ire != NULL && sctp_ire == NULL)
20807 			IRE_REFRELE_NOTR(ire);
20808 
20809 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20810 		if (ire == NULL)
20811 			goto noirefound;
20812 		IRE_REFHOLD_NOTR(ire);
20813 
20814 		mutex_enter(&connp->conn_lock);
20815 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20816 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20817 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20818 				if (connp->conn_ulp == IPPROTO_TCP)
20819 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20820 				connp->conn_ire_cache = ire;
20821 				cached = B_TRUE;
20822 			}
20823 			rw_exit(&ire->ire_bucket->irb_lock);
20824 		}
20825 		mutex_exit(&connp->conn_lock);
20826 
20827 		/*
20828 		 * We can continue to use the ire but since it was
20829 		 * not cached, we should drop the extra reference.
20830 		 */
20831 		if (!cached)
20832 			IRE_REFRELE_NOTR(ire);
20833 	}
20834 
20835 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20836 	    "ip_wput_end: q %p (%S)", q, "end");
20837 
20838 	/*
20839 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20840 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20841 	 */
20842 	if (ire->ire_flags & RTF_MULTIRT) {
20843 		/*
20844 		 * Force the TTL of multirouted packets if required.
20845 		 * The TTL of such packets is bounded by the
20846 		 * ip_multirt_ttl ndd variable.
20847 		 */
20848 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20849 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20850 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20851 			    "(was %d), dst 0x%08x\n",
20852 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20853 			    ntohl(ire->ire_addr)));
20854 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20855 		}
20856 
20857 		/*
20858 		 * At this point, we check to see if there are any pending
20859 		 * unresolved routes. ire_multirt_resolvable()
20860 		 * checks in O(n) that all IRE_OFFSUBNET ire
20861 		 * entries for the packet's destination and
20862 		 * flagged RTF_MULTIRT are currently resolved.
20863 		 * If some remain unresolved, we make a copy
20864 		 * of the current message. It will be used
20865 		 * to initiate additional route resolutions.
20866 		 */
20867 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20868 		    msg_getlabel(first_mp), ipst);
20869 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20870 		    "multirt_need_resolve %d, first_mp %p\n",
20871 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20872 		if (multirt_need_resolve) {
20873 			copy_mp = copymsg(first_mp);
20874 			if (copy_mp != NULL) {
20875 				MULTIRT_DEBUG_TAG(copy_mp);
20876 			}
20877 		}
20878 	}
20879 
20880 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20881 
20882 	/*
20883 	 * Try to resolve another multiroute if
20884 	 * ire_multirt_resolvable() deemed it necessary
20885 	 */
20886 	if (copy_mp != NULL)
20887 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20888 	if (need_decref)
20889 		CONN_DEC_REF(connp);
20890 	return;
20891 
20892 qnext:
20893 	/*
20894 	 * Upper Level Protocols pass down complete IP datagrams
20895 	 * as M_DATA messages.	Everything else is a sideshow.
20896 	 *
20897 	 * 1) We could be re-entering ip_wput because of ip_neworute
20898 	 *    in which case we could have a IPSEC_OUT message. We
20899 	 *    need to pass through ip_wput like other datagrams and
20900 	 *    hence cannot branch to ip_wput_nondata.
20901 	 *
20902 	 * 2) ARP, AH, ESP, and other clients who are on the module
20903 	 *    instance of IP stream, give us something to deal with.
20904 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20905 	 *
20906 	 * 3) ICMP replies also could come here.
20907 	 */
20908 	ipst = ILLQ_TO_IPST(q);
20909 
20910 	if (DB_TYPE(mp) != M_DATA) {
20911 notdata:
20912 		if (DB_TYPE(mp) == M_CTL) {
20913 			/*
20914 			 * M_CTL messages are used by ARP, AH and ESP to
20915 			 * communicate with IP. We deal with IPSEC_IN and
20916 			 * IPSEC_OUT here. ip_wput_nondata handles other
20917 			 * cases.
20918 			 */
20919 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20920 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20921 				first_mp = mp->b_cont;
20922 				first_mp->b_flag &= ~MSGHASREF;
20923 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20924 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20925 				CONN_DEC_REF(connp);
20926 				connp = NULL;
20927 			}
20928 			if (ii->ipsec_info_type == IPSEC_IN) {
20929 				/*
20930 				 * Either this message goes back to
20931 				 * IPsec for further processing or to
20932 				 * ULP after policy checks.
20933 				 */
20934 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20935 				return;
20936 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20937 				io = (ipsec_out_t *)ii;
20938 				if (io->ipsec_out_proc_begin) {
20939 					/*
20940 					 * IPsec processing has already started.
20941 					 * Complete it.
20942 					 * IPQoS notes: We don't care what is
20943 					 * in ipsec_out_ill_index since this
20944 					 * won't be processed for IPQoS policies
20945 					 * in ipsec_out_process.
20946 					 */
20947 					ipsec_out_process(q, mp, NULL,
20948 					    io->ipsec_out_ill_index);
20949 					return;
20950 				} else {
20951 					connp = (q->q_next != NULL) ?
20952 					    NULL : Q_TO_CONN(q);
20953 					first_mp = mp;
20954 					mp = mp->b_cont;
20955 					mctl_present = B_TRUE;
20956 				}
20957 				zoneid = io->ipsec_out_zoneid;
20958 				ASSERT(zoneid != ALL_ZONES);
20959 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20960 				/*
20961 				 * It's an IPsec control message requesting
20962 				 * an SADB update to be sent to the IPsec
20963 				 * hardware acceleration capable ills.
20964 				 */
20965 				ipsec_ctl_t *ipsec_ctl =
20966 				    (ipsec_ctl_t *)mp->b_rptr;
20967 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20968 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20969 				mblk_t *cmp = mp->b_cont;
20970 
20971 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20972 				ASSERT(cmp != NULL);
20973 
20974 				freeb(mp);
20975 				ill_ipsec_capab_send_all(satype, cmp, sa,
20976 				    ipst->ips_netstack);
20977 				return;
20978 			} else {
20979 				/*
20980 				 * This must be ARP or special TSOL signaling.
20981 				 */
20982 				ip_wput_nondata(NULL, q, mp, NULL);
20983 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20984 				    "ip_wput_end: q %p (%S)", q, "nondata");
20985 				return;
20986 			}
20987 		} else {
20988 			/*
20989 			 * This must be non-(ARP/AH/ESP) messages.
20990 			 */
20991 			ASSERT(!need_decref);
20992 			ip_wput_nondata(NULL, q, mp, NULL);
20993 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20994 			    "ip_wput_end: q %p (%S)", q, "nondata");
20995 			return;
20996 		}
20997 	} else {
20998 		first_mp = mp;
20999 		mctl_present = B_FALSE;
21000 	}
21001 
21002 	ASSERT(first_mp != NULL);
21003 
21004 	if (mctl_present) {
21005 		io = (ipsec_out_t *)first_mp->b_rptr;
21006 		if (io->ipsec_out_ip_nexthop) {
21007 			/*
21008 			 * We may have lost the conn context if we are
21009 			 * coming here from ip_newroute(). Copy the
21010 			 * nexthop information.
21011 			 */
21012 			ip_nexthop = B_TRUE;
21013 			nexthop_addr = io->ipsec_out_nexthop_addr;
21014 
21015 			ipha = (ipha_t *)mp->b_rptr;
21016 			dst = ipha->ipha_dst;
21017 			goto send_from_ill;
21018 		}
21019 	}
21020 
21021 	ASSERT(xmit_ill == NULL);
21022 
21023 	/* We have a complete IP datagram heading outbound. */
21024 	ipha = (ipha_t *)mp->b_rptr;
21025 
21026 #ifndef SPEED_BEFORE_SAFETY
21027 	/*
21028 	 * Make sure we have a full-word aligned message and that at least
21029 	 * a simple IP header is accessible in the first message.  If not,
21030 	 * try a pullup.  For labeled systems we need to always take this
21031 	 * path as M_CTLs are "notdata" but have trailing data to process.
21032 	 */
21033 	if (!OK_32PTR(rptr) ||
21034 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21035 hdrtoosmall:
21036 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21037 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21038 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21039 			if (first_mp == NULL)
21040 				first_mp = mp;
21041 			goto discard_pkt;
21042 		}
21043 
21044 		/* This function assumes that mp points to an IPv4 packet. */
21045 		if (is_system_labeled() && q->q_next == NULL &&
21046 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21047 		    !connp->conn_ulp_labeled) {
21048 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21049 			    connp->conn_mac_exempt, ipst);
21050 			ipha = (ipha_t *)mp->b_rptr;
21051 			if (first_mp != NULL)
21052 				first_mp->b_cont = mp;
21053 			if (err != 0) {
21054 				if (first_mp == NULL)
21055 					first_mp = mp;
21056 				if (err == EINVAL)
21057 					goto icmp_parameter_problem;
21058 				ip2dbg(("ip_wput: label check failed (%d)\n",
21059 				    err));
21060 				goto discard_pkt;
21061 			}
21062 		}
21063 
21064 		ipha = (ipha_t *)mp->b_rptr;
21065 		if (first_mp == NULL) {
21066 			ASSERT(xmit_ill == NULL);
21067 			/*
21068 			 * If we got here because of "goto hdrtoosmall"
21069 			 * We need to attach a IPSEC_OUT.
21070 			 */
21071 			if (connp->conn_out_enforce_policy) {
21072 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21073 				    NULL, ipha->ipha_protocol,
21074 				    ipst->ips_netstack)) == NULL)) {
21075 					BUMP_MIB(&ipst->ips_ip_mib,
21076 					    ipIfStatsOutDiscards);
21077 					if (need_decref)
21078 						CONN_DEC_REF(connp);
21079 					return;
21080 				} else {
21081 					ASSERT(mp->b_datap->db_type == M_CTL);
21082 					first_mp = mp;
21083 					mp = mp->b_cont;
21084 					mctl_present = B_TRUE;
21085 				}
21086 			} else {
21087 				first_mp = mp;
21088 				mctl_present = B_FALSE;
21089 			}
21090 		}
21091 	}
21092 #endif
21093 
21094 	/* Most of the code below is written for speed, not readability */
21095 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21096 
21097 	/*
21098 	 * If ip_newroute() fails, we're going to need a full
21099 	 * header for the icmp wraparound.
21100 	 */
21101 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21102 		uint_t	v_hlen;
21103 version_hdrlen_check:
21104 		ASSERT(first_mp != NULL);
21105 		v_hlen = V_HLEN;
21106 		/*
21107 		 * siphon off IPv6 packets coming down from transport
21108 		 * layer modules here.
21109 		 * Note: high-order bit carries NUD reachability confirmation
21110 		 */
21111 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21112 			/*
21113 			 * FIXME: assume that callers of ip_output* call
21114 			 * the right version?
21115 			 */
21116 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21117 			ASSERT(xmit_ill == NULL);
21118 			if (need_decref)
21119 				mp->b_flag |= MSGHASREF;
21120 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21121 			return;
21122 		}
21123 
21124 		if ((v_hlen >> 4) != IP_VERSION) {
21125 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21126 			    "ip_wput_end: q %p (%S)", q, "badvers");
21127 			goto discard_pkt;
21128 		}
21129 		/*
21130 		 * Is the header length at least 20 bytes?
21131 		 *
21132 		 * Are there enough bytes accessible in the header?  If
21133 		 * not, try a pullup.
21134 		 */
21135 		v_hlen &= 0xF;
21136 		v_hlen <<= 2;
21137 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21138 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21139 			    "ip_wput_end: q %p (%S)", q, "badlen");
21140 			goto discard_pkt;
21141 		}
21142 		if (v_hlen > (mp->b_wptr - rptr)) {
21143 			if (!pullupmsg(mp, v_hlen)) {
21144 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21145 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21146 				goto discard_pkt;
21147 			}
21148 			ipha = (ipha_t *)mp->b_rptr;
21149 		}
21150 		/*
21151 		 * Move first entry from any source route into ipha_dst and
21152 		 * verify the options
21153 		 */
21154 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21155 		    zoneid, ipst)) {
21156 			ASSERT(xmit_ill == NULL);
21157 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21158 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21159 			    "ip_wput_end: q %p (%S)", q, "badopts");
21160 			if (need_decref)
21161 				CONN_DEC_REF(connp);
21162 			return;
21163 		}
21164 	}
21165 	dst = ipha->ipha_dst;
21166 
21167 	/*
21168 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21169 	 * we have to run the packet through ip_newroute which will take
21170 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21171 	 * a resolver, or assigning a default gateway, etc.
21172 	 */
21173 	if (CLASSD(dst)) {
21174 		ipif_t	*ipif;
21175 		uint32_t setsrc = 0;
21176 
21177 multicast:
21178 		ASSERT(first_mp != NULL);
21179 		ip2dbg(("ip_wput: CLASSD\n"));
21180 		if (connp == NULL) {
21181 			/*
21182 			 * Use the first good ipif on the ill.
21183 			 * XXX Should this ever happen? (Appears
21184 			 * to show up with just ppp and no ethernet due
21185 			 * to in.rdisc.)
21186 			 * However, ire_send should be able to
21187 			 * call ip_wput_ire directly.
21188 			 *
21189 			 * XXX Also, this can happen for ICMP and other packets
21190 			 * with multicast source addresses.  Perhaps we should
21191 			 * fix things so that we drop the packet in question,
21192 			 * but for now, just run with it.
21193 			 */
21194 			ill_t *ill = (ill_t *)q->q_ptr;
21195 
21196 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21197 			if (ipif == NULL) {
21198 				if (need_decref)
21199 					CONN_DEC_REF(connp);
21200 				freemsg(first_mp);
21201 				return;
21202 			}
21203 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21204 			    ntohl(dst), ill->ill_name));
21205 		} else {
21206 			/*
21207 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21208 			 * and IP_MULTICAST_IF.  The block comment above this
21209 			 * function explains the locking mechanism used here.
21210 			 */
21211 			if (xmit_ill == NULL) {
21212 				xmit_ill = conn_get_held_ill(connp,
21213 				    &connp->conn_outgoing_ill, &err);
21214 				if (err == ILL_LOOKUP_FAILED) {
21215 					ip1dbg(("ip_wput: No ill for "
21216 					    "IP_BOUND_IF\n"));
21217 					BUMP_MIB(&ipst->ips_ip_mib,
21218 					    ipIfStatsOutNoRoutes);
21219 					goto drop_pkt;
21220 				}
21221 			}
21222 
21223 			if (xmit_ill == NULL) {
21224 				ipif = conn_get_held_ipif(connp,
21225 				    &connp->conn_multicast_ipif, &err);
21226 				if (err == IPIF_LOOKUP_FAILED) {
21227 					ip1dbg(("ip_wput: No ipif for "
21228 					    "multicast\n"));
21229 					BUMP_MIB(&ipst->ips_ip_mib,
21230 					    ipIfStatsOutNoRoutes);
21231 					goto drop_pkt;
21232 				}
21233 			}
21234 			if (xmit_ill != NULL) {
21235 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21236 				if (ipif == NULL) {
21237 					ip1dbg(("ip_wput: No ipif for "
21238 					    "xmit_ill\n"));
21239 					BUMP_MIB(&ipst->ips_ip_mib,
21240 					    ipIfStatsOutNoRoutes);
21241 					goto drop_pkt;
21242 				}
21243 			} else if (ipif == NULL || ipif->ipif_isv6) {
21244 				/*
21245 				 * We must do this ipif determination here
21246 				 * else we could pass through ip_newroute
21247 				 * and come back here without the conn context.
21248 				 *
21249 				 * Note: we do late binding i.e. we bind to
21250 				 * the interface when the first packet is sent.
21251 				 * For performance reasons we do not rebind on
21252 				 * each packet but keep the binding until the
21253 				 * next IP_MULTICAST_IF option.
21254 				 *
21255 				 * conn_multicast_{ipif,ill} are shared between
21256 				 * IPv4 and IPv6 and AF_INET6 sockets can
21257 				 * send both IPv4 and IPv6 packets. Hence
21258 				 * we have to check that "isv6" matches above.
21259 				 */
21260 				if (ipif != NULL)
21261 					ipif_refrele(ipif);
21262 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21263 				if (ipif == NULL) {
21264 					ip1dbg(("ip_wput: No ipif for "
21265 					    "multicast\n"));
21266 					BUMP_MIB(&ipst->ips_ip_mib,
21267 					    ipIfStatsOutNoRoutes);
21268 					goto drop_pkt;
21269 				}
21270 				err = conn_set_held_ipif(connp,
21271 				    &connp->conn_multicast_ipif, ipif);
21272 				if (err == IPIF_LOOKUP_FAILED) {
21273 					ipif_refrele(ipif);
21274 					ip1dbg(("ip_wput: No ipif for "
21275 					    "multicast\n"));
21276 					BUMP_MIB(&ipst->ips_ip_mib,
21277 					    ipIfStatsOutNoRoutes);
21278 					goto drop_pkt;
21279 				}
21280 			}
21281 		}
21282 		ASSERT(!ipif->ipif_isv6);
21283 		/*
21284 		 * As we may lose the conn by the time we reach ip_wput_ire,
21285 		 * we copy conn_multicast_loop and conn_dontroute on to an
21286 		 * ipsec_out. In case if this datagram goes out secure,
21287 		 * we need the ill_index also. Copy that also into the
21288 		 * ipsec_out.
21289 		 */
21290 		if (mctl_present) {
21291 			io = (ipsec_out_t *)first_mp->b_rptr;
21292 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21293 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21294 		} else {
21295 			ASSERT(mp == first_mp);
21296 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21297 			    BPRI_HI)) == NULL) {
21298 				ipif_refrele(ipif);
21299 				first_mp = mp;
21300 				goto discard_pkt;
21301 			}
21302 			first_mp->b_datap->db_type = M_CTL;
21303 			first_mp->b_wptr += sizeof (ipsec_info_t);
21304 			/* ipsec_out_secure is B_FALSE now */
21305 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21306 			io = (ipsec_out_t *)first_mp->b_rptr;
21307 			io->ipsec_out_type = IPSEC_OUT;
21308 			io->ipsec_out_len = sizeof (ipsec_out_t);
21309 			io->ipsec_out_use_global_policy = B_TRUE;
21310 			io->ipsec_out_ns = ipst->ips_netstack;
21311 			first_mp->b_cont = mp;
21312 			mctl_present = B_TRUE;
21313 		}
21314 
21315 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21316 		io->ipsec_out_ill_index =
21317 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21318 
21319 		if (connp != NULL) {
21320 			io->ipsec_out_multicast_loop =
21321 			    connp->conn_multicast_loop;
21322 			io->ipsec_out_dontroute = connp->conn_dontroute;
21323 			io->ipsec_out_zoneid = connp->conn_zoneid;
21324 		}
21325 		/*
21326 		 * If the application uses IP_MULTICAST_IF with
21327 		 * different logical addresses of the same ILL, we
21328 		 * need to make sure that the soruce address of
21329 		 * the packet matches the logical IP address used
21330 		 * in the option. We do it by initializing ipha_src
21331 		 * here. This should keep IPsec also happy as
21332 		 * when we return from IPsec processing, we don't
21333 		 * have to worry about getting the right address on
21334 		 * the packet. Thus it is sufficient to look for
21335 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21336 		 * MATCH_IRE_IPIF.
21337 		 *
21338 		 * NOTE : We need to do it for non-secure case also as
21339 		 * this might go out secure if there is a global policy
21340 		 * match in ip_wput_ire.
21341 		 *
21342 		 * As we do not have the ire yet, it is possible that
21343 		 * we set the source address here and then later discover
21344 		 * that the ire implies the source address to be assigned
21345 		 * through the RTF_SETSRC flag.
21346 		 * In that case, the setsrc variable will remind us
21347 		 * that overwritting the source address by the one
21348 		 * of the RTF_SETSRC-flagged ire is allowed.
21349 		 */
21350 		if (ipha->ipha_src == INADDR_ANY &&
21351 		    (connp == NULL || !connp->conn_unspec_src)) {
21352 			ipha->ipha_src = ipif->ipif_src_addr;
21353 			setsrc = RTF_SETSRC;
21354 		}
21355 		/*
21356 		 * Find an IRE which matches the destination and the outgoing
21357 		 * queue (i.e. the outgoing interface.)
21358 		 * For loopback use a unicast IP address for
21359 		 * the ire lookup.
21360 		 */
21361 		if (IS_LOOPBACK(ipif->ipif_ill))
21362 			dst = ipif->ipif_lcl_addr;
21363 
21364 		/*
21365 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21366 		 * We don't need to lookup ire in ctable as the packet
21367 		 * needs to be sent to the destination through the specified
21368 		 * ill irrespective of ires in the cache table.
21369 		 */
21370 		ire = NULL;
21371 		if (xmit_ill == NULL) {
21372 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21373 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21374 		}
21375 
21376 		if (ire == NULL) {
21377 			/*
21378 			 * Multicast loopback and multicast forwarding is
21379 			 * done in ip_wput_ire.
21380 			 *
21381 			 * Mark this packet to make it be delivered to
21382 			 * ip_wput_ire after the new ire has been
21383 			 * created.
21384 			 *
21385 			 * The call to ip_newroute_ipif takes into account
21386 			 * the setsrc reminder. In any case, we take care
21387 			 * of the RTF_MULTIRT flag.
21388 			 */
21389 			mp->b_prev = mp->b_next = NULL;
21390 			if (xmit_ill == NULL ||
21391 			    xmit_ill->ill_ipif_up_count > 0) {
21392 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21393 				    setsrc | RTF_MULTIRT, zoneid, infop);
21394 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21395 				    "ip_wput_end: q %p (%S)", q, "noire");
21396 			} else {
21397 				freemsg(first_mp);
21398 			}
21399 			ipif_refrele(ipif);
21400 			if (xmit_ill != NULL)
21401 				ill_refrele(xmit_ill);
21402 			if (need_decref)
21403 				CONN_DEC_REF(connp);
21404 			return;
21405 		}
21406 
21407 		ipif_refrele(ipif);
21408 		ipif = NULL;
21409 		ASSERT(xmit_ill == NULL);
21410 
21411 		/*
21412 		 * Honor the RTF_SETSRC flag for multicast packets,
21413 		 * if allowed by the setsrc reminder.
21414 		 */
21415 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21416 			ipha->ipha_src = ire->ire_src_addr;
21417 		}
21418 
21419 		/*
21420 		 * Unconditionally force the TTL to 1 for
21421 		 * multirouted multicast packets:
21422 		 * multirouted multicast should not cross
21423 		 * multicast routers.
21424 		 */
21425 		if (ire->ire_flags & RTF_MULTIRT) {
21426 			if (ipha->ipha_ttl > 1) {
21427 				ip2dbg(("ip_wput: forcing multicast "
21428 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21429 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21430 				ipha->ipha_ttl = 1;
21431 			}
21432 		}
21433 	} else {
21434 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21435 		if ((ire != NULL) && (ire->ire_type &
21436 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21437 			ignore_dontroute = B_TRUE;
21438 			ignore_nexthop = B_TRUE;
21439 		}
21440 		if (ire != NULL) {
21441 			ire_refrele(ire);
21442 			ire = NULL;
21443 		}
21444 		/*
21445 		 * Guard against coming in from arp in which case conn is NULL.
21446 		 * Also guard against non M_DATA with dontroute set but
21447 		 * destined to local, loopback or broadcast addresses.
21448 		 */
21449 		if (connp != NULL && connp->conn_dontroute &&
21450 		    !ignore_dontroute) {
21451 dontroute:
21452 			/*
21453 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21454 			 * routing protocols from seeing false direct
21455 			 * connectivity.
21456 			 */
21457 			ipha->ipha_ttl = 1;
21458 			/* If suitable ipif not found, drop packet */
21459 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21460 			if (dst_ipif == NULL) {
21461 noroute:
21462 				ip1dbg(("ip_wput: no route for dst using"
21463 				    " SO_DONTROUTE\n"));
21464 				BUMP_MIB(&ipst->ips_ip_mib,
21465 				    ipIfStatsOutNoRoutes);
21466 				mp->b_prev = mp->b_next = NULL;
21467 				if (first_mp == NULL)
21468 					first_mp = mp;
21469 				goto drop_pkt;
21470 			} else {
21471 				/*
21472 				 * If suitable ipif has been found, set
21473 				 * xmit_ill to the corresponding
21474 				 * ipif_ill because we'll be using the
21475 				 * send_from_ill logic below.
21476 				 */
21477 				ASSERT(xmit_ill == NULL);
21478 				xmit_ill = dst_ipif->ipif_ill;
21479 				mutex_enter(&xmit_ill->ill_lock);
21480 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21481 					mutex_exit(&xmit_ill->ill_lock);
21482 					xmit_ill = NULL;
21483 					ipif_refrele(dst_ipif);
21484 					goto noroute;
21485 				}
21486 				ill_refhold_locked(xmit_ill);
21487 				mutex_exit(&xmit_ill->ill_lock);
21488 				ipif_refrele(dst_ipif);
21489 			}
21490 		}
21491 
21492 send_from_ill:
21493 		if (xmit_ill != NULL) {
21494 			ipif_t *ipif;
21495 
21496 			/*
21497 			 * Mark this packet as originated locally
21498 			 */
21499 			mp->b_prev = mp->b_next = NULL;
21500 
21501 			/*
21502 			 * Could be SO_DONTROUTE case also.
21503 			 * Verify that at least one ipif is up on the ill.
21504 			 */
21505 			if (xmit_ill->ill_ipif_up_count == 0) {
21506 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21507 				    xmit_ill->ill_name));
21508 				goto drop_pkt;
21509 			}
21510 
21511 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21512 			if (ipif == NULL) {
21513 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21514 				    xmit_ill->ill_name));
21515 				goto drop_pkt;
21516 			}
21517 
21518 			match_flags = 0;
21519 			if (IS_UNDER_IPMP(xmit_ill))
21520 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21521 
21522 			/*
21523 			 * Look for a ire that is part of the group,
21524 			 * if found use it else call ip_newroute_ipif.
21525 			 * IPCL_ZONEID is not used for matching because
21526 			 * IP_ALLZONES option is valid only when the
21527 			 * ill is accessible from all zones i.e has a
21528 			 * valid ipif in all zones.
21529 			 */
21530 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21531 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21532 			    msg_getlabel(mp), match_flags, ipst);
21533 			/*
21534 			 * If an ire exists use it or else create
21535 			 * an ire but don't add it to the cache.
21536 			 * Adding an ire may cause issues with
21537 			 * asymmetric routing.
21538 			 * In case of multiroute always act as if
21539 			 * ire does not exist.
21540 			 */
21541 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21542 				if (ire != NULL)
21543 					ire_refrele(ire);
21544 				ip_newroute_ipif(q, first_mp, ipif,
21545 				    dst, connp, 0, zoneid, infop);
21546 				ipif_refrele(ipif);
21547 				ip1dbg(("ip_output: xmit_ill via %s\n",
21548 				    xmit_ill->ill_name));
21549 				ill_refrele(xmit_ill);
21550 				if (need_decref)
21551 					CONN_DEC_REF(connp);
21552 				return;
21553 			}
21554 			ipif_refrele(ipif);
21555 		} else if (ip_nexthop || (connp != NULL &&
21556 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21557 			if (!ip_nexthop) {
21558 				ip_nexthop = B_TRUE;
21559 				nexthop_addr = connp->conn_nexthop_v4;
21560 			}
21561 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21562 			    MATCH_IRE_GW;
21563 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21564 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21565 		} else {
21566 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21567 			    ipst);
21568 		}
21569 		if (!ire) {
21570 			if (ip_nexthop && !ignore_nexthop) {
21571 				if (mctl_present) {
21572 					io = (ipsec_out_t *)first_mp->b_rptr;
21573 					ASSERT(first_mp->b_datap->db_type ==
21574 					    M_CTL);
21575 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21576 				} else {
21577 					ASSERT(mp == first_mp);
21578 					first_mp = allocb(
21579 					    sizeof (ipsec_info_t), BPRI_HI);
21580 					if (first_mp == NULL) {
21581 						first_mp = mp;
21582 						goto discard_pkt;
21583 					}
21584 					first_mp->b_datap->db_type = M_CTL;
21585 					first_mp->b_wptr +=
21586 					    sizeof (ipsec_info_t);
21587 					/* ipsec_out_secure is B_FALSE now */
21588 					bzero(first_mp->b_rptr,
21589 					    sizeof (ipsec_info_t));
21590 					io = (ipsec_out_t *)first_mp->b_rptr;
21591 					io->ipsec_out_type = IPSEC_OUT;
21592 					io->ipsec_out_len =
21593 					    sizeof (ipsec_out_t);
21594 					io->ipsec_out_use_global_policy =
21595 					    B_TRUE;
21596 					io->ipsec_out_ns = ipst->ips_netstack;
21597 					first_mp->b_cont = mp;
21598 					mctl_present = B_TRUE;
21599 				}
21600 				io->ipsec_out_ip_nexthop = ip_nexthop;
21601 				io->ipsec_out_nexthop_addr = nexthop_addr;
21602 			}
21603 noirefound:
21604 			/*
21605 			 * Mark this packet as having originated on
21606 			 * this machine.  This will be noted in
21607 			 * ire_add_then_send, which needs to know
21608 			 * whether to run it back through ip_wput or
21609 			 * ip_rput following successful resolution.
21610 			 */
21611 			mp->b_prev = NULL;
21612 			mp->b_next = NULL;
21613 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21614 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21615 			    "ip_wput_end: q %p (%S)", q, "newroute");
21616 			if (xmit_ill != NULL)
21617 				ill_refrele(xmit_ill);
21618 			if (need_decref)
21619 				CONN_DEC_REF(connp);
21620 			return;
21621 		}
21622 	}
21623 
21624 	/* We now know where we are going with it. */
21625 
21626 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21627 	    "ip_wput_end: q %p (%S)", q, "end");
21628 
21629 	/*
21630 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21631 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21632 	 */
21633 	if (ire->ire_flags & RTF_MULTIRT) {
21634 		/*
21635 		 * Force the TTL of multirouted packets if required.
21636 		 * The TTL of such packets is bounded by the
21637 		 * ip_multirt_ttl ndd variable.
21638 		 */
21639 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21640 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21641 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21642 			    "(was %d), dst 0x%08x\n",
21643 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21644 			    ntohl(ire->ire_addr)));
21645 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21646 		}
21647 		/*
21648 		 * At this point, we check to see if there are any pending
21649 		 * unresolved routes. ire_multirt_resolvable()
21650 		 * checks in O(n) that all IRE_OFFSUBNET ire
21651 		 * entries for the packet's destination and
21652 		 * flagged RTF_MULTIRT are currently resolved.
21653 		 * If some remain unresolved, we make a copy
21654 		 * of the current message. It will be used
21655 		 * to initiate additional route resolutions.
21656 		 */
21657 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21658 		    msg_getlabel(first_mp), ipst);
21659 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21660 		    "multirt_need_resolve %d, first_mp %p\n",
21661 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21662 		if (multirt_need_resolve) {
21663 			copy_mp = copymsg(first_mp);
21664 			if (copy_mp != NULL) {
21665 				MULTIRT_DEBUG_TAG(copy_mp);
21666 			}
21667 		}
21668 	}
21669 
21670 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21671 	/*
21672 	 * Try to resolve another multiroute if
21673 	 * ire_multirt_resolvable() deemed it necessary.
21674 	 * At this point, we need to distinguish
21675 	 * multicasts from other packets. For multicasts,
21676 	 * we call ip_newroute_ipif() and request that both
21677 	 * multirouting and setsrc flags are checked.
21678 	 */
21679 	if (copy_mp != NULL) {
21680 		if (CLASSD(dst)) {
21681 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21682 			if (ipif) {
21683 				ASSERT(infop->ip_opt_ill_index == 0);
21684 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21685 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21686 				ipif_refrele(ipif);
21687 			} else {
21688 				MULTIRT_DEBUG_UNTAG(copy_mp);
21689 				freemsg(copy_mp);
21690 				copy_mp = NULL;
21691 			}
21692 		} else {
21693 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21694 		}
21695 	}
21696 	if (xmit_ill != NULL)
21697 		ill_refrele(xmit_ill);
21698 	if (need_decref)
21699 		CONN_DEC_REF(connp);
21700 	return;
21701 
21702 icmp_parameter_problem:
21703 	/* could not have originated externally */
21704 	ASSERT(mp->b_prev == NULL);
21705 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21706 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21707 		/* it's the IP header length that's in trouble */
21708 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21709 		first_mp = NULL;
21710 	}
21711 
21712 discard_pkt:
21713 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21714 drop_pkt:
21715 	ip1dbg(("ip_wput: dropped packet\n"));
21716 	if (ire != NULL)
21717 		ire_refrele(ire);
21718 	if (need_decref)
21719 		CONN_DEC_REF(connp);
21720 	freemsg(first_mp);
21721 	if (xmit_ill != NULL)
21722 		ill_refrele(xmit_ill);
21723 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21724 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21725 }
21726 
21727 /*
21728  * If this is a conn_t queue, then we pass in the conn. This includes the
21729  * zoneid.
21730  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21731  * in which case we use the global zoneid since those are all part of
21732  * the global zone.
21733  */
21734 void
21735 ip_wput(queue_t *q, mblk_t *mp)
21736 {
21737 	if (CONN_Q(q))
21738 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21739 	else
21740 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21741 }
21742 
21743 /*
21744  *
21745  * The following rules must be observed when accessing any ipif or ill
21746  * that has been cached in the conn. Typically conn_outgoing_ill,
21747  * conn_multicast_ipif and conn_multicast_ill.
21748  *
21749  * Access: The ipif or ill pointed to from the conn can be accessed under
21750  * the protection of the conn_lock or after it has been refheld under the
21751  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21752  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21753  * The reason for this is that a concurrent unplumb could actually be
21754  * cleaning up these cached pointers by walking the conns and might have
21755  * finished cleaning up the conn in question. The macros check that an
21756  * unplumb has not yet started on the ipif or ill.
21757  *
21758  * Caching: An ipif or ill pointer may be cached in the conn only after
21759  * making sure that an unplumb has not started. So the caching is done
21760  * while holding both the conn_lock and the ill_lock and after using the
21761  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21762  * flag before starting the cleanup of conns.
21763  *
21764  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21765  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21766  * or a reference to the ipif or a reference to an ire that references the
21767  * ipif. An ipif only changes its ill when migrating from an underlying ill
21768  * to an IPMP ill in ipif_up().
21769  */
21770 ipif_t *
21771 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21772 {
21773 	ipif_t	*ipif;
21774 	ill_t	*ill;
21775 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21776 
21777 	*err = 0;
21778 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21779 	mutex_enter(&connp->conn_lock);
21780 	ipif = *ipifp;
21781 	if (ipif != NULL) {
21782 		ill = ipif->ipif_ill;
21783 		mutex_enter(&ill->ill_lock);
21784 		if (IPIF_CAN_LOOKUP(ipif)) {
21785 			ipif_refhold_locked(ipif);
21786 			mutex_exit(&ill->ill_lock);
21787 			mutex_exit(&connp->conn_lock);
21788 			rw_exit(&ipst->ips_ill_g_lock);
21789 			return (ipif);
21790 		} else {
21791 			*err = IPIF_LOOKUP_FAILED;
21792 		}
21793 		mutex_exit(&ill->ill_lock);
21794 	}
21795 	mutex_exit(&connp->conn_lock);
21796 	rw_exit(&ipst->ips_ill_g_lock);
21797 	return (NULL);
21798 }
21799 
21800 ill_t *
21801 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21802 {
21803 	ill_t	*ill;
21804 
21805 	*err = 0;
21806 	mutex_enter(&connp->conn_lock);
21807 	ill = *illp;
21808 	if (ill != NULL) {
21809 		mutex_enter(&ill->ill_lock);
21810 		if (ILL_CAN_LOOKUP(ill)) {
21811 			ill_refhold_locked(ill);
21812 			mutex_exit(&ill->ill_lock);
21813 			mutex_exit(&connp->conn_lock);
21814 			return (ill);
21815 		} else {
21816 			*err = ILL_LOOKUP_FAILED;
21817 		}
21818 		mutex_exit(&ill->ill_lock);
21819 	}
21820 	mutex_exit(&connp->conn_lock);
21821 	return (NULL);
21822 }
21823 
21824 static int
21825 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21826 {
21827 	ill_t	*ill;
21828 
21829 	ill = ipif->ipif_ill;
21830 	mutex_enter(&connp->conn_lock);
21831 	mutex_enter(&ill->ill_lock);
21832 	if (IPIF_CAN_LOOKUP(ipif)) {
21833 		*ipifp = ipif;
21834 		mutex_exit(&ill->ill_lock);
21835 		mutex_exit(&connp->conn_lock);
21836 		return (0);
21837 	}
21838 	mutex_exit(&ill->ill_lock);
21839 	mutex_exit(&connp->conn_lock);
21840 	return (IPIF_LOOKUP_FAILED);
21841 }
21842 
21843 /*
21844  * This is called if the outbound datagram needs fragmentation.
21845  *
21846  * NOTE : This function does not ire_refrele the ire argument passed in.
21847  */
21848 static void
21849 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21850     ip_stack_t *ipst, conn_t *connp)
21851 {
21852 	ipha_t		*ipha;
21853 	mblk_t		*mp;
21854 	uint32_t	v_hlen_tos_len;
21855 	uint32_t	max_frag;
21856 	uint32_t	frag_flag;
21857 	boolean_t	dont_use;
21858 
21859 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21860 		mp = ipsec_mp->b_cont;
21861 	} else {
21862 		mp = ipsec_mp;
21863 	}
21864 
21865 	ipha = (ipha_t *)mp->b_rptr;
21866 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21867 
21868 #ifdef	_BIG_ENDIAN
21869 #define	V_HLEN	(v_hlen_tos_len >> 24)
21870 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21871 #else
21872 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21873 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21874 #endif
21875 
21876 #ifndef SPEED_BEFORE_SAFETY
21877 	/*
21878 	 * Check that ipha_length is consistent with
21879 	 * the mblk length
21880 	 */
21881 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21882 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21883 		    LENGTH, msgdsize(mp)));
21884 		freemsg(ipsec_mp);
21885 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21886 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21887 		    "packet length mismatch");
21888 		return;
21889 	}
21890 #endif
21891 	/*
21892 	 * Don't use frag_flag if pre-built packet or source
21893 	 * routed or if multicast (since multicast packets do not solicit
21894 	 * ICMP "packet too big" messages). Get the values of
21895 	 * max_frag and frag_flag atomically by acquiring the
21896 	 * ire_lock.
21897 	 */
21898 	mutex_enter(&ire->ire_lock);
21899 	max_frag = ire->ire_max_frag;
21900 	frag_flag = ire->ire_frag_flag;
21901 	mutex_exit(&ire->ire_lock);
21902 
21903 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21904 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21905 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21906 
21907 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21908 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21909 }
21910 
21911 /*
21912  * Used for deciding the MSS size for the upper layer. Thus
21913  * we need to check the outbound policy values in the conn.
21914  */
21915 int
21916 conn_ipsec_length(conn_t *connp)
21917 {
21918 	ipsec_latch_t *ipl;
21919 
21920 	ipl = connp->conn_latch;
21921 	if (ipl == NULL)
21922 		return (0);
21923 
21924 	if (ipl->ipl_out_policy == NULL)
21925 		return (0);
21926 
21927 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21928 }
21929 
21930 /*
21931  * Returns an estimate of the IPsec headers size. This is used if
21932  * we don't want to call into IPsec to get the exact size.
21933  */
21934 int
21935 ipsec_out_extra_length(mblk_t *ipsec_mp)
21936 {
21937 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21938 	ipsec_action_t *a;
21939 
21940 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21941 	if (!io->ipsec_out_secure)
21942 		return (0);
21943 
21944 	a = io->ipsec_out_act;
21945 
21946 	if (a == NULL) {
21947 		ASSERT(io->ipsec_out_policy != NULL);
21948 		a = io->ipsec_out_policy->ipsp_act;
21949 	}
21950 	ASSERT(a != NULL);
21951 
21952 	return (a->ipa_ovhd);
21953 }
21954 
21955 /*
21956  * Returns an estimate of the IPsec headers size. This is used if
21957  * we don't want to call into IPsec to get the exact size.
21958  */
21959 int
21960 ipsec_in_extra_length(mblk_t *ipsec_mp)
21961 {
21962 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21963 	ipsec_action_t *a;
21964 
21965 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21966 
21967 	a = ii->ipsec_in_action;
21968 	return (a == NULL ? 0 : a->ipa_ovhd);
21969 }
21970 
21971 /*
21972  * If there are any source route options, return the true final
21973  * destination. Otherwise, return the destination.
21974  */
21975 ipaddr_t
21976 ip_get_dst(ipha_t *ipha)
21977 {
21978 	ipoptp_t	opts;
21979 	uchar_t		*opt;
21980 	uint8_t		optval;
21981 	uint8_t		optlen;
21982 	ipaddr_t	dst;
21983 	uint32_t off;
21984 
21985 	dst = ipha->ipha_dst;
21986 
21987 	if (IS_SIMPLE_IPH(ipha))
21988 		return (dst);
21989 
21990 	for (optval = ipoptp_first(&opts, ipha);
21991 	    optval != IPOPT_EOL;
21992 	    optval = ipoptp_next(&opts)) {
21993 		opt = opts.ipoptp_cur;
21994 		optlen = opts.ipoptp_len;
21995 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21996 		switch (optval) {
21997 		case IPOPT_SSRR:
21998 		case IPOPT_LSRR:
21999 			off = opt[IPOPT_OFFSET];
22000 			/*
22001 			 * If one of the conditions is true, it means
22002 			 * end of options and dst already has the right
22003 			 * value.
22004 			 */
22005 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22006 				off = optlen - IP_ADDR_LEN;
22007 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22008 			}
22009 			return (dst);
22010 		default:
22011 			break;
22012 		}
22013 	}
22014 
22015 	return (dst);
22016 }
22017 
22018 mblk_t *
22019 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22020     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22021 {
22022 	ipsec_out_t	*io;
22023 	mblk_t		*first_mp;
22024 	boolean_t policy_present;
22025 	ip_stack_t	*ipst;
22026 	ipsec_stack_t	*ipss;
22027 
22028 	ASSERT(ire != NULL);
22029 	ipst = ire->ire_ipst;
22030 	ipss = ipst->ips_netstack->netstack_ipsec;
22031 
22032 	first_mp = mp;
22033 	if (mp->b_datap->db_type == M_CTL) {
22034 		io = (ipsec_out_t *)first_mp->b_rptr;
22035 		/*
22036 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22037 		 *
22038 		 * 1) There is per-socket policy (including cached global
22039 		 *    policy) or a policy on the IP-in-IP tunnel.
22040 		 * 2) There is no per-socket policy, but it is
22041 		 *    a multicast packet that needs to go out
22042 		 *    on a specific interface. This is the case
22043 		 *    where (ip_wput and ip_wput_multicast) attaches
22044 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22045 		 *
22046 		 * In case (2) we check with global policy to
22047 		 * see if there is a match and set the ill_index
22048 		 * appropriately so that we can lookup the ire
22049 		 * properly in ip_wput_ipsec_out.
22050 		 */
22051 
22052 		/*
22053 		 * ipsec_out_use_global_policy is set to B_FALSE
22054 		 * in ipsec_in_to_out(). Refer to that function for
22055 		 * details.
22056 		 */
22057 		if ((io->ipsec_out_latch == NULL) &&
22058 		    (io->ipsec_out_use_global_policy)) {
22059 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22060 			    ire, connp, unspec_src, zoneid));
22061 		}
22062 		if (!io->ipsec_out_secure) {
22063 			/*
22064 			 * If this is not a secure packet, drop
22065 			 * the IPSEC_OUT mp and treat it as a clear
22066 			 * packet. This happens when we are sending
22067 			 * a ICMP reply back to a clear packet. See
22068 			 * ipsec_in_to_out() for details.
22069 			 */
22070 			mp = first_mp->b_cont;
22071 			freeb(first_mp);
22072 		}
22073 		return (mp);
22074 	}
22075 	/*
22076 	 * See whether we need to attach a global policy here. We
22077 	 * don't depend on the conn (as it could be null) for deciding
22078 	 * what policy this datagram should go through because it
22079 	 * should have happened in ip_wput if there was some
22080 	 * policy. This normally happens for connections which are not
22081 	 * fully bound preventing us from caching policies in
22082 	 * ip_bind. Packets coming from the TCP listener/global queue
22083 	 * - which are non-hard_bound - could also be affected by
22084 	 * applying policy here.
22085 	 *
22086 	 * If this packet is coming from tcp global queue or listener,
22087 	 * we will be applying policy here.  This may not be *right*
22088 	 * if these packets are coming from the detached connection as
22089 	 * it could have gone in clear before. This happens only if a
22090 	 * TCP connection started when there is no policy and somebody
22091 	 * added policy before it became detached. Thus packets of the
22092 	 * detached connection could go out secure and the other end
22093 	 * would drop it because it will be expecting in clear. The
22094 	 * converse is not true i.e if somebody starts a TCP
22095 	 * connection and deletes the policy, all the packets will
22096 	 * still go out with the policy that existed before deleting
22097 	 * because ip_unbind sends up policy information which is used
22098 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22099 	 * TCP to attach a dummy IPSEC_OUT and set
22100 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22101 	 * affect performance for normal cases, we are not doing it.
22102 	 * Thus, set policy before starting any TCP connections.
22103 	 *
22104 	 * NOTE - We might apply policy even for a hard bound connection
22105 	 * - for which we cached policy in ip_bind - if somebody added
22106 	 * global policy after we inherited the policy in ip_bind.
22107 	 * This means that the packets that were going out in clear
22108 	 * previously would start going secure and hence get dropped
22109 	 * on the other side. To fix this, TCP attaches a dummy
22110 	 * ipsec_out and make sure that we don't apply global policy.
22111 	 */
22112 	if (ipha != NULL)
22113 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22114 	else
22115 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22116 	if (!policy_present)
22117 		return (mp);
22118 
22119 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22120 	    zoneid));
22121 }
22122 
22123 /*
22124  * This function does the ire_refrele of the ire passed in as the
22125  * argument. As this function looks up more ires i.e broadcast ires,
22126  * it needs to REFRELE them. Currently, for simplicity we don't
22127  * differentiate the one passed in and looked up here. We always
22128  * REFRELE.
22129  * IPQoS Notes:
22130  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22131  * IPsec packets are done in ipsec_out_process.
22132  */
22133 void
22134 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22135     zoneid_t zoneid)
22136 {
22137 	ipha_t		*ipha;
22138 #define	rptr	((uchar_t *)ipha)
22139 	queue_t		*stq;
22140 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22141 	uint32_t	v_hlen_tos_len;
22142 	uint32_t	ttl_protocol;
22143 	ipaddr_t	src;
22144 	ipaddr_t	dst;
22145 	uint32_t	cksum;
22146 	ipaddr_t	orig_src;
22147 	ire_t		*ire1;
22148 	mblk_t		*next_mp;
22149 	uint_t		hlen;
22150 	uint16_t	*up;
22151 	uint32_t	max_frag = ire->ire_max_frag;
22152 	ill_t		*ill = ire_to_ill(ire);
22153 	int		clusterwide;
22154 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22155 	int		ipsec_len;
22156 	mblk_t		*first_mp;
22157 	ipsec_out_t	*io;
22158 	boolean_t	conn_dontroute;		/* conn value for multicast */
22159 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22160 	boolean_t	multicast_forward;	/* Should we forward ? */
22161 	boolean_t	unspec_src;
22162 	ill_t		*conn_outgoing_ill = NULL;
22163 	ill_t		*ire_ill;
22164 	ill_t		*ire1_ill;
22165 	ill_t		*out_ill;
22166 	uint32_t 	ill_index = 0;
22167 	boolean_t	multirt_send = B_FALSE;
22168 	int		err;
22169 	ipxmit_state_t	pktxmit_state;
22170 	ip_stack_t	*ipst = ire->ire_ipst;
22171 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22172 
22173 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22174 	    "ip_wput_ire_start: q %p", q);
22175 
22176 	multicast_forward = B_FALSE;
22177 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22178 
22179 	if (ire->ire_flags & RTF_MULTIRT) {
22180 		/*
22181 		 * Multirouting case. The bucket where ire is stored
22182 		 * probably holds other RTF_MULTIRT flagged ire
22183 		 * to the destination. In this call to ip_wput_ire,
22184 		 * we attempt to send the packet through all
22185 		 * those ires. Thus, we first ensure that ire is the
22186 		 * first RTF_MULTIRT ire in the bucket,
22187 		 * before walking the ire list.
22188 		 */
22189 		ire_t *first_ire;
22190 		irb_t *irb = ire->ire_bucket;
22191 		ASSERT(irb != NULL);
22192 
22193 		/* Make sure we do not omit any multiroute ire. */
22194 		IRB_REFHOLD(irb);
22195 		for (first_ire = irb->irb_ire;
22196 		    first_ire != NULL;
22197 		    first_ire = first_ire->ire_next) {
22198 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22199 			    (first_ire->ire_addr == ire->ire_addr) &&
22200 			    !(first_ire->ire_marks &
22201 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22202 				break;
22203 		}
22204 
22205 		if ((first_ire != NULL) && (first_ire != ire)) {
22206 			IRE_REFHOLD(first_ire);
22207 			ire_refrele(ire);
22208 			ire = first_ire;
22209 			ill = ire_to_ill(ire);
22210 		}
22211 		IRB_REFRELE(irb);
22212 	}
22213 
22214 	/*
22215 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22216 	 * for performance we don't grab the mutexs in the fastpath
22217 	 */
22218 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22219 	    connp->conn_outgoing_ill != NULL) {
22220 		conn_outgoing_ill = conn_get_held_ill(connp,
22221 		    &connp->conn_outgoing_ill, &err);
22222 		if (err == ILL_LOOKUP_FAILED) {
22223 			ire_refrele(ire);
22224 			freemsg(mp);
22225 			return;
22226 		}
22227 	}
22228 
22229 	if (mp->b_datap->db_type != M_CTL) {
22230 		ipha = (ipha_t *)mp->b_rptr;
22231 	} else {
22232 		io = (ipsec_out_t *)mp->b_rptr;
22233 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22234 		ASSERT(zoneid == io->ipsec_out_zoneid);
22235 		ASSERT(zoneid != ALL_ZONES);
22236 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22237 		dst = ipha->ipha_dst;
22238 		/*
22239 		 * For the multicast case, ipsec_out carries conn_dontroute and
22240 		 * conn_multicast_loop as conn may not be available here. We
22241 		 * need this for multicast loopback and forwarding which is done
22242 		 * later in the code.
22243 		 */
22244 		if (CLASSD(dst)) {
22245 			conn_dontroute = io->ipsec_out_dontroute;
22246 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22247 			/*
22248 			 * If conn_dontroute is not set or conn_multicast_loop
22249 			 * is set, we need to do forwarding/loopback. For
22250 			 * datagrams from ip_wput_multicast, conn_dontroute is
22251 			 * set to B_TRUE and conn_multicast_loop is set to
22252 			 * B_FALSE so that we neither do forwarding nor
22253 			 * loopback.
22254 			 */
22255 			if (!conn_dontroute || conn_multicast_loop)
22256 				multicast_forward = B_TRUE;
22257 		}
22258 	}
22259 
22260 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22261 	    ire->ire_zoneid != ALL_ZONES) {
22262 		/*
22263 		 * When a zone sends a packet to another zone, we try to deliver
22264 		 * the packet under the same conditions as if the destination
22265 		 * was a real node on the network. To do so, we look for a
22266 		 * matching route in the forwarding table.
22267 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22268 		 * ip_newroute() does.
22269 		 * Note that IRE_LOCAL are special, since they are used
22270 		 * when the zoneid doesn't match in some cases. This means that
22271 		 * we need to handle ipha_src differently since ire_src_addr
22272 		 * belongs to the receiving zone instead of the sending zone.
22273 		 * When ip_restrict_interzone_loopback is set, then
22274 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22275 		 * for loopback between zones when the logical "Ethernet" would
22276 		 * have looped them back.
22277 		 */
22278 		ire_t *src_ire;
22279 
22280 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22281 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22282 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22283 		if (src_ire != NULL &&
22284 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22285 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22286 		    ire_local_same_lan(ire, src_ire))) {
22287 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22288 				ipha->ipha_src = src_ire->ire_src_addr;
22289 			ire_refrele(src_ire);
22290 		} else {
22291 			ire_refrele(ire);
22292 			if (conn_outgoing_ill != NULL)
22293 				ill_refrele(conn_outgoing_ill);
22294 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22295 			if (src_ire != NULL) {
22296 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22297 					ire_refrele(src_ire);
22298 					freemsg(mp);
22299 					return;
22300 				}
22301 				ire_refrele(src_ire);
22302 			}
22303 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22304 				/* Failed */
22305 				freemsg(mp);
22306 				return;
22307 			}
22308 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22309 			    ipst);
22310 			return;
22311 		}
22312 	}
22313 
22314 	if (mp->b_datap->db_type == M_CTL ||
22315 	    ipss->ipsec_outbound_v4_policy_present) {
22316 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22317 		    unspec_src, zoneid);
22318 		if (mp == NULL) {
22319 			ire_refrele(ire);
22320 			if (conn_outgoing_ill != NULL)
22321 				ill_refrele(conn_outgoing_ill);
22322 			return;
22323 		}
22324 		/*
22325 		 * Trusted Extensions supports all-zones interfaces, so
22326 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22327 		 * the global zone.
22328 		 */
22329 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22330 			io = (ipsec_out_t *)mp->b_rptr;
22331 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22332 			zoneid = io->ipsec_out_zoneid;
22333 		}
22334 	}
22335 
22336 	first_mp = mp;
22337 	ipsec_len = 0;
22338 
22339 	if (first_mp->b_datap->db_type == M_CTL) {
22340 		io = (ipsec_out_t *)first_mp->b_rptr;
22341 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22342 		mp = first_mp->b_cont;
22343 		ipsec_len = ipsec_out_extra_length(first_mp);
22344 		ASSERT(ipsec_len >= 0);
22345 		/* We already picked up the zoneid from the M_CTL above */
22346 		ASSERT(zoneid == io->ipsec_out_zoneid);
22347 		ASSERT(zoneid != ALL_ZONES);
22348 
22349 		/*
22350 		 * Drop M_CTL here if IPsec processing is not needed.
22351 		 * (Non-IPsec use of M_CTL extracted any information it
22352 		 * needed above).
22353 		 */
22354 		if (ipsec_len == 0) {
22355 			freeb(first_mp);
22356 			first_mp = mp;
22357 		}
22358 	}
22359 
22360 	/*
22361 	 * Fast path for ip_wput_ire
22362 	 */
22363 
22364 	ipha = (ipha_t *)mp->b_rptr;
22365 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22366 	dst = ipha->ipha_dst;
22367 
22368 	/*
22369 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22370 	 * if the socket is a SOCK_RAW type. The transport checksum should
22371 	 * be provided in the pre-built packet, so we don't need to compute it.
22372 	 * Also, other application set flags, like DF, should not be altered.
22373 	 * Other transport MUST pass down zero.
22374 	 */
22375 	ip_hdr_included = ipha->ipha_ident;
22376 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22377 
22378 	if (CLASSD(dst)) {
22379 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22380 		    ntohl(dst),
22381 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22382 		    ntohl(ire->ire_addr)));
22383 	}
22384 
22385 /* Macros to extract header fields from data already in registers */
22386 #ifdef	_BIG_ENDIAN
22387 #define	V_HLEN	(v_hlen_tos_len >> 24)
22388 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22389 #define	PROTO	(ttl_protocol & 0xFF)
22390 #else
22391 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22392 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22393 #define	PROTO	(ttl_protocol >> 8)
22394 #endif
22395 
22396 	orig_src = src = ipha->ipha_src;
22397 	/* (The loop back to "another" is explained down below.) */
22398 another:;
22399 	/*
22400 	 * Assign an ident value for this packet.  We assign idents on
22401 	 * a per destination basis out of the IRE.  There could be
22402 	 * other threads targeting the same destination, so we have to
22403 	 * arrange for a atomic increment.  Note that we use a 32-bit
22404 	 * atomic add because it has better performance than its
22405 	 * 16-bit sibling.
22406 	 *
22407 	 * If running in cluster mode and if the source address
22408 	 * belongs to a replicated service then vector through
22409 	 * cl_inet_ipident vector to allocate ip identifier
22410 	 * NOTE: This is a contract private interface with the
22411 	 * clustering group.
22412 	 */
22413 	clusterwide = 0;
22414 	if (cl_inet_ipident) {
22415 		ASSERT(cl_inet_isclusterwide);
22416 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22417 
22418 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22419 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22420 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22421 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22422 			    (uint8_t *)(uintptr_t)dst, NULL);
22423 			clusterwide = 1;
22424 		}
22425 	}
22426 	if (!clusterwide) {
22427 		ipha->ipha_ident =
22428 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22429 	}
22430 
22431 #ifndef _BIG_ENDIAN
22432 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22433 #endif
22434 
22435 	/*
22436 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22437 	 * This is needed to obey conn_unspec_src when packets go through
22438 	 * ip_newroute + arp.
22439 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22440 	 */
22441 	if (src == INADDR_ANY && !unspec_src) {
22442 		/*
22443 		 * Assign the appropriate source address from the IRE if none
22444 		 * was specified.
22445 		 */
22446 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22447 
22448 		src = ire->ire_src_addr;
22449 		if (connp == NULL) {
22450 			ip1dbg(("ip_wput_ire: no connp and no src "
22451 			    "address for dst 0x%x, using src 0x%x\n",
22452 			    ntohl(dst),
22453 			    ntohl(src)));
22454 		}
22455 		ipha->ipha_src = src;
22456 	}
22457 	stq = ire->ire_stq;
22458 
22459 	/*
22460 	 * We only allow ire chains for broadcasts since there will
22461 	 * be multiple IRE_CACHE entries for the same multicast
22462 	 * address (one per ipif).
22463 	 */
22464 	next_mp = NULL;
22465 
22466 	/* broadcast packet */
22467 	if (ire->ire_type == IRE_BROADCAST)
22468 		goto broadcast;
22469 
22470 	/* loopback ? */
22471 	if (stq == NULL)
22472 		goto nullstq;
22473 
22474 	/* The ill_index for outbound ILL */
22475 	ill_index = Q_TO_INDEX(stq);
22476 
22477 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22478 	ttl_protocol = ((uint16_t *)ipha)[4];
22479 
22480 	/* pseudo checksum (do it in parts for IP header checksum) */
22481 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22482 
22483 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22484 		queue_t *dev_q = stq->q_next;
22485 
22486 		/*
22487 		 * For DIRECT_CAPABLE, we do flow control at
22488 		 * the time of sending the packet. See
22489 		 * ILL_SEND_TX().
22490 		 */
22491 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22492 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22493 			goto blocked;
22494 
22495 		if ((PROTO == IPPROTO_UDP) &&
22496 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22497 			hlen = (V_HLEN & 0xF) << 2;
22498 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22499 			if (*up != 0) {
22500 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22501 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22502 				/* Software checksum? */
22503 				if (DB_CKSUMFLAGS(mp) == 0) {
22504 					IP_STAT(ipst, ip_out_sw_cksum);
22505 					IP_STAT_UPDATE(ipst,
22506 					    ip_udp_out_sw_cksum_bytes,
22507 					    LENGTH - hlen);
22508 				}
22509 			}
22510 		}
22511 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22512 		hlen = (V_HLEN & 0xF) << 2;
22513 		if (PROTO == IPPROTO_TCP) {
22514 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22515 			/*
22516 			 * The packet header is processed once and for all, even
22517 			 * in the multirouting case. We disable hardware
22518 			 * checksum if the packet is multirouted, as it will be
22519 			 * replicated via several interfaces, and not all of
22520 			 * them may have this capability.
22521 			 */
22522 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22523 			    LENGTH, max_frag, ipsec_len, cksum);
22524 			/* Software checksum? */
22525 			if (DB_CKSUMFLAGS(mp) == 0) {
22526 				IP_STAT(ipst, ip_out_sw_cksum);
22527 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22528 				    LENGTH - hlen);
22529 			}
22530 		} else {
22531 			sctp_hdr_t	*sctph;
22532 
22533 			ASSERT(PROTO == IPPROTO_SCTP);
22534 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22535 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22536 			/*
22537 			 * Zero out the checksum field to ensure proper
22538 			 * checksum calculation.
22539 			 */
22540 			sctph->sh_chksum = 0;
22541 #ifdef	DEBUG
22542 			if (!skip_sctp_cksum)
22543 #endif
22544 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22545 		}
22546 	}
22547 
22548 	/*
22549 	 * If this is a multicast packet and originated from ip_wput
22550 	 * we need to do loopback and forwarding checks. If it comes
22551 	 * from ip_wput_multicast, we SHOULD not do this.
22552 	 */
22553 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22554 
22555 	/* checksum */
22556 	cksum += ttl_protocol;
22557 
22558 	/* fragment the packet */
22559 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22560 		goto fragmentit;
22561 	/*
22562 	 * Don't use frag_flag if packet is pre-built or source
22563 	 * routed or if multicast (since multicast packets do
22564 	 * not solicit ICMP "packet too big" messages).
22565 	 */
22566 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22567 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22568 	    !ip_source_route_included(ipha)) &&
22569 	    !CLASSD(ipha->ipha_dst))
22570 		ipha->ipha_fragment_offset_and_flags |=
22571 		    htons(ire->ire_frag_flag);
22572 
22573 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22574 		/* calculate IP header checksum */
22575 		cksum += ipha->ipha_ident;
22576 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22577 		cksum += ipha->ipha_fragment_offset_and_flags;
22578 
22579 		/* IP options present */
22580 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22581 		if (hlen)
22582 			goto checksumoptions;
22583 
22584 		/* calculate hdr checksum */
22585 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22586 		cksum = ~(cksum + (cksum >> 16));
22587 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22588 	}
22589 	if (ipsec_len != 0) {
22590 		/*
22591 		 * We will do the rest of the processing after
22592 		 * we come back from IPsec in ip_wput_ipsec_out().
22593 		 */
22594 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22595 
22596 		io = (ipsec_out_t *)first_mp->b_rptr;
22597 		io->ipsec_out_ill_index =
22598 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22599 		ipsec_out_process(q, first_mp, ire, 0);
22600 		ire_refrele(ire);
22601 		if (conn_outgoing_ill != NULL)
22602 			ill_refrele(conn_outgoing_ill);
22603 		return;
22604 	}
22605 
22606 	/*
22607 	 * In most cases, the emission loop below is entered only
22608 	 * once. Only in the case where the ire holds the
22609 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22610 	 * flagged ires in the bucket, and send the packet
22611 	 * through all crossed RTF_MULTIRT routes.
22612 	 */
22613 	if (ire->ire_flags & RTF_MULTIRT) {
22614 		multirt_send = B_TRUE;
22615 	}
22616 	do {
22617 		if (multirt_send) {
22618 			irb_t *irb;
22619 			/*
22620 			 * We are in a multiple send case, need to get
22621 			 * the next ire and make a duplicate of the packet.
22622 			 * ire1 holds here the next ire to process in the
22623 			 * bucket. If multirouting is expected,
22624 			 * any non-RTF_MULTIRT ire that has the
22625 			 * right destination address is ignored.
22626 			 */
22627 			irb = ire->ire_bucket;
22628 			ASSERT(irb != NULL);
22629 
22630 			IRB_REFHOLD(irb);
22631 			for (ire1 = ire->ire_next;
22632 			    ire1 != NULL;
22633 			    ire1 = ire1->ire_next) {
22634 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22635 					continue;
22636 				if (ire1->ire_addr != ire->ire_addr)
22637 					continue;
22638 				if (ire1->ire_marks &
22639 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22640 					continue;
22641 
22642 				/* Got one */
22643 				IRE_REFHOLD(ire1);
22644 				break;
22645 			}
22646 			IRB_REFRELE(irb);
22647 
22648 			if (ire1 != NULL) {
22649 				next_mp = copyb(mp);
22650 				if ((next_mp == NULL) ||
22651 				    ((mp->b_cont != NULL) &&
22652 				    ((next_mp->b_cont =
22653 				    dupmsg(mp->b_cont)) == NULL))) {
22654 					freemsg(next_mp);
22655 					next_mp = NULL;
22656 					ire_refrele(ire1);
22657 					ire1 = NULL;
22658 				}
22659 			}
22660 
22661 			/* Last multiroute ire; don't loop anymore. */
22662 			if (ire1 == NULL) {
22663 				multirt_send = B_FALSE;
22664 			}
22665 		}
22666 
22667 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22668 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22669 		    mblk_t *, mp);
22670 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22671 		    ipst->ips_ipv4firewall_physical_out,
22672 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22673 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22674 
22675 		if (mp == NULL)
22676 			goto release_ire_and_ill;
22677 
22678 		if (ipst->ips_ipobs_enabled) {
22679 			zoneid_t szone;
22680 
22681 			/*
22682 			 * On the outbound path the destination zone will be
22683 			 * unknown as we're sending this packet out on the
22684 			 * wire.
22685 			 */
22686 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22687 			    ALL_ZONES);
22688 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22689 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22690 		}
22691 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22692 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22693 
22694 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22695 
22696 		if ((pktxmit_state == SEND_FAILED) ||
22697 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22698 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22699 			    "- packet dropped\n"));
22700 release_ire_and_ill:
22701 			ire_refrele(ire);
22702 			if (next_mp != NULL) {
22703 				freemsg(next_mp);
22704 				ire_refrele(ire1);
22705 			}
22706 			if (conn_outgoing_ill != NULL)
22707 				ill_refrele(conn_outgoing_ill);
22708 			return;
22709 		}
22710 
22711 		if (CLASSD(dst)) {
22712 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22713 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22714 			    LENGTH);
22715 		}
22716 
22717 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22718 		    "ip_wput_ire_end: q %p (%S)",
22719 		    q, "last copy out");
22720 		IRE_REFRELE(ire);
22721 
22722 		if (multirt_send) {
22723 			ASSERT(ire1);
22724 			/*
22725 			 * Proceed with the next RTF_MULTIRT ire,
22726 			 * Also set up the send-to queue accordingly.
22727 			 */
22728 			ire = ire1;
22729 			ire1 = NULL;
22730 			stq = ire->ire_stq;
22731 			mp = next_mp;
22732 			next_mp = NULL;
22733 			ipha = (ipha_t *)mp->b_rptr;
22734 			ill_index = Q_TO_INDEX(stq);
22735 			ill = (ill_t *)stq->q_ptr;
22736 		}
22737 	} while (multirt_send);
22738 	if (conn_outgoing_ill != NULL)
22739 		ill_refrele(conn_outgoing_ill);
22740 	return;
22741 
22742 	/*
22743 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22744 	 */
22745 broadcast:
22746 	{
22747 		/*
22748 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22749 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22750 		 * can be overridden stack-wide through the ip_broadcast_ttl
22751 		 * ndd tunable, or on a per-connection basis through the
22752 		 * IP_BROADCAST_TTL socket option.
22753 		 *
22754 		 * In the event that we are replying to incoming ICMP packets,
22755 		 * connp could be NULL.
22756 		 */
22757 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22758 		if (connp != NULL) {
22759 			if (connp->conn_dontroute)
22760 				ipha->ipha_ttl = 1;
22761 			else if (connp->conn_broadcast_ttl != 0)
22762 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22763 		}
22764 
22765 		/*
22766 		 * Note that we are not doing a IRB_REFHOLD here.
22767 		 * Actually we don't care if the list changes i.e
22768 		 * if somebody deletes an IRE from the list while
22769 		 * we drop the lock, the next time we come around
22770 		 * ire_next will be NULL and hence we won't send
22771 		 * out multiple copies which is fine.
22772 		 */
22773 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22774 		ire1 = ire->ire_next;
22775 		if (conn_outgoing_ill != NULL) {
22776 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22777 				ASSERT(ire1 == ire->ire_next);
22778 				if (ire1 != NULL && ire1->ire_addr == dst) {
22779 					ire_refrele(ire);
22780 					ire = ire1;
22781 					IRE_REFHOLD(ire);
22782 					ire1 = ire->ire_next;
22783 					continue;
22784 				}
22785 				rw_exit(&ire->ire_bucket->irb_lock);
22786 				/* Did not find a matching ill */
22787 				ip1dbg(("ip_wput_ire: broadcast with no "
22788 				    "matching IP_BOUND_IF ill %s dst %x\n",
22789 				    conn_outgoing_ill->ill_name, dst));
22790 				freemsg(first_mp);
22791 				if (ire != NULL)
22792 					ire_refrele(ire);
22793 				ill_refrele(conn_outgoing_ill);
22794 				return;
22795 			}
22796 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22797 			/*
22798 			 * If the next IRE has the same address and is not one
22799 			 * of the two copies that we need to send, try to see
22800 			 * whether this copy should be sent at all. This
22801 			 * assumes that we insert loopbacks first and then
22802 			 * non-loopbacks. This is acheived by inserting the
22803 			 * loopback always before non-loopback.
22804 			 * This is used to send a single copy of a broadcast
22805 			 * packet out all physical interfaces that have an
22806 			 * matching IRE_BROADCAST while also looping
22807 			 * back one copy (to ip_wput_local) for each
22808 			 * matching physical interface. However, we avoid
22809 			 * sending packets out different logical that match by
22810 			 * having ipif_up/ipif_down supress duplicate
22811 			 * IRE_BROADCASTS.
22812 			 *
22813 			 * This feature is currently used to get broadcasts
22814 			 * sent to multiple interfaces, when the broadcast
22815 			 * address being used applies to multiple interfaces.
22816 			 * For example, a whole net broadcast will be
22817 			 * replicated on every connected subnet of
22818 			 * the target net.
22819 			 *
22820 			 * Each zone has its own set of IRE_BROADCASTs, so that
22821 			 * we're able to distribute inbound packets to multiple
22822 			 * zones who share a broadcast address. We avoid looping
22823 			 * back outbound packets in different zones but on the
22824 			 * same ill, as the application would see duplicates.
22825 			 *
22826 			 * This logic assumes that ire_add_v4() groups the
22827 			 * IRE_BROADCAST entries so that those with the same
22828 			 * ire_addr are kept together.
22829 			 */
22830 			ire_ill = ire->ire_ipif->ipif_ill;
22831 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22832 				while (ire1 != NULL && ire1->ire_addr == dst) {
22833 					ire1_ill = ire1->ire_ipif->ipif_ill;
22834 					if (ire1_ill != ire_ill)
22835 						break;
22836 					ire1 = ire1->ire_next;
22837 				}
22838 			}
22839 		}
22840 		ASSERT(multirt_send == B_FALSE);
22841 		if (ire1 != NULL && ire1->ire_addr == dst) {
22842 			if ((ire->ire_flags & RTF_MULTIRT) &&
22843 			    (ire1->ire_flags & RTF_MULTIRT)) {
22844 				/*
22845 				 * We are in the multirouting case.
22846 				 * The message must be sent at least
22847 				 * on both ires. These ires have been
22848 				 * inserted AFTER the standard ones
22849 				 * in ip_rt_add(). There are thus no
22850 				 * other ire entries for the destination
22851 				 * address in the rest of the bucket
22852 				 * that do not have the RTF_MULTIRT
22853 				 * flag. We don't process a copy
22854 				 * of the message here. This will be
22855 				 * done in the final sending loop.
22856 				 */
22857 				multirt_send = B_TRUE;
22858 			} else {
22859 				next_mp = ip_copymsg(first_mp);
22860 				if (next_mp != NULL)
22861 					IRE_REFHOLD(ire1);
22862 			}
22863 		}
22864 		rw_exit(&ire->ire_bucket->irb_lock);
22865 	}
22866 
22867 	if (stq) {
22868 		/*
22869 		 * A non-NULL send-to queue means this packet is going
22870 		 * out of this machine.
22871 		 */
22872 		out_ill = (ill_t *)stq->q_ptr;
22873 
22874 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22875 		ttl_protocol = ((uint16_t *)ipha)[4];
22876 		/*
22877 		 * We accumulate the pseudo header checksum in cksum.
22878 		 * This is pretty hairy code, so watch close.  One
22879 		 * thing to keep in mind is that UDP and TCP have
22880 		 * stored their respective datagram lengths in their
22881 		 * checksum fields.  This lines things up real nice.
22882 		 */
22883 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22884 		    (src >> 16) + (src & 0xFFFF);
22885 		/*
22886 		 * We assume the udp checksum field contains the
22887 		 * length, so to compute the pseudo header checksum,
22888 		 * all we need is the protocol number and src/dst.
22889 		 */
22890 		/* Provide the checksums for UDP and TCP. */
22891 		if ((PROTO == IPPROTO_TCP) &&
22892 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22893 			/* hlen gets the number of uchar_ts in the IP header */
22894 			hlen = (V_HLEN & 0xF) << 2;
22895 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22896 			IP_STAT(ipst, ip_out_sw_cksum);
22897 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22898 			    LENGTH - hlen);
22899 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22900 		} else if (PROTO == IPPROTO_SCTP &&
22901 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22902 			sctp_hdr_t	*sctph;
22903 
22904 			hlen = (V_HLEN & 0xF) << 2;
22905 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22906 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22907 			sctph->sh_chksum = 0;
22908 #ifdef	DEBUG
22909 			if (!skip_sctp_cksum)
22910 #endif
22911 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22912 		} else {
22913 			queue_t	*dev_q = stq->q_next;
22914 
22915 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22916 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22917 blocked:
22918 				ipha->ipha_ident = ip_hdr_included;
22919 				/*
22920 				 * If we don't have a conn to apply
22921 				 * backpressure, free the message.
22922 				 * In the ire_send path, we don't know
22923 				 * the position to requeue the packet. Rather
22924 				 * than reorder packets, we just drop this
22925 				 * packet.
22926 				 */
22927 				if (ipst->ips_ip_output_queue &&
22928 				    connp != NULL &&
22929 				    caller != IRE_SEND) {
22930 					if (caller == IP_WSRV) {
22931 						idl_tx_list_t *idl_txl;
22932 
22933 						idl_txl =
22934 						    &ipst->ips_idl_tx_list[0];
22935 						connp->conn_did_putbq = 1;
22936 						(void) putbq(connp->conn_wq,
22937 						    first_mp);
22938 						conn_drain_insert(connp,
22939 						    idl_txl);
22940 						/*
22941 						 * This is the service thread,
22942 						 * and the queue is already
22943 						 * noenabled. The check for
22944 						 * canput and the putbq is not
22945 						 * atomic. So we need to check
22946 						 * again.
22947 						 */
22948 						if (canput(stq->q_next))
22949 							connp->conn_did_putbq
22950 							    = 0;
22951 						IP_STAT(ipst, ip_conn_flputbq);
22952 					} else {
22953 						/*
22954 						 * We are not the service proc.
22955 						 * ip_wsrv will be scheduled or
22956 						 * is already running.
22957 						 */
22958 
22959 						(void) putq(connp->conn_wq,
22960 						    first_mp);
22961 					}
22962 				} else {
22963 					out_ill = (ill_t *)stq->q_ptr;
22964 					BUMP_MIB(out_ill->ill_ip_mib,
22965 					    ipIfStatsOutDiscards);
22966 					freemsg(first_mp);
22967 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22968 					    "ip_wput_ire_end: q %p (%S)",
22969 					    q, "discard");
22970 				}
22971 				ire_refrele(ire);
22972 				if (next_mp) {
22973 					ire_refrele(ire1);
22974 					freemsg(next_mp);
22975 				}
22976 				if (conn_outgoing_ill != NULL)
22977 					ill_refrele(conn_outgoing_ill);
22978 				return;
22979 			}
22980 			if ((PROTO == IPPROTO_UDP) &&
22981 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22982 				/*
22983 				 * hlen gets the number of uchar_ts in the
22984 				 * IP header
22985 				 */
22986 				hlen = (V_HLEN & 0xF) << 2;
22987 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22988 				max_frag = ire->ire_max_frag;
22989 				if (*up != 0) {
22990 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22991 					    up, PROTO, hlen, LENGTH, max_frag,
22992 					    ipsec_len, cksum);
22993 					/* Software checksum? */
22994 					if (DB_CKSUMFLAGS(mp) == 0) {
22995 						IP_STAT(ipst, ip_out_sw_cksum);
22996 						IP_STAT_UPDATE(ipst,
22997 						    ip_udp_out_sw_cksum_bytes,
22998 						    LENGTH - hlen);
22999 					}
23000 				}
23001 			}
23002 		}
23003 		/*
23004 		 * Need to do this even when fragmenting. The local
23005 		 * loopback can be done without computing checksums
23006 		 * but forwarding out other interface must be done
23007 		 * after the IP checksum (and ULP checksums) have been
23008 		 * computed.
23009 		 *
23010 		 * NOTE : multicast_forward is set only if this packet
23011 		 * originated from ip_wput. For packets originating from
23012 		 * ip_wput_multicast, it is not set.
23013 		 */
23014 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23015 multi_loopback:
23016 			ip2dbg(("ip_wput: multicast, loop %d\n",
23017 			    conn_multicast_loop));
23018 
23019 			/*  Forget header checksum offload */
23020 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23021 
23022 			/*
23023 			 * Local loopback of multicasts?  Check the
23024 			 * ill.
23025 			 *
23026 			 * Note that the loopback function will not come
23027 			 * in through ip_rput - it will only do the
23028 			 * client fanout thus we need to do an mforward
23029 			 * as well.  The is different from the BSD
23030 			 * logic.
23031 			 */
23032 			if (ill != NULL) {
23033 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23034 				    ALL_ZONES) != NULL) {
23035 					/*
23036 					 * Pass along the virtual output q.
23037 					 * ip_wput_local() will distribute the
23038 					 * packet to all the matching zones,
23039 					 * except the sending zone when
23040 					 * IP_MULTICAST_LOOP is false.
23041 					 */
23042 					ip_multicast_loopback(q, ill, first_mp,
23043 					    conn_multicast_loop ? 0 :
23044 					    IP_FF_NO_MCAST_LOOP, zoneid);
23045 				}
23046 			}
23047 			if (ipha->ipha_ttl == 0) {
23048 				/*
23049 				 * 0 => only to this host i.e. we are
23050 				 * done. We are also done if this was the
23051 				 * loopback interface since it is sufficient
23052 				 * to loopback one copy of a multicast packet.
23053 				 */
23054 				freemsg(first_mp);
23055 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23056 				    "ip_wput_ire_end: q %p (%S)",
23057 				    q, "loopback");
23058 				ire_refrele(ire);
23059 				if (conn_outgoing_ill != NULL)
23060 					ill_refrele(conn_outgoing_ill);
23061 				return;
23062 			}
23063 			/*
23064 			 * ILLF_MULTICAST is checked in ip_newroute
23065 			 * i.e. we don't need to check it here since
23066 			 * all IRE_CACHEs come from ip_newroute.
23067 			 * For multicast traffic, SO_DONTROUTE is interpreted
23068 			 * to mean only send the packet out the interface
23069 			 * (optionally specified with IP_MULTICAST_IF)
23070 			 * and do not forward it out additional interfaces.
23071 			 * RSVP and the rsvp daemon is an example of a
23072 			 * protocol and user level process that
23073 			 * handles it's own routing. Hence, it uses the
23074 			 * SO_DONTROUTE option to accomplish this.
23075 			 */
23076 
23077 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23078 			    ill != NULL) {
23079 				/* Unconditionally redo the checksum */
23080 				ipha->ipha_hdr_checksum = 0;
23081 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23082 
23083 				/*
23084 				 * If this needs to go out secure, we need
23085 				 * to wait till we finish the IPsec
23086 				 * processing.
23087 				 */
23088 				if (ipsec_len == 0 &&
23089 				    ip_mforward(ill, ipha, mp)) {
23090 					freemsg(first_mp);
23091 					ip1dbg(("ip_wput: mforward failed\n"));
23092 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23093 					    "ip_wput_ire_end: q %p (%S)",
23094 					    q, "mforward failed");
23095 					ire_refrele(ire);
23096 					if (conn_outgoing_ill != NULL)
23097 						ill_refrele(conn_outgoing_ill);
23098 					return;
23099 				}
23100 			}
23101 		}
23102 		max_frag = ire->ire_max_frag;
23103 		cksum += ttl_protocol;
23104 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23105 			/* No fragmentation required for this one. */
23106 			/*
23107 			 * Don't use frag_flag if packet is pre-built or source
23108 			 * routed or if multicast (since multicast packets do
23109 			 * not solicit ICMP "packet too big" messages).
23110 			 */
23111 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23112 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23113 			    !ip_source_route_included(ipha)) &&
23114 			    !CLASSD(ipha->ipha_dst))
23115 				ipha->ipha_fragment_offset_and_flags |=
23116 				    htons(ire->ire_frag_flag);
23117 
23118 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23119 				/* Complete the IP header checksum. */
23120 				cksum += ipha->ipha_ident;
23121 				cksum += (v_hlen_tos_len >> 16)+
23122 				    (v_hlen_tos_len & 0xFFFF);
23123 				cksum += ipha->ipha_fragment_offset_and_flags;
23124 				hlen = (V_HLEN & 0xF) -
23125 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23126 				if (hlen) {
23127 checksumoptions:
23128 					/*
23129 					 * Account for the IP Options in the IP
23130 					 * header checksum.
23131 					 */
23132 					up = (uint16_t *)(rptr+
23133 					    IP_SIMPLE_HDR_LENGTH);
23134 					do {
23135 						cksum += up[0];
23136 						cksum += up[1];
23137 						up += 2;
23138 					} while (--hlen);
23139 				}
23140 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23141 				cksum = ~(cksum + (cksum >> 16));
23142 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23143 			}
23144 			if (ipsec_len != 0) {
23145 				ipsec_out_process(q, first_mp, ire, ill_index);
23146 				if (!next_mp) {
23147 					ire_refrele(ire);
23148 					if (conn_outgoing_ill != NULL)
23149 						ill_refrele(conn_outgoing_ill);
23150 					return;
23151 				}
23152 				goto next;
23153 			}
23154 
23155 			/*
23156 			 * multirt_send has already been handled
23157 			 * for broadcast, but not yet for multicast
23158 			 * or IP options.
23159 			 */
23160 			if (next_mp == NULL) {
23161 				if (ire->ire_flags & RTF_MULTIRT) {
23162 					multirt_send = B_TRUE;
23163 				}
23164 			}
23165 
23166 			/*
23167 			 * In most cases, the emission loop below is
23168 			 * entered only once. Only in the case where
23169 			 * the ire holds the RTF_MULTIRT flag, do we loop
23170 			 * to process all RTF_MULTIRT ires in the bucket,
23171 			 * and send the packet through all crossed
23172 			 * RTF_MULTIRT routes.
23173 			 */
23174 			do {
23175 				if (multirt_send) {
23176 					irb_t *irb;
23177 
23178 					irb = ire->ire_bucket;
23179 					ASSERT(irb != NULL);
23180 					/*
23181 					 * We are in a multiple send case,
23182 					 * need to get the next IRE and make
23183 					 * a duplicate of the packet.
23184 					 */
23185 					IRB_REFHOLD(irb);
23186 					for (ire1 = ire->ire_next;
23187 					    ire1 != NULL;
23188 					    ire1 = ire1->ire_next) {
23189 						if (!(ire1->ire_flags &
23190 						    RTF_MULTIRT))
23191 							continue;
23192 
23193 						if (ire1->ire_addr !=
23194 						    ire->ire_addr)
23195 							continue;
23196 
23197 						if (ire1->ire_marks &
23198 						    (IRE_MARK_CONDEMNED |
23199 						    IRE_MARK_TESTHIDDEN))
23200 							continue;
23201 
23202 						/* Got one */
23203 						IRE_REFHOLD(ire1);
23204 						break;
23205 					}
23206 					IRB_REFRELE(irb);
23207 
23208 					if (ire1 != NULL) {
23209 						next_mp = copyb(mp);
23210 						if ((next_mp == NULL) ||
23211 						    ((mp->b_cont != NULL) &&
23212 						    ((next_mp->b_cont =
23213 						    dupmsg(mp->b_cont))
23214 						    == NULL))) {
23215 							freemsg(next_mp);
23216 							next_mp = NULL;
23217 							ire_refrele(ire1);
23218 							ire1 = NULL;
23219 						}
23220 					}
23221 
23222 					/*
23223 					 * Last multiroute ire; don't loop
23224 					 * anymore. The emission is over
23225 					 * and next_mp is NULL.
23226 					 */
23227 					if (ire1 == NULL) {
23228 						multirt_send = B_FALSE;
23229 					}
23230 				}
23231 
23232 				out_ill = ire_to_ill(ire);
23233 				DTRACE_PROBE4(ip4__physical__out__start,
23234 				    ill_t *, NULL,
23235 				    ill_t *, out_ill,
23236 				    ipha_t *, ipha, mblk_t *, mp);
23237 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23238 				    ipst->ips_ipv4firewall_physical_out,
23239 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23240 				DTRACE_PROBE1(ip4__physical__out__end,
23241 				    mblk_t *, mp);
23242 				if (mp == NULL)
23243 					goto release_ire_and_ill_2;
23244 
23245 				ASSERT(ipsec_len == 0);
23246 				mp->b_prev =
23247 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23248 				DTRACE_PROBE2(ip__xmit__2,
23249 				    mblk_t *, mp, ire_t *, ire);
23250 				pktxmit_state = ip_xmit_v4(mp, ire,
23251 				    NULL, B_TRUE, connp);
23252 				if ((pktxmit_state == SEND_FAILED) ||
23253 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23254 release_ire_and_ill_2:
23255 					if (next_mp) {
23256 						freemsg(next_mp);
23257 						ire_refrele(ire1);
23258 					}
23259 					ire_refrele(ire);
23260 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23261 					    "ip_wput_ire_end: q %p (%S)",
23262 					    q, "discard MDATA");
23263 					if (conn_outgoing_ill != NULL)
23264 						ill_refrele(conn_outgoing_ill);
23265 					return;
23266 				}
23267 
23268 				if (CLASSD(dst)) {
23269 					BUMP_MIB(out_ill->ill_ip_mib,
23270 					    ipIfStatsHCOutMcastPkts);
23271 					UPDATE_MIB(out_ill->ill_ip_mib,
23272 					    ipIfStatsHCOutMcastOctets,
23273 					    LENGTH);
23274 				} else if (ire->ire_type == IRE_BROADCAST) {
23275 					BUMP_MIB(out_ill->ill_ip_mib,
23276 					    ipIfStatsHCOutBcastPkts);
23277 				}
23278 
23279 				if (multirt_send) {
23280 					/*
23281 					 * We are in a multiple send case,
23282 					 * need to re-enter the sending loop
23283 					 * using the next ire.
23284 					 */
23285 					ire_refrele(ire);
23286 					ire = ire1;
23287 					stq = ire->ire_stq;
23288 					mp = next_mp;
23289 					next_mp = NULL;
23290 					ipha = (ipha_t *)mp->b_rptr;
23291 					ill_index = Q_TO_INDEX(stq);
23292 				}
23293 			} while (multirt_send);
23294 
23295 			if (!next_mp) {
23296 				/*
23297 				 * Last copy going out (the ultra-common
23298 				 * case).  Note that we intentionally replicate
23299 				 * the putnext rather than calling it before
23300 				 * the next_mp check in hopes of a little
23301 				 * tail-call action out of the compiler.
23302 				 */
23303 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23304 				    "ip_wput_ire_end: q %p (%S)",
23305 				    q, "last copy out(1)");
23306 				ire_refrele(ire);
23307 				if (conn_outgoing_ill != NULL)
23308 					ill_refrele(conn_outgoing_ill);
23309 				return;
23310 			}
23311 			/* More copies going out below. */
23312 		} else {
23313 			int offset;
23314 fragmentit:
23315 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23316 			/*
23317 			 * If this would generate a icmp_frag_needed message,
23318 			 * we need to handle it before we do the IPsec
23319 			 * processing. Otherwise, we need to strip the IPsec
23320 			 * headers before we send up the message to the ULPs
23321 			 * which becomes messy and difficult.
23322 			 */
23323 			if (ipsec_len != 0) {
23324 				if ((max_frag < (unsigned int)(LENGTH +
23325 				    ipsec_len)) && (offset & IPH_DF)) {
23326 					out_ill = (ill_t *)stq->q_ptr;
23327 					BUMP_MIB(out_ill->ill_ip_mib,
23328 					    ipIfStatsOutFragFails);
23329 					BUMP_MIB(out_ill->ill_ip_mib,
23330 					    ipIfStatsOutFragReqds);
23331 					ipha->ipha_hdr_checksum = 0;
23332 					ipha->ipha_hdr_checksum =
23333 					    (uint16_t)ip_csum_hdr(ipha);
23334 					icmp_frag_needed(ire->ire_stq, first_mp,
23335 					    max_frag, zoneid, ipst);
23336 					if (!next_mp) {
23337 						ire_refrele(ire);
23338 						if (conn_outgoing_ill != NULL) {
23339 							ill_refrele(
23340 							    conn_outgoing_ill);
23341 						}
23342 						return;
23343 					}
23344 				} else {
23345 					/*
23346 					 * This won't cause a icmp_frag_needed
23347 					 * message. to be generated. Send it on
23348 					 * the wire. Note that this could still
23349 					 * cause fragmentation and all we
23350 					 * do is the generation of the message
23351 					 * to the ULP if needed before IPsec.
23352 					 */
23353 					if (!next_mp) {
23354 						ipsec_out_process(q, first_mp,
23355 						    ire, ill_index);
23356 						TRACE_2(TR_FAC_IP,
23357 						    TR_IP_WPUT_IRE_END,
23358 						    "ip_wput_ire_end: q %p "
23359 						    "(%S)", q,
23360 						    "last ipsec_out_process");
23361 						ire_refrele(ire);
23362 						if (conn_outgoing_ill != NULL) {
23363 							ill_refrele(
23364 							    conn_outgoing_ill);
23365 						}
23366 						return;
23367 					}
23368 					ipsec_out_process(q, first_mp,
23369 					    ire, ill_index);
23370 				}
23371 			} else {
23372 				/*
23373 				 * Initiate IPPF processing. For
23374 				 * fragmentable packets we finish
23375 				 * all QOS packet processing before
23376 				 * calling:
23377 				 * ip_wput_ire_fragmentit->ip_wput_frag
23378 				 */
23379 
23380 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23381 					ip_process(IPP_LOCAL_OUT, &mp,
23382 					    ill_index);
23383 					if (mp == NULL) {
23384 						out_ill = (ill_t *)stq->q_ptr;
23385 						BUMP_MIB(out_ill->ill_ip_mib,
23386 						    ipIfStatsOutDiscards);
23387 						if (next_mp != NULL) {
23388 							freemsg(next_mp);
23389 							ire_refrele(ire1);
23390 						}
23391 						ire_refrele(ire);
23392 						TRACE_2(TR_FAC_IP,
23393 						    TR_IP_WPUT_IRE_END,
23394 						    "ip_wput_ire: q %p (%S)",
23395 						    q, "discard MDATA");
23396 						if (conn_outgoing_ill != NULL) {
23397 							ill_refrele(
23398 							    conn_outgoing_ill);
23399 						}
23400 						return;
23401 					}
23402 				}
23403 				if (!next_mp) {
23404 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23405 					    "ip_wput_ire_end: q %p (%S)",
23406 					    q, "last fragmentation");
23407 					ip_wput_ire_fragmentit(mp, ire,
23408 					    zoneid, ipst, connp);
23409 					ire_refrele(ire);
23410 					if (conn_outgoing_ill != NULL)
23411 						ill_refrele(conn_outgoing_ill);
23412 					return;
23413 				}
23414 				ip_wput_ire_fragmentit(mp, ire,
23415 				    zoneid, ipst, connp);
23416 			}
23417 		}
23418 	} else {
23419 nullstq:
23420 		/* A NULL stq means the destination address is local. */
23421 		UPDATE_OB_PKT_COUNT(ire);
23422 		ire->ire_last_used_time = lbolt;
23423 		ASSERT(ire->ire_ipif != NULL);
23424 		if (!next_mp) {
23425 			/*
23426 			 * Is there an "in" and "out" for traffic local
23427 			 * to a host (loopback)?  The code in Solaris doesn't
23428 			 * explicitly draw a line in its code for in vs out,
23429 			 * so we've had to draw a line in the sand: ip_wput_ire
23430 			 * is considered to be the "output" side and
23431 			 * ip_wput_local to be the "input" side.
23432 			 */
23433 			out_ill = ire_to_ill(ire);
23434 
23435 			/*
23436 			 * DTrace this as ip:::send.  A blocked packet will
23437 			 * fire the send probe, but not the receive probe.
23438 			 */
23439 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23440 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23441 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23442 
23443 			DTRACE_PROBE4(ip4__loopback__out__start,
23444 			    ill_t *, NULL, ill_t *, out_ill,
23445 			    ipha_t *, ipha, mblk_t *, first_mp);
23446 
23447 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23448 			    ipst->ips_ipv4firewall_loopback_out,
23449 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23450 
23451 			DTRACE_PROBE1(ip4__loopback__out_end,
23452 			    mblk_t *, first_mp);
23453 
23454 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23455 			    "ip_wput_ire_end: q %p (%S)",
23456 			    q, "local address");
23457 
23458 			if (first_mp != NULL)
23459 				ip_wput_local(q, out_ill, ipha,
23460 				    first_mp, ire, 0, ire->ire_zoneid);
23461 			ire_refrele(ire);
23462 			if (conn_outgoing_ill != NULL)
23463 				ill_refrele(conn_outgoing_ill);
23464 			return;
23465 		}
23466 
23467 		out_ill = ire_to_ill(ire);
23468 
23469 		/*
23470 		 * DTrace this as ip:::send.  A blocked packet will fire the
23471 		 * send probe, but not the receive probe.
23472 		 */
23473 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23474 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23475 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23476 
23477 		DTRACE_PROBE4(ip4__loopback__out__start,
23478 		    ill_t *, NULL, ill_t *, out_ill,
23479 		    ipha_t *, ipha, mblk_t *, first_mp);
23480 
23481 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23482 		    ipst->ips_ipv4firewall_loopback_out,
23483 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23484 
23485 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23486 
23487 		if (first_mp != NULL)
23488 			ip_wput_local(q, out_ill, ipha,
23489 			    first_mp, ire, 0, ire->ire_zoneid);
23490 	}
23491 next:
23492 	/*
23493 	 * More copies going out to additional interfaces.
23494 	 * ire1 has already been held. We don't need the
23495 	 * "ire" anymore.
23496 	 */
23497 	ire_refrele(ire);
23498 	ire = ire1;
23499 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23500 	mp = next_mp;
23501 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23502 	ill = ire_to_ill(ire);
23503 	first_mp = mp;
23504 	if (ipsec_len != 0) {
23505 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23506 		mp = mp->b_cont;
23507 	}
23508 	dst = ire->ire_addr;
23509 	ipha = (ipha_t *)mp->b_rptr;
23510 	/*
23511 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23512 	 * Restore ipha_ident "no checksum" flag.
23513 	 */
23514 	src = orig_src;
23515 	ipha->ipha_ident = ip_hdr_included;
23516 	goto another;
23517 
23518 #undef	rptr
23519 #undef	Q_TO_INDEX
23520 }
23521 
23522 /*
23523  * Routine to allocate a message that is used to notify the ULP about MDT.
23524  * The caller may provide a pointer to the link-layer MDT capabilities,
23525  * or NULL if MDT is to be disabled on the stream.
23526  */
23527 mblk_t *
23528 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23529 {
23530 	mblk_t *mp;
23531 	ip_mdt_info_t *mdti;
23532 	ill_mdt_capab_t *idst;
23533 
23534 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23535 		DB_TYPE(mp) = M_CTL;
23536 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23537 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23538 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23539 		idst = &(mdti->mdt_capab);
23540 
23541 		/*
23542 		 * If the caller provides us with the capability, copy
23543 		 * it over into our notification message; otherwise
23544 		 * we zero out the capability portion.
23545 		 */
23546 		if (isrc != NULL)
23547 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23548 		else
23549 			bzero((caddr_t)idst, sizeof (*idst));
23550 	}
23551 	return (mp);
23552 }
23553 
23554 /*
23555  * Routine which determines whether MDT can be enabled on the destination
23556  * IRE and IPC combination, and if so, allocates and returns the MDT
23557  * notification mblk that may be used by ULP.  We also check if we need to
23558  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23559  * MDT usage in the past have been lifted.  This gets called during IP
23560  * and ULP binding.
23561  */
23562 mblk_t *
23563 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23564     ill_mdt_capab_t *mdt_cap)
23565 {
23566 	mblk_t *mp;
23567 	boolean_t rc = B_FALSE;
23568 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23569 
23570 	ASSERT(dst_ire != NULL);
23571 	ASSERT(connp != NULL);
23572 	ASSERT(mdt_cap != NULL);
23573 
23574 	/*
23575 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23576 	 * Multidata, which is handled in tcp_multisend().  This
23577 	 * is the reason why we do all these checks here, to ensure
23578 	 * that we don't enable Multidata for the cases which we
23579 	 * can't handle at the moment.
23580 	 */
23581 	do {
23582 		/* Only do TCP at the moment */
23583 		if (connp->conn_ulp != IPPROTO_TCP)
23584 			break;
23585 
23586 		/*
23587 		 * IPsec outbound policy present?  Note that we get here
23588 		 * after calling ipsec_conn_cache_policy() where the global
23589 		 * policy checking is performed.  conn_latch will be
23590 		 * non-NULL as long as there's a policy defined,
23591 		 * i.e. conn_out_enforce_policy may be NULL in such case
23592 		 * when the connection is non-secure, and hence we check
23593 		 * further if the latch refers to an outbound policy.
23594 		 */
23595 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23596 			break;
23597 
23598 		/* CGTP (multiroute) is enabled? */
23599 		if (dst_ire->ire_flags & RTF_MULTIRT)
23600 			break;
23601 
23602 		/* Outbound IPQoS enabled? */
23603 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23604 			/*
23605 			 * In this case, we disable MDT for this and all
23606 			 * future connections going over the interface.
23607 			 */
23608 			mdt_cap->ill_mdt_on = 0;
23609 			break;
23610 		}
23611 
23612 		/* socket option(s) present? */
23613 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23614 			break;
23615 
23616 		rc = B_TRUE;
23617 	/* CONSTCOND */
23618 	} while (0);
23619 
23620 	/* Remember the result */
23621 	connp->conn_mdt_ok = rc;
23622 
23623 	if (!rc)
23624 		return (NULL);
23625 	else if (!mdt_cap->ill_mdt_on) {
23626 		/*
23627 		 * If MDT has been previously turned off in the past, and we
23628 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23629 		 * then enable it for this interface.
23630 		 */
23631 		mdt_cap->ill_mdt_on = 1;
23632 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23633 		    "interface %s\n", ill_name));
23634 	}
23635 
23636 	/* Allocate the MDT info mblk */
23637 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23638 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23639 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23640 		return (NULL);
23641 	}
23642 	return (mp);
23643 }
23644 
23645 /*
23646  * Routine to allocate a message that is used to notify the ULP about LSO.
23647  * The caller may provide a pointer to the link-layer LSO capabilities,
23648  * or NULL if LSO is to be disabled on the stream.
23649  */
23650 mblk_t *
23651 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23652 {
23653 	mblk_t *mp;
23654 	ip_lso_info_t *lsoi;
23655 	ill_lso_capab_t *idst;
23656 
23657 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23658 		DB_TYPE(mp) = M_CTL;
23659 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23660 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23661 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23662 		idst = &(lsoi->lso_capab);
23663 
23664 		/*
23665 		 * If the caller provides us with the capability, copy
23666 		 * it over into our notification message; otherwise
23667 		 * we zero out the capability portion.
23668 		 */
23669 		if (isrc != NULL)
23670 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23671 		else
23672 			bzero((caddr_t)idst, sizeof (*idst));
23673 	}
23674 	return (mp);
23675 }
23676 
23677 /*
23678  * Routine which determines whether LSO can be enabled on the destination
23679  * IRE and IPC combination, and if so, allocates and returns the LSO
23680  * notification mblk that may be used by ULP.  We also check if we need to
23681  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23682  * LSO usage in the past have been lifted.  This gets called during IP
23683  * and ULP binding.
23684  */
23685 mblk_t *
23686 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23687     ill_lso_capab_t *lso_cap)
23688 {
23689 	mblk_t *mp;
23690 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23691 
23692 	ASSERT(dst_ire != NULL);
23693 	ASSERT(connp != NULL);
23694 	ASSERT(lso_cap != NULL);
23695 
23696 	connp->conn_lso_ok = B_TRUE;
23697 
23698 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23699 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23700 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23701 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23702 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23703 		connp->conn_lso_ok = B_FALSE;
23704 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23705 			/*
23706 			 * Disable LSO for this and all future connections going
23707 			 * over the interface.
23708 			 */
23709 			lso_cap->ill_lso_on = 0;
23710 		}
23711 	}
23712 
23713 	if (!connp->conn_lso_ok)
23714 		return (NULL);
23715 	else if (!lso_cap->ill_lso_on) {
23716 		/*
23717 		 * If LSO has been previously turned off in the past, and we
23718 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23719 		 * then enable it for this interface.
23720 		 */
23721 		lso_cap->ill_lso_on = 1;
23722 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23723 		    ill_name));
23724 	}
23725 
23726 	/* Allocate the LSO info mblk */
23727 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23728 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23729 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23730 
23731 	return (mp);
23732 }
23733 
23734 /*
23735  * Create destination address attribute, and fill it with the physical
23736  * destination address and SAP taken from the template DL_UNITDATA_REQ
23737  * message block.
23738  */
23739 boolean_t
23740 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23741 {
23742 	dl_unitdata_req_t *dlurp;
23743 	pattr_t *pa;
23744 	pattrinfo_t pa_info;
23745 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23746 	uint_t das_len, das_off;
23747 
23748 	ASSERT(dlmp != NULL);
23749 
23750 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23751 	das_len = dlurp->dl_dest_addr_length;
23752 	das_off = dlurp->dl_dest_addr_offset;
23753 
23754 	pa_info.type = PATTR_DSTADDRSAP;
23755 	pa_info.len = sizeof (**das) + das_len - 1;
23756 
23757 	/* create and associate the attribute */
23758 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23759 	if (pa != NULL) {
23760 		ASSERT(*das != NULL);
23761 		(*das)->addr_is_group = 0;
23762 		(*das)->addr_len = (uint8_t)das_len;
23763 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23764 	}
23765 
23766 	return (pa != NULL);
23767 }
23768 
23769 /*
23770  * Create hardware checksum attribute and fill it with the values passed.
23771  */
23772 boolean_t
23773 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23774     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23775 {
23776 	pattr_t *pa;
23777 	pattrinfo_t pa_info;
23778 
23779 	ASSERT(mmd != NULL);
23780 
23781 	pa_info.type = PATTR_HCKSUM;
23782 	pa_info.len = sizeof (pattr_hcksum_t);
23783 
23784 	/* create and associate the attribute */
23785 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23786 	if (pa != NULL) {
23787 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23788 
23789 		hck->hcksum_start_offset = start_offset;
23790 		hck->hcksum_stuff_offset = stuff_offset;
23791 		hck->hcksum_end_offset = end_offset;
23792 		hck->hcksum_flags = flags;
23793 	}
23794 	return (pa != NULL);
23795 }
23796 
23797 /*
23798  * Create zerocopy attribute and fill it with the specified flags
23799  */
23800 boolean_t
23801 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23802 {
23803 	pattr_t *pa;
23804 	pattrinfo_t pa_info;
23805 
23806 	ASSERT(mmd != NULL);
23807 	pa_info.type = PATTR_ZCOPY;
23808 	pa_info.len = sizeof (pattr_zcopy_t);
23809 
23810 	/* create and associate the attribute */
23811 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23812 	if (pa != NULL) {
23813 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23814 
23815 		zcopy->zcopy_flags = flags;
23816 	}
23817 	return (pa != NULL);
23818 }
23819 
23820 /*
23821  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23822  * block chain. We could rewrite to handle arbitrary message block chains but
23823  * that would make the code complicated and slow. Right now there three
23824  * restrictions:
23825  *
23826  *   1. The first message block must contain the complete IP header and
23827  *	at least 1 byte of payload data.
23828  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23829  *	so that we can use a single Multidata message.
23830  *   3. No frag must be distributed over two or more message blocks so
23831  *	that we don't need more than two packet descriptors per frag.
23832  *
23833  * The above restrictions allow us to support userland applications (which
23834  * will send down a single message block) and NFS over UDP (which will
23835  * send down a chain of at most three message blocks).
23836  *
23837  * We also don't use MDT for payloads with less than or equal to
23838  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23839  */
23840 boolean_t
23841 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23842 {
23843 	int	blocks;
23844 	ssize_t	total, missing, size;
23845 
23846 	ASSERT(mp != NULL);
23847 	ASSERT(hdr_len > 0);
23848 
23849 	size = MBLKL(mp) - hdr_len;
23850 	if (size <= 0)
23851 		return (B_FALSE);
23852 
23853 	/* The first mblk contains the header and some payload. */
23854 	blocks = 1;
23855 	total = size;
23856 	size %= len;
23857 	missing = (size == 0) ? 0 : (len - size);
23858 	mp = mp->b_cont;
23859 
23860 	while (mp != NULL) {
23861 		/*
23862 		 * Give up if we encounter a zero length message block.
23863 		 * In practice, this should rarely happen and therefore
23864 		 * not worth the trouble of freeing and re-linking the
23865 		 * mblk from the chain to handle such case.
23866 		 */
23867 		if ((size = MBLKL(mp)) == 0)
23868 			return (B_FALSE);
23869 
23870 		/* Too many payload buffers for a single Multidata message? */
23871 		if (++blocks > MULTIDATA_MAX_PBUFS)
23872 			return (B_FALSE);
23873 
23874 		total += size;
23875 		/* Is a frag distributed over two or more message blocks? */
23876 		if (missing > size)
23877 			return (B_FALSE);
23878 		size -= missing;
23879 
23880 		size %= len;
23881 		missing = (size == 0) ? 0 : (len - size);
23882 
23883 		mp = mp->b_cont;
23884 	}
23885 
23886 	return (total > ip_wput_frag_mdt_min);
23887 }
23888 
23889 /*
23890  * Outbound IPv4 fragmentation routine using MDT.
23891  */
23892 static void
23893 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23894     uint32_t frag_flag, int offset)
23895 {
23896 	ipha_t		*ipha_orig;
23897 	int		i1, ip_data_end;
23898 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23899 	mblk_t		*hdr_mp, *md_mp = NULL;
23900 	unsigned char	*hdr_ptr, *pld_ptr;
23901 	multidata_t	*mmd;
23902 	ip_pdescinfo_t	pdi;
23903 	ill_t		*ill;
23904 	ip_stack_t	*ipst = ire->ire_ipst;
23905 
23906 	ASSERT(DB_TYPE(mp) == M_DATA);
23907 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23908 
23909 	ill = ire_to_ill(ire);
23910 	ASSERT(ill != NULL);
23911 
23912 	ipha_orig = (ipha_t *)mp->b_rptr;
23913 	mp->b_rptr += sizeof (ipha_t);
23914 
23915 	/* Calculate how many packets we will send out */
23916 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23917 	pkts = (i1 + len - 1) / len;
23918 	ASSERT(pkts > 1);
23919 
23920 	/* Allocate a message block which will hold all the IP Headers. */
23921 	wroff = ipst->ips_ip_wroff_extra;
23922 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23923 
23924 	i1 = pkts * hdr_chunk_len;
23925 	/*
23926 	 * Create the header buffer, Multidata and destination address
23927 	 * and SAP attribute that should be associated with it.
23928 	 */
23929 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23930 	    ((hdr_mp->b_wptr += i1),
23931 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23932 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23933 		freemsg(mp);
23934 		if (md_mp == NULL) {
23935 			freemsg(hdr_mp);
23936 		} else {
23937 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23938 			freemsg(md_mp);
23939 		}
23940 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23941 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23942 		return;
23943 	}
23944 	IP_STAT(ipst, ip_frag_mdt_allocd);
23945 
23946 	/*
23947 	 * Add a payload buffer to the Multidata; this operation must not
23948 	 * fail, or otherwise our logic in this routine is broken.  There
23949 	 * is no memory allocation done by the routine, so any returned
23950 	 * failure simply tells us that we've done something wrong.
23951 	 *
23952 	 * A failure tells us that either we're adding the same payload
23953 	 * buffer more than once, or we're trying to add more buffers than
23954 	 * allowed.  None of the above cases should happen, and we panic
23955 	 * because either there's horrible heap corruption, and/or
23956 	 * programming mistake.
23957 	 */
23958 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23959 		goto pbuf_panic;
23960 
23961 	hdr_ptr = hdr_mp->b_rptr;
23962 	pld_ptr = mp->b_rptr;
23963 
23964 	/* Establish the ending byte offset, based on the starting offset. */
23965 	offset <<= 3;
23966 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23967 	    IP_SIMPLE_HDR_LENGTH;
23968 
23969 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23970 
23971 	while (pld_ptr < mp->b_wptr) {
23972 		ipha_t		*ipha;
23973 		uint16_t	offset_and_flags;
23974 		uint16_t	ip_len;
23975 		int		error;
23976 
23977 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23978 		ipha = (ipha_t *)(hdr_ptr + wroff);
23979 		ASSERT(OK_32PTR(ipha));
23980 		*ipha = *ipha_orig;
23981 
23982 		if (ip_data_end - offset > len) {
23983 			offset_and_flags = IPH_MF;
23984 		} else {
23985 			/*
23986 			 * Last frag. Set len to the length of this last piece.
23987 			 */
23988 			len = ip_data_end - offset;
23989 			/* A frag of a frag might have IPH_MF non-zero */
23990 			offset_and_flags =
23991 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23992 			    IPH_MF;
23993 		}
23994 		offset_and_flags |= (uint16_t)(offset >> 3);
23995 		offset_and_flags |= (uint16_t)frag_flag;
23996 		/* Store the offset and flags in the IP header. */
23997 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23998 
23999 		/* Store the length in the IP header. */
24000 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24001 		ipha->ipha_length = htons(ip_len);
24002 
24003 		/*
24004 		 * Set the IP header checksum.  Note that mp is just
24005 		 * the header, so this is easy to pass to ip_csum.
24006 		 */
24007 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24008 
24009 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24010 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24011 		    NULL, int, 0);
24012 
24013 		/*
24014 		 * Record offset and size of header and data of the next packet
24015 		 * in the multidata message.
24016 		 */
24017 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24018 		PDESC_PLD_INIT(&pdi);
24019 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24020 		ASSERT(i1 > 0);
24021 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24022 		if (i1 == len) {
24023 			pld_ptr += len;
24024 		} else {
24025 			i1 = len - i1;
24026 			mp = mp->b_cont;
24027 			ASSERT(mp != NULL);
24028 			ASSERT(MBLKL(mp) >= i1);
24029 			/*
24030 			 * Attach the next payload message block to the
24031 			 * multidata message.
24032 			 */
24033 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24034 				goto pbuf_panic;
24035 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24036 			pld_ptr = mp->b_rptr + i1;
24037 		}
24038 
24039 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24040 		    KM_NOSLEEP)) == NULL) {
24041 			/*
24042 			 * Any failure other than ENOMEM indicates that we
24043 			 * have passed in invalid pdesc info or parameters
24044 			 * to mmd_addpdesc, which must not happen.
24045 			 *
24046 			 * EINVAL is a result of failure on boundary checks
24047 			 * against the pdesc info contents.  It should not
24048 			 * happen, and we panic because either there's
24049 			 * horrible heap corruption, and/or programming
24050 			 * mistake.
24051 			 */
24052 			if (error != ENOMEM) {
24053 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24054 				    "pdesc logic error detected for "
24055 				    "mmd %p pinfo %p (%d)\n",
24056 				    (void *)mmd, (void *)&pdi, error);
24057 				/* NOTREACHED */
24058 			}
24059 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24060 			/* Free unattached payload message blocks as well */
24061 			md_mp->b_cont = mp->b_cont;
24062 			goto free_mmd;
24063 		}
24064 
24065 		/* Advance fragment offset. */
24066 		offset += len;
24067 
24068 		/* Advance to location for next header in the buffer. */
24069 		hdr_ptr += hdr_chunk_len;
24070 
24071 		/* Did we reach the next payload message block? */
24072 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24073 			mp = mp->b_cont;
24074 			/*
24075 			 * Attach the next message block with payload
24076 			 * data to the multidata message.
24077 			 */
24078 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24079 				goto pbuf_panic;
24080 			pld_ptr = mp->b_rptr;
24081 		}
24082 	}
24083 
24084 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24085 	ASSERT(mp->b_wptr == pld_ptr);
24086 
24087 	/* Update IP statistics */
24088 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24089 
24090 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24091 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24092 
24093 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24094 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24095 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24096 
24097 	if (pkt_type == OB_PKT) {
24098 		ire->ire_ob_pkt_count += pkts;
24099 		if (ire->ire_ipif != NULL)
24100 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24101 	} else {
24102 		/* The type is IB_PKT in the forwarding path. */
24103 		ire->ire_ib_pkt_count += pkts;
24104 		ASSERT(!IRE_IS_LOCAL(ire));
24105 		if (ire->ire_type & IRE_BROADCAST) {
24106 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24107 		} else {
24108 			UPDATE_MIB(ill->ill_ip_mib,
24109 			    ipIfStatsHCOutForwDatagrams, pkts);
24110 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24111 		}
24112 	}
24113 	ire->ire_last_used_time = lbolt;
24114 	/* Send it down */
24115 	putnext(ire->ire_stq, md_mp);
24116 	return;
24117 
24118 pbuf_panic:
24119 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24120 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24121 	    pbuf_idx);
24122 	/* NOTREACHED */
24123 }
24124 
24125 /*
24126  * Outbound IP fragmentation routine.
24127  *
24128  * NOTE : This routine does not ire_refrele the ire that is passed in
24129  * as the argument.
24130  */
24131 static void
24132 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24133     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24134 {
24135 	int		i1;
24136 	mblk_t		*ll_hdr_mp;
24137 	int 		ll_hdr_len;
24138 	int		hdr_len;
24139 	mblk_t		*hdr_mp;
24140 	ipha_t		*ipha;
24141 	int		ip_data_end;
24142 	int		len;
24143 	mblk_t		*mp = mp_orig, *mp1;
24144 	int		offset;
24145 	queue_t		*q;
24146 	uint32_t	v_hlen_tos_len;
24147 	mblk_t		*first_mp;
24148 	boolean_t	mctl_present;
24149 	ill_t		*ill;
24150 	ill_t		*out_ill;
24151 	mblk_t		*xmit_mp;
24152 	mblk_t		*carve_mp;
24153 	ire_t		*ire1 = NULL;
24154 	ire_t		*save_ire = NULL;
24155 	mblk_t  	*next_mp = NULL;
24156 	boolean_t	last_frag = B_FALSE;
24157 	boolean_t	multirt_send = B_FALSE;
24158 	ire_t		*first_ire = NULL;
24159 	irb_t		*irb = NULL;
24160 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24161 
24162 	ill = ire_to_ill(ire);
24163 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24164 
24165 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24166 
24167 	if (max_frag == 0) {
24168 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24169 		    " -  dropping packet\n"));
24170 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24171 		freemsg(mp);
24172 		return;
24173 	}
24174 
24175 	/*
24176 	 * IPsec does not allow hw accelerated packets to be fragmented
24177 	 * This check is made in ip_wput_ipsec_out prior to coming here
24178 	 * via ip_wput_ire_fragmentit.
24179 	 *
24180 	 * If at this point we have an ire whose ARP request has not
24181 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24182 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24183 	 * This packet and all fragmentable packets for this ire will
24184 	 * continue to get dropped while ire_nce->nce_state remains in
24185 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24186 	 * ND_REACHABLE, all subsquent large packets for this ire will
24187 	 * get fragemented and sent out by this function.
24188 	 */
24189 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24190 		/* If nce_state is ND_INITIAL, trigger ARP query */
24191 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24192 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24193 		    " -  dropping packet\n"));
24194 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24195 		freemsg(mp);
24196 		return;
24197 	}
24198 
24199 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24200 	    "ip_wput_frag_start:");
24201 
24202 	if (mp->b_datap->db_type == M_CTL) {
24203 		first_mp = mp;
24204 		mp_orig = mp = mp->b_cont;
24205 		mctl_present = B_TRUE;
24206 	} else {
24207 		first_mp = mp;
24208 		mctl_present = B_FALSE;
24209 	}
24210 
24211 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24212 	ipha = (ipha_t *)mp->b_rptr;
24213 
24214 	/*
24215 	 * If the Don't Fragment flag is on, generate an ICMP destination
24216 	 * unreachable, fragmentation needed.
24217 	 */
24218 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24219 	if (offset & IPH_DF) {
24220 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24221 		if (is_system_labeled()) {
24222 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24223 			    ire->ire_max_frag - max_frag, AF_INET);
24224 		}
24225 		/*
24226 		 * Need to compute hdr checksum if called from ip_wput_ire.
24227 		 * Note that ip_rput_forward verifies the checksum before
24228 		 * calling this routine so in that case this is a noop.
24229 		 */
24230 		ipha->ipha_hdr_checksum = 0;
24231 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24232 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24233 		    ipst);
24234 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24235 		    "ip_wput_frag_end:(%S)",
24236 		    "don't fragment");
24237 		return;
24238 	}
24239 	/*
24240 	 * Labeled systems adjust max_frag if they add a label
24241 	 * to send the correct path mtu.  We need the real mtu since we
24242 	 * are fragmenting the packet after label adjustment.
24243 	 */
24244 	if (is_system_labeled())
24245 		max_frag = ire->ire_max_frag;
24246 	if (mctl_present)
24247 		freeb(first_mp);
24248 	/*
24249 	 * Establish the starting offset.  May not be zero if we are fragging
24250 	 * a fragment that is being forwarded.
24251 	 */
24252 	offset = offset & IPH_OFFSET;
24253 
24254 	/* TODO why is this test needed? */
24255 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24256 	if (((max_frag - LENGTH) & ~7) < 8) {
24257 		/* TODO: notify ulp somehow */
24258 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24259 		freemsg(mp);
24260 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24261 		    "ip_wput_frag_end:(%S)",
24262 		    "len < 8");
24263 		return;
24264 	}
24265 
24266 	hdr_len = (V_HLEN & 0xF) << 2;
24267 
24268 	ipha->ipha_hdr_checksum = 0;
24269 
24270 	/*
24271 	 * Establish the number of bytes maximum per frag, after putting
24272 	 * in the header.
24273 	 */
24274 	len = (max_frag - hdr_len) & ~7;
24275 
24276 	/* Check if we can use MDT to send out the frags. */
24277 	ASSERT(!IRE_IS_LOCAL(ire));
24278 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24279 	    ipst->ips_ip_multidata_outbound &&
24280 	    !(ire->ire_flags & RTF_MULTIRT) &&
24281 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24282 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24283 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24284 		ASSERT(ill->ill_mdt_capab != NULL);
24285 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24286 			/*
24287 			 * If MDT has been previously turned off in the past,
24288 			 * and we currently can do MDT (due to IPQoS policy
24289 			 * removal, etc.) then enable it for this interface.
24290 			 */
24291 			ill->ill_mdt_capab->ill_mdt_on = 1;
24292 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24293 			    ill->ill_name));
24294 		}
24295 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24296 		    offset);
24297 		return;
24298 	}
24299 
24300 	/* Get a copy of the header for the trailing frags */
24301 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24302 	    mp);
24303 	if (!hdr_mp) {
24304 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24305 		freemsg(mp);
24306 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24307 		    "ip_wput_frag_end:(%S)",
24308 		    "couldn't copy hdr");
24309 		return;
24310 	}
24311 
24312 	/* Store the starting offset, with the MoreFrags flag. */
24313 	i1 = offset | IPH_MF | frag_flag;
24314 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24315 
24316 	/* Establish the ending byte offset, based on the starting offset. */
24317 	offset <<= 3;
24318 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24319 
24320 	/* Store the length of the first fragment in the IP header. */
24321 	i1 = len + hdr_len;
24322 	ASSERT(i1 <= IP_MAXPACKET);
24323 	ipha->ipha_length = htons((uint16_t)i1);
24324 
24325 	/*
24326 	 * Compute the IP header checksum for the first frag.  We have to
24327 	 * watch out that we stop at the end of the header.
24328 	 */
24329 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24330 
24331 	/*
24332 	 * Now carve off the first frag.  Note that this will include the
24333 	 * original IP header.
24334 	 */
24335 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24336 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24337 		freeb(hdr_mp);
24338 		freemsg(mp_orig);
24339 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24340 		    "ip_wput_frag_end:(%S)",
24341 		    "couldn't carve first");
24342 		return;
24343 	}
24344 
24345 	/*
24346 	 * Multirouting case. Each fragment is replicated
24347 	 * via all non-condemned RTF_MULTIRT routes
24348 	 * currently resolved.
24349 	 * We ensure that first_ire is the first RTF_MULTIRT
24350 	 * ire in the bucket.
24351 	 */
24352 	if (ire->ire_flags & RTF_MULTIRT) {
24353 		irb = ire->ire_bucket;
24354 		ASSERT(irb != NULL);
24355 
24356 		multirt_send = B_TRUE;
24357 
24358 		/* Make sure we do not omit any multiroute ire. */
24359 		IRB_REFHOLD(irb);
24360 		for (first_ire = irb->irb_ire;
24361 		    first_ire != NULL;
24362 		    first_ire = first_ire->ire_next) {
24363 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24364 			    (first_ire->ire_addr == ire->ire_addr) &&
24365 			    !(first_ire->ire_marks &
24366 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24367 				break;
24368 		}
24369 
24370 		if (first_ire != NULL) {
24371 			if (first_ire != ire) {
24372 				IRE_REFHOLD(first_ire);
24373 				/*
24374 				 * Do not release the ire passed in
24375 				 * as the argument.
24376 				 */
24377 				ire = first_ire;
24378 			} else {
24379 				first_ire = NULL;
24380 			}
24381 		}
24382 		IRB_REFRELE(irb);
24383 
24384 		/*
24385 		 * Save the first ire; we will need to restore it
24386 		 * for the trailing frags.
24387 		 * We REFHOLD save_ire, as each iterated ire will be
24388 		 * REFRELEd.
24389 		 */
24390 		save_ire = ire;
24391 		IRE_REFHOLD(save_ire);
24392 	}
24393 
24394 	/*
24395 	 * First fragment emission loop.
24396 	 * In most cases, the emission loop below is entered only
24397 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24398 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24399 	 * bucket, and send the fragment through all crossed
24400 	 * RTF_MULTIRT routes.
24401 	 */
24402 	do {
24403 		if (ire->ire_flags & RTF_MULTIRT) {
24404 			/*
24405 			 * We are in a multiple send case, need to get
24406 			 * the next ire and make a copy of the packet.
24407 			 * ire1 holds here the next ire to process in the
24408 			 * bucket. If multirouting is expected,
24409 			 * any non-RTF_MULTIRT ire that has the
24410 			 * right destination address is ignored.
24411 			 *
24412 			 * We have to take into account the MTU of
24413 			 * each walked ire. max_frag is set by the
24414 			 * the caller and generally refers to
24415 			 * the primary ire entry. Here we ensure that
24416 			 * no route with a lower MTU will be used, as
24417 			 * fragments are carved once for all ires,
24418 			 * then replicated.
24419 			 */
24420 			ASSERT(irb != NULL);
24421 			IRB_REFHOLD(irb);
24422 			for (ire1 = ire->ire_next;
24423 			    ire1 != NULL;
24424 			    ire1 = ire1->ire_next) {
24425 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24426 					continue;
24427 				if (ire1->ire_addr != ire->ire_addr)
24428 					continue;
24429 				if (ire1->ire_marks &
24430 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24431 					continue;
24432 				/*
24433 				 * Ensure we do not exceed the MTU
24434 				 * of the next route.
24435 				 */
24436 				if (ire1->ire_max_frag < max_frag) {
24437 					ip_multirt_bad_mtu(ire1, max_frag);
24438 					continue;
24439 				}
24440 
24441 				/* Got one. */
24442 				IRE_REFHOLD(ire1);
24443 				break;
24444 			}
24445 			IRB_REFRELE(irb);
24446 
24447 			if (ire1 != NULL) {
24448 				next_mp = copyb(mp);
24449 				if ((next_mp == NULL) ||
24450 				    ((mp->b_cont != NULL) &&
24451 				    ((next_mp->b_cont =
24452 				    dupmsg(mp->b_cont)) == NULL))) {
24453 					freemsg(next_mp);
24454 					next_mp = NULL;
24455 					ire_refrele(ire1);
24456 					ire1 = NULL;
24457 				}
24458 			}
24459 
24460 			/* Last multiroute ire; don't loop anymore. */
24461 			if (ire1 == NULL) {
24462 				multirt_send = B_FALSE;
24463 			}
24464 		}
24465 
24466 		ll_hdr_len = 0;
24467 		LOCK_IRE_FP_MP(ire);
24468 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24469 		if (ll_hdr_mp != NULL) {
24470 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24471 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24472 		} else {
24473 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24474 		}
24475 
24476 		/* If there is a transmit header, get a copy for this frag. */
24477 		/*
24478 		 * TODO: should check db_ref before calling ip_carve_mp since
24479 		 * it might give us a dup.
24480 		 */
24481 		if (!ll_hdr_mp) {
24482 			/* No xmit header. */
24483 			xmit_mp = mp;
24484 
24485 		/* We have a link-layer header that can fit in our mblk. */
24486 		} else if (mp->b_datap->db_ref == 1 &&
24487 		    ll_hdr_len != 0 &&
24488 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24489 			/* M_DATA fastpath */
24490 			mp->b_rptr -= ll_hdr_len;
24491 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24492 			xmit_mp = mp;
24493 
24494 		/* Corner case if copyb has failed */
24495 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24496 			UNLOCK_IRE_FP_MP(ire);
24497 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24498 			freeb(hdr_mp);
24499 			freemsg(mp);
24500 			freemsg(mp_orig);
24501 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24502 			    "ip_wput_frag_end:(%S)",
24503 			    "discard");
24504 
24505 			if (multirt_send) {
24506 				ASSERT(ire1);
24507 				ASSERT(next_mp);
24508 
24509 				freemsg(next_mp);
24510 				ire_refrele(ire1);
24511 			}
24512 			if (save_ire != NULL)
24513 				IRE_REFRELE(save_ire);
24514 
24515 			if (first_ire != NULL)
24516 				ire_refrele(first_ire);
24517 			return;
24518 
24519 		/*
24520 		 * Case of res_mp OR the fastpath mp can't fit
24521 		 * in the mblk
24522 		 */
24523 		} else {
24524 			xmit_mp->b_cont = mp;
24525 
24526 			/*
24527 			 * Get priority marking, if any.
24528 			 * We propagate the CoS marking from the
24529 			 * original packet that went to QoS processing
24530 			 * in ip_wput_ire to the newly carved mp.
24531 			 */
24532 			if (DB_TYPE(xmit_mp) == M_DATA)
24533 				xmit_mp->b_band = mp->b_band;
24534 		}
24535 		UNLOCK_IRE_FP_MP(ire);
24536 
24537 		q = ire->ire_stq;
24538 		out_ill = (ill_t *)q->q_ptr;
24539 
24540 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24541 
24542 		DTRACE_PROBE4(ip4__physical__out__start,
24543 		    ill_t *, NULL, ill_t *, out_ill,
24544 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24545 
24546 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24547 		    ipst->ips_ipv4firewall_physical_out,
24548 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24549 
24550 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24551 
24552 		if (xmit_mp != NULL) {
24553 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24554 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24555 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24556 
24557 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24558 
24559 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24560 			UPDATE_MIB(out_ill->ill_ip_mib,
24561 			    ipIfStatsHCOutOctets, i1);
24562 
24563 			if (pkt_type != OB_PKT) {
24564 				/*
24565 				 * Update the packet count and MIB stats
24566 				 * of trailing RTF_MULTIRT ires.
24567 				 */
24568 				UPDATE_OB_PKT_COUNT(ire);
24569 				BUMP_MIB(out_ill->ill_ip_mib,
24570 				    ipIfStatsOutFragReqds);
24571 			}
24572 		}
24573 
24574 		if (multirt_send) {
24575 			/*
24576 			 * We are in a multiple send case; look for
24577 			 * the next ire and re-enter the loop.
24578 			 */
24579 			ASSERT(ire1);
24580 			ASSERT(next_mp);
24581 			/* REFRELE the current ire before looping */
24582 			ire_refrele(ire);
24583 			ire = ire1;
24584 			ire1 = NULL;
24585 			mp = next_mp;
24586 			next_mp = NULL;
24587 		}
24588 	} while (multirt_send);
24589 
24590 	ASSERT(ire1 == NULL);
24591 
24592 	/* Restore the original ire; we need it for the trailing frags */
24593 	if (save_ire != NULL) {
24594 		/* REFRELE the last iterated ire */
24595 		ire_refrele(ire);
24596 		/* save_ire has been REFHOLDed */
24597 		ire = save_ire;
24598 		save_ire = NULL;
24599 		q = ire->ire_stq;
24600 	}
24601 
24602 	if (pkt_type == OB_PKT) {
24603 		UPDATE_OB_PKT_COUNT(ire);
24604 	} else {
24605 		out_ill = (ill_t *)q->q_ptr;
24606 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24607 		UPDATE_IB_PKT_COUNT(ire);
24608 	}
24609 
24610 	/* Advance the offset to the second frag starting point. */
24611 	offset += len;
24612 	/*
24613 	 * Update hdr_len from the copied header - there might be less options
24614 	 * in the later fragments.
24615 	 */
24616 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24617 	/* Loop until done. */
24618 	for (;;) {
24619 		uint16_t	offset_and_flags;
24620 		uint16_t	ip_len;
24621 
24622 		if (ip_data_end - offset > len) {
24623 			/*
24624 			 * Carve off the appropriate amount from the original
24625 			 * datagram.
24626 			 */
24627 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24628 				mp = NULL;
24629 				break;
24630 			}
24631 			/*
24632 			 * More frags after this one.  Get another copy
24633 			 * of the header.
24634 			 */
24635 			if (carve_mp->b_datap->db_ref == 1 &&
24636 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24637 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24638 				/* Inline IP header */
24639 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24640 				    hdr_mp->b_rptr;
24641 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24642 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24643 				mp = carve_mp;
24644 			} else {
24645 				if (!(mp = copyb(hdr_mp))) {
24646 					freemsg(carve_mp);
24647 					break;
24648 				}
24649 				/* Get priority marking, if any. */
24650 				mp->b_band = carve_mp->b_band;
24651 				mp->b_cont = carve_mp;
24652 			}
24653 			ipha = (ipha_t *)mp->b_rptr;
24654 			offset_and_flags = IPH_MF;
24655 		} else {
24656 			/*
24657 			 * Last frag.  Consume the header. Set len to
24658 			 * the length of this last piece.
24659 			 */
24660 			len = ip_data_end - offset;
24661 
24662 			/*
24663 			 * Carve off the appropriate amount from the original
24664 			 * datagram.
24665 			 */
24666 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24667 				mp = NULL;
24668 				break;
24669 			}
24670 			if (carve_mp->b_datap->db_ref == 1 &&
24671 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24672 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24673 				/* Inline IP header */
24674 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24675 				    hdr_mp->b_rptr;
24676 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24677 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24678 				mp = carve_mp;
24679 				freeb(hdr_mp);
24680 				hdr_mp = mp;
24681 			} else {
24682 				mp = hdr_mp;
24683 				/* Get priority marking, if any. */
24684 				mp->b_band = carve_mp->b_band;
24685 				mp->b_cont = carve_mp;
24686 			}
24687 			ipha = (ipha_t *)mp->b_rptr;
24688 			/* A frag of a frag might have IPH_MF non-zero */
24689 			offset_and_flags =
24690 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24691 			    IPH_MF;
24692 		}
24693 		offset_and_flags |= (uint16_t)(offset >> 3);
24694 		offset_and_flags |= (uint16_t)frag_flag;
24695 		/* Store the offset and flags in the IP header. */
24696 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24697 
24698 		/* Store the length in the IP header. */
24699 		ip_len = (uint16_t)(len + hdr_len);
24700 		ipha->ipha_length = htons(ip_len);
24701 
24702 		/*
24703 		 * Set the IP header checksum.	Note that mp is just
24704 		 * the header, so this is easy to pass to ip_csum.
24705 		 */
24706 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24707 
24708 		/* Attach a transmit header, if any, and ship it. */
24709 		if (pkt_type == OB_PKT) {
24710 			UPDATE_OB_PKT_COUNT(ire);
24711 		} else {
24712 			out_ill = (ill_t *)q->q_ptr;
24713 			BUMP_MIB(out_ill->ill_ip_mib,
24714 			    ipIfStatsHCOutForwDatagrams);
24715 			UPDATE_IB_PKT_COUNT(ire);
24716 		}
24717 
24718 		if (ire->ire_flags & RTF_MULTIRT) {
24719 			irb = ire->ire_bucket;
24720 			ASSERT(irb != NULL);
24721 
24722 			multirt_send = B_TRUE;
24723 
24724 			/*
24725 			 * Save the original ire; we will need to restore it
24726 			 * for the tailing frags.
24727 			 */
24728 			save_ire = ire;
24729 			IRE_REFHOLD(save_ire);
24730 		}
24731 		/*
24732 		 * Emission loop for this fragment, similar
24733 		 * to what is done for the first fragment.
24734 		 */
24735 		do {
24736 			if (multirt_send) {
24737 				/*
24738 				 * We are in a multiple send case, need to get
24739 				 * the next ire and make a copy of the packet.
24740 				 */
24741 				ASSERT(irb != NULL);
24742 				IRB_REFHOLD(irb);
24743 				for (ire1 = ire->ire_next;
24744 				    ire1 != NULL;
24745 				    ire1 = ire1->ire_next) {
24746 					if (!(ire1->ire_flags & RTF_MULTIRT))
24747 						continue;
24748 					if (ire1->ire_addr != ire->ire_addr)
24749 						continue;
24750 					if (ire1->ire_marks &
24751 					    (IRE_MARK_CONDEMNED |
24752 					    IRE_MARK_TESTHIDDEN))
24753 						continue;
24754 					/*
24755 					 * Ensure we do not exceed the MTU
24756 					 * of the next route.
24757 					 */
24758 					if (ire1->ire_max_frag < max_frag) {
24759 						ip_multirt_bad_mtu(ire1,
24760 						    max_frag);
24761 						continue;
24762 					}
24763 
24764 					/* Got one. */
24765 					IRE_REFHOLD(ire1);
24766 					break;
24767 				}
24768 				IRB_REFRELE(irb);
24769 
24770 				if (ire1 != NULL) {
24771 					next_mp = copyb(mp);
24772 					if ((next_mp == NULL) ||
24773 					    ((mp->b_cont != NULL) &&
24774 					    ((next_mp->b_cont =
24775 					    dupmsg(mp->b_cont)) == NULL))) {
24776 						freemsg(next_mp);
24777 						next_mp = NULL;
24778 						ire_refrele(ire1);
24779 						ire1 = NULL;
24780 					}
24781 				}
24782 
24783 				/* Last multiroute ire; don't loop anymore. */
24784 				if (ire1 == NULL) {
24785 					multirt_send = B_FALSE;
24786 				}
24787 			}
24788 
24789 			/* Update transmit header */
24790 			ll_hdr_len = 0;
24791 			LOCK_IRE_FP_MP(ire);
24792 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24793 			if (ll_hdr_mp != NULL) {
24794 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24795 				ll_hdr_len = MBLKL(ll_hdr_mp);
24796 			} else {
24797 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24798 			}
24799 
24800 			if (!ll_hdr_mp) {
24801 				xmit_mp = mp;
24802 
24803 			/*
24804 			 * We have link-layer header that can fit in
24805 			 * our mblk.
24806 			 */
24807 			} else if (mp->b_datap->db_ref == 1 &&
24808 			    ll_hdr_len != 0 &&
24809 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24810 				/* M_DATA fastpath */
24811 				mp->b_rptr -= ll_hdr_len;
24812 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24813 				    ll_hdr_len);
24814 				xmit_mp = mp;
24815 
24816 			/*
24817 			 * Case of res_mp OR the fastpath mp can't fit
24818 			 * in the mblk
24819 			 */
24820 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24821 				xmit_mp->b_cont = mp;
24822 				/* Get priority marking, if any. */
24823 				if (DB_TYPE(xmit_mp) == M_DATA)
24824 					xmit_mp->b_band = mp->b_band;
24825 
24826 			/* Corner case if copyb failed */
24827 			} else {
24828 				/*
24829 				 * Exit both the replication and
24830 				 * fragmentation loops.
24831 				 */
24832 				UNLOCK_IRE_FP_MP(ire);
24833 				goto drop_pkt;
24834 			}
24835 			UNLOCK_IRE_FP_MP(ire);
24836 
24837 			mp1 = mp;
24838 			out_ill = (ill_t *)q->q_ptr;
24839 
24840 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24841 
24842 			DTRACE_PROBE4(ip4__physical__out__start,
24843 			    ill_t *, NULL, ill_t *, out_ill,
24844 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24845 
24846 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24847 			    ipst->ips_ipv4firewall_physical_out,
24848 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24849 
24850 			DTRACE_PROBE1(ip4__physical__out__end,
24851 			    mblk_t *, xmit_mp);
24852 
24853 			if (mp != mp1 && hdr_mp == mp1)
24854 				hdr_mp = mp;
24855 			if (mp != mp1 && mp_orig == mp1)
24856 				mp_orig = mp;
24857 
24858 			if (xmit_mp != NULL) {
24859 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24860 				    NULL, void_ip_t *, ipha,
24861 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24862 				    ipha, ip6_t *, NULL, int, 0);
24863 
24864 				ILL_SEND_TX(out_ill, ire, connp,
24865 				    xmit_mp, 0, connp);
24866 
24867 				BUMP_MIB(out_ill->ill_ip_mib,
24868 				    ipIfStatsHCOutTransmits);
24869 				UPDATE_MIB(out_ill->ill_ip_mib,
24870 				    ipIfStatsHCOutOctets, ip_len);
24871 
24872 				if (pkt_type != OB_PKT) {
24873 					/*
24874 					 * Update the packet count of trailing
24875 					 * RTF_MULTIRT ires.
24876 					 */
24877 					UPDATE_OB_PKT_COUNT(ire);
24878 				}
24879 			}
24880 
24881 			/* All done if we just consumed the hdr_mp. */
24882 			if (mp == hdr_mp) {
24883 				last_frag = B_TRUE;
24884 				BUMP_MIB(out_ill->ill_ip_mib,
24885 				    ipIfStatsOutFragOKs);
24886 			}
24887 
24888 			if (multirt_send) {
24889 				/*
24890 				 * We are in a multiple send case; look for
24891 				 * the next ire and re-enter the loop.
24892 				 */
24893 				ASSERT(ire1);
24894 				ASSERT(next_mp);
24895 				/* REFRELE the current ire before looping */
24896 				ire_refrele(ire);
24897 				ire = ire1;
24898 				ire1 = NULL;
24899 				q = ire->ire_stq;
24900 				mp = next_mp;
24901 				next_mp = NULL;
24902 			}
24903 		} while (multirt_send);
24904 		/*
24905 		 * Restore the original ire; we need it for the
24906 		 * trailing frags
24907 		 */
24908 		if (save_ire != NULL) {
24909 			ASSERT(ire1 == NULL);
24910 			/* REFRELE the last iterated ire */
24911 			ire_refrele(ire);
24912 			/* save_ire has been REFHOLDed */
24913 			ire = save_ire;
24914 			q = ire->ire_stq;
24915 			save_ire = NULL;
24916 		}
24917 
24918 		if (last_frag) {
24919 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24920 			    "ip_wput_frag_end:(%S)",
24921 			    "consumed hdr_mp");
24922 
24923 			if (first_ire != NULL)
24924 				ire_refrele(first_ire);
24925 			return;
24926 		}
24927 		/* Otherwise, advance and loop. */
24928 		offset += len;
24929 	}
24930 
24931 drop_pkt:
24932 	/* Clean up following allocation failure. */
24933 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24934 	freemsg(mp);
24935 	if (mp != hdr_mp)
24936 		freeb(hdr_mp);
24937 	if (mp != mp_orig)
24938 		freemsg(mp_orig);
24939 
24940 	if (save_ire != NULL)
24941 		IRE_REFRELE(save_ire);
24942 	if (first_ire != NULL)
24943 		ire_refrele(first_ire);
24944 
24945 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24946 	    "ip_wput_frag_end:(%S)",
24947 	    "end--alloc failure");
24948 }
24949 
24950 /*
24951  * Copy the header plus those options which have the copy bit set
24952  * src is the template to make sure we preserve the cred for TX purposes.
24953  */
24954 static mblk_t *
24955 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24956     mblk_t *src)
24957 {
24958 	mblk_t	*mp;
24959 	uchar_t	*up;
24960 
24961 	/*
24962 	 * Quick check if we need to look for options without the copy bit
24963 	 * set
24964 	 */
24965 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24966 	if (!mp)
24967 		return (mp);
24968 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24969 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24970 		bcopy(rptr, mp->b_rptr, hdr_len);
24971 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24972 		return (mp);
24973 	}
24974 	up  = mp->b_rptr;
24975 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24976 	up += IP_SIMPLE_HDR_LENGTH;
24977 	rptr += IP_SIMPLE_HDR_LENGTH;
24978 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24979 	while (hdr_len > 0) {
24980 		uint32_t optval;
24981 		uint32_t optlen;
24982 
24983 		optval = *rptr;
24984 		if (optval == IPOPT_EOL)
24985 			break;
24986 		if (optval == IPOPT_NOP)
24987 			optlen = 1;
24988 		else
24989 			optlen = rptr[1];
24990 		if (optval & IPOPT_COPY) {
24991 			bcopy(rptr, up, optlen);
24992 			up += optlen;
24993 		}
24994 		rptr += optlen;
24995 		hdr_len -= optlen;
24996 	}
24997 	/*
24998 	 * Make sure that we drop an even number of words by filling
24999 	 * with EOL to the next word boundary.
25000 	 */
25001 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25002 	    hdr_len & 0x3; hdr_len++)
25003 		*up++ = IPOPT_EOL;
25004 	mp->b_wptr = up;
25005 	/* Update header length */
25006 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25007 	return (mp);
25008 }
25009 
25010 /*
25011  * Delivery to local recipients including fanout to multiple recipients.
25012  * Does not do checksumming of UDP/TCP.
25013  * Note: q should be the read side queue for either the ill or conn.
25014  * Note: rq should be the read side q for the lower (ill) stream.
25015  * We don't send packets to IPPF processing, thus the last argument
25016  * to all the fanout calls are B_FALSE.
25017  */
25018 void
25019 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25020     int fanout_flags, zoneid_t zoneid)
25021 {
25022 	uint32_t	protocol;
25023 	mblk_t		*first_mp;
25024 	boolean_t	mctl_present;
25025 	int		ire_type;
25026 #define	rptr	((uchar_t *)ipha)
25027 	ip_stack_t	*ipst = ill->ill_ipst;
25028 
25029 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25030 	    "ip_wput_local_start: q %p", q);
25031 
25032 	if (ire != NULL) {
25033 		ire_type = ire->ire_type;
25034 	} else {
25035 		/*
25036 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25037 		 * packet is not multicast, we can't tell the ire type.
25038 		 */
25039 		ASSERT(CLASSD(ipha->ipha_dst));
25040 		ire_type = IRE_BROADCAST;
25041 	}
25042 
25043 	first_mp = mp;
25044 	if (first_mp->b_datap->db_type == M_CTL) {
25045 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25046 		if (!io->ipsec_out_secure) {
25047 			/*
25048 			 * This ipsec_out_t was allocated in ip_wput
25049 			 * for multicast packets to store the ill_index.
25050 			 * As this is being delivered locally, we don't
25051 			 * need this anymore.
25052 			 */
25053 			mp = first_mp->b_cont;
25054 			freeb(first_mp);
25055 			first_mp = mp;
25056 			mctl_present = B_FALSE;
25057 		} else {
25058 			/*
25059 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25060 			 * security properties for the looped-back packet.
25061 			 */
25062 			mctl_present = B_TRUE;
25063 			mp = first_mp->b_cont;
25064 			ASSERT(mp != NULL);
25065 			ipsec_out_to_in(first_mp);
25066 		}
25067 	} else {
25068 		mctl_present = B_FALSE;
25069 	}
25070 
25071 	DTRACE_PROBE4(ip4__loopback__in__start,
25072 	    ill_t *, ill, ill_t *, NULL,
25073 	    ipha_t *, ipha, mblk_t *, first_mp);
25074 
25075 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25076 	    ipst->ips_ipv4firewall_loopback_in,
25077 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25078 
25079 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25080 
25081 	if (first_mp == NULL)
25082 		return;
25083 
25084 	if (ipst->ips_ipobs_enabled) {
25085 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25086 		zoneid_t stackzoneid = netstackid_to_zoneid(
25087 		    ipst->ips_netstack->netstack_stackid);
25088 
25089 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25090 		/*
25091 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25092 		 * address.  Restrict the lookup below to the destination zone.
25093 		 */
25094 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25095 			lookup_zoneid = zoneid;
25096 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25097 		    lookup_zoneid);
25098 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25099 		    IPV4_VERSION, 0, ipst);
25100 	}
25101 
25102 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25103 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25104 	    int, 1);
25105 
25106 	ipst->ips_loopback_packets++;
25107 
25108 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25109 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25110 	if (!IS_SIMPLE_IPH(ipha)) {
25111 		ip_wput_local_options(ipha, ipst);
25112 	}
25113 
25114 	protocol = ipha->ipha_protocol;
25115 	switch (protocol) {
25116 	case IPPROTO_ICMP: {
25117 		ire_t		*ire_zone;
25118 		ilm_t		*ilm;
25119 		mblk_t		*mp1;
25120 		zoneid_t	last_zoneid;
25121 		ilm_walker_t	ilw;
25122 
25123 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25124 			ASSERT(ire_type == IRE_BROADCAST);
25125 			/*
25126 			 * In the multicast case, applications may have joined
25127 			 * the group from different zones, so we need to deliver
25128 			 * the packet to each of them. Loop through the
25129 			 * multicast memberships structures (ilm) on the receive
25130 			 * ill and send a copy of the packet up each matching
25131 			 * one. However, we don't do this for multicasts sent on
25132 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25133 			 * they must stay in the sender's zone.
25134 			 *
25135 			 * ilm_add_v6() ensures that ilms in the same zone are
25136 			 * contiguous in the ill_ilm list. We use this property
25137 			 * to avoid sending duplicates needed when two
25138 			 * applications in the same zone join the same group on
25139 			 * different logical interfaces: we ignore the ilm if
25140 			 * it's zoneid is the same as the last matching one.
25141 			 * In addition, the sending of the packet for
25142 			 * ire_zoneid is delayed until all of the other ilms
25143 			 * have been exhausted.
25144 			 */
25145 			last_zoneid = -1;
25146 			ilm = ilm_walker_start(&ilw, ill);
25147 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25148 				if (ipha->ipha_dst != ilm->ilm_addr ||
25149 				    ilm->ilm_zoneid == last_zoneid ||
25150 				    ilm->ilm_zoneid == zoneid ||
25151 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25152 					continue;
25153 				mp1 = ip_copymsg(first_mp);
25154 				if (mp1 == NULL)
25155 					continue;
25156 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25157 				    0, 0, mctl_present, B_FALSE, ill,
25158 				    ilm->ilm_zoneid);
25159 				last_zoneid = ilm->ilm_zoneid;
25160 			}
25161 			ilm_walker_finish(&ilw);
25162 			/*
25163 			 * Loopback case: the sending endpoint has
25164 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25165 			 * dispatch the multicast packet to the sending zone.
25166 			 */
25167 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25168 				freemsg(first_mp);
25169 				return;
25170 			}
25171 		} else if (ire_type == IRE_BROADCAST) {
25172 			/*
25173 			 * In the broadcast case, there may be many zones
25174 			 * which need a copy of the packet delivered to them.
25175 			 * There is one IRE_BROADCAST per broadcast address
25176 			 * and per zone; we walk those using a helper function.
25177 			 * In addition, the sending of the packet for zoneid is
25178 			 * delayed until all of the other ires have been
25179 			 * processed.
25180 			 */
25181 			IRB_REFHOLD(ire->ire_bucket);
25182 			ire_zone = NULL;
25183 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25184 			    ire)) != NULL) {
25185 				mp1 = ip_copymsg(first_mp);
25186 				if (mp1 == NULL)
25187 					continue;
25188 
25189 				UPDATE_IB_PKT_COUNT(ire_zone);
25190 				ire_zone->ire_last_used_time = lbolt;
25191 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25192 				    mctl_present, B_FALSE, ill,
25193 				    ire_zone->ire_zoneid);
25194 			}
25195 			IRB_REFRELE(ire->ire_bucket);
25196 		}
25197 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25198 		    0, mctl_present, B_FALSE, ill, zoneid);
25199 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25200 		    "ip_wput_local_end: q %p (%S)",
25201 		    q, "icmp");
25202 		return;
25203 	}
25204 	case IPPROTO_IGMP:
25205 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25206 			/* Bad packet - discarded by igmp_input */
25207 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25208 			    "ip_wput_local_end: q %p (%S)",
25209 			    q, "igmp_input--bad packet");
25210 			if (mctl_present)
25211 				freeb(first_mp);
25212 			return;
25213 		}
25214 		/*
25215 		 * igmp_input() may have returned the pulled up message.
25216 		 * So first_mp and ipha need to be reinitialized.
25217 		 */
25218 		ipha = (ipha_t *)mp->b_rptr;
25219 		if (mctl_present)
25220 			first_mp->b_cont = mp;
25221 		else
25222 			first_mp = mp;
25223 		/* deliver to local raw users */
25224 		break;
25225 	case IPPROTO_ENCAP:
25226 		/*
25227 		 * This case is covered by either ip_fanout_proto, or by
25228 		 * the above security processing for self-tunneled packets.
25229 		 */
25230 		break;
25231 	case IPPROTO_UDP: {
25232 		uint16_t	*up;
25233 		uint32_t	ports;
25234 
25235 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25236 		    UDP_PORTS_OFFSET);
25237 		/* Force a 'valid' checksum. */
25238 		up[3] = 0;
25239 
25240 		ports = *(uint32_t *)up;
25241 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25242 		    (ire_type == IRE_BROADCAST),
25243 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25244 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25245 		    ill, zoneid);
25246 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25247 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25248 		return;
25249 	}
25250 	case IPPROTO_TCP: {
25251 
25252 		/*
25253 		 * For TCP, discard broadcast packets.
25254 		 */
25255 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25256 			freemsg(first_mp);
25257 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25258 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25259 			return;
25260 		}
25261 
25262 		if (mp->b_datap->db_type == M_DATA) {
25263 			/*
25264 			 * M_DATA mblk, so init mblk (chain) for no struio().
25265 			 */
25266 			mblk_t	*mp1 = mp;
25267 
25268 			do {
25269 				mp1->b_datap->db_struioflag = 0;
25270 			} while ((mp1 = mp1->b_cont) != NULL);
25271 		}
25272 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25273 		    <= mp->b_wptr);
25274 		ip_fanout_tcp(q, first_mp, ill, ipha,
25275 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25276 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25277 		    mctl_present, B_FALSE, zoneid);
25278 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25279 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25280 		return;
25281 	}
25282 	case IPPROTO_SCTP:
25283 	{
25284 		uint32_t	ports;
25285 
25286 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25287 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25288 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25289 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25290 		return;
25291 	}
25292 
25293 	default:
25294 		break;
25295 	}
25296 	/*
25297 	 * Find a client for some other protocol.  We give
25298 	 * copies to multiple clients, if more than one is
25299 	 * bound.
25300 	 */
25301 	ip_fanout_proto(q, first_mp, ill, ipha,
25302 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25303 	    mctl_present, B_FALSE, ill, zoneid);
25304 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25305 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25306 #undef	rptr
25307 }
25308 
25309 /*
25310  * Update any source route, record route, or timestamp options.
25311  * Check that we are at end of strict source route.
25312  * The options have been sanity checked by ip_wput_options().
25313  */
25314 static void
25315 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25316 {
25317 	ipoptp_t	opts;
25318 	uchar_t		*opt;
25319 	uint8_t		optval;
25320 	uint8_t		optlen;
25321 	ipaddr_t	dst;
25322 	uint32_t	ts;
25323 	ire_t		*ire;
25324 	timestruc_t	now;
25325 
25326 	ip2dbg(("ip_wput_local_options\n"));
25327 	for (optval = ipoptp_first(&opts, ipha);
25328 	    optval != IPOPT_EOL;
25329 	    optval = ipoptp_next(&opts)) {
25330 		opt = opts.ipoptp_cur;
25331 		optlen = opts.ipoptp_len;
25332 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25333 		switch (optval) {
25334 			uint32_t off;
25335 		case IPOPT_SSRR:
25336 		case IPOPT_LSRR:
25337 			off = opt[IPOPT_OFFSET];
25338 			off--;
25339 			if (optlen < IP_ADDR_LEN ||
25340 			    off > optlen - IP_ADDR_LEN) {
25341 				/* End of source route */
25342 				break;
25343 			}
25344 			/*
25345 			 * This will only happen if two consecutive entries
25346 			 * in the source route contains our address or if
25347 			 * it is a packet with a loose source route which
25348 			 * reaches us before consuming the whole source route
25349 			 */
25350 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25351 			if (optval == IPOPT_SSRR) {
25352 				return;
25353 			}
25354 			/*
25355 			 * Hack: instead of dropping the packet truncate the
25356 			 * source route to what has been used by filling the
25357 			 * rest with IPOPT_NOP.
25358 			 */
25359 			opt[IPOPT_OLEN] = (uint8_t)off;
25360 			while (off < optlen) {
25361 				opt[off++] = IPOPT_NOP;
25362 			}
25363 			break;
25364 		case IPOPT_RR:
25365 			off = opt[IPOPT_OFFSET];
25366 			off--;
25367 			if (optlen < IP_ADDR_LEN ||
25368 			    off > optlen - IP_ADDR_LEN) {
25369 				/* No more room - ignore */
25370 				ip1dbg((
25371 				    "ip_wput_forward_options: end of RR\n"));
25372 				break;
25373 			}
25374 			dst = htonl(INADDR_LOOPBACK);
25375 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25376 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25377 			break;
25378 		case IPOPT_TS:
25379 			/* Insert timestamp if there is romm */
25380 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25381 			case IPOPT_TS_TSONLY:
25382 				off = IPOPT_TS_TIMELEN;
25383 				break;
25384 			case IPOPT_TS_PRESPEC:
25385 			case IPOPT_TS_PRESPEC_RFC791:
25386 				/* Verify that the address matched */
25387 				off = opt[IPOPT_OFFSET] - 1;
25388 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25389 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25390 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25391 				    ipst);
25392 				if (ire == NULL) {
25393 					/* Not for us */
25394 					break;
25395 				}
25396 				ire_refrele(ire);
25397 				/* FALLTHRU */
25398 			case IPOPT_TS_TSANDADDR:
25399 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25400 				break;
25401 			default:
25402 				/*
25403 				 * ip_*put_options should have already
25404 				 * dropped this packet.
25405 				 */
25406 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25407 				    "unknown IT - bug in ip_wput_options?\n");
25408 				return;	/* Keep "lint" happy */
25409 			}
25410 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25411 				/* Increase overflow counter */
25412 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25413 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25414 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25415 				    (off << 4);
25416 				break;
25417 			}
25418 			off = opt[IPOPT_OFFSET] - 1;
25419 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25420 			case IPOPT_TS_PRESPEC:
25421 			case IPOPT_TS_PRESPEC_RFC791:
25422 			case IPOPT_TS_TSANDADDR:
25423 				dst = htonl(INADDR_LOOPBACK);
25424 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25425 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25426 				/* FALLTHRU */
25427 			case IPOPT_TS_TSONLY:
25428 				off = opt[IPOPT_OFFSET] - 1;
25429 				/* Compute # of milliseconds since midnight */
25430 				gethrestime(&now);
25431 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25432 				    now.tv_nsec / (NANOSEC / MILLISEC);
25433 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25434 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25435 				break;
25436 			}
25437 			break;
25438 		}
25439 	}
25440 }
25441 
25442 /*
25443  * Send out a multicast packet on interface ipif.
25444  * The sender does not have an conn.
25445  * Caller verifies that this isn't a PHYI_LOOPBACK.
25446  */
25447 void
25448 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25449 {
25450 	ipha_t	*ipha;
25451 	ire_t	*ire;
25452 	ipaddr_t	dst;
25453 	mblk_t		*first_mp;
25454 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25455 
25456 	/* igmp_sendpkt always allocates a ipsec_out_t */
25457 	ASSERT(mp->b_datap->db_type == M_CTL);
25458 	ASSERT(!ipif->ipif_isv6);
25459 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25460 
25461 	first_mp = mp;
25462 	mp = first_mp->b_cont;
25463 	ASSERT(mp->b_datap->db_type == M_DATA);
25464 	ipha = (ipha_t *)mp->b_rptr;
25465 
25466 	/*
25467 	 * Find an IRE which matches the destination and the outgoing
25468 	 * queue (i.e. the outgoing interface.)
25469 	 */
25470 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25471 		dst = ipif->ipif_pp_dst_addr;
25472 	else
25473 		dst = ipha->ipha_dst;
25474 	/*
25475 	 * The source address has already been initialized by the
25476 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25477 	 * be sufficient rather than MATCH_IRE_IPIF.
25478 	 *
25479 	 * This function is used for sending IGMP packets.  For IPMP,
25480 	 * we sidestep IGMP snooping issues by sending all multicast
25481 	 * traffic on a single interface in the IPMP group.
25482 	 */
25483 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25484 	    MATCH_IRE_ILL, ipst);
25485 	if (!ire) {
25486 		/*
25487 		 * Mark this packet to make it be delivered to
25488 		 * ip_wput_ire after the new ire has been
25489 		 * created.
25490 		 */
25491 		mp->b_prev = NULL;
25492 		mp->b_next = NULL;
25493 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25494 		    zoneid, &zero_info);
25495 		return;
25496 	}
25497 
25498 	/*
25499 	 * Honor the RTF_SETSRC flag; this is the only case
25500 	 * where we force this addr whatever the current src addr is,
25501 	 * because this address is set by igmp_sendpkt(), and
25502 	 * cannot be specified by any user.
25503 	 */
25504 	if (ire->ire_flags & RTF_SETSRC) {
25505 		ipha->ipha_src = ire->ire_src_addr;
25506 	}
25507 
25508 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25509 }
25510 
25511 /*
25512  * NOTE : This function does not ire_refrele the ire argument passed in.
25513  *
25514  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25515  * failure. The nce_fp_mp can vanish any time in the case of
25516  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25517  * the ire_lock to access the nce_fp_mp in this case.
25518  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25519  * prepending a fastpath message IPQoS processing must precede it, we also set
25520  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25521  * (IPQoS might have set the b_band for CoS marking).
25522  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25523  * must follow it so that IPQoS can mark the dl_priority field for CoS
25524  * marking, if needed.
25525  */
25526 static mblk_t *
25527 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25528     uint32_t ill_index, ipha_t **iphap)
25529 {
25530 	uint_t	hlen;
25531 	ipha_t *ipha;
25532 	mblk_t *mp1;
25533 	boolean_t qos_done = B_FALSE;
25534 	uchar_t	*ll_hdr;
25535 	ip_stack_t	*ipst = ire->ire_ipst;
25536 
25537 #define	rptr	((uchar_t *)ipha)
25538 
25539 	ipha = (ipha_t *)mp->b_rptr;
25540 	hlen = 0;
25541 	LOCK_IRE_FP_MP(ire);
25542 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25543 		ASSERT(DB_TYPE(mp1) == M_DATA);
25544 		/* Initiate IPPF processing */
25545 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25546 			UNLOCK_IRE_FP_MP(ire);
25547 			ip_process(proc, &mp, ill_index);
25548 			if (mp == NULL)
25549 				return (NULL);
25550 
25551 			ipha = (ipha_t *)mp->b_rptr;
25552 			LOCK_IRE_FP_MP(ire);
25553 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25554 				qos_done = B_TRUE;
25555 				goto no_fp_mp;
25556 			}
25557 			ASSERT(DB_TYPE(mp1) == M_DATA);
25558 		}
25559 		hlen = MBLKL(mp1);
25560 		/*
25561 		 * Check if we have enough room to prepend fastpath
25562 		 * header
25563 		 */
25564 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25565 			ll_hdr = rptr - hlen;
25566 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25567 			/*
25568 			 * Set the b_rptr to the start of the link layer
25569 			 * header
25570 			 */
25571 			mp->b_rptr = ll_hdr;
25572 			mp1 = mp;
25573 		} else {
25574 			mp1 = copyb(mp1);
25575 			if (mp1 == NULL)
25576 				goto unlock_err;
25577 			mp1->b_band = mp->b_band;
25578 			mp1->b_cont = mp;
25579 			/*
25580 			 * XXX disable ICK_VALID and compute checksum
25581 			 * here; can happen if nce_fp_mp changes and
25582 			 * it can't be copied now due to insufficient
25583 			 * space. (unlikely, fp mp can change, but it
25584 			 * does not increase in length)
25585 			 */
25586 		}
25587 		UNLOCK_IRE_FP_MP(ire);
25588 	} else {
25589 no_fp_mp:
25590 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25591 		if (mp1 == NULL) {
25592 unlock_err:
25593 			UNLOCK_IRE_FP_MP(ire);
25594 			freemsg(mp);
25595 			return (NULL);
25596 		}
25597 		UNLOCK_IRE_FP_MP(ire);
25598 		mp1->b_cont = mp;
25599 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25600 			ip_process(proc, &mp1, ill_index);
25601 			if (mp1 == NULL)
25602 				return (NULL);
25603 
25604 			if (mp1->b_cont == NULL)
25605 				ipha = NULL;
25606 			else
25607 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25608 		}
25609 	}
25610 
25611 	*iphap = ipha;
25612 	return (mp1);
25613 #undef rptr
25614 }
25615 
25616 /*
25617  * Finish the outbound IPsec processing for an IPv6 packet. This function
25618  * is called from ipsec_out_process() if the IPsec packet was processed
25619  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25620  * asynchronously.
25621  */
25622 void
25623 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25624     ire_t *ire_arg)
25625 {
25626 	in6_addr_t *v6dstp;
25627 	ire_t *ire;
25628 	mblk_t *mp;
25629 	ip6_t *ip6h1;
25630 	uint_t	ill_index;
25631 	ipsec_out_t *io;
25632 	boolean_t hwaccel;
25633 	uint32_t flags = IP6_NO_IPPOLICY;
25634 	int match_flags;
25635 	zoneid_t zoneid;
25636 	boolean_t ill_need_rele = B_FALSE;
25637 	boolean_t ire_need_rele = B_FALSE;
25638 	ip_stack_t	*ipst;
25639 
25640 	mp = ipsec_mp->b_cont;
25641 	ip6h1 = (ip6_t *)mp->b_rptr;
25642 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25643 	ASSERT(io->ipsec_out_ns != NULL);
25644 	ipst = io->ipsec_out_ns->netstack_ip;
25645 	ill_index = io->ipsec_out_ill_index;
25646 	if (io->ipsec_out_reachable) {
25647 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25648 	}
25649 	hwaccel = io->ipsec_out_accelerated;
25650 	zoneid = io->ipsec_out_zoneid;
25651 	ASSERT(zoneid != ALL_ZONES);
25652 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25653 	/* Multicast addresses should have non-zero ill_index. */
25654 	v6dstp = &ip6h->ip6_dst;
25655 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25656 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25657 
25658 	if (ill == NULL && ill_index != 0) {
25659 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25660 		/* Failure case frees things for us. */
25661 		if (ill == NULL)
25662 			return;
25663 
25664 		ill_need_rele = B_TRUE;
25665 	}
25666 	ASSERT(mp != NULL);
25667 
25668 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25669 		boolean_t unspec_src;
25670 		ipif_t	*ipif;
25671 
25672 		/*
25673 		 * Use the ill_index to get the right ill.
25674 		 */
25675 		unspec_src = io->ipsec_out_unspec_src;
25676 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25677 		if (ipif == NULL) {
25678 			if (ill_need_rele)
25679 				ill_refrele(ill);
25680 			freemsg(ipsec_mp);
25681 			return;
25682 		}
25683 
25684 		if (ire_arg != NULL) {
25685 			ire = ire_arg;
25686 		} else {
25687 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25688 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25689 			ire_need_rele = B_TRUE;
25690 		}
25691 		if (ire != NULL) {
25692 			ipif_refrele(ipif);
25693 			/*
25694 			 * XXX Do the multicast forwarding now, as the IPsec
25695 			 * processing has been done.
25696 			 */
25697 			goto send;
25698 		}
25699 
25700 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25701 		mp->b_prev = NULL;
25702 		mp->b_next = NULL;
25703 
25704 		/*
25705 		 * If the IPsec packet was processed asynchronously,
25706 		 * drop it now.
25707 		 */
25708 		if (q == NULL) {
25709 			if (ill_need_rele)
25710 				ill_refrele(ill);
25711 			freemsg(ipsec_mp);
25712 			return;
25713 		}
25714 
25715 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25716 		    unspec_src, zoneid);
25717 		ipif_refrele(ipif);
25718 	} else {
25719 		if (ire_arg != NULL) {
25720 			ire = ire_arg;
25721 		} else {
25722 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25723 			ire_need_rele = B_TRUE;
25724 		}
25725 		if (ire != NULL)
25726 			goto send;
25727 		/*
25728 		 * ire disappeared underneath.
25729 		 *
25730 		 * What we need to do here is the ip_newroute
25731 		 * logic to get the ire without doing the IPsec
25732 		 * processing. Follow the same old path. But this
25733 		 * time, ip_wput or ire_add_then_send will call us
25734 		 * directly as all the IPsec operations are done.
25735 		 */
25736 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25737 		mp->b_prev = NULL;
25738 		mp->b_next = NULL;
25739 
25740 		/*
25741 		 * If the IPsec packet was processed asynchronously,
25742 		 * drop it now.
25743 		 */
25744 		if (q == NULL) {
25745 			if (ill_need_rele)
25746 				ill_refrele(ill);
25747 			freemsg(ipsec_mp);
25748 			return;
25749 		}
25750 
25751 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25752 		    zoneid, ipst);
25753 	}
25754 	if (ill != NULL && ill_need_rele)
25755 		ill_refrele(ill);
25756 	return;
25757 send:
25758 	if (ill != NULL && ill_need_rele)
25759 		ill_refrele(ill);
25760 
25761 	/* Local delivery */
25762 	if (ire->ire_stq == NULL) {
25763 		ill_t	*out_ill;
25764 		ASSERT(q != NULL);
25765 
25766 		/* PFHooks: LOOPBACK_OUT */
25767 		out_ill = ire_to_ill(ire);
25768 
25769 		/*
25770 		 * DTrace this as ip:::send.  A blocked packet will fire the
25771 		 * send probe, but not the receive probe.
25772 		 */
25773 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25774 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25775 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25776 
25777 		DTRACE_PROBE4(ip6__loopback__out__start,
25778 		    ill_t *, NULL, ill_t *, out_ill,
25779 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25780 
25781 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25782 		    ipst->ips_ipv6firewall_loopback_out,
25783 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25784 
25785 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25786 
25787 		if (ipsec_mp != NULL) {
25788 			ip_wput_local_v6(RD(q), out_ill,
25789 			    ip6h, ipsec_mp, ire, 0, zoneid);
25790 		}
25791 		if (ire_need_rele)
25792 			ire_refrele(ire);
25793 		return;
25794 	}
25795 	/*
25796 	 * Everything is done. Send it out on the wire.
25797 	 * We force the insertion of a fragment header using the
25798 	 * IPH_FRAG_HDR flag in two cases:
25799 	 * - after reception of an ICMPv6 "packet too big" message
25800 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25801 	 * - for multirouted IPv6 packets, so that the receiver can
25802 	 *   discard duplicates according to their fragment identifier
25803 	 */
25804 	/* XXX fix flow control problems. */
25805 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25806 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25807 		if (hwaccel) {
25808 			/*
25809 			 * hardware acceleration does not handle these
25810 			 * "slow path" cases.
25811 			 */
25812 			/* IPsec KSTATS: should bump bean counter here. */
25813 			if (ire_need_rele)
25814 				ire_refrele(ire);
25815 			freemsg(ipsec_mp);
25816 			return;
25817 		}
25818 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25819 		    (mp->b_cont ? msgdsize(mp) :
25820 		    mp->b_wptr - (uchar_t *)ip6h)) {
25821 			/* IPsec KSTATS: should bump bean counter here. */
25822 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25823 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25824 			    msgdsize(mp)));
25825 			if (ire_need_rele)
25826 				ire_refrele(ire);
25827 			freemsg(ipsec_mp);
25828 			return;
25829 		}
25830 		ASSERT(mp->b_prev == NULL);
25831 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25832 		    ntohs(ip6h->ip6_plen) +
25833 		    IPV6_HDR_LEN, ire->ire_max_frag));
25834 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25835 		    ire->ire_max_frag);
25836 	} else {
25837 		UPDATE_OB_PKT_COUNT(ire);
25838 		ire->ire_last_used_time = lbolt;
25839 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25840 	}
25841 	if (ire_need_rele)
25842 		ire_refrele(ire);
25843 	freeb(ipsec_mp);
25844 }
25845 
25846 void
25847 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25848 {
25849 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25850 	da_ipsec_t *hada;	/* data attributes */
25851 	ill_t *ill = (ill_t *)q->q_ptr;
25852 
25853 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25854 
25855 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25856 		/* IPsec KSTATS: Bump lose counter here! */
25857 		freemsg(mp);
25858 		return;
25859 	}
25860 
25861 	/*
25862 	 * It's an IPsec packet that must be
25863 	 * accelerated by the Provider, and the
25864 	 * outbound ill is IPsec acceleration capable.
25865 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25866 	 * to the ill.
25867 	 * IPsec KSTATS: should bump packet counter here.
25868 	 */
25869 
25870 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25871 	if (hada_mp == NULL) {
25872 		/* IPsec KSTATS: should bump packet counter here. */
25873 		freemsg(mp);
25874 		return;
25875 	}
25876 
25877 	hada_mp->b_datap->db_type = M_CTL;
25878 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25879 	hada_mp->b_cont = mp;
25880 
25881 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25882 	bzero(hada, sizeof (da_ipsec_t));
25883 	hada->da_type = IPHADA_M_CTL;
25884 
25885 	putnext(q, hada_mp);
25886 }
25887 
25888 /*
25889  * Finish the outbound IPsec processing. This function is called from
25890  * ipsec_out_process() if the IPsec packet was processed
25891  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25892  * asynchronously.
25893  */
25894 void
25895 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25896     ire_t *ire_arg)
25897 {
25898 	uint32_t v_hlen_tos_len;
25899 	ipaddr_t	dst;
25900 	ipif_t	*ipif = NULL;
25901 	ire_t *ire;
25902 	ire_t *ire1 = NULL;
25903 	mblk_t *next_mp = NULL;
25904 	uint32_t max_frag;
25905 	boolean_t multirt_send = B_FALSE;
25906 	mblk_t *mp;
25907 	ipha_t *ipha1;
25908 	uint_t	ill_index;
25909 	ipsec_out_t *io;
25910 	int match_flags;
25911 	irb_t *irb = NULL;
25912 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25913 	zoneid_t zoneid;
25914 	ipxmit_state_t	pktxmit_state;
25915 	ip_stack_t	*ipst;
25916 
25917 #ifdef	_BIG_ENDIAN
25918 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25919 #else
25920 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25921 #endif
25922 
25923 	mp = ipsec_mp->b_cont;
25924 	ipha1 = (ipha_t *)mp->b_rptr;
25925 	ASSERT(mp != NULL);
25926 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25927 	dst = ipha->ipha_dst;
25928 
25929 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25930 	ill_index = io->ipsec_out_ill_index;
25931 	zoneid = io->ipsec_out_zoneid;
25932 	ASSERT(zoneid != ALL_ZONES);
25933 	ipst = io->ipsec_out_ns->netstack_ip;
25934 	ASSERT(io->ipsec_out_ns != NULL);
25935 
25936 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25937 	if (ill == NULL && ill_index != 0) {
25938 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25939 		/* Failure case frees things for us. */
25940 		if (ill == NULL)
25941 			return;
25942 
25943 		ill_need_rele = B_TRUE;
25944 	}
25945 
25946 	if (CLASSD(dst)) {
25947 		boolean_t conn_dontroute;
25948 		/*
25949 		 * Use the ill_index to get the right ipif.
25950 		 */
25951 		conn_dontroute = io->ipsec_out_dontroute;
25952 		if (ill_index == 0)
25953 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25954 		else
25955 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25956 		if (ipif == NULL) {
25957 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25958 			    " multicast\n"));
25959 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25960 			freemsg(ipsec_mp);
25961 			goto done;
25962 		}
25963 		/*
25964 		 * ipha_src has already been intialized with the
25965 		 * value of the ipif in ip_wput. All we need now is
25966 		 * an ire to send this downstream.
25967 		 */
25968 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25969 		    msg_getlabel(mp), match_flags, ipst);
25970 		if (ire != NULL) {
25971 			ill_t *ill1;
25972 			/*
25973 			 * Do the multicast forwarding now, as the IPsec
25974 			 * processing has been done.
25975 			 */
25976 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25977 			    (ill1 = ire_to_ill(ire))) {
25978 				if (ip_mforward(ill1, ipha, mp)) {
25979 					freemsg(ipsec_mp);
25980 					ip1dbg(("ip_wput_ipsec_out: mforward "
25981 					    "failed\n"));
25982 					ire_refrele(ire);
25983 					goto done;
25984 				}
25985 			}
25986 			goto send;
25987 		}
25988 
25989 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25990 		mp->b_prev = NULL;
25991 		mp->b_next = NULL;
25992 
25993 		/*
25994 		 * If the IPsec packet was processed asynchronously,
25995 		 * drop it now.
25996 		 */
25997 		if (q == NULL) {
25998 			freemsg(ipsec_mp);
25999 			goto done;
26000 		}
26001 
26002 		/*
26003 		 * We may be using a wrong ipif to create the ire.
26004 		 * But it is okay as the source address is assigned
26005 		 * for the packet already. Next outbound packet would
26006 		 * create the IRE with the right IPIF in ip_wput.
26007 		 *
26008 		 * Also handle RTF_MULTIRT routes.
26009 		 */
26010 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26011 		    zoneid, &zero_info);
26012 	} else {
26013 		if (ire_arg != NULL) {
26014 			ire = ire_arg;
26015 			ire_need_rele = B_FALSE;
26016 		} else {
26017 			ire = ire_cache_lookup(dst, zoneid,
26018 			    msg_getlabel(mp), ipst);
26019 		}
26020 		if (ire != NULL) {
26021 			goto send;
26022 		}
26023 
26024 		/*
26025 		 * ire disappeared underneath.
26026 		 *
26027 		 * What we need to do here is the ip_newroute
26028 		 * logic to get the ire without doing the IPsec
26029 		 * processing. Follow the same old path. But this
26030 		 * time, ip_wput or ire_add_then_put will call us
26031 		 * directly as all the IPsec operations are done.
26032 		 */
26033 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26034 		mp->b_prev = NULL;
26035 		mp->b_next = NULL;
26036 
26037 		/*
26038 		 * If the IPsec packet was processed asynchronously,
26039 		 * drop it now.
26040 		 */
26041 		if (q == NULL) {
26042 			freemsg(ipsec_mp);
26043 			goto done;
26044 		}
26045 
26046 		/*
26047 		 * Since we're going through ip_newroute() again, we
26048 		 * need to make sure we don't:
26049 		 *
26050 		 *	1.) Trigger the ASSERT() with the ipha_ident
26051 		 *	    overloading.
26052 		 *	2.) Redo transport-layer checksumming, since we've
26053 		 *	    already done all that to get this far.
26054 		 *
26055 		 * The easiest way not do either of the above is to set
26056 		 * the ipha_ident field to IP_HDR_INCLUDED.
26057 		 */
26058 		ipha->ipha_ident = IP_HDR_INCLUDED;
26059 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26060 		    zoneid, ipst);
26061 	}
26062 	goto done;
26063 send:
26064 	if (ire->ire_stq == NULL) {
26065 		ill_t	*out_ill;
26066 		/*
26067 		 * Loopbacks go through ip_wput_local except for one case.
26068 		 * We come here if we generate a icmp_frag_needed message
26069 		 * after IPsec processing is over. When this function calls
26070 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26071 		 * icmp_frag_needed. The message generated comes back here
26072 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26073 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26074 		 * source address as it is usually set in ip_wput_ire. As
26075 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26076 		 * and we end up here. We can't enter ip_wput_ire once the
26077 		 * IPsec processing is over and hence we need to do it here.
26078 		 */
26079 		ASSERT(q != NULL);
26080 		UPDATE_OB_PKT_COUNT(ire);
26081 		ire->ire_last_used_time = lbolt;
26082 		if (ipha->ipha_src == 0)
26083 			ipha->ipha_src = ire->ire_src_addr;
26084 
26085 		/* PFHooks: LOOPBACK_OUT */
26086 		out_ill = ire_to_ill(ire);
26087 
26088 		/*
26089 		 * DTrace this as ip:::send.  A blocked packet will fire the
26090 		 * send probe, but not the receive probe.
26091 		 */
26092 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26093 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26094 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26095 
26096 		DTRACE_PROBE4(ip4__loopback__out__start,
26097 		    ill_t *, NULL, ill_t *, out_ill,
26098 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26099 
26100 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26101 		    ipst->ips_ipv4firewall_loopback_out,
26102 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26103 
26104 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26105 
26106 		if (ipsec_mp != NULL)
26107 			ip_wput_local(RD(q), out_ill,
26108 			    ipha, ipsec_mp, ire, 0, zoneid);
26109 		if (ire_need_rele)
26110 			ire_refrele(ire);
26111 		goto done;
26112 	}
26113 
26114 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26115 		/*
26116 		 * We are through with IPsec processing.
26117 		 * Fragment this and send it on the wire.
26118 		 */
26119 		if (io->ipsec_out_accelerated) {
26120 			/*
26121 			 * The packet has been accelerated but must
26122 			 * be fragmented. This should not happen
26123 			 * since AH and ESP must not accelerate
26124 			 * packets that need fragmentation, however
26125 			 * the configuration could have changed
26126 			 * since the AH or ESP processing.
26127 			 * Drop packet.
26128 			 * IPsec KSTATS: bump bean counter here.
26129 			 */
26130 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26131 			    "fragmented accelerated packet!\n"));
26132 			freemsg(ipsec_mp);
26133 		} else {
26134 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26135 			    zoneid, ipst, NULL);
26136 		}
26137 		if (ire_need_rele)
26138 			ire_refrele(ire);
26139 		goto done;
26140 	}
26141 
26142 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26143 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26144 	    (void *)ire->ire_ipif, (void *)ipif));
26145 
26146 	/*
26147 	 * Multiroute the secured packet.
26148 	 */
26149 	if (ire->ire_flags & RTF_MULTIRT) {
26150 		ire_t *first_ire;
26151 		irb = ire->ire_bucket;
26152 		ASSERT(irb != NULL);
26153 		/*
26154 		 * This ire has been looked up as the one that
26155 		 * goes through the given ipif;
26156 		 * make sure we do not omit any other multiroute ire
26157 		 * that may be present in the bucket before this one.
26158 		 */
26159 		IRB_REFHOLD(irb);
26160 		for (first_ire = irb->irb_ire;
26161 		    first_ire != NULL;
26162 		    first_ire = first_ire->ire_next) {
26163 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26164 			    (first_ire->ire_addr == ire->ire_addr) &&
26165 			    !(first_ire->ire_marks &
26166 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26167 				break;
26168 		}
26169 
26170 		if ((first_ire != NULL) && (first_ire != ire)) {
26171 			/*
26172 			 * Don't change the ire if the packet must
26173 			 * be fragmented if sent via this new one.
26174 			 */
26175 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26176 				IRE_REFHOLD(first_ire);
26177 				if (ire_need_rele)
26178 					ire_refrele(ire);
26179 				else
26180 					ire_need_rele = B_TRUE;
26181 				ire = first_ire;
26182 			}
26183 		}
26184 		IRB_REFRELE(irb);
26185 
26186 		multirt_send = B_TRUE;
26187 		max_frag = ire->ire_max_frag;
26188 	}
26189 
26190 	/*
26191 	 * In most cases, the emission loop below is entered only once.
26192 	 * Only in the case where the ire holds the RTF_MULTIRT
26193 	 * flag, we loop to process all RTF_MULTIRT ires in the
26194 	 * bucket, and send the packet through all crossed
26195 	 * RTF_MULTIRT routes.
26196 	 */
26197 	do {
26198 		if (multirt_send) {
26199 			/*
26200 			 * ire1 holds here the next ire to process in the
26201 			 * bucket. If multirouting is expected,
26202 			 * any non-RTF_MULTIRT ire that has the
26203 			 * right destination address is ignored.
26204 			 */
26205 			ASSERT(irb != NULL);
26206 			IRB_REFHOLD(irb);
26207 			for (ire1 = ire->ire_next;
26208 			    ire1 != NULL;
26209 			    ire1 = ire1->ire_next) {
26210 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26211 					continue;
26212 				if (ire1->ire_addr != ire->ire_addr)
26213 					continue;
26214 				if (ire1->ire_marks &
26215 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26216 					continue;
26217 				/* No loopback here */
26218 				if (ire1->ire_stq == NULL)
26219 					continue;
26220 				/*
26221 				 * Ensure we do not exceed the MTU
26222 				 * of the next route.
26223 				 */
26224 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26225 					ip_multirt_bad_mtu(ire1, max_frag);
26226 					continue;
26227 				}
26228 
26229 				IRE_REFHOLD(ire1);
26230 				break;
26231 			}
26232 			IRB_REFRELE(irb);
26233 			if (ire1 != NULL) {
26234 				/*
26235 				 * We are in a multiple send case, need to
26236 				 * make a copy of the packet.
26237 				 */
26238 				next_mp = copymsg(ipsec_mp);
26239 				if (next_mp == NULL) {
26240 					ire_refrele(ire1);
26241 					ire1 = NULL;
26242 				}
26243 			}
26244 		}
26245 		/*
26246 		 * Everything is done. Send it out on the wire
26247 		 *
26248 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26249 		 * either send it on the wire or, in the case of
26250 		 * HW acceleration, call ipsec_hw_putnext.
26251 		 */
26252 		if (ire->ire_nce &&
26253 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26254 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26255 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26256 			/*
26257 			 * If ire's link-layer is unresolved (this
26258 			 * would only happen if the incomplete ire
26259 			 * was added to cachetable via forwarding path)
26260 			 * don't bother going to ip_xmit_v4. Just drop the
26261 			 * packet.
26262 			 * There is a slight risk here, in that, if we
26263 			 * have the forwarding path create an incomplete
26264 			 * IRE, then until the IRE is completed, any
26265 			 * transmitted IPsec packets will be dropped
26266 			 * instead of being queued waiting for resolution.
26267 			 *
26268 			 * But the likelihood of a forwarding packet and a wput
26269 			 * packet sending to the same dst at the same time
26270 			 * and there not yet be an ARP entry for it is small.
26271 			 * Furthermore, if this actually happens, it might
26272 			 * be likely that wput would generate multiple
26273 			 * packets (and forwarding would also have a train
26274 			 * of packets) for that destination. If this is
26275 			 * the case, some of them would have been dropped
26276 			 * anyway, since ARP only queues a few packets while
26277 			 * waiting for resolution
26278 			 *
26279 			 * NOTE: We should really call ip_xmit_v4,
26280 			 * and let it queue the packet and send the
26281 			 * ARP query and have ARP come back thus:
26282 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26283 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26284 			 * hw accel work. But it's too complex to get
26285 			 * the IPsec hw  acceleration approach to fit
26286 			 * well with ip_xmit_v4 doing ARP without
26287 			 * doing IPsec simplification. For now, we just
26288 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26289 			 * that we can continue with the send on the next
26290 			 * attempt.
26291 			 *
26292 			 * XXX THis should be revisited, when
26293 			 * the IPsec/IP interaction is cleaned up
26294 			 */
26295 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26296 			    " - dropping packet\n"));
26297 			freemsg(ipsec_mp);
26298 			/*
26299 			 * Call ip_xmit_v4() to trigger ARP query
26300 			 * in case the nce_state is ND_INITIAL
26301 			 */
26302 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26303 			goto drop_pkt;
26304 		}
26305 
26306 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26307 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26308 		    mblk_t *, ipsec_mp);
26309 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26310 		    ipst->ips_ipv4firewall_physical_out, NULL,
26311 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26312 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26313 		if (ipsec_mp == NULL)
26314 			goto drop_pkt;
26315 
26316 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26317 		pktxmit_state = ip_xmit_v4(mp, ire,
26318 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26319 
26320 		if ((pktxmit_state ==  SEND_FAILED) ||
26321 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26322 
26323 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26324 drop_pkt:
26325 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26326 			    ipIfStatsOutDiscards);
26327 			if (ire_need_rele)
26328 				ire_refrele(ire);
26329 			if (ire1 != NULL) {
26330 				ire_refrele(ire1);
26331 				freemsg(next_mp);
26332 			}
26333 			goto done;
26334 		}
26335 
26336 		freeb(ipsec_mp);
26337 		if (ire_need_rele)
26338 			ire_refrele(ire);
26339 
26340 		if (ire1 != NULL) {
26341 			ire = ire1;
26342 			ire_need_rele = B_TRUE;
26343 			ASSERT(next_mp);
26344 			ipsec_mp = next_mp;
26345 			mp = ipsec_mp->b_cont;
26346 			ire1 = NULL;
26347 			next_mp = NULL;
26348 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26349 		} else {
26350 			multirt_send = B_FALSE;
26351 		}
26352 	} while (multirt_send);
26353 done:
26354 	if (ill != NULL && ill_need_rele)
26355 		ill_refrele(ill);
26356 	if (ipif != NULL)
26357 		ipif_refrele(ipif);
26358 }
26359 
26360 /*
26361  * Get the ill corresponding to the specified ire, and compare its
26362  * capabilities with the protocol and algorithms specified by the
26363  * the SA obtained from ipsec_out. If they match, annotate the
26364  * ipsec_out structure to indicate that the packet needs acceleration.
26365  *
26366  *
26367  * A packet is eligible for outbound hardware acceleration if the
26368  * following conditions are satisfied:
26369  *
26370  * 1. the packet will not be fragmented
26371  * 2. the provider supports the algorithm
26372  * 3. there is no pending control message being exchanged
26373  * 4. snoop is not attached
26374  * 5. the destination address is not a broadcast or multicast address.
26375  *
26376  * Rationale:
26377  *	- Hardware drivers do not support fragmentation with
26378  *	  the current interface.
26379  *	- snoop, multicast, and broadcast may result in exposure of
26380  *	  a cleartext datagram.
26381  * We check all five of these conditions here.
26382  *
26383  * XXX would like to nuke "ire_t *" parameter here; problem is that
26384  * IRE is only way to figure out if a v4 address is a broadcast and
26385  * thus ineligible for acceleration...
26386  */
26387 static void
26388 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26389 {
26390 	ipsec_out_t *io;
26391 	mblk_t *data_mp;
26392 	uint_t plen, overhead;
26393 	ip_stack_t	*ipst;
26394 
26395 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26396 		return;
26397 
26398 	if (ill == NULL)
26399 		return;
26400 	ipst = ill->ill_ipst;
26401 	/*
26402 	 * Destination address is a broadcast or multicast.  Punt.
26403 	 */
26404 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26405 	    IRE_LOCAL)))
26406 		return;
26407 
26408 	data_mp = ipsec_mp->b_cont;
26409 
26410 	if (ill->ill_isv6) {
26411 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26412 
26413 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26414 			return;
26415 
26416 		plen = ip6h->ip6_plen;
26417 	} else {
26418 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26419 
26420 		if (CLASSD(ipha->ipha_dst))
26421 			return;
26422 
26423 		plen = ipha->ipha_length;
26424 	}
26425 	/*
26426 	 * Is there a pending DLPI control message being exchanged
26427 	 * between IP/IPsec and the DLS Provider? If there is, it
26428 	 * could be a SADB update, and the state of the DLS Provider
26429 	 * SADB might not be in sync with the SADB maintained by
26430 	 * IPsec. To avoid dropping packets or using the wrong keying
26431 	 * material, we do not accelerate this packet.
26432 	 */
26433 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26434 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26435 		    "ill_dlpi_pending! don't accelerate packet\n"));
26436 		return;
26437 	}
26438 
26439 	/*
26440 	 * Is the Provider in promiscous mode? If it does, we don't
26441 	 * accelerate the packet since it will bounce back up to the
26442 	 * listeners in the clear.
26443 	 */
26444 	if (ill->ill_promisc_on_phys) {
26445 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26446 		    "ill in promiscous mode, don't accelerate packet\n"));
26447 		return;
26448 	}
26449 
26450 	/*
26451 	 * Will the packet require fragmentation?
26452 	 */
26453 
26454 	/*
26455 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26456 	 * as is used elsewhere.
26457 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26458 	 *	+ 2-byte trailer
26459 	 */
26460 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26461 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26462 
26463 	if ((plen + overhead) > ill->ill_max_mtu)
26464 		return;
26465 
26466 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26467 
26468 	/*
26469 	 * Can the ill accelerate this IPsec protocol and algorithm
26470 	 * specified by the SA?
26471 	 */
26472 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26473 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26474 		return;
26475 	}
26476 
26477 	/*
26478 	 * Tell AH or ESP that the outbound ill is capable of
26479 	 * accelerating this packet.
26480 	 */
26481 	io->ipsec_out_is_capab_ill = B_TRUE;
26482 }
26483 
26484 /*
26485  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26486  *
26487  * If this function returns B_TRUE, the requested SA's have been filled
26488  * into the ipsec_out_*_sa pointers.
26489  *
26490  * If the function returns B_FALSE, the packet has been "consumed", most
26491  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26492  *
26493  * The SA references created by the protocol-specific "select"
26494  * function will be released when the ipsec_mp is freed, thanks to the
26495  * ipsec_out_free destructor -- see spd.c.
26496  */
26497 static boolean_t
26498 ipsec_out_select_sa(mblk_t *ipsec_mp)
26499 {
26500 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26501 	ipsec_out_t *io;
26502 	ipsec_policy_t *pp;
26503 	ipsec_action_t *ap;
26504 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26505 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26506 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26507 
26508 	if (!io->ipsec_out_secure) {
26509 		/*
26510 		 * We came here by mistake.
26511 		 * Don't bother with ipsec processing
26512 		 * We should "discourage" this path in the future.
26513 		 */
26514 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26515 		return (B_FALSE);
26516 	}
26517 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26518 	ASSERT((io->ipsec_out_policy != NULL) ||
26519 	    (io->ipsec_out_act != NULL));
26520 
26521 	ASSERT(io->ipsec_out_failed == B_FALSE);
26522 
26523 	/*
26524 	 * IPsec processing has started.
26525 	 */
26526 	io->ipsec_out_proc_begin = B_TRUE;
26527 	ap = io->ipsec_out_act;
26528 	if (ap == NULL) {
26529 		pp = io->ipsec_out_policy;
26530 		ASSERT(pp != NULL);
26531 		ap = pp->ipsp_act;
26532 		ASSERT(ap != NULL);
26533 	}
26534 
26535 	/*
26536 	 * We have an action.  now, let's select SA's.
26537 	 * (In the future, we can cache this in the conn_t..)
26538 	 */
26539 	if (ap->ipa_want_esp) {
26540 		if (io->ipsec_out_esp_sa == NULL) {
26541 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26542 			    IPPROTO_ESP);
26543 		}
26544 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26545 	}
26546 
26547 	if (ap->ipa_want_ah) {
26548 		if (io->ipsec_out_ah_sa == NULL) {
26549 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26550 			    IPPROTO_AH);
26551 		}
26552 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26553 		/*
26554 		 * The ESP and AH processing order needs to be preserved
26555 		 * when both protocols are required (ESP should be applied
26556 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26557 		 * when both ESP and AH are required, and an AH ACQUIRE
26558 		 * is needed.
26559 		 */
26560 		if (ap->ipa_want_esp && need_ah_acquire)
26561 			need_esp_acquire = B_TRUE;
26562 	}
26563 
26564 	/*
26565 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26566 	 * Release SAs that got referenced, but will not be used until we
26567 	 * acquire _all_ of the SAs we need.
26568 	 */
26569 	if (need_ah_acquire || need_esp_acquire) {
26570 		if (io->ipsec_out_ah_sa != NULL) {
26571 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26572 			io->ipsec_out_ah_sa = NULL;
26573 		}
26574 		if (io->ipsec_out_esp_sa != NULL) {
26575 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26576 			io->ipsec_out_esp_sa = NULL;
26577 		}
26578 
26579 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26580 		return (B_FALSE);
26581 	}
26582 
26583 	return (B_TRUE);
26584 }
26585 
26586 /*
26587  * Process an IPSEC_OUT message and see what you can
26588  * do with it.
26589  * IPQoS Notes:
26590  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26591  * IPsec.
26592  * XXX would like to nuke ire_t.
26593  * XXX ill_index better be "real"
26594  */
26595 void
26596 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26597 {
26598 	ipsec_out_t *io;
26599 	ipsec_policy_t *pp;
26600 	ipsec_action_t *ap;
26601 	ipha_t *ipha;
26602 	ip6_t *ip6h;
26603 	mblk_t *mp;
26604 	ill_t *ill;
26605 	zoneid_t zoneid;
26606 	ipsec_status_t ipsec_rc;
26607 	boolean_t ill_need_rele = B_FALSE;
26608 	ip_stack_t	*ipst;
26609 	ipsec_stack_t	*ipss;
26610 
26611 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26612 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26613 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26614 	ipst = io->ipsec_out_ns->netstack_ip;
26615 	mp = ipsec_mp->b_cont;
26616 
26617 	/*
26618 	 * Initiate IPPF processing. We do it here to account for packets
26619 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26620 	 * We can check for ipsec_out_proc_begin even for such packets, as
26621 	 * they will always be false (asserted below).
26622 	 */
26623 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26624 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26625 		    io->ipsec_out_ill_index : ill_index);
26626 		if (mp == NULL) {
26627 			ip2dbg(("ipsec_out_process: packet dropped "\
26628 			    "during IPPF processing\n"));
26629 			freeb(ipsec_mp);
26630 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26631 			return;
26632 		}
26633 	}
26634 
26635 	if (!io->ipsec_out_secure) {
26636 		/*
26637 		 * We came here by mistake.
26638 		 * Don't bother with ipsec processing
26639 		 * Should "discourage" this path in the future.
26640 		 */
26641 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26642 		goto done;
26643 	}
26644 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26645 	ASSERT((io->ipsec_out_policy != NULL) ||
26646 	    (io->ipsec_out_act != NULL));
26647 	ASSERT(io->ipsec_out_failed == B_FALSE);
26648 
26649 	ipss = ipst->ips_netstack->netstack_ipsec;
26650 	if (!ipsec_loaded(ipss)) {
26651 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26652 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26653 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26654 		} else {
26655 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26656 		}
26657 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26658 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26659 		    &ipss->ipsec_dropper);
26660 		return;
26661 	}
26662 
26663 	/*
26664 	 * IPsec processing has started.
26665 	 */
26666 	io->ipsec_out_proc_begin = B_TRUE;
26667 	ap = io->ipsec_out_act;
26668 	if (ap == NULL) {
26669 		pp = io->ipsec_out_policy;
26670 		ASSERT(pp != NULL);
26671 		ap = pp->ipsp_act;
26672 		ASSERT(ap != NULL);
26673 	}
26674 
26675 	/*
26676 	 * Save the outbound ill index. When the packet comes back
26677 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26678 	 * before sending it the accelerated packet.
26679 	 */
26680 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26681 		ill = ire_to_ill(ire);
26682 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26683 	}
26684 
26685 	/*
26686 	 * The order of processing is first insert a IP header if needed.
26687 	 * Then insert the ESP header and then the AH header.
26688 	 */
26689 	if ((io->ipsec_out_se_done == B_FALSE) &&
26690 	    (ap->ipa_want_se)) {
26691 		/*
26692 		 * First get the outer IP header before sending
26693 		 * it to ESP.
26694 		 */
26695 		ipha_t *oipha, *iipha;
26696 		mblk_t *outer_mp, *inner_mp;
26697 
26698 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26699 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26700 			    "ipsec_out_process: "
26701 			    "Self-Encapsulation failed: Out of memory\n");
26702 			freemsg(ipsec_mp);
26703 			if (ill != NULL) {
26704 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26705 			} else {
26706 				BUMP_MIB(&ipst->ips_ip_mib,
26707 				    ipIfStatsOutDiscards);
26708 			}
26709 			return;
26710 		}
26711 		inner_mp = ipsec_mp->b_cont;
26712 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26713 		oipha = (ipha_t *)outer_mp->b_rptr;
26714 		iipha = (ipha_t *)inner_mp->b_rptr;
26715 		*oipha = *iipha;
26716 		outer_mp->b_wptr += sizeof (ipha_t);
26717 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26718 		    sizeof (ipha_t));
26719 		oipha->ipha_protocol = IPPROTO_ENCAP;
26720 		oipha->ipha_version_and_hdr_length =
26721 		    IP_SIMPLE_HDR_VERSION;
26722 		oipha->ipha_hdr_checksum = 0;
26723 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26724 		outer_mp->b_cont = inner_mp;
26725 		ipsec_mp->b_cont = outer_mp;
26726 
26727 		io->ipsec_out_se_done = B_TRUE;
26728 		io->ipsec_out_tunnel = B_TRUE;
26729 	}
26730 
26731 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26732 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26733 	    !ipsec_out_select_sa(ipsec_mp))
26734 		return;
26735 
26736 	/*
26737 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26738 	 * to do the heavy lifting.
26739 	 */
26740 	zoneid = io->ipsec_out_zoneid;
26741 	ASSERT(zoneid != ALL_ZONES);
26742 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26743 		ASSERT(io->ipsec_out_esp_sa != NULL);
26744 		io->ipsec_out_esp_done = B_TRUE;
26745 		/*
26746 		 * Note that since hw accel can only apply one transform,
26747 		 * not two, we skip hw accel for ESP if we also have AH
26748 		 * This is an design limitation of the interface
26749 		 * which should be revisited.
26750 		 */
26751 		ASSERT(ire != NULL);
26752 		if (io->ipsec_out_ah_sa == NULL) {
26753 			ill = (ill_t *)ire->ire_stq->q_ptr;
26754 			ipsec_out_is_accelerated(ipsec_mp,
26755 			    io->ipsec_out_esp_sa, ill, ire);
26756 		}
26757 
26758 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26759 		switch (ipsec_rc) {
26760 		case IPSEC_STATUS_SUCCESS:
26761 			break;
26762 		case IPSEC_STATUS_FAILED:
26763 			if (ill != NULL) {
26764 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26765 			} else {
26766 				BUMP_MIB(&ipst->ips_ip_mib,
26767 				    ipIfStatsOutDiscards);
26768 			}
26769 			/* FALLTHRU */
26770 		case IPSEC_STATUS_PENDING:
26771 			return;
26772 		}
26773 	}
26774 
26775 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26776 		ASSERT(io->ipsec_out_ah_sa != NULL);
26777 		io->ipsec_out_ah_done = B_TRUE;
26778 		if (ire == NULL) {
26779 			int idx = io->ipsec_out_capab_ill_index;
26780 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26781 			    NULL, NULL, NULL, NULL, ipst);
26782 			ill_need_rele = B_TRUE;
26783 		} else {
26784 			ill = (ill_t *)ire->ire_stq->q_ptr;
26785 		}
26786 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26787 		    ire);
26788 
26789 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26790 		switch (ipsec_rc) {
26791 		case IPSEC_STATUS_SUCCESS:
26792 			break;
26793 		case IPSEC_STATUS_FAILED:
26794 			if (ill != NULL) {
26795 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26796 			} else {
26797 				BUMP_MIB(&ipst->ips_ip_mib,
26798 				    ipIfStatsOutDiscards);
26799 			}
26800 			/* FALLTHRU */
26801 		case IPSEC_STATUS_PENDING:
26802 			if (ill != NULL && ill_need_rele)
26803 				ill_refrele(ill);
26804 			return;
26805 		}
26806 	}
26807 	/*
26808 	 * We are done with IPsec processing. Send it over the wire.
26809 	 */
26810 done:
26811 	mp = ipsec_mp->b_cont;
26812 	ipha = (ipha_t *)mp->b_rptr;
26813 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26814 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26815 		    ire);
26816 	} else {
26817 		ip6h = (ip6_t *)ipha;
26818 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26819 		    ire);
26820 	}
26821 	if (ill != NULL && ill_need_rele)
26822 		ill_refrele(ill);
26823 }
26824 
26825 /* ARGSUSED */
26826 void
26827 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26828 {
26829 	opt_restart_t	*or;
26830 	int	err;
26831 	conn_t	*connp;
26832 	cred_t	*cr;
26833 
26834 	ASSERT(CONN_Q(q));
26835 	connp = Q_TO_CONN(q);
26836 
26837 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26838 	or = (opt_restart_t *)first_mp->b_rptr;
26839 	/*
26840 	 * We checked for a db_credp the first time svr4_optcom_req
26841 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26842 	 */
26843 	cr = msg_getcred(first_mp, NULL);
26844 	ASSERT(cr != NULL);
26845 
26846 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26847 		err = svr4_optcom_req(q, first_mp, cr,
26848 		    &ip_opt_obj, B_FALSE);
26849 	} else {
26850 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26851 		err = tpi_optcom_req(q, first_mp, cr,
26852 		    &ip_opt_obj, B_FALSE);
26853 	}
26854 	if (err != EINPROGRESS) {
26855 		/* operation is done */
26856 		CONN_OPER_PENDING_DONE(connp);
26857 	}
26858 }
26859 
26860 /*
26861  * ioctls that go through a down/up sequence may need to wait for the down
26862  * to complete. This involves waiting for the ire and ipif refcnts to go down
26863  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26864  */
26865 /* ARGSUSED */
26866 void
26867 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26868 {
26869 	struct iocblk *iocp;
26870 	mblk_t *mp1;
26871 	ip_ioctl_cmd_t *ipip;
26872 	int err;
26873 	sin_t	*sin;
26874 	struct lifreq *lifr;
26875 	struct ifreq *ifr;
26876 
26877 	iocp = (struct iocblk *)mp->b_rptr;
26878 	ASSERT(ipsq != NULL);
26879 	/* Existence of mp1 verified in ip_wput_nondata */
26880 	mp1 = mp->b_cont->b_cont;
26881 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26882 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26883 		/*
26884 		 * Special case where ipx_current_ipif is not set:
26885 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26886 		 * We are here as were not able to complete the operation in
26887 		 * ipif_set_values because we could not become exclusive on
26888 		 * the new ipsq.
26889 		 */
26890 		ill_t *ill = q->q_ptr;
26891 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26892 	}
26893 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26894 
26895 	if (ipip->ipi_cmd_type == IF_CMD) {
26896 		/* This a old style SIOC[GS]IF* command */
26897 		ifr = (struct ifreq *)mp1->b_rptr;
26898 		sin = (sin_t *)&ifr->ifr_addr;
26899 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26900 		/* This a new style SIOC[GS]LIF* command */
26901 		lifr = (struct lifreq *)mp1->b_rptr;
26902 		sin = (sin_t *)&lifr->lifr_addr;
26903 	} else {
26904 		sin = NULL;
26905 	}
26906 
26907 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26908 	    q, mp, ipip, mp1->b_rptr);
26909 
26910 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26911 }
26912 
26913 /*
26914  * ioctl processing
26915  *
26916  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26917  * the ioctl command in the ioctl tables, determines the copyin data size
26918  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26919  *
26920  * ioctl processing then continues when the M_IOCDATA makes its way down to
26921  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26922  * associated 'conn' is refheld till the end of the ioctl and the general
26923  * ioctl processing function ip_process_ioctl() is called to extract the
26924  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26925  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26926  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26927  * is used to extract the ioctl's arguments.
26928  *
26929  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26930  * so goes thru the serialization primitive ipsq_try_enter. Then the
26931  * appropriate function to handle the ioctl is called based on the entry in
26932  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26933  * which also refreleases the 'conn' that was refheld at the start of the
26934  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26935  *
26936  * Many exclusive ioctls go thru an internal down up sequence as part of
26937  * the operation. For example an attempt to change the IP address of an
26938  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26939  * does all the cleanup such as deleting all ires that use this address.
26940  * Then we need to wait till all references to the interface go away.
26941  */
26942 void
26943 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26944 {
26945 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26946 	ip_ioctl_cmd_t *ipip = arg;
26947 	ip_extract_func_t *extract_funcp;
26948 	cmd_info_t ci;
26949 	int err;
26950 	boolean_t entered_ipsq = B_FALSE;
26951 
26952 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26953 
26954 	if (ipip == NULL)
26955 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26956 
26957 	/*
26958 	 * SIOCLIFADDIF needs to go thru a special path since the
26959 	 * ill may not exist yet. This happens in the case of lo0
26960 	 * which is created using this ioctl.
26961 	 */
26962 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26963 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26964 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26965 		return;
26966 	}
26967 
26968 	ci.ci_ipif = NULL;
26969 	if (ipip->ipi_cmd_type == MISC_CMD) {
26970 		/*
26971 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26972 		 */
26973 		if (ipip->ipi_cmd == IF_UNITSEL) {
26974 			/* ioctl comes down the ill */
26975 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26976 			ipif_refhold(ci.ci_ipif);
26977 		}
26978 		err = 0;
26979 		ci.ci_sin = NULL;
26980 		ci.ci_sin6 = NULL;
26981 		ci.ci_lifr = NULL;
26982 	} else {
26983 		switch (ipip->ipi_cmd_type) {
26984 		case IF_CMD:
26985 		case LIF_CMD:
26986 			extract_funcp = ip_extract_lifreq;
26987 			break;
26988 
26989 		case ARP_CMD:
26990 		case XARP_CMD:
26991 			extract_funcp = ip_extract_arpreq;
26992 			break;
26993 
26994 		case TUN_CMD:
26995 			extract_funcp = ip_extract_tunreq;
26996 			break;
26997 
26998 		case MSFILT_CMD:
26999 			extract_funcp = ip_extract_msfilter;
27000 			break;
27001 
27002 		default:
27003 			ASSERT(0);
27004 		}
27005 
27006 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27007 		if (err != 0) {
27008 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27009 			return;
27010 		}
27011 
27012 		/*
27013 		 * All of the extraction functions return a refheld ipif.
27014 		 */
27015 		ASSERT(ci.ci_ipif != NULL);
27016 	}
27017 
27018 	if (!(ipip->ipi_flags & IPI_WR)) {
27019 		/*
27020 		 * A return value of EINPROGRESS means the ioctl is
27021 		 * either queued and waiting for some reason or has
27022 		 * already completed.
27023 		 */
27024 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27025 		    ci.ci_lifr);
27026 		if (ci.ci_ipif != NULL)
27027 			ipif_refrele(ci.ci_ipif);
27028 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27029 		return;
27030 	}
27031 
27032 	ASSERT(ci.ci_ipif != NULL);
27033 
27034 	/*
27035 	 * If ipsq is non-NULL, we are already being called exclusively.
27036 	 */
27037 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27038 	if (ipsq == NULL) {
27039 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27040 		    NEW_OP, B_TRUE);
27041 		if (ipsq == NULL) {
27042 			ipif_refrele(ci.ci_ipif);
27043 			return;
27044 		}
27045 		entered_ipsq = B_TRUE;
27046 	}
27047 
27048 	/*
27049 	 * Release the ipif so that ipif_down and friends that wait for
27050 	 * references to go away are not misled about the current ipif_refcnt
27051 	 * values. We are writer so we can access the ipif even after releasing
27052 	 * the ipif.
27053 	 */
27054 	ipif_refrele(ci.ci_ipif);
27055 
27056 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27057 
27058 	/*
27059 	 * A return value of EINPROGRESS means the ioctl is
27060 	 * either queued and waiting for some reason or has
27061 	 * already completed.
27062 	 */
27063 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27064 
27065 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27066 
27067 	if (entered_ipsq)
27068 		ipsq_exit(ipsq);
27069 }
27070 
27071 /*
27072  * Complete the ioctl. Typically ioctls use the mi package and need to
27073  * do mi_copyout/mi_copy_done.
27074  */
27075 void
27076 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27077 {
27078 	conn_t	*connp = NULL;
27079 
27080 	if (err == EINPROGRESS)
27081 		return;
27082 
27083 	if (CONN_Q(q)) {
27084 		connp = Q_TO_CONN(q);
27085 		ASSERT(connp->conn_ref >= 2);
27086 	}
27087 
27088 	switch (mode) {
27089 	case COPYOUT:
27090 		if (err == 0)
27091 			mi_copyout(q, mp);
27092 		else
27093 			mi_copy_done(q, mp, err);
27094 		break;
27095 
27096 	case NO_COPYOUT:
27097 		mi_copy_done(q, mp, err);
27098 		break;
27099 
27100 	default:
27101 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27102 		break;
27103 	}
27104 
27105 	/*
27106 	 * The refhold placed at the start of the ioctl is released here.
27107 	 */
27108 	if (connp != NULL)
27109 		CONN_OPER_PENDING_DONE(connp);
27110 
27111 	if (ipsq != NULL)
27112 		ipsq_current_finish(ipsq);
27113 }
27114 
27115 /* Called from ip_wput for all non data messages */
27116 /* ARGSUSED */
27117 void
27118 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27119 {
27120 	mblk_t		*mp1;
27121 	ire_t		*ire, *fake_ire;
27122 	ill_t		*ill;
27123 	struct iocblk	*iocp;
27124 	ip_ioctl_cmd_t	*ipip;
27125 	cred_t		*cr;
27126 	conn_t		*connp;
27127 	int		err;
27128 	nce_t		*nce;
27129 	ipif_t		*ipif;
27130 	ip_stack_t	*ipst;
27131 	char		*proto_str;
27132 
27133 	if (CONN_Q(q)) {
27134 		connp = Q_TO_CONN(q);
27135 		ipst = connp->conn_netstack->netstack_ip;
27136 	} else {
27137 		connp = NULL;
27138 		ipst = ILLQ_TO_IPST(q);
27139 	}
27140 
27141 	switch (DB_TYPE(mp)) {
27142 	case M_IOCTL:
27143 		/*
27144 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27145 		 * will arrange to copy in associated control structures.
27146 		 */
27147 		ip_sioctl_copyin_setup(q, mp);
27148 		return;
27149 	case M_IOCDATA:
27150 		/*
27151 		 * Ensure that this is associated with one of our trans-
27152 		 * parent ioctls.  If it's not ours, discard it if we're
27153 		 * running as a driver, or pass it on if we're a module.
27154 		 */
27155 		iocp = (struct iocblk *)mp->b_rptr;
27156 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27157 		if (ipip == NULL) {
27158 			if (q->q_next == NULL) {
27159 				goto nak;
27160 			} else {
27161 				putnext(q, mp);
27162 			}
27163 			return;
27164 		}
27165 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27166 			/*
27167 			 * the ioctl is one we recognise, but is not
27168 			 * consumed by IP as a module, pass M_IOCDATA
27169 			 * for processing downstream, but only for
27170 			 * common Streams ioctls.
27171 			 */
27172 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27173 				putnext(q, mp);
27174 				return;
27175 			} else {
27176 				goto nak;
27177 			}
27178 		}
27179 
27180 		/* IOCTL continuation following copyin or copyout. */
27181 		if (mi_copy_state(q, mp, NULL) == -1) {
27182 			/*
27183 			 * The copy operation failed.  mi_copy_state already
27184 			 * cleaned up, so we're out of here.
27185 			 */
27186 			return;
27187 		}
27188 		/*
27189 		 * If we just completed a copy in, we become writer and
27190 		 * continue processing in ip_sioctl_copyin_done.  If it
27191 		 * was a copy out, we call mi_copyout again.  If there is
27192 		 * nothing more to copy out, it will complete the IOCTL.
27193 		 */
27194 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27195 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27196 				mi_copy_done(q, mp, EPROTO);
27197 				return;
27198 			}
27199 			/*
27200 			 * Check for cases that need more copying.  A return
27201 			 * value of 0 means a second copyin has been started,
27202 			 * so we return; a return value of 1 means no more
27203 			 * copying is needed, so we continue.
27204 			 */
27205 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27206 			    MI_COPY_COUNT(mp) == 1) {
27207 				if (ip_copyin_msfilter(q, mp) == 0)
27208 					return;
27209 			}
27210 			/*
27211 			 * Refhold the conn, till the ioctl completes. This is
27212 			 * needed in case the ioctl ends up in the pending mp
27213 			 * list. Every mp in the ill_pending_mp list and
27214 			 * the ipx_pending_mp must have a refhold on the conn
27215 			 * to resume processing. The refhold is released when
27216 			 * the ioctl completes. (normally or abnormally)
27217 			 * In all cases ip_ioctl_finish is called to finish
27218 			 * the ioctl.
27219 			 */
27220 			if (connp != NULL) {
27221 				/* This is not a reentry */
27222 				ASSERT(ipsq == NULL);
27223 				CONN_INC_REF(connp);
27224 			} else {
27225 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27226 					mi_copy_done(q, mp, EINVAL);
27227 					return;
27228 				}
27229 			}
27230 
27231 			ip_process_ioctl(ipsq, q, mp, ipip);
27232 
27233 		} else {
27234 			mi_copyout(q, mp);
27235 		}
27236 		return;
27237 nak:
27238 		iocp->ioc_error = EINVAL;
27239 		mp->b_datap->db_type = M_IOCNAK;
27240 		iocp->ioc_count = 0;
27241 		qreply(q, mp);
27242 		return;
27243 
27244 	case M_IOCNAK:
27245 		/*
27246 		 * The only way we could get here is if a resolver didn't like
27247 		 * an IOCTL we sent it.	 This shouldn't happen.
27248 		 */
27249 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27250 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27251 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27252 		freemsg(mp);
27253 		return;
27254 	case M_IOCACK:
27255 		/* /dev/ip shouldn't see this */
27256 		if (CONN_Q(q))
27257 			goto nak;
27258 
27259 		/*
27260 		 * Finish socket ioctls passed through to ARP.  We use the
27261 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27262 		 * we need to become writer before calling ip_sioctl_iocack().
27263 		 * Note that qwriter_ip() will release the refhold, and that a
27264 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27265 		 * ill stream.
27266 		 */
27267 		iocp = (struct iocblk *)mp->b_rptr;
27268 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27269 			ip_sioctl_iocack(NULL, q, mp, NULL);
27270 			return;
27271 		}
27272 
27273 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27274 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27275 		ill = q->q_ptr;
27276 		ill_refhold(ill);
27277 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27278 		return;
27279 	case M_FLUSH:
27280 		if (*mp->b_rptr & FLUSHW)
27281 			flushq(q, FLUSHALL);
27282 		if (q->q_next) {
27283 			putnext(q, mp);
27284 			return;
27285 		}
27286 		if (*mp->b_rptr & FLUSHR) {
27287 			*mp->b_rptr &= ~FLUSHW;
27288 			qreply(q, mp);
27289 			return;
27290 		}
27291 		freemsg(mp);
27292 		return;
27293 	case IRE_DB_REQ_TYPE:
27294 		if (connp == NULL) {
27295 			proto_str = "IRE_DB_REQ_TYPE";
27296 			goto protonak;
27297 		}
27298 		/* An Upper Level Protocol wants a copy of an IRE. */
27299 		ip_ire_req(q, mp);
27300 		return;
27301 	case M_CTL:
27302 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27303 			break;
27304 
27305 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27306 		    TUN_HELLO) {
27307 			ASSERT(connp != NULL);
27308 			connp->conn_flags |= IPCL_IPTUN;
27309 			freeb(mp);
27310 			return;
27311 		}
27312 
27313 		/* M_CTL messages are used by ARP to tell us things. */
27314 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27315 			break;
27316 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27317 		case AR_ENTRY_SQUERY:
27318 			putnext(q, mp);
27319 			return;
27320 		case AR_CLIENT_NOTIFY:
27321 			ip_arp_news(q, mp);
27322 			return;
27323 		case AR_DLPIOP_DONE:
27324 			ASSERT(q->q_next != NULL);
27325 			ill = (ill_t *)q->q_ptr;
27326 			/* qwriter_ip releases the refhold */
27327 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27328 			ill_refhold(ill);
27329 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27330 			return;
27331 		case AR_ARP_CLOSING:
27332 			/*
27333 			 * ARP (above us) is closing. If no ARP bringup is
27334 			 * currently pending, ack the message so that ARP
27335 			 * can complete its close. Also mark ill_arp_closing
27336 			 * so that new ARP bringups will fail. If any
27337 			 * ARP bringup is currently in progress, we will
27338 			 * ack this when the current ARP bringup completes.
27339 			 */
27340 			ASSERT(q->q_next != NULL);
27341 			ill = (ill_t *)q->q_ptr;
27342 			mutex_enter(&ill->ill_lock);
27343 			ill->ill_arp_closing = 1;
27344 			if (!ill->ill_arp_bringup_pending) {
27345 				mutex_exit(&ill->ill_lock);
27346 				qreply(q, mp);
27347 			} else {
27348 				mutex_exit(&ill->ill_lock);
27349 				freemsg(mp);
27350 			}
27351 			return;
27352 		case AR_ARP_EXTEND:
27353 			/*
27354 			 * The ARP module above us is capable of duplicate
27355 			 * address detection.  Old ATM drivers will not send
27356 			 * this message.
27357 			 */
27358 			ASSERT(q->q_next != NULL);
27359 			ill = (ill_t *)q->q_ptr;
27360 			ill->ill_arp_extend = B_TRUE;
27361 			freemsg(mp);
27362 			return;
27363 		default:
27364 			break;
27365 		}
27366 		break;
27367 	case M_PROTO:
27368 	case M_PCPROTO:
27369 		/*
27370 		 * The only PROTO messages we expect are copies of option
27371 		 * negotiation acknowledgements, AH and ESP bind requests
27372 		 * are also expected.
27373 		 */
27374 		switch (((union T_primitives *)mp->b_rptr)->type) {
27375 		case O_T_BIND_REQ:
27376 		case T_BIND_REQ: {
27377 			/* Request can get queued in bind */
27378 			if (connp == NULL) {
27379 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27380 				goto protonak;
27381 			}
27382 			/*
27383 			 * The transports except SCTP call ip_bind_{v4,v6}()
27384 			 * directly instead of a a putnext. SCTP doesn't
27385 			 * generate any T_BIND_REQ since it has its own
27386 			 * fanout data structures. However, ESP and AH
27387 			 * come in for regular binds; all other cases are
27388 			 * bind retries.
27389 			 */
27390 			ASSERT(!IPCL_IS_SCTP(connp));
27391 
27392 			/* Don't increment refcnt if this is a re-entry */
27393 			if (ipsq == NULL)
27394 				CONN_INC_REF(connp);
27395 
27396 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27397 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27398 			ASSERT(mp != NULL);
27399 
27400 			ASSERT(!IPCL_IS_TCP(connp));
27401 			ASSERT(!IPCL_IS_UDP(connp));
27402 			ASSERT(!IPCL_IS_RAWIP(connp));
27403 
27404 			/* The case of AH and ESP */
27405 			qreply(q, mp);
27406 			CONN_OPER_PENDING_DONE(connp);
27407 			return;
27408 		}
27409 		case T_SVR4_OPTMGMT_REQ:
27410 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27411 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27412 
27413 			if (connp == NULL) {
27414 				proto_str = "T_SVR4_OPTMGMT_REQ";
27415 				goto protonak;
27416 			}
27417 
27418 			/*
27419 			 * All Solaris components should pass a db_credp
27420 			 * for this TPI message, hence we ASSERT.
27421 			 * But in case there is some other M_PROTO that looks
27422 			 * like a TPI message sent by some other kernel
27423 			 * component, we check and return an error.
27424 			 */
27425 			cr = msg_getcred(mp, NULL);
27426 			ASSERT(cr != NULL);
27427 			if (cr == NULL) {
27428 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27429 				if (mp != NULL)
27430 					qreply(q, mp);
27431 				return;
27432 			}
27433 
27434 			if (!snmpcom_req(q, mp, ip_snmp_set,
27435 			    ip_snmp_get, cr)) {
27436 				/*
27437 				 * Call svr4_optcom_req so that it can
27438 				 * generate the ack. We don't come here
27439 				 * if this operation is being restarted.
27440 				 * ip_restart_optmgmt will drop the conn ref.
27441 				 * In the case of ipsec option after the ipsec
27442 				 * load is complete conn_restart_ipsec_waiter
27443 				 * drops the conn ref.
27444 				 */
27445 				ASSERT(ipsq == NULL);
27446 				CONN_INC_REF(connp);
27447 				if (ip_check_for_ipsec_opt(q, mp))
27448 					return;
27449 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27450 				    B_FALSE);
27451 				if (err != EINPROGRESS) {
27452 					/* Operation is done */
27453 					CONN_OPER_PENDING_DONE(connp);
27454 				}
27455 			}
27456 			return;
27457 		case T_OPTMGMT_REQ:
27458 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27459 			/*
27460 			 * Note: No snmpcom_req support through new
27461 			 * T_OPTMGMT_REQ.
27462 			 * Call tpi_optcom_req so that it can
27463 			 * generate the ack.
27464 			 */
27465 			if (connp == NULL) {
27466 				proto_str = "T_OPTMGMT_REQ";
27467 				goto protonak;
27468 			}
27469 
27470 			/*
27471 			 * All Solaris components should pass a db_credp
27472 			 * for this TPI message, hence we ASSERT.
27473 			 * But in case there is some other M_PROTO that looks
27474 			 * like a TPI message sent by some other kernel
27475 			 * component, we check and return an error.
27476 			 */
27477 			cr = msg_getcred(mp, NULL);
27478 			ASSERT(cr != NULL);
27479 			if (cr == NULL) {
27480 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27481 				if (mp != NULL)
27482 					qreply(q, mp);
27483 				return;
27484 			}
27485 			ASSERT(ipsq == NULL);
27486 			/*
27487 			 * We don't come here for restart. ip_restart_optmgmt
27488 			 * will drop the conn ref. In the case of ipsec option
27489 			 * after the ipsec load is complete
27490 			 * conn_restart_ipsec_waiter drops the conn ref.
27491 			 */
27492 			CONN_INC_REF(connp);
27493 			if (ip_check_for_ipsec_opt(q, mp))
27494 				return;
27495 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27496 			if (err != EINPROGRESS) {
27497 				/* Operation is done */
27498 				CONN_OPER_PENDING_DONE(connp);
27499 			}
27500 			return;
27501 		case T_UNBIND_REQ:
27502 			if (connp == NULL) {
27503 				proto_str = "T_UNBIND_REQ";
27504 				goto protonak;
27505 			}
27506 			ip_unbind(Q_TO_CONN(q));
27507 			mp = mi_tpi_ok_ack_alloc(mp);
27508 			qreply(q, mp);
27509 			return;
27510 		default:
27511 			/*
27512 			 * Have to drop any DLPI messages coming down from
27513 			 * arp (such as an info_req which would cause ip
27514 			 * to receive an extra info_ack if it was passed
27515 			 * through.
27516 			 */
27517 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27518 			    (int)*(uint_t *)mp->b_rptr));
27519 			freemsg(mp);
27520 			return;
27521 		}
27522 		/* NOTREACHED */
27523 	case IRE_DB_TYPE: {
27524 		nce_t		*nce;
27525 		ill_t		*ill;
27526 		in6_addr_t	gw_addr_v6;
27527 
27528 		/*
27529 		 * This is a response back from a resolver.  It
27530 		 * consists of a message chain containing:
27531 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27532 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27533 		 * The LL_HDR_MBLK is the DLPI header to use to get
27534 		 * the attached packet, and subsequent ones for the
27535 		 * same destination, transmitted.
27536 		 */
27537 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27538 			break;
27539 		/*
27540 		 * First, check to make sure the resolution succeeded.
27541 		 * If it failed, the second mblk will be empty.
27542 		 * If it is, free the chain, dropping the packet.
27543 		 * (We must ire_delete the ire; that frees the ire mblk)
27544 		 * We're doing this now to support PVCs for ATM; it's
27545 		 * a partial xresolv implementation. When we fully implement
27546 		 * xresolv interfaces, instead of freeing everything here
27547 		 * we'll initiate neighbor discovery.
27548 		 *
27549 		 * For v4 (ARP and other external resolvers) the resolver
27550 		 * frees the message, so no check is needed. This check
27551 		 * is required, though, for a full xresolve implementation.
27552 		 * Including this code here now both shows how external
27553 		 * resolvers can NACK a resolution request using an
27554 		 * existing design that has no specific provisions for NACKs,
27555 		 * and also takes into account that the current non-ARP
27556 		 * external resolver has been coded to use this method of
27557 		 * NACKing for all IPv6 (xresolv) cases,
27558 		 * whether our xresolv implementation is complete or not.
27559 		 *
27560 		 */
27561 		ire = (ire_t *)mp->b_rptr;
27562 		ill = ire_to_ill(ire);
27563 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27564 		if (mp1->b_rptr == mp1->b_wptr) {
27565 			if (ire->ire_ipversion == IPV6_VERSION) {
27566 				/*
27567 				 * XRESOLV interface.
27568 				 */
27569 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27570 				mutex_enter(&ire->ire_lock);
27571 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27572 				mutex_exit(&ire->ire_lock);
27573 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27574 					nce = ndp_lookup_v6(ill, B_FALSE,
27575 					    &ire->ire_addr_v6, B_FALSE);
27576 				} else {
27577 					nce = ndp_lookup_v6(ill, B_FALSE,
27578 					    &gw_addr_v6, B_FALSE);
27579 				}
27580 				if (nce != NULL) {
27581 					nce_resolv_failed(nce);
27582 					ndp_delete(nce);
27583 					NCE_REFRELE(nce);
27584 				}
27585 			}
27586 			mp->b_cont = NULL;
27587 			freemsg(mp1);		/* frees the pkt as well */
27588 			ASSERT(ire->ire_nce == NULL);
27589 			ire_delete((ire_t *)mp->b_rptr);
27590 			return;
27591 		}
27592 
27593 		/*
27594 		 * Split them into IRE_MBLK and pkt and feed it into
27595 		 * ire_add_then_send. Then in ire_add_then_send
27596 		 * the IRE will be added, and then the packet will be
27597 		 * run back through ip_wput. This time it will make
27598 		 * it to the wire.
27599 		 */
27600 		mp->b_cont = NULL;
27601 		mp = mp1->b_cont;		/* now, mp points to pkt */
27602 		mp1->b_cont = NULL;
27603 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27604 		if (ire->ire_ipversion == IPV6_VERSION) {
27605 			/*
27606 			 * XRESOLV interface. Find the nce and put a copy
27607 			 * of the dl_unitdata_req in nce_res_mp
27608 			 */
27609 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27610 			mutex_enter(&ire->ire_lock);
27611 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27612 			mutex_exit(&ire->ire_lock);
27613 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27614 				nce = ndp_lookup_v6(ill, B_FALSE,
27615 				    &ire->ire_addr_v6, B_FALSE);
27616 			} else {
27617 				nce = ndp_lookup_v6(ill, B_FALSE,
27618 				    &gw_addr_v6, B_FALSE);
27619 			}
27620 			if (nce != NULL) {
27621 				/*
27622 				 * We have to protect nce_res_mp here
27623 				 * from being accessed by other threads
27624 				 * while we change the mblk pointer.
27625 				 * Other functions will also lock the nce when
27626 				 * accessing nce_res_mp.
27627 				 *
27628 				 * The reason we change the mblk pointer
27629 				 * here rather than copying the resolved address
27630 				 * into the template is that, unlike with
27631 				 * ethernet, we have no guarantee that the
27632 				 * resolved address length will be
27633 				 * smaller than or equal to the lla length
27634 				 * with which the template was allocated,
27635 				 * (for ethernet, they're equal)
27636 				 * so we have to use the actual resolved
27637 				 * address mblk - which holds the real
27638 				 * dl_unitdata_req with the resolved address.
27639 				 *
27640 				 * Doing this is the same behavior as was
27641 				 * previously used in the v4 ARP case.
27642 				 */
27643 				mutex_enter(&nce->nce_lock);
27644 				if (nce->nce_res_mp != NULL)
27645 					freemsg(nce->nce_res_mp);
27646 				nce->nce_res_mp = mp1;
27647 				mutex_exit(&nce->nce_lock);
27648 				/*
27649 				 * We do a fastpath probe here because
27650 				 * we have resolved the address without
27651 				 * using Neighbor Discovery.
27652 				 * In the non-XRESOLV v6 case, the fastpath
27653 				 * probe is done right after neighbor
27654 				 * discovery completes.
27655 				 */
27656 				if (nce->nce_res_mp != NULL) {
27657 					int res;
27658 					nce_fastpath_list_add(nce);
27659 					res = ill_fastpath_probe(ill,
27660 					    nce->nce_res_mp);
27661 					if (res != 0 && res != EAGAIN)
27662 						nce_fastpath_list_delete(nce);
27663 				}
27664 
27665 				ire_add_then_send(q, ire, mp);
27666 				/*
27667 				 * Now we have to clean out any packets
27668 				 * that may have been queued on the nce
27669 				 * while it was waiting for address resolution
27670 				 * to complete.
27671 				 */
27672 				mutex_enter(&nce->nce_lock);
27673 				mp1 = nce->nce_qd_mp;
27674 				nce->nce_qd_mp = NULL;
27675 				mutex_exit(&nce->nce_lock);
27676 				while (mp1 != NULL) {
27677 					mblk_t *nxt_mp;
27678 					queue_t *fwdq = NULL;
27679 					ill_t   *inbound_ill;
27680 					uint_t ifindex;
27681 
27682 					nxt_mp = mp1->b_next;
27683 					mp1->b_next = NULL;
27684 					/*
27685 					 * Retrieve ifindex stored in
27686 					 * ip_rput_data_v6()
27687 					 */
27688 					ifindex =
27689 					    (uint_t)(uintptr_t)mp1->b_prev;
27690 					inbound_ill =
27691 					    ill_lookup_on_ifindex(ifindex,
27692 					    B_TRUE, NULL, NULL, NULL,
27693 					    NULL, ipst);
27694 					mp1->b_prev = NULL;
27695 					if (inbound_ill != NULL)
27696 						fwdq = inbound_ill->ill_rq;
27697 
27698 					if (fwdq != NULL) {
27699 						put(fwdq, mp1);
27700 						ill_refrele(inbound_ill);
27701 					} else
27702 						put(WR(ill->ill_rq), mp1);
27703 					mp1 = nxt_mp;
27704 				}
27705 				NCE_REFRELE(nce);
27706 			} else {	/* nce is NULL; clean up */
27707 				ire_delete(ire);
27708 				freemsg(mp);
27709 				freemsg(mp1);
27710 				return;
27711 			}
27712 		} else {
27713 			nce_t *arpce;
27714 			/*
27715 			 * Link layer resolution succeeded. Recompute the
27716 			 * ire_nce.
27717 			 */
27718 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27719 			if ((arpce = ndp_lookup_v4(ill,
27720 			    (ire->ire_gateway_addr != INADDR_ANY ?
27721 			    &ire->ire_gateway_addr : &ire->ire_addr),
27722 			    B_FALSE)) == NULL) {
27723 				freeb(ire->ire_mp);
27724 				freeb(mp1);
27725 				freemsg(mp);
27726 				return;
27727 			}
27728 			mutex_enter(&arpce->nce_lock);
27729 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27730 			if (arpce->nce_state == ND_REACHABLE) {
27731 				/*
27732 				 * Someone resolved this before us;
27733 				 * cleanup the res_mp. Since ire has
27734 				 * not been added yet, the call to ire_add_v4
27735 				 * from ire_add_then_send (when a dup is
27736 				 * detected) will clean up the ire.
27737 				 */
27738 				freeb(mp1);
27739 			} else {
27740 				ASSERT(arpce->nce_res_mp == NULL);
27741 				arpce->nce_res_mp = mp1;
27742 				arpce->nce_state = ND_REACHABLE;
27743 			}
27744 			mutex_exit(&arpce->nce_lock);
27745 			if (ire->ire_marks & IRE_MARK_NOADD) {
27746 				/*
27747 				 * this ire will not be added to the ire
27748 				 * cache table, so we can set the ire_nce
27749 				 * here, as there are no atomicity constraints.
27750 				 */
27751 				ire->ire_nce = arpce;
27752 				/*
27753 				 * We are associating this nce with the ire
27754 				 * so change the nce ref taken in
27755 				 * ndp_lookup_v4() from
27756 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27757 				 */
27758 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27759 			} else {
27760 				NCE_REFRELE(arpce);
27761 			}
27762 			ire_add_then_send(q, ire, mp);
27763 		}
27764 		return;	/* All is well, the packet has been sent. */
27765 	}
27766 	case IRE_ARPRESOLVE_TYPE: {
27767 
27768 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27769 			break;
27770 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27771 		mp->b_cont = NULL;
27772 		/*
27773 		 * First, check to make sure the resolution succeeded.
27774 		 * If it failed, the second mblk will be empty.
27775 		 */
27776 		if (mp1->b_rptr == mp1->b_wptr) {
27777 			/* cleanup  the incomplete ire, free queued packets */
27778 			freemsg(mp); /* fake ire */
27779 			freeb(mp1);  /* dl_unitdata response */
27780 			return;
27781 		}
27782 
27783 		/*
27784 		 * Update any incomplete nce_t found. We search the ctable
27785 		 * and find the nce from the ire->ire_nce because we need
27786 		 * to pass the ire to ip_xmit_v4 later, and can find both
27787 		 * ire and nce in one lookup.
27788 		 */
27789 		fake_ire = (ire_t *)mp->b_rptr;
27790 
27791 		/*
27792 		 * By the time we come back here from ARP the logical outgoing
27793 		 * interface of the incomplete ire we added in ire_forward()
27794 		 * could have disappeared, causing the incomplete ire to also
27795 		 * disappear.  So we need to retreive the proper ipif for the
27796 		 * ire before looking in ctable.  In the case of IPMP, the
27797 		 * ipif may be on the IPMP ill, so look it up based on the
27798 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27799 		 * Then, we can verify that ire_ipif_seqid still exists.
27800 		 */
27801 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27802 		    NULL, NULL, NULL, NULL, ipst);
27803 		if (ill == NULL) {
27804 			ip1dbg(("ill for incomplete ire vanished\n"));
27805 			freemsg(mp); /* fake ire */
27806 			freeb(mp1);  /* dl_unitdata response */
27807 			return;
27808 		}
27809 
27810 		/* Get the outgoing ipif */
27811 		mutex_enter(&ill->ill_lock);
27812 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27813 		if (ipif == NULL) {
27814 			mutex_exit(&ill->ill_lock);
27815 			ill_refrele(ill);
27816 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27817 			freemsg(mp); /* fake_ire */
27818 			freeb(mp1);  /* dl_unitdata response */
27819 			return;
27820 		}
27821 
27822 		ipif_refhold_locked(ipif);
27823 		mutex_exit(&ill->ill_lock);
27824 		ill_refrele(ill);
27825 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27826 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27827 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27828 		ipif_refrele(ipif);
27829 		if (ire == NULL) {
27830 			/*
27831 			 * no ire was found; check if there is an nce
27832 			 * for this lookup; if it has no ire's pointing at it
27833 			 * cleanup.
27834 			 */
27835 			if ((nce = ndp_lookup_v4(q->q_ptr,
27836 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27837 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27838 			    B_FALSE)) != NULL) {
27839 				/*
27840 				 * cleanup:
27841 				 * We check for refcnt 2 (one for the nce
27842 				 * hash list + 1 for the ref taken by
27843 				 * ndp_lookup_v4) to check that there are
27844 				 * no ire's pointing at the nce.
27845 				 */
27846 				if (nce->nce_refcnt == 2)
27847 					ndp_delete(nce);
27848 				NCE_REFRELE(nce);
27849 			}
27850 			freeb(mp1);  /* dl_unitdata response */
27851 			freemsg(mp); /* fake ire */
27852 			return;
27853 		}
27854 
27855 		nce = ire->ire_nce;
27856 		DTRACE_PROBE2(ire__arpresolve__type,
27857 		    ire_t *, ire, nce_t *, nce);
27858 		ASSERT(nce->nce_state != ND_INITIAL);
27859 		mutex_enter(&nce->nce_lock);
27860 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27861 		if (nce->nce_state == ND_REACHABLE) {
27862 			/*
27863 			 * Someone resolved this before us;
27864 			 * our response is not needed any more.
27865 			 */
27866 			mutex_exit(&nce->nce_lock);
27867 			freeb(mp1);  /* dl_unitdata response */
27868 		} else {
27869 			ASSERT(nce->nce_res_mp == NULL);
27870 			nce->nce_res_mp = mp1;
27871 			nce->nce_state = ND_REACHABLE;
27872 			mutex_exit(&nce->nce_lock);
27873 			nce_fastpath(nce);
27874 		}
27875 		/*
27876 		 * The cached nce_t has been updated to be reachable;
27877 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27878 		 */
27879 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27880 		freemsg(mp);
27881 		/*
27882 		 * send out queued packets.
27883 		 */
27884 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27885 
27886 		IRE_REFRELE(ire);
27887 		return;
27888 	}
27889 	default:
27890 		break;
27891 	}
27892 	if (q->q_next) {
27893 		putnext(q, mp);
27894 	} else
27895 		freemsg(mp);
27896 	return;
27897 
27898 protonak:
27899 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27900 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27901 		qreply(q, mp);
27902 }
27903 
27904 /*
27905  * Process IP options in an outbound packet.  Modify the destination if there
27906  * is a source route option.
27907  * Returns non-zero if something fails in which case an ICMP error has been
27908  * sent and mp freed.
27909  */
27910 static int
27911 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27912     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27913 {
27914 	ipoptp_t	opts;
27915 	uchar_t		*opt;
27916 	uint8_t		optval;
27917 	uint8_t		optlen;
27918 	ipaddr_t	dst;
27919 	intptr_t	code = 0;
27920 	mblk_t		*mp;
27921 	ire_t		*ire = NULL;
27922 
27923 	ip2dbg(("ip_wput_options\n"));
27924 	mp = ipsec_mp;
27925 	if (mctl_present) {
27926 		mp = ipsec_mp->b_cont;
27927 	}
27928 
27929 	dst = ipha->ipha_dst;
27930 	for (optval = ipoptp_first(&opts, ipha);
27931 	    optval != IPOPT_EOL;
27932 	    optval = ipoptp_next(&opts)) {
27933 		opt = opts.ipoptp_cur;
27934 		optlen = opts.ipoptp_len;
27935 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27936 		    optval, optlen));
27937 		switch (optval) {
27938 			uint32_t off;
27939 		case IPOPT_SSRR:
27940 		case IPOPT_LSRR:
27941 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27942 				ip1dbg((
27943 				    "ip_wput_options: bad option offset\n"));
27944 				code = (char *)&opt[IPOPT_OLEN] -
27945 				    (char *)ipha;
27946 				goto param_prob;
27947 			}
27948 			off = opt[IPOPT_OFFSET];
27949 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27950 			    ntohl(dst)));
27951 			/*
27952 			 * For strict: verify that dst is directly
27953 			 * reachable.
27954 			 */
27955 			if (optval == IPOPT_SSRR) {
27956 				ire = ire_ftable_lookup(dst, 0, 0,
27957 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27958 				    msg_getlabel(mp),
27959 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27960 				if (ire == NULL) {
27961 					ip1dbg(("ip_wput_options: SSRR not"
27962 					    " directly reachable: 0x%x\n",
27963 					    ntohl(dst)));
27964 					goto bad_src_route;
27965 				}
27966 				ire_refrele(ire);
27967 			}
27968 			break;
27969 		case IPOPT_RR:
27970 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27971 				ip1dbg((
27972 				    "ip_wput_options: bad option offset\n"));
27973 				code = (char *)&opt[IPOPT_OLEN] -
27974 				    (char *)ipha;
27975 				goto param_prob;
27976 			}
27977 			break;
27978 		case IPOPT_TS:
27979 			/*
27980 			 * Verify that length >=5 and that there is either
27981 			 * room for another timestamp or that the overflow
27982 			 * counter is not maxed out.
27983 			 */
27984 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27985 			if (optlen < IPOPT_MINLEN_IT) {
27986 				goto param_prob;
27987 			}
27988 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27989 				ip1dbg((
27990 				    "ip_wput_options: bad option offset\n"));
27991 				code = (char *)&opt[IPOPT_OFFSET] -
27992 				    (char *)ipha;
27993 				goto param_prob;
27994 			}
27995 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27996 			case IPOPT_TS_TSONLY:
27997 				off = IPOPT_TS_TIMELEN;
27998 				break;
27999 			case IPOPT_TS_TSANDADDR:
28000 			case IPOPT_TS_PRESPEC:
28001 			case IPOPT_TS_PRESPEC_RFC791:
28002 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28003 				break;
28004 			default:
28005 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28006 				    (char *)ipha;
28007 				goto param_prob;
28008 			}
28009 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28010 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28011 				/*
28012 				 * No room and the overflow counter is 15
28013 				 * already.
28014 				 */
28015 				goto param_prob;
28016 			}
28017 			break;
28018 		}
28019 	}
28020 
28021 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28022 		return (0);
28023 
28024 	ip1dbg(("ip_wput_options: error processing IP options."));
28025 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28026 
28027 param_prob:
28028 	/*
28029 	 * Since ip_wput() isn't close to finished, we fill
28030 	 * in enough of the header for credible error reporting.
28031 	 */
28032 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28033 		/* Failed */
28034 		freemsg(ipsec_mp);
28035 		return (-1);
28036 	}
28037 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28038 	return (-1);
28039 
28040 bad_src_route:
28041 	/*
28042 	 * Since ip_wput() isn't close to finished, we fill
28043 	 * in enough of the header for credible error reporting.
28044 	 */
28045 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28046 		/* Failed */
28047 		freemsg(ipsec_mp);
28048 		return (-1);
28049 	}
28050 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28051 	return (-1);
28052 }
28053 
28054 /*
28055  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28056  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28057  * thru /etc/system.
28058  */
28059 #define	CONN_MAXDRAINCNT	64
28060 
28061 static void
28062 conn_drain_init(ip_stack_t *ipst)
28063 {
28064 	int i, j;
28065 	idl_tx_list_t *itl_tx;
28066 
28067 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28068 
28069 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28070 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28071 		/*
28072 		 * Default value of the number of drainers is the
28073 		 * number of cpus, subject to maximum of 8 drainers.
28074 		 */
28075 		if (boot_max_ncpus != -1)
28076 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28077 		else
28078 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28079 	}
28080 
28081 	ipst->ips_idl_tx_list =
28082 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28083 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28084 		itl_tx =  &ipst->ips_idl_tx_list[i];
28085 		itl_tx->txl_drain_list =
28086 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28087 		    sizeof (idl_t), KM_SLEEP);
28088 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28089 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28090 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28091 			    MUTEX_DEFAULT, NULL);
28092 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28093 		}
28094 	}
28095 }
28096 
28097 static void
28098 conn_drain_fini(ip_stack_t *ipst)
28099 {
28100 	int i;
28101 	idl_tx_list_t *itl_tx;
28102 
28103 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28104 		itl_tx =  &ipst->ips_idl_tx_list[i];
28105 		kmem_free(itl_tx->txl_drain_list,
28106 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28107 	}
28108 	kmem_free(ipst->ips_idl_tx_list,
28109 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28110 	ipst->ips_idl_tx_list = NULL;
28111 }
28112 
28113 /*
28114  * Note: For an overview of how flowcontrol is handled in IP please see the
28115  * IP Flowcontrol notes at the top of this file.
28116  *
28117  * Flow control has blocked us from proceeding. Insert the given conn in one
28118  * of the conn drain lists. These conn wq's will be qenabled later on when
28119  * STREAMS flow control does a backenable. conn_walk_drain will enable
28120  * the first conn in each of these drain lists. Each of these qenabled conns
28121  * in turn enables the next in the list, after it runs, or when it closes,
28122  * thus sustaining the drain process.
28123  */
28124 void
28125 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28126 {
28127 	idl_t	*idl = tx_list->txl_drain_list;
28128 	uint_t	index;
28129 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28130 
28131 	mutex_enter(&connp->conn_lock);
28132 	if (connp->conn_state_flags & CONN_CLOSING) {
28133 		/*
28134 		 * The conn is closing as a result of which CONN_CLOSING
28135 		 * is set. Return.
28136 		 */
28137 		mutex_exit(&connp->conn_lock);
28138 		return;
28139 	} else if (connp->conn_idl == NULL) {
28140 		/*
28141 		 * Assign the next drain list round robin. We dont' use
28142 		 * a lock, and thus it may not be strictly round robin.
28143 		 * Atomicity of load/stores is enough to make sure that
28144 		 * conn_drain_list_index is always within bounds.
28145 		 */
28146 		index = tx_list->txl_drain_index;
28147 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28148 		connp->conn_idl = &tx_list->txl_drain_list[index];
28149 		index++;
28150 		if (index == ipst->ips_conn_drain_list_cnt)
28151 			index = 0;
28152 		tx_list->txl_drain_index = index;
28153 	}
28154 	mutex_exit(&connp->conn_lock);
28155 
28156 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28157 	if ((connp->conn_drain_prev != NULL) ||
28158 	    (connp->conn_state_flags & CONN_CLOSING)) {
28159 		/*
28160 		 * The conn is already in the drain list, OR
28161 		 * the conn is closing. We need to check again for
28162 		 * the closing case again since close can happen
28163 		 * after we drop the conn_lock, and before we
28164 		 * acquire the CONN_DRAIN_LIST_LOCK.
28165 		 */
28166 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28167 		return;
28168 	} else {
28169 		idl = connp->conn_idl;
28170 	}
28171 
28172 	/*
28173 	 * The conn is not in the drain list. Insert it at the
28174 	 * tail of the drain list. The drain list is circular
28175 	 * and doubly linked. idl_conn points to the 1st element
28176 	 * in the list.
28177 	 */
28178 	if (idl->idl_conn == NULL) {
28179 		idl->idl_conn = connp;
28180 		connp->conn_drain_next = connp;
28181 		connp->conn_drain_prev = connp;
28182 	} else {
28183 		conn_t *head = idl->idl_conn;
28184 
28185 		connp->conn_drain_next = head;
28186 		connp->conn_drain_prev = head->conn_drain_prev;
28187 		head->conn_drain_prev->conn_drain_next = connp;
28188 		head->conn_drain_prev = connp;
28189 	}
28190 	/*
28191 	 * For non streams based sockets assert flow control.
28192 	 */
28193 	if (IPCL_IS_NONSTR(connp)) {
28194 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28195 		(*connp->conn_upcalls->su_txq_full)
28196 		    (connp->conn_upper_handle, B_TRUE);
28197 	} else {
28198 		conn_setqfull(connp);
28199 		noenable(connp->conn_wq);
28200 	}
28201 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28202 }
28203 
28204 /*
28205  * This conn is closing, and we are called from ip_close. OR
28206  * This conn has been serviced by ip_wsrv, and we need to do the tail
28207  * processing.
28208  * If this conn is part of the drain list, we may need to sustain the drain
28209  * process by qenabling the next conn in the drain list. We may also need to
28210  * remove this conn from the list, if it is done.
28211  */
28212 static void
28213 conn_drain_tail(conn_t *connp, boolean_t closing)
28214 {
28215 	idl_t *idl;
28216 
28217 	/*
28218 	 * connp->conn_idl is stable at this point, and no lock is needed
28219 	 * to check it. If we are called from ip_close, close has already
28220 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28221 	 * called us only because conn_idl is non-null. If we are called thru
28222 	 * service, conn_idl could be null, but it cannot change because
28223 	 * service is single-threaded per queue, and there cannot be another
28224 	 * instance of service trying to call conn_drain_insert on this conn
28225 	 * now.
28226 	 */
28227 	ASSERT(!closing || (connp->conn_idl != NULL));
28228 
28229 	/*
28230 	 * If connp->conn_idl is null, the conn has not been inserted into any
28231 	 * drain list even once since creation of the conn. Just return.
28232 	 */
28233 	if (connp->conn_idl == NULL)
28234 		return;
28235 
28236 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28237 
28238 	if (connp->conn_drain_prev == NULL) {
28239 		/* This conn is currently not in the drain list.  */
28240 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28241 		return;
28242 	}
28243 	idl = connp->conn_idl;
28244 	if (idl->idl_conn_draining == connp) {
28245 		/*
28246 		 * This conn is the current drainer. If this is the last conn
28247 		 * in the drain list, we need to do more checks, in the 'if'
28248 		 * below. Otherwwise we need to just qenable the next conn,
28249 		 * to sustain the draining, and is handled in the 'else'
28250 		 * below.
28251 		 */
28252 		if (connp->conn_drain_next == idl->idl_conn) {
28253 			/*
28254 			 * This conn is the last in this list. This round
28255 			 * of draining is complete. If idl_repeat is set,
28256 			 * it means another flow enabling has happened from
28257 			 * the driver/streams and we need to another round
28258 			 * of draining.
28259 			 * If there are more than 2 conns in the drain list,
28260 			 * do a left rotate by 1, so that all conns except the
28261 			 * conn at the head move towards the head by 1, and the
28262 			 * the conn at the head goes to the tail. This attempts
28263 			 * a more even share for all queues that are being
28264 			 * drained.
28265 			 */
28266 			if ((connp->conn_drain_next != connp) &&
28267 			    (idl->idl_conn->conn_drain_next != connp)) {
28268 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28269 			}
28270 			if (idl->idl_repeat) {
28271 				qenable(idl->idl_conn->conn_wq);
28272 				idl->idl_conn_draining = idl->idl_conn;
28273 				idl->idl_repeat = 0;
28274 			} else {
28275 				idl->idl_conn_draining = NULL;
28276 			}
28277 		} else {
28278 			/*
28279 			 * If the next queue that we are now qenable'ing,
28280 			 * is closing, it will remove itself from this list
28281 			 * and qenable the subsequent queue in ip_close().
28282 			 * Serialization is acheived thru idl_lock.
28283 			 */
28284 			qenable(connp->conn_drain_next->conn_wq);
28285 			idl->idl_conn_draining = connp->conn_drain_next;
28286 		}
28287 	}
28288 	if (!connp->conn_did_putbq || closing) {
28289 		/*
28290 		 * Remove ourself from the drain list, if we did not do
28291 		 * a putbq, or if the conn is closing.
28292 		 * Note: It is possible that q->q_first is non-null. It means
28293 		 * that these messages landed after we did a enableok() in
28294 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28295 		 * service them.
28296 		 */
28297 		if (connp->conn_drain_next == connp) {
28298 			/* Singleton in the list */
28299 			ASSERT(connp->conn_drain_prev == connp);
28300 			idl->idl_conn = NULL;
28301 			idl->idl_conn_draining = NULL;
28302 		} else {
28303 			connp->conn_drain_prev->conn_drain_next =
28304 			    connp->conn_drain_next;
28305 			connp->conn_drain_next->conn_drain_prev =
28306 			    connp->conn_drain_prev;
28307 			if (idl->idl_conn == connp)
28308 				idl->idl_conn = connp->conn_drain_next;
28309 			ASSERT(idl->idl_conn_draining != connp);
28310 
28311 		}
28312 		connp->conn_drain_next = NULL;
28313 		connp->conn_drain_prev = NULL;
28314 
28315 		/*
28316 		 * For non streams based sockets open up flow control.
28317 		 */
28318 		if (IPCL_IS_NONSTR(connp)) {
28319 			(*connp->conn_upcalls->su_txq_full)
28320 			    (connp->conn_upper_handle, B_FALSE);
28321 		} else {
28322 			conn_clrqfull(connp);
28323 			enableok(connp->conn_wq);
28324 		}
28325 	}
28326 
28327 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28328 }
28329 
28330 /*
28331  * Write service routine. Shared perimeter entry point.
28332  * ip_wsrv can be called in any of the following ways.
28333  * 1. The device queue's messages has fallen below the low water mark
28334  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28335  *    the drain lists and backenable the first conn in each list.
28336  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28337  *    qenabled non-tcp upper layers. We start dequeing messages and call
28338  *    ip_wput for each message.
28339  */
28340 
28341 void
28342 ip_wsrv(queue_t *q)
28343 {
28344 	conn_t	*connp;
28345 	ill_t	*ill;
28346 	mblk_t	*mp;
28347 
28348 	if (q->q_next) {
28349 		ill = (ill_t *)q->q_ptr;
28350 		if (ill->ill_state_flags == 0) {
28351 			ip_stack_t *ipst = ill->ill_ipst;
28352 
28353 			/*
28354 			 * The device flow control has opened up.
28355 			 * Walk through conn drain lists and qenable the
28356 			 * first conn in each list. This makes sense only
28357 			 * if the stream is fully plumbed and setup.
28358 			 * Hence the if check above.
28359 			 */
28360 			ip1dbg(("ip_wsrv: walking\n"));
28361 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28362 		}
28363 		return;
28364 	}
28365 
28366 	connp = Q_TO_CONN(q);
28367 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28368 
28369 	/*
28370 	 * 1. Set conn_draining flag to signal that service is active.
28371 	 *
28372 	 * 2. ip_output determines whether it has been called from service,
28373 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28374 	 *    has been called from service.
28375 	 *
28376 	 * 3. Message ordering is preserved by the following logic.
28377 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28378 	 *    the message at the tail, if conn_draining is set (i.e. service
28379 	 *    is running) or if q->q_first is non-null.
28380 	 *
28381 	 *    ii. If ip_output is called from service, and if ip_output cannot
28382 	 *    putnext due to flow control, it does a putbq.
28383 	 *
28384 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28385 	 *    (causing an infinite loop).
28386 	 */
28387 	ASSERT(!connp->conn_did_putbq);
28388 
28389 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28390 		connp->conn_draining = 1;
28391 		noenable(q);
28392 		while ((mp = getq(q)) != NULL) {
28393 			ASSERT(CONN_Q(q));
28394 
28395 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28396 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28397 			if (connp->conn_did_putbq) {
28398 				/* ip_wput did a putbq */
28399 				break;
28400 			}
28401 		}
28402 		/*
28403 		 * At this point, a thread coming down from top, calling
28404 		 * ip_wput, may end up queueing the message. We have not yet
28405 		 * enabled the queue, so ip_wsrv won't be called again.
28406 		 * To avoid this race, check q->q_first again (in the loop)
28407 		 * If the other thread queued the message before we call
28408 		 * enableok(), we will catch it in the q->q_first check.
28409 		 * If the other thread queues the message after we call
28410 		 * enableok(), ip_wsrv will be called again by STREAMS.
28411 		 */
28412 		connp->conn_draining = 0;
28413 		enableok(q);
28414 	}
28415 
28416 	/* Enable the next conn for draining */
28417 	conn_drain_tail(connp, B_FALSE);
28418 
28419 	/*
28420 	 * conn_direct_blocked is used to indicate blocked
28421 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28422 	 * This is the only place where it is set without
28423 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28424 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28425 	 */
28426 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28427 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28428 		connp->conn_direct_blocked = B_FALSE;
28429 	}
28430 
28431 	connp->conn_did_putbq = 0;
28432 }
28433 
28434 /*
28435  * Callback to disable flow control in IP.
28436  *
28437  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28438  * is enabled.
28439  *
28440  * When MAC_TX() is not able to send any more packets, dld sets its queue
28441  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28442  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28443  * function and wakes up corresponding mac worker threads, which in turn
28444  * calls this callback function, and disables flow control.
28445  */
28446 void
28447 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28448 {
28449 	ill_t *ill = (ill_t *)arg;
28450 	ip_stack_t *ipst = ill->ill_ipst;
28451 	idl_tx_list_t *idl_txl;
28452 
28453 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28454 	mutex_enter(&idl_txl->txl_lock);
28455 	/* add code to to set a flag to indicate idl_txl is enabled */
28456 	conn_walk_drain(ipst, idl_txl);
28457 	mutex_exit(&idl_txl->txl_lock);
28458 }
28459 
28460 /*
28461  * Walk the list of all conn's calling the function provided with the
28462  * specified argument for each.	 Note that this only walks conn's that
28463  * have been bound.
28464  * Applies to both IPv4 and IPv6.
28465  */
28466 static void
28467 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28468 {
28469 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28470 	    ipst->ips_ipcl_udp_fanout_size,
28471 	    func, arg, zoneid);
28472 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28473 	    ipst->ips_ipcl_conn_fanout_size,
28474 	    func, arg, zoneid);
28475 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28476 	    ipst->ips_ipcl_bind_fanout_size,
28477 	    func, arg, zoneid);
28478 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28479 	    IPPROTO_MAX, func, arg, zoneid);
28480 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28481 	    IPPROTO_MAX, func, arg, zoneid);
28482 }
28483 
28484 /*
28485  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28486  * of conns that need to be drained, check if drain is already in progress.
28487  * If so set the idl_repeat bit, indicating that the last conn in the list
28488  * needs to reinitiate the drain once again, for the list. If drain is not
28489  * in progress for the list, initiate the draining, by qenabling the 1st
28490  * conn in the list. The drain is self-sustaining, each qenabled conn will
28491  * in turn qenable the next conn, when it is done/blocked/closing.
28492  */
28493 static void
28494 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28495 {
28496 	int i;
28497 	idl_t *idl;
28498 
28499 	IP_STAT(ipst, ip_conn_walk_drain);
28500 
28501 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28502 		idl = &tx_list->txl_drain_list[i];
28503 		mutex_enter(&idl->idl_lock);
28504 		if (idl->idl_conn == NULL) {
28505 			mutex_exit(&idl->idl_lock);
28506 			continue;
28507 		}
28508 		/*
28509 		 * If this list is not being drained currently by
28510 		 * an ip_wsrv thread, start the process.
28511 		 */
28512 		if (idl->idl_conn_draining == NULL) {
28513 			ASSERT(idl->idl_repeat == 0);
28514 			qenable(idl->idl_conn->conn_wq);
28515 			idl->idl_conn_draining = idl->idl_conn;
28516 		} else {
28517 			idl->idl_repeat = 1;
28518 		}
28519 		mutex_exit(&idl->idl_lock);
28520 	}
28521 }
28522 
28523 /*
28524  * Walk an conn hash table of `count' buckets, calling func for each entry.
28525  */
28526 static void
28527 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28528     zoneid_t zoneid)
28529 {
28530 	conn_t	*connp;
28531 
28532 	while (count-- > 0) {
28533 		mutex_enter(&connfp->connf_lock);
28534 		for (connp = connfp->connf_head; connp != NULL;
28535 		    connp = connp->conn_next) {
28536 			if (zoneid == GLOBAL_ZONEID ||
28537 			    zoneid == connp->conn_zoneid) {
28538 				CONN_INC_REF(connp);
28539 				mutex_exit(&connfp->connf_lock);
28540 				(*func)(connp, arg);
28541 				mutex_enter(&connfp->connf_lock);
28542 				CONN_DEC_REF(connp);
28543 			}
28544 		}
28545 		mutex_exit(&connfp->connf_lock);
28546 		connfp++;
28547 	}
28548 }
28549 
28550 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28551 static void
28552 conn_report1(conn_t *connp, void *mp)
28553 {
28554 	char	buf1[INET6_ADDRSTRLEN];
28555 	char	buf2[INET6_ADDRSTRLEN];
28556 	uint_t	print_len, buf_len;
28557 
28558 	ASSERT(connp != NULL);
28559 
28560 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28561 	if (buf_len <= 0)
28562 		return;
28563 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28564 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28565 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28566 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28567 	    "%5d %s/%05d %s/%05d\n",
28568 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28569 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28570 	    buf1, connp->conn_lport,
28571 	    buf2, connp->conn_fport);
28572 	if (print_len < buf_len) {
28573 		((mblk_t *)mp)->b_wptr += print_len;
28574 	} else {
28575 		((mblk_t *)mp)->b_wptr += buf_len;
28576 	}
28577 }
28578 
28579 /*
28580  * Named Dispatch routine to produce a formatted report on all conns
28581  * that are listed in one of the fanout tables.
28582  * This report is accessed by using the ndd utility to "get" ND variable
28583  * "ip_conn_status".
28584  */
28585 /* ARGSUSED */
28586 static int
28587 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28588 {
28589 	conn_t *connp = Q_TO_CONN(q);
28590 
28591 	(void) mi_mpprintf(mp,
28592 	    "CONN      " MI_COL_HDRPAD_STR
28593 	    "rfq      " MI_COL_HDRPAD_STR
28594 	    "stq      " MI_COL_HDRPAD_STR
28595 	    " zone local		 remote");
28596 
28597 	/*
28598 	 * Because of the ndd constraint, at most we can have 64K buffer
28599 	 * to put in all conn info.  So to be more efficient, just
28600 	 * allocate a 64K buffer here, assuming we need that large buffer.
28601 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28602 	 */
28603 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28604 		/* The following may work even if we cannot get a large buf. */
28605 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28606 		return (0);
28607 	}
28608 
28609 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28610 	    connp->conn_netstack->netstack_ip);
28611 	return (0);
28612 }
28613 
28614 /*
28615  * Determine if the ill and multicast aspects of that packets
28616  * "matches" the conn.
28617  */
28618 boolean_t
28619 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28620     zoneid_t zoneid)
28621 {
28622 	ill_t *bound_ill;
28623 	boolean_t found;
28624 	ipif_t *ipif;
28625 	ire_t *ire;
28626 	ipaddr_t dst, src;
28627 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28628 
28629 	dst = ipha->ipha_dst;
28630 	src = ipha->ipha_src;
28631 
28632 	/*
28633 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28634 	 * unicast, broadcast and multicast reception to
28635 	 * conn_incoming_ill. conn_wantpacket itself is called
28636 	 * only for BROADCAST and multicast.
28637 	 */
28638 	bound_ill = connp->conn_incoming_ill;
28639 	if (bound_ill != NULL) {
28640 		if (IS_IPMP(bound_ill)) {
28641 			if (bound_ill->ill_grp != ill->ill_grp)
28642 				return (B_FALSE);
28643 		} else {
28644 			if (bound_ill != ill)
28645 				return (B_FALSE);
28646 		}
28647 	}
28648 
28649 	if (!CLASSD(dst)) {
28650 		if (IPCL_ZONE_MATCH(connp, zoneid))
28651 			return (B_TRUE);
28652 		/*
28653 		 * The conn is in a different zone; we need to check that this
28654 		 * broadcast address is configured in the application's zone.
28655 		 */
28656 		ipif = ipif_get_next_ipif(NULL, ill);
28657 		if (ipif == NULL)
28658 			return (B_FALSE);
28659 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28660 		    connp->conn_zoneid, NULL,
28661 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28662 		ipif_refrele(ipif);
28663 		if (ire != NULL) {
28664 			ire_refrele(ire);
28665 			return (B_TRUE);
28666 		} else {
28667 			return (B_FALSE);
28668 		}
28669 	}
28670 
28671 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28672 	    connp->conn_zoneid == zoneid) {
28673 		/*
28674 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28675 		 * disabled, therefore we don't dispatch the multicast packet to
28676 		 * the sending zone.
28677 		 */
28678 		return (B_FALSE);
28679 	}
28680 
28681 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28682 		/*
28683 		 * Multicast packet on the loopback interface: we only match
28684 		 * conns who joined the group in the specified zone.
28685 		 */
28686 		return (B_FALSE);
28687 	}
28688 
28689 	if (connp->conn_multi_router) {
28690 		/* multicast packet and multicast router socket: send up */
28691 		return (B_TRUE);
28692 	}
28693 
28694 	mutex_enter(&connp->conn_lock);
28695 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28696 	mutex_exit(&connp->conn_lock);
28697 	return (found);
28698 }
28699 
28700 static void
28701 conn_setqfull(conn_t *connp)
28702 {
28703 	queue_t *q = connp->conn_wq;
28704 
28705 	if (!(q->q_flag & QFULL)) {
28706 		mutex_enter(QLOCK(q));
28707 		if (!(q->q_flag & QFULL)) {
28708 			/* still need to set QFULL */
28709 			q->q_flag |= QFULL;
28710 			mutex_exit(QLOCK(q));
28711 		} else {
28712 			mutex_exit(QLOCK(q));
28713 		}
28714 	}
28715 }
28716 
28717 static void
28718 conn_clrqfull(conn_t *connp)
28719 {
28720 	queue_t *q = connp->conn_wq;
28721 
28722 	if (q->q_flag & QFULL) {
28723 		mutex_enter(QLOCK(q));
28724 		if (q->q_flag & QFULL) {
28725 			q->q_flag &= ~QFULL;
28726 			mutex_exit(QLOCK(q));
28727 			if (q->q_flag & QWANTW)
28728 				qbackenable(q, 0);
28729 		} else {
28730 			mutex_exit(QLOCK(q));
28731 		}
28732 	}
28733 }
28734 
28735 /*
28736  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28737  */
28738 /* ARGSUSED */
28739 static void
28740 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28741 {
28742 	ill_t *ill = (ill_t *)q->q_ptr;
28743 	mblk_t	*mp1, *mp2;
28744 	ipif_t  *ipif;
28745 	int err = 0;
28746 	conn_t *connp = NULL;
28747 	ipsq_t	*ipsq;
28748 	arc_t	*arc;
28749 
28750 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28751 
28752 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28753 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28754 
28755 	ASSERT(IAM_WRITER_ILL(ill));
28756 	mp2 = mp->b_cont;
28757 	mp->b_cont = NULL;
28758 
28759 	/*
28760 	 * We have now received the arp bringup completion message
28761 	 * from ARP. Mark the arp bringup as done. Also if the arp
28762 	 * stream has already started closing, send up the AR_ARP_CLOSING
28763 	 * ack now since ARP is waiting in close for this ack.
28764 	 */
28765 	mutex_enter(&ill->ill_lock);
28766 	ill->ill_arp_bringup_pending = 0;
28767 	if (ill->ill_arp_closing) {
28768 		mutex_exit(&ill->ill_lock);
28769 		/* Let's reuse the mp for sending the ack */
28770 		arc = (arc_t *)mp->b_rptr;
28771 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28772 		arc->arc_cmd = AR_ARP_CLOSING;
28773 		qreply(q, mp);
28774 	} else {
28775 		mutex_exit(&ill->ill_lock);
28776 		freeb(mp);
28777 	}
28778 
28779 	ipsq = ill->ill_phyint->phyint_ipsq;
28780 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28781 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28782 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28783 	if (mp1 == NULL) {
28784 		/* bringup was aborted by the user */
28785 		freemsg(mp2);
28786 		return;
28787 	}
28788 
28789 	/*
28790 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28791 	 * must have an associated conn_t.  Otherwise, we're bringing this
28792 	 * interface back up as part of handling an asynchronous event (e.g.,
28793 	 * physical address change).
28794 	 */
28795 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28796 		ASSERT(connp != NULL);
28797 		q = CONNP_TO_WQ(connp);
28798 	} else {
28799 		ASSERT(connp == NULL);
28800 		q = ill->ill_rq;
28801 	}
28802 
28803 	/*
28804 	 * If the DL_BIND_REQ fails, it is noted
28805 	 * in arc_name_offset.
28806 	 */
28807 	err = *((int *)mp2->b_rptr);
28808 	if (err == 0) {
28809 		if (ipif->ipif_isv6) {
28810 			if ((err = ipif_up_done_v6(ipif)) != 0)
28811 				ip0dbg(("ip_arp_done: init failed\n"));
28812 		} else {
28813 			if ((err = ipif_up_done(ipif)) != 0)
28814 				ip0dbg(("ip_arp_done: init failed\n"));
28815 		}
28816 	} else {
28817 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28818 	}
28819 
28820 	freemsg(mp2);
28821 
28822 	if ((err == 0) && (ill->ill_up_ipifs)) {
28823 		err = ill_up_ipifs(ill, q, mp1);
28824 		if (err == EINPROGRESS)
28825 			return;
28826 	}
28827 
28828 	/*
28829 	 * If we have a moved ipif to bring up, and everything has succeeded
28830 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28831 	 * down -- the admin can try to bring it up by hand if need be.
28832 	 */
28833 	if (ill->ill_move_ipif != NULL) {
28834 		ipif = ill->ill_move_ipif;
28835 		ill->ill_move_ipif = NULL;
28836 		if (err == 0) {
28837 			err = ipif_up(ipif, q, mp1);
28838 			if (err == EINPROGRESS)
28839 				return;
28840 		}
28841 	}
28842 
28843 	/*
28844 	 * The operation must complete without EINPROGRESS since
28845 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28846 	 * operation will be stuck forever in the ipsq.
28847 	 */
28848 	ASSERT(err != EINPROGRESS);
28849 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28850 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28851 	else
28852 		ipsq_current_finish(ipsq);
28853 }
28854 
28855 /* Allocate the private structure */
28856 static int
28857 ip_priv_alloc(void **bufp)
28858 {
28859 	void	*buf;
28860 
28861 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28862 		return (ENOMEM);
28863 
28864 	*bufp = buf;
28865 	return (0);
28866 }
28867 
28868 /* Function to delete the private structure */
28869 void
28870 ip_priv_free(void *buf)
28871 {
28872 	ASSERT(buf != NULL);
28873 	kmem_free(buf, sizeof (ip_priv_t));
28874 }
28875 
28876 /*
28877  * The entry point for IPPF processing.
28878  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28879  * routine just returns.
28880  *
28881  * When called, ip_process generates an ipp_packet_t structure
28882  * which holds the state information for this packet and invokes the
28883  * the classifier (via ipp_packet_process). The classification, depending on
28884  * configured filters, results in a list of actions for this packet. Invoking
28885  * an action may cause the packet to be dropped, in which case the resulting
28886  * mblk (*mpp) is NULL. proc indicates the callout position for
28887  * this packet and ill_index is the interface this packet on or will leave
28888  * on (inbound and outbound resp.).
28889  */
28890 void
28891 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28892 {
28893 	mblk_t		*mp;
28894 	ip_priv_t	*priv;
28895 	ipp_action_id_t	aid;
28896 	int		rc = 0;
28897 	ipp_packet_t	*pp;
28898 #define	IP_CLASS	"ip"
28899 
28900 	/* If the classifier is not loaded, return  */
28901 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28902 		return;
28903 	}
28904 
28905 	mp = *mpp;
28906 	ASSERT(mp != NULL);
28907 
28908 	/* Allocate the packet structure */
28909 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28910 	if (rc != 0) {
28911 		*mpp = NULL;
28912 		freemsg(mp);
28913 		return;
28914 	}
28915 
28916 	/* Allocate the private structure */
28917 	rc = ip_priv_alloc((void **)&priv);
28918 	if (rc != 0) {
28919 		*mpp = NULL;
28920 		freemsg(mp);
28921 		ipp_packet_free(pp);
28922 		return;
28923 	}
28924 	priv->proc = proc;
28925 	priv->ill_index = ill_index;
28926 	ipp_packet_set_private(pp, priv, ip_priv_free);
28927 	ipp_packet_set_data(pp, mp);
28928 
28929 	/* Invoke the classifier */
28930 	rc = ipp_packet_process(&pp);
28931 	if (pp != NULL) {
28932 		mp = ipp_packet_get_data(pp);
28933 		ipp_packet_free(pp);
28934 		if (rc != 0) {
28935 			freemsg(mp);
28936 			*mpp = NULL;
28937 		}
28938 	} else {
28939 		*mpp = NULL;
28940 	}
28941 #undef	IP_CLASS
28942 }
28943 
28944 /*
28945  * Propagate a multicast group membership operation (add/drop) on
28946  * all the interfaces crossed by the related multirt routes.
28947  * The call is considered successful if the operation succeeds
28948  * on at least one interface.
28949  */
28950 static int
28951 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28952     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28953     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28954     mblk_t *first_mp)
28955 {
28956 	ire_t		*ire_gw;
28957 	irb_t		*irb;
28958 	int		error = 0;
28959 	opt_restart_t	*or;
28960 	ip_stack_t	*ipst = ire->ire_ipst;
28961 
28962 	irb = ire->ire_bucket;
28963 	ASSERT(irb != NULL);
28964 
28965 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28966 
28967 	or = (opt_restart_t *)first_mp->b_rptr;
28968 	IRB_REFHOLD(irb);
28969 	for (; ire != NULL; ire = ire->ire_next) {
28970 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28971 			continue;
28972 		if (ire->ire_addr != group)
28973 			continue;
28974 
28975 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28976 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28977 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28978 		/* No resolver exists for the gateway; skip this ire. */
28979 		if (ire_gw == NULL)
28980 			continue;
28981 
28982 		/*
28983 		 * This function can return EINPROGRESS. If so the operation
28984 		 * will be restarted from ip_restart_optmgmt which will
28985 		 * call ip_opt_set and option processing will restart for
28986 		 * this option. So we may end up calling 'fn' more than once.
28987 		 * This requires that 'fn' is idempotent except for the
28988 		 * return value. The operation is considered a success if
28989 		 * it succeeds at least once on any one interface.
28990 		 */
28991 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28992 		    NULL, fmode, src, first_mp);
28993 		if (error == 0)
28994 			or->or_private = CGTP_MCAST_SUCCESS;
28995 
28996 		if (ip_debug > 0) {
28997 			ulong_t	off;
28998 			char	*ksym;
28999 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29000 			ip2dbg(("ip_multirt_apply_membership: "
29001 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29002 			    "error %d [success %u]\n",
29003 			    ksym ? ksym : "?",
29004 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29005 			    error, or->or_private));
29006 		}
29007 
29008 		ire_refrele(ire_gw);
29009 		if (error == EINPROGRESS) {
29010 			IRB_REFRELE(irb);
29011 			return (error);
29012 		}
29013 	}
29014 	IRB_REFRELE(irb);
29015 	/*
29016 	 * Consider the call as successful if we succeeded on at least
29017 	 * one interface. Otherwise, return the last encountered error.
29018 	 */
29019 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29020 }
29021 
29022 /*
29023  * Issue a warning regarding a route crossing an interface with an
29024  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29025  * amount of time is logged.
29026  */
29027 static void
29028 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29029 {
29030 	hrtime_t	current = gethrtime();
29031 	char		buf[INET_ADDRSTRLEN];
29032 	ip_stack_t	*ipst = ire->ire_ipst;
29033 
29034 	/* Convert interval in ms to hrtime in ns */
29035 	if (ipst->ips_multirt_bad_mtu_last_time +
29036 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29037 	    current) {
29038 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29039 		    "to %s, incorrect MTU %u (expected %u)\n",
29040 		    ip_dot_addr(ire->ire_addr, buf),
29041 		    ire->ire_max_frag, max_frag);
29042 
29043 		ipst->ips_multirt_bad_mtu_last_time = current;
29044 	}
29045 }
29046 
29047 /*
29048  * Get the CGTP (multirouting) filtering status.
29049  * If 0, the CGTP hooks are transparent.
29050  */
29051 /* ARGSUSED */
29052 static int
29053 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29054 {
29055 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29056 
29057 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29058 	return (0);
29059 }
29060 
29061 /*
29062  * Set the CGTP (multirouting) filtering status.
29063  * If the status is changed from active to transparent
29064  * or from transparent to active, forward the new status
29065  * to the filtering module (if loaded).
29066  */
29067 /* ARGSUSED */
29068 static int
29069 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29070     cred_t *ioc_cr)
29071 {
29072 	long		new_value;
29073 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29074 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29075 
29076 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29077 		return (EPERM);
29078 
29079 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29080 	    new_value < 0 || new_value > 1) {
29081 		return (EINVAL);
29082 	}
29083 
29084 	if ((!*ip_cgtp_filter_value) && new_value) {
29085 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29086 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29087 		    " (module not loaded)" : "");
29088 	}
29089 	if (*ip_cgtp_filter_value && (!new_value)) {
29090 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29091 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29092 		    " (module not loaded)" : "");
29093 	}
29094 
29095 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29096 		int	res;
29097 		netstackid_t stackid;
29098 
29099 		stackid = ipst->ips_netstack->netstack_stackid;
29100 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29101 		    new_value);
29102 		if (res)
29103 			return (res);
29104 	}
29105 
29106 	*ip_cgtp_filter_value = (boolean_t)new_value;
29107 
29108 	return (0);
29109 }
29110 
29111 /*
29112  * Return the expected CGTP hooks version number.
29113  */
29114 int
29115 ip_cgtp_filter_supported(void)
29116 {
29117 	return (ip_cgtp_filter_rev);
29118 }
29119 
29120 /*
29121  * CGTP hooks can be registered by invoking this function.
29122  * Checks that the version number matches.
29123  */
29124 int
29125 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29126 {
29127 	netstack_t *ns;
29128 	ip_stack_t *ipst;
29129 
29130 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29131 		return (ENOTSUP);
29132 
29133 	ns = netstack_find_by_stackid(stackid);
29134 	if (ns == NULL)
29135 		return (EINVAL);
29136 	ipst = ns->netstack_ip;
29137 	ASSERT(ipst != NULL);
29138 
29139 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29140 		netstack_rele(ns);
29141 		return (EALREADY);
29142 	}
29143 
29144 	ipst->ips_ip_cgtp_filter_ops = ops;
29145 	netstack_rele(ns);
29146 	return (0);
29147 }
29148 
29149 /*
29150  * CGTP hooks can be unregistered by invoking this function.
29151  * Returns ENXIO if there was no registration.
29152  * Returns EBUSY if the ndd variable has not been turned off.
29153  */
29154 int
29155 ip_cgtp_filter_unregister(netstackid_t stackid)
29156 {
29157 	netstack_t *ns;
29158 	ip_stack_t *ipst;
29159 
29160 	ns = netstack_find_by_stackid(stackid);
29161 	if (ns == NULL)
29162 		return (EINVAL);
29163 	ipst = ns->netstack_ip;
29164 	ASSERT(ipst != NULL);
29165 
29166 	if (ipst->ips_ip_cgtp_filter) {
29167 		netstack_rele(ns);
29168 		return (EBUSY);
29169 	}
29170 
29171 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29172 		netstack_rele(ns);
29173 		return (ENXIO);
29174 	}
29175 	ipst->ips_ip_cgtp_filter_ops = NULL;
29176 	netstack_rele(ns);
29177 	return (0);
29178 }
29179 
29180 /*
29181  * Check whether there is a CGTP filter registration.
29182  * Returns non-zero if there is a registration, otherwise returns zero.
29183  * Note: returns zero if bad stackid.
29184  */
29185 int
29186 ip_cgtp_filter_is_registered(netstackid_t stackid)
29187 {
29188 	netstack_t *ns;
29189 	ip_stack_t *ipst;
29190 	int ret;
29191 
29192 	ns = netstack_find_by_stackid(stackid);
29193 	if (ns == NULL)
29194 		return (0);
29195 	ipst = ns->netstack_ip;
29196 	ASSERT(ipst != NULL);
29197 
29198 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29199 		ret = 1;
29200 	else
29201 		ret = 0;
29202 
29203 	netstack_rele(ns);
29204 	return (ret);
29205 }
29206 
29207 static int
29208 ip_squeue_switch(int val)
29209 {
29210 	int rval = SQ_FILL;
29211 
29212 	switch (val) {
29213 	case IP_SQUEUE_ENTER_NODRAIN:
29214 		rval = SQ_NODRAIN;
29215 		break;
29216 	case IP_SQUEUE_ENTER:
29217 		rval = SQ_PROCESS;
29218 		break;
29219 	default:
29220 		break;
29221 	}
29222 	return (rval);
29223 }
29224 
29225 /* ARGSUSED */
29226 static int
29227 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29228     caddr_t addr, cred_t *cr)
29229 {
29230 	int *v = (int *)addr;
29231 	long new_value;
29232 
29233 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29234 		return (EPERM);
29235 
29236 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29237 		return (EINVAL);
29238 
29239 	ip_squeue_flag = ip_squeue_switch(new_value);
29240 	*v = new_value;
29241 	return (0);
29242 }
29243 
29244 /*
29245  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29246  * ip_debug.
29247  */
29248 /* ARGSUSED */
29249 static int
29250 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29251     caddr_t addr, cred_t *cr)
29252 {
29253 	int *v = (int *)addr;
29254 	long new_value;
29255 
29256 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29257 		return (EPERM);
29258 
29259 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29260 		return (EINVAL);
29261 
29262 	*v = new_value;
29263 	return (0);
29264 }
29265 
29266 static void *
29267 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29268 {
29269 	kstat_t *ksp;
29270 
29271 	ip_stat_t template = {
29272 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29273 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29274 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29275 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29276 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29277 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29278 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29279 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29280 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29281 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29282 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29283 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29284 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29285 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29286 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29287 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29288 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29289 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29290 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29291 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29292 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29293 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29294 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29295 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29296 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29297 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29298 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29299 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29300 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29301 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29302 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29303 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29304 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29305 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29306 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29307 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29308 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29309 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29310 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29311 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29312 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29313 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29314 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29315 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29316 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29317 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29318 	};
29319 
29320 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29321 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29322 	    KSTAT_FLAG_VIRTUAL, stackid);
29323 
29324 	if (ksp == NULL)
29325 		return (NULL);
29326 
29327 	bcopy(&template, ip_statisticsp, sizeof (template));
29328 	ksp->ks_data = (void *)ip_statisticsp;
29329 	ksp->ks_private = (void *)(uintptr_t)stackid;
29330 
29331 	kstat_install(ksp);
29332 	return (ksp);
29333 }
29334 
29335 static void
29336 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29337 {
29338 	if (ksp != NULL) {
29339 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29340 		kstat_delete_netstack(ksp, stackid);
29341 	}
29342 }
29343 
29344 static void *
29345 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29346 {
29347 	kstat_t	*ksp;
29348 
29349 	ip_named_kstat_t template = {
29350 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29351 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29352 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29353 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29354 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29355 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29356 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29357 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29358 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29359 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29360 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29361 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29362 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29363 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29364 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29365 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29366 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29367 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29368 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29369 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29370 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29371 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29372 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29373 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29374 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29375 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29376 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29377 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29378 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29379 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29380 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29381 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29382 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29383 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29384 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29385 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29386 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29387 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29388 	};
29389 
29390 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29391 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29392 	if (ksp == NULL || ksp->ks_data == NULL)
29393 		return (NULL);
29394 
29395 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29396 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29397 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29398 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29399 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29400 
29401 	template.netToMediaEntrySize.value.i32 =
29402 	    sizeof (mib2_ipNetToMediaEntry_t);
29403 
29404 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29405 
29406 	bcopy(&template, ksp->ks_data, sizeof (template));
29407 	ksp->ks_update = ip_kstat_update;
29408 	ksp->ks_private = (void *)(uintptr_t)stackid;
29409 
29410 	kstat_install(ksp);
29411 	return (ksp);
29412 }
29413 
29414 static void
29415 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29416 {
29417 	if (ksp != NULL) {
29418 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29419 		kstat_delete_netstack(ksp, stackid);
29420 	}
29421 }
29422 
29423 static int
29424 ip_kstat_update(kstat_t *kp, int rw)
29425 {
29426 	ip_named_kstat_t *ipkp;
29427 	mib2_ipIfStatsEntry_t ipmib;
29428 	ill_walk_context_t ctx;
29429 	ill_t *ill;
29430 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29431 	netstack_t	*ns;
29432 	ip_stack_t	*ipst;
29433 
29434 	if (kp == NULL || kp->ks_data == NULL)
29435 		return (EIO);
29436 
29437 	if (rw == KSTAT_WRITE)
29438 		return (EACCES);
29439 
29440 	ns = netstack_find_by_stackid(stackid);
29441 	if (ns == NULL)
29442 		return (-1);
29443 	ipst = ns->netstack_ip;
29444 	if (ipst == NULL) {
29445 		netstack_rele(ns);
29446 		return (-1);
29447 	}
29448 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29449 
29450 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29451 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29452 	ill = ILL_START_WALK_V4(&ctx, ipst);
29453 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29454 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29455 	rw_exit(&ipst->ips_ill_g_lock);
29456 
29457 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29458 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29459 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29460 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29461 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29462 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29463 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29464 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29465 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29466 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29467 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29468 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29469 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29470 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29471 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29472 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29473 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29474 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29475 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29476 
29477 	ipkp->routingDiscards.value.ui32 =	0;
29478 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29479 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29480 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29481 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29482 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29483 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29484 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29485 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29486 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29487 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29488 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29489 
29490 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29491 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29492 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29493 
29494 	netstack_rele(ns);
29495 
29496 	return (0);
29497 }
29498 
29499 static void *
29500 icmp_kstat_init(netstackid_t stackid)
29501 {
29502 	kstat_t	*ksp;
29503 
29504 	icmp_named_kstat_t template = {
29505 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29506 		{ "inErrors",		KSTAT_DATA_UINT32 },
29507 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29508 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29509 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29510 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29511 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29512 		{ "inEchos",		KSTAT_DATA_UINT32 },
29513 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29514 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29515 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29516 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29517 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29518 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29519 		{ "outErrors",		KSTAT_DATA_UINT32 },
29520 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29521 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29522 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29523 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29524 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29525 		{ "outEchos",		KSTAT_DATA_UINT32 },
29526 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29527 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29528 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29529 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29530 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29531 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29532 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29533 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29534 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29535 		{ "outDrops",		KSTAT_DATA_UINT32 },
29536 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29537 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29538 	};
29539 
29540 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29541 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29542 	if (ksp == NULL || ksp->ks_data == NULL)
29543 		return (NULL);
29544 
29545 	bcopy(&template, ksp->ks_data, sizeof (template));
29546 
29547 	ksp->ks_update = icmp_kstat_update;
29548 	ksp->ks_private = (void *)(uintptr_t)stackid;
29549 
29550 	kstat_install(ksp);
29551 	return (ksp);
29552 }
29553 
29554 static void
29555 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29556 {
29557 	if (ksp != NULL) {
29558 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29559 		kstat_delete_netstack(ksp, stackid);
29560 	}
29561 }
29562 
29563 static int
29564 icmp_kstat_update(kstat_t *kp, int rw)
29565 {
29566 	icmp_named_kstat_t *icmpkp;
29567 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29568 	netstack_t	*ns;
29569 	ip_stack_t	*ipst;
29570 
29571 	if ((kp == NULL) || (kp->ks_data == NULL))
29572 		return (EIO);
29573 
29574 	if (rw == KSTAT_WRITE)
29575 		return (EACCES);
29576 
29577 	ns = netstack_find_by_stackid(stackid);
29578 	if (ns == NULL)
29579 		return (-1);
29580 	ipst = ns->netstack_ip;
29581 	if (ipst == NULL) {
29582 		netstack_rele(ns);
29583 		return (-1);
29584 	}
29585 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29586 
29587 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29588 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29589 	icmpkp->inDestUnreachs.value.ui32 =
29590 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29591 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29592 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29593 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29594 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29595 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29596 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29597 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29598 	icmpkp->inTimestampReps.value.ui32 =
29599 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29600 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29601 	icmpkp->inAddrMaskReps.value.ui32 =
29602 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29603 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29604 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29605 	icmpkp->outDestUnreachs.value.ui32 =
29606 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29607 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29608 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29609 	icmpkp->outSrcQuenchs.value.ui32 =
29610 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29611 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29612 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29613 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29614 	icmpkp->outTimestamps.value.ui32 =
29615 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29616 	icmpkp->outTimestampReps.value.ui32 =
29617 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29618 	icmpkp->outAddrMasks.value.ui32 =
29619 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29620 	icmpkp->outAddrMaskReps.value.ui32 =
29621 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29622 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29623 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29624 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29625 	icmpkp->outFragNeeded.value.ui32 =
29626 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29627 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29628 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29629 	icmpkp->inBadRedirects.value.ui32 =
29630 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29631 
29632 	netstack_rele(ns);
29633 	return (0);
29634 }
29635 
29636 /*
29637  * This is the fanout function for raw socket opened for SCTP.  Note
29638  * that it is called after SCTP checks that there is no socket which
29639  * wants a packet.  Then before SCTP handles this out of the blue packet,
29640  * this function is called to see if there is any raw socket for SCTP.
29641  * If there is and it is bound to the correct address, the packet will
29642  * be sent to that socket.  Note that only one raw socket can be bound to
29643  * a port.  This is assured in ipcl_sctp_hash_insert();
29644  */
29645 void
29646 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29647     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29648     zoneid_t zoneid)
29649 {
29650 	conn_t		*connp;
29651 	queue_t		*rq;
29652 	mblk_t		*first_mp;
29653 	boolean_t	secure;
29654 	ip6_t		*ip6h;
29655 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29656 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29657 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29658 	boolean_t	sctp_csum_err = B_FALSE;
29659 
29660 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29661 		sctp_csum_err = B_TRUE;
29662 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29663 	}
29664 
29665 	first_mp = mp;
29666 	if (mctl_present) {
29667 		mp = first_mp->b_cont;
29668 		secure = ipsec_in_is_secure(first_mp);
29669 		ASSERT(mp != NULL);
29670 	} else {
29671 		secure = B_FALSE;
29672 	}
29673 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29674 
29675 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29676 	if (connp == NULL) {
29677 		/*
29678 		 * Although raw sctp is not summed, OOB chunks must be.
29679 		 * Drop the packet here if the sctp checksum failed.
29680 		 */
29681 		if (sctp_csum_err) {
29682 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29683 			freemsg(first_mp);
29684 			return;
29685 		}
29686 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29687 		return;
29688 	}
29689 	rq = connp->conn_rq;
29690 	if (!canputnext(rq)) {
29691 		CONN_DEC_REF(connp);
29692 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29693 		freemsg(first_mp);
29694 		return;
29695 	}
29696 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29697 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29698 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29699 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29700 		if (first_mp == NULL) {
29701 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29702 			CONN_DEC_REF(connp);
29703 			return;
29704 		}
29705 	}
29706 	/*
29707 	 * We probably should not send M_CTL message up to
29708 	 * raw socket.
29709 	 */
29710 	if (mctl_present)
29711 		freeb(first_mp);
29712 
29713 	/* Initiate IPPF processing here if needed. */
29714 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29715 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29716 		ip_process(IPP_LOCAL_IN, &mp,
29717 		    recv_ill->ill_phyint->phyint_ifindex);
29718 		if (mp == NULL) {
29719 			CONN_DEC_REF(connp);
29720 			return;
29721 		}
29722 	}
29723 
29724 	if (connp->conn_recvif || connp->conn_recvslla ||
29725 	    ((connp->conn_ip_recvpktinfo ||
29726 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29727 	    (flags & IP_FF_IPINFO))) {
29728 		int in_flags = 0;
29729 
29730 		/*
29731 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29732 		 * IPF_RECVIF.
29733 		 */
29734 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29735 			in_flags = IPF_RECVIF;
29736 		}
29737 		if (connp->conn_recvslla) {
29738 			in_flags |= IPF_RECVSLLA;
29739 		}
29740 		if (isv4) {
29741 			mp = ip_add_info(mp, recv_ill, in_flags,
29742 			    IPCL_ZONEID(connp), ipst);
29743 		} else {
29744 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29745 			if (mp == NULL) {
29746 				BUMP_MIB(recv_ill->ill_ip_mib,
29747 				    ipIfStatsInDiscards);
29748 				CONN_DEC_REF(connp);
29749 				return;
29750 			}
29751 		}
29752 	}
29753 
29754 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29755 	/*
29756 	 * We are sending the IPSEC_IN message also up. Refer
29757 	 * to comments above this function.
29758 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29759 	 */
29760 	(connp->conn_recv)(connp, mp, NULL);
29761 	CONN_DEC_REF(connp);
29762 }
29763 
29764 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29765 {									\
29766 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29767 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29768 }
29769 /*
29770  * This function should be called only if all packet processing
29771  * including fragmentation is complete. Callers of this function
29772  * must set mp->b_prev to one of these values:
29773  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29774  * prior to handing over the mp as first argument to this function.
29775  *
29776  * If the ire passed by caller is incomplete, this function
29777  * queues the packet and if necessary, sends ARP request and bails.
29778  * If the ire passed is fully resolved, we simply prepend
29779  * the link-layer header to the packet, do ipsec hw acceleration
29780  * work if necessary, and send the packet out on the wire.
29781  *
29782  * NOTE: IPsec will only call this function with fully resolved
29783  * ires if hw acceleration is involved.
29784  * TODO list :
29785  * 	a Handle M_MULTIDATA so that
29786  *	  tcp_multisend->tcp_multisend_data can
29787  *	  call ip_xmit_v4 directly
29788  *	b Handle post-ARP work for fragments so that
29789  *	  ip_wput_frag can call this function.
29790  */
29791 ipxmit_state_t
29792 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29793     boolean_t flow_ctl_enabled, conn_t *connp)
29794 {
29795 	nce_t		*arpce;
29796 	ipha_t		*ipha;
29797 	queue_t		*q;
29798 	int		ill_index;
29799 	mblk_t		*nxt_mp, *first_mp;
29800 	boolean_t	xmit_drop = B_FALSE;
29801 	ip_proc_t	proc;
29802 	ill_t		*out_ill;
29803 	int		pkt_len;
29804 
29805 	arpce = ire->ire_nce;
29806 	ASSERT(arpce != NULL);
29807 
29808 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29809 
29810 	mutex_enter(&arpce->nce_lock);
29811 	switch (arpce->nce_state) {
29812 	case ND_REACHABLE:
29813 		/* If there are other queued packets, queue this packet */
29814 		if (arpce->nce_qd_mp != NULL) {
29815 			if (mp != NULL)
29816 				nce_queue_mp_common(arpce, mp, B_FALSE);
29817 			mp = arpce->nce_qd_mp;
29818 		}
29819 		arpce->nce_qd_mp = NULL;
29820 		mutex_exit(&arpce->nce_lock);
29821 
29822 		/*
29823 		 * Flush the queue.  In the common case, where the
29824 		 * ARP is already resolved,  it will go through the
29825 		 * while loop only once.
29826 		 */
29827 		while (mp != NULL) {
29828 
29829 			nxt_mp = mp->b_next;
29830 			mp->b_next = NULL;
29831 			ASSERT(mp->b_datap->db_type != M_CTL);
29832 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29833 			/*
29834 			 * This info is needed for IPQOS to do COS marking
29835 			 * in ip_wput_attach_llhdr->ip_process.
29836 			 */
29837 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29838 			mp->b_prev = NULL;
29839 
29840 			/* set up ill index for outbound qos processing */
29841 			out_ill = ire_to_ill(ire);
29842 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29843 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29844 			    ill_index, &ipha);
29845 			if (first_mp == NULL) {
29846 				xmit_drop = B_TRUE;
29847 				BUMP_MIB(out_ill->ill_ip_mib,
29848 				    ipIfStatsOutDiscards);
29849 				goto next_mp;
29850 			}
29851 
29852 			/* non-ipsec hw accel case */
29853 			if (io == NULL || !io->ipsec_out_accelerated) {
29854 				/* send it */
29855 				q = ire->ire_stq;
29856 				if (proc == IPP_FWD_OUT) {
29857 					UPDATE_IB_PKT_COUNT(ire);
29858 				} else {
29859 					UPDATE_OB_PKT_COUNT(ire);
29860 				}
29861 				ire->ire_last_used_time = lbolt;
29862 
29863 				if (flow_ctl_enabled || canputnext(q)) {
29864 					if (proc == IPP_FWD_OUT) {
29865 
29866 					BUMP_MIB(out_ill->ill_ip_mib,
29867 					    ipIfStatsHCOutForwDatagrams);
29868 
29869 					}
29870 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29871 					    pkt_len);
29872 
29873 					DTRACE_IP7(send, mblk_t *, first_mp,
29874 					    conn_t *, NULL, void_ip_t *, ipha,
29875 					    __dtrace_ipsr_ill_t *, out_ill,
29876 					    ipha_t *, ipha, ip6_t *, NULL, int,
29877 					    0);
29878 
29879 					ILL_SEND_TX(out_ill,
29880 					    ire, connp, first_mp, 0, connp);
29881 				} else {
29882 					BUMP_MIB(out_ill->ill_ip_mib,
29883 					    ipIfStatsOutDiscards);
29884 					xmit_drop = B_TRUE;
29885 					freemsg(first_mp);
29886 				}
29887 			} else {
29888 				/*
29889 				 * Safety Pup says: make sure this
29890 				 *  is going to the right interface!
29891 				 */
29892 				ill_t *ill1 =
29893 				    (ill_t *)ire->ire_stq->q_ptr;
29894 				int ifindex =
29895 				    ill1->ill_phyint->phyint_ifindex;
29896 				if (ifindex !=
29897 				    io->ipsec_out_capab_ill_index) {
29898 					xmit_drop = B_TRUE;
29899 					freemsg(mp);
29900 				} else {
29901 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29902 					    pkt_len);
29903 
29904 					DTRACE_IP7(send, mblk_t *, first_mp,
29905 					    conn_t *, NULL, void_ip_t *, ipha,
29906 					    __dtrace_ipsr_ill_t *, ill1,
29907 					    ipha_t *, ipha, ip6_t *, NULL,
29908 					    int, 0);
29909 
29910 					ipsec_hw_putnext(ire->ire_stq, mp);
29911 				}
29912 			}
29913 next_mp:
29914 			mp = nxt_mp;
29915 		} /* while (mp != NULL) */
29916 		if (xmit_drop)
29917 			return (SEND_FAILED);
29918 		else
29919 			return (SEND_PASSED);
29920 
29921 	case ND_INITIAL:
29922 	case ND_INCOMPLETE:
29923 
29924 		/*
29925 		 * While we do send off packets to dests that
29926 		 * use fully-resolved CGTP routes, we do not
29927 		 * handle unresolved CGTP routes.
29928 		 */
29929 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29930 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29931 
29932 		if (mp != NULL) {
29933 			/* queue the packet */
29934 			nce_queue_mp_common(arpce, mp, B_FALSE);
29935 		}
29936 
29937 		if (arpce->nce_state == ND_INCOMPLETE) {
29938 			mutex_exit(&arpce->nce_lock);
29939 			DTRACE_PROBE3(ip__xmit__incomplete,
29940 			    (ire_t *), ire, (mblk_t *), mp,
29941 			    (ipsec_out_t *), io);
29942 			return (LOOKUP_IN_PROGRESS);
29943 		}
29944 
29945 		arpce->nce_state = ND_INCOMPLETE;
29946 		mutex_exit(&arpce->nce_lock);
29947 
29948 		/*
29949 		 * Note that ire_add() (called from ire_forward())
29950 		 * holds a ref on the ire until ARP is completed.
29951 		 */
29952 		ire_arpresolve(ire);
29953 		return (LOOKUP_IN_PROGRESS);
29954 	default:
29955 		ASSERT(0);
29956 		mutex_exit(&arpce->nce_lock);
29957 		return (LLHDR_RESLV_FAILED);
29958 	}
29959 }
29960 
29961 #undef	UPDATE_IP_MIB_OB_COUNTERS
29962 
29963 /*
29964  * Return B_TRUE if the buffers differ in length or content.
29965  * This is used for comparing extension header buffers.
29966  * Note that an extension header would be declared different
29967  * even if all that changed was the next header value in that header i.e.
29968  * what really changed is the next extension header.
29969  */
29970 boolean_t
29971 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29972     uint_t blen)
29973 {
29974 	if (!b_valid)
29975 		blen = 0;
29976 
29977 	if (alen != blen)
29978 		return (B_TRUE);
29979 	if (alen == 0)
29980 		return (B_FALSE);	/* Both zero length */
29981 	return (bcmp(abuf, bbuf, alen));
29982 }
29983 
29984 /*
29985  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29986  * Return B_FALSE if memory allocation fails - don't change any state!
29987  */
29988 boolean_t
29989 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29990     const void *src, uint_t srclen)
29991 {
29992 	void *dst;
29993 
29994 	if (!src_valid)
29995 		srclen = 0;
29996 
29997 	ASSERT(*dstlenp == 0);
29998 	if (src != NULL && srclen != 0) {
29999 		dst = mi_alloc(srclen, BPRI_MED);
30000 		if (dst == NULL)
30001 			return (B_FALSE);
30002 	} else {
30003 		dst = NULL;
30004 	}
30005 	if (*dstp != NULL)
30006 		mi_free(*dstp);
30007 	*dstp = dst;
30008 	*dstlenp = dst == NULL ? 0 : srclen;
30009 	return (B_TRUE);
30010 }
30011 
30012 /*
30013  * Replace what is in *dst, *dstlen with the source.
30014  * Assumes ip_allocbuf has already been called.
30015  */
30016 void
30017 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30018     const void *src, uint_t srclen)
30019 {
30020 	if (!src_valid)
30021 		srclen = 0;
30022 
30023 	ASSERT(*dstlenp == srclen);
30024 	if (src != NULL && srclen != 0)
30025 		bcopy(src, *dstp, srclen);
30026 }
30027 
30028 /*
30029  * Free the storage pointed to by the members of an ip6_pkt_t.
30030  */
30031 void
30032 ip6_pkt_free(ip6_pkt_t *ipp)
30033 {
30034 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30035 
30036 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30037 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30038 		ipp->ipp_hopopts = NULL;
30039 		ipp->ipp_hopoptslen = 0;
30040 	}
30041 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30042 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30043 		ipp->ipp_rtdstopts = NULL;
30044 		ipp->ipp_rtdstoptslen = 0;
30045 	}
30046 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30047 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30048 		ipp->ipp_dstopts = NULL;
30049 		ipp->ipp_dstoptslen = 0;
30050 	}
30051 	if (ipp->ipp_fields & IPPF_RTHDR) {
30052 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30053 		ipp->ipp_rthdr = NULL;
30054 		ipp->ipp_rthdrlen = 0;
30055 	}
30056 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30057 	    IPPF_RTHDR);
30058 }
30059 
30060 zoneid_t
30061 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30062     zoneid_t lookup_zoneid)
30063 {
30064 	ire_t		*ire;
30065 	int		ire_flags = MATCH_IRE_TYPE;
30066 	zoneid_t	zoneid = ALL_ZONES;
30067 
30068 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30069 		return (ALL_ZONES);
30070 
30071 	if (lookup_zoneid != ALL_ZONES)
30072 		ire_flags |= MATCH_IRE_ZONEONLY;
30073 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30074 	    lookup_zoneid, NULL, ire_flags, ipst);
30075 	if (ire != NULL) {
30076 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30077 		ire_refrele(ire);
30078 	}
30079 	return (zoneid);
30080 }
30081 
30082 zoneid_t
30083 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30084     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30085 {
30086 	ire_t		*ire;
30087 	int		ire_flags = MATCH_IRE_TYPE;
30088 	zoneid_t	zoneid = ALL_ZONES;
30089 	ipif_t		*ipif_arg = NULL;
30090 
30091 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30092 		return (ALL_ZONES);
30093 
30094 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30095 		ire_flags |= MATCH_IRE_ILL;
30096 		ipif_arg = ill->ill_ipif;
30097 	}
30098 	if (lookup_zoneid != ALL_ZONES)
30099 		ire_flags |= MATCH_IRE_ZONEONLY;
30100 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30101 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30102 	if (ire != NULL) {
30103 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30104 		ire_refrele(ire);
30105 	}
30106 	return (zoneid);
30107 }
30108 
30109 /*
30110  * IP obserability hook support functions.
30111  */
30112 
30113 static void
30114 ipobs_init(ip_stack_t *ipst)
30115 {
30116 	ipst->ips_ipobs_enabled = B_FALSE;
30117 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30118 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30119 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30120 	ipst->ips_ipobs_cb_nwalkers = 0;
30121 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30122 }
30123 
30124 static void
30125 ipobs_fini(ip_stack_t *ipst)
30126 {
30127 	ipobs_cb_t *cb;
30128 
30129 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30130 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30131 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30132 
30133 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30134 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30135 		kmem_free(cb, sizeof (*cb));
30136 	}
30137 	list_destroy(&ipst->ips_ipobs_cb_list);
30138 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30139 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30140 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30141 }
30142 
30143 void
30144 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30145     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30146 {
30147 	mblk_t *mp2;
30148 	ipobs_cb_t *ipobs_cb;
30149 	ipobs_hook_data_t *ihd;
30150 	uint64_t grifindex = 0;
30151 
30152 	ASSERT(DB_TYPE(mp) == M_DATA);
30153 
30154 	if (IS_UNDER_IPMP(ill))
30155 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30156 
30157 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30158 	ipst->ips_ipobs_cb_nwalkers++;
30159 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30160 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30161 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30162 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30163 		if (mp2 != NULL) {
30164 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30165 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30166 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30167 				freemsg(mp2);
30168 				continue;
30169 			}
30170 			ihd->ihd_mp->b_rptr += hlen;
30171 			ihd->ihd_htype = htype;
30172 			ihd->ihd_ipver = ipver;
30173 			ihd->ihd_zsrc = zsrc;
30174 			ihd->ihd_zdst = zdst;
30175 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30176 			ihd->ihd_grifindex = grifindex;
30177 			ihd->ihd_stack = ipst->ips_netstack;
30178 			mp2->b_wptr += sizeof (*ihd);
30179 			ipobs_cb->ipobs_cbfunc(mp2);
30180 		}
30181 	}
30182 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30183 	ipst->ips_ipobs_cb_nwalkers--;
30184 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30185 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30186 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30187 }
30188 
30189 void
30190 ipobs_register_hook(netstack_t *ns, pfv_t func)
30191 {
30192 	ipobs_cb_t   *cb;
30193 	ip_stack_t *ipst = ns->netstack_ip;
30194 
30195 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30196 
30197 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30198 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30199 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30200 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30201 
30202 	cb->ipobs_cbfunc = func;
30203 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30204 	ipst->ips_ipobs_enabled = B_TRUE;
30205 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30206 }
30207 
30208 void
30209 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30210 {
30211 	ipobs_cb_t	*curcb;
30212 	ip_stack_t	*ipst = ns->netstack_ip;
30213 
30214 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30215 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30216 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30217 
30218 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30219 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30220 		if (func == curcb->ipobs_cbfunc) {
30221 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30222 			kmem_free(curcb, sizeof (*curcb));
30223 			break;
30224 		}
30225 	}
30226 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30227 		ipst->ips_ipobs_enabled = B_FALSE;
30228 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30229 }
30230