xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 39b0b3b7a730af51562e3efcb6ee9a2c52f62fb3)
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_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT		15
873 #define	IPV6_FRAG_TIMEOUT	60
874 
875 /*
876  * Threshold which determines whether MDT should be used when
877  * generating IP fragments; payload size must be greater than
878  * this threshold for MDT to take place.
879  */
880 #define	IP_WPUT_FRAG_MDT_MIN	32768
881 
882 /* Setable in /etc/system only */
883 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
884 
885 static long ip_rput_pullups;
886 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
887 
888 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
889 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
890 
891 int	ip_debug;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 
902 /*
903  * XXX following really should only be in a header. Would need more
904  * header and .c clean up first.
905  */
906 extern optdb_obj_t	ip_opt_obj;
907 
908 ulong_t ip_squeue_enter_unbound = 0;
909 
910 /*
911  * Named Dispatch Parameter Table.
912  * All of these are alterable, within the min/max values given, at run time.
913  */
914 static ipparam_t	lcl_param_arr[] = {
915 	/* min	max	value	name */
916 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
921 	{  0,	1,	1,	"ip_send_redirects"},
922 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
923 	{  0,	10,	0,	"ip_mrtdebug"},
924 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
925 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
926 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
927 	{  1,	255,	255,	"ip_def_ttl" },
928 	{  0,	1,	0,	"ip_forward_src_routed"},
929 	{  0,	256,	32,	"ip_wroff_extra" },
930 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
931 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
932 	{  0,	1,	1,	"ip_path_mtu_discovery" },
933 	{  0,	240,	30,	"ip_ignore_delete_time" },
934 	{  0,	1,	0,	"ip_ignore_redirect" },
935 	{  0,	1,	1,	"ip_output_queue" },
936 	{  1,	254,	1,	"ip_broadcast_ttl" },
937 	{  0,	99999,	100,	"ip_icmp_err_interval" },
938 	{  1,	99999,	10,	"ip_icmp_err_burst" },
939 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
940 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
941 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
942 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
943 	{  0,	1,	1,	"icmp_accept_clear_messages" },
944 	{  0,	1,	1,	"igmp_accept_clear_messages" },
945 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
946 				"ip_ndp_delay_first_probe_time"},
947 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
948 				"ip_ndp_max_unicast_solicit"},
949 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
950 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
951 	{  0,	1,	0,	"ip6_forward_src_routed"},
952 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
953 	{  0,	1,	1,	"ip6_send_redirects"},
954 	{  0,	1,	0,	"ip6_ignore_redirect" },
955 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
956 
957 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
958 
959 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
960 
961 	{  0,	1,	1,	"pim_accept_clear_messages" },
962 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
963 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
964 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
965 	{  0,	15,	0,	"ip_policy_mask" },
966 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
967 	{  0,	255,	1,	"ip_multirt_ttl" },
968 	{  0,	1,	1,	"ip_multidata_outbound" },
969 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
970 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
971 	{  0,	1000,	1,	"ip_max_temp_defend" },
972 	{  0,	1000,	3,	"ip_max_defend" },
973 	{  0,	999999,	30,	"ip_defend_interval" },
974 	{  0,	3600000, 300000, "ip_dup_recovery" },
975 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
976 	{  0,	1,	1,	"ip_lso_outbound" },
977 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
978 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
979 	{ 68,	65535,	576,	"ip_pmtu_min" },
980 #ifdef DEBUG
981 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
982 #else
983 	{  0,	0,	0,	"" },
984 #endif
985 };
986 
987 /*
988  * Extended NDP table
989  * The addresses for the first two are filled in to be ips_ip_g_forward
990  * and ips_ipv6_forward at init time.
991  */
992 static ipndp_t	lcl_ndp_arr[] = {
993 	/* getf			setf		data			name */
994 #define	IPNDP_IP_FORWARDING_OFFSET	0
995 	{  ip_param_generic_get,	ip_forward_set,	NULL,
996 	    "ip_forwarding" },
997 #define	IPNDP_IP6_FORWARDING_OFFSET	1
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip6_forwarding" },
1000 	{ ip_param_generic_get, ip_input_proc_set,
1001 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1002 	{ ip_param_generic_get, ip_int_set,
1003 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1004 #define	IPNDP_CGTP_FILTER_OFFSET	4
1005 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1006 	    "ip_cgtp_filter" },
1007 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1008 	    "ip_debug" },
1009 };
1010 
1011 /*
1012  * Table of IP ioctls encoding the various properties of the ioctl and
1013  * indexed based on the last byte of the ioctl command. Occasionally there
1014  * is a clash, and there is more than 1 ioctl with the same last byte.
1015  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1016  * ioctls are encoded in the misc table. An entry in the ndx table is
1017  * retrieved by indexing on the last byte of the ioctl command and comparing
1018  * the ioctl command with the value in the ndx table. In the event of a
1019  * mismatch the misc table is then searched sequentially for the desired
1020  * ioctl command.
1021  *
1022  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1023  */
1024 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1025 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1037 			MISC_CMD, ip_siocaddrt, NULL },
1038 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1039 			MISC_CMD, ip_siocdelrt, NULL },
1040 
1041 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1042 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1043 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1044 			IF_CMD, ip_sioctl_get_addr, NULL },
1045 
1046 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1048 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1050 
1051 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1052 			IPI_PRIV | IPI_WR,
1053 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1054 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1055 			IPI_MODOK | IPI_GET_CMD,
1056 			IF_CMD, ip_sioctl_get_flags, NULL },
1057 
1058 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* copyin size cannot be coded for SIOCGIFCONF */
1062 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1063 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1064 
1065 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_mtu, NULL },
1067 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1068 			IF_CMD, ip_sioctl_get_mtu, NULL },
1069 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1070 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1071 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1072 			IF_CMD, ip_sioctl_brdaddr, NULL },
1073 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1074 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1075 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1076 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1077 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1078 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1079 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1080 			IF_CMD, ip_sioctl_metric, NULL },
1081 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* See 166-168 below for extended SIOC*XARP ioctls */
1084 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1085 			ARP_CMD, ip_sioctl_arp, NULL },
1086 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1087 			ARP_CMD, ip_sioctl_arp, NULL },
1088 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1089 			ARP_CMD, ip_sioctl_arp, NULL },
1090 
1091 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1114 			MISC_CMD, if_unitsel, if_unitsel_restart },
1115 
1116 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1136 			IPI_PRIV | IPI_WR | IPI_MODOK,
1137 			IF_CMD, ip_sioctl_sifname, NULL },
1138 
1139 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 
1153 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1154 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1155 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1156 			IF_CMD, ip_sioctl_get_muxid, NULL },
1157 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1159 
1160 	/* Both if and lif variants share same func */
1161 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1162 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1163 	/* Both if and lif variants share same func */
1164 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1165 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1190 			ip_sioctl_removeif_restart },
1191 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_addif, NULL },
1194 #define	SIOCLIFADDR_NDX 112
1195 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1197 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1198 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1203 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1206 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_get_flags, NULL },
1209 
1210 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 
1213 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1214 			ip_sioctl_get_lifconf, NULL },
1215 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_mtu, NULL },
1217 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1218 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1219 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1220 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1221 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1223 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1225 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1227 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1229 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_metric, NULL },
1231 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR | IPI_MODOK,
1233 			LIF_CMD, ip_sioctl_slifname,
1234 			ip_sioctl_slifname_restart },
1235 
1236 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1237 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1238 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1239 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1240 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1242 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1244 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1246 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 			LIF_CMD, ip_sioctl_token, NULL },
1248 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1249 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1250 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1252 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1253 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1254 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1256 
1257 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1258 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1259 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1260 			LIF_CMD, ip_siocdelndp_v6, NULL },
1261 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1262 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1263 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1264 			LIF_CMD, ip_siocsetndp_v6, NULL },
1265 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1266 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1267 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1268 			MISC_CMD, ip_sioctl_tonlink, NULL },
1269 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1270 			MISC_CMD, ip_sioctl_tmysite, NULL },
1271 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1272 			TUN_CMD, ip_sioctl_tunparam, NULL },
1273 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1274 		    IPI_PRIV | IPI_WR,
1275 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1276 
1277 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1278 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1280 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1281 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1282 
1283 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1284 
1285 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1286 			LIF_CMD, ip_sioctl_get_binding, NULL },
1287 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1288 			IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1290 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1291 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1292 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1293 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1294 
1295 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1296 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 
1300 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 
1302 	/* These are handled in ip_sioctl_copyin_setup itself */
1303 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1304 			MISC_CMD, NULL, NULL },
1305 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1306 			MISC_CMD, NULL, NULL },
1307 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1308 
1309 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1310 			ip_sioctl_get_lifconf, NULL },
1311 
1312 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1313 			XARP_CMD, ip_sioctl_arp, NULL },
1314 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1315 			XARP_CMD, ip_sioctl_arp, NULL },
1316 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1317 			XARP_CMD, ip_sioctl_arp, NULL },
1318 
1319 	/* SIOCPOPSOCKFS is not handled by IP */
1320 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1321 
1322 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1323 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1324 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1325 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1326 			ip_sioctl_slifzone_restart },
1327 	/* 172-174 are SCTP ioctls and not handled by IP */
1328 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1329 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1330 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1331 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1332 			IPI_GET_CMD, LIF_CMD,
1333 			ip_sioctl_get_lifusesrc, 0 },
1334 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1335 			IPI_PRIV | IPI_WR,
1336 			LIF_CMD, ip_sioctl_slifusesrc,
1337 			NULL },
1338 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1339 			ip_sioctl_get_lifsrcof, NULL },
1340 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1341 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1342 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1343 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1344 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1345 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1346 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1347 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1348 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1349 	/* SIOCSENABLESDP is handled by SDP */
1350 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1351 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1352 };
1353 
1354 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1355 
1356 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1357 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1358 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1359 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1360 		TUN_CMD, ip_sioctl_tunparam, NULL },
1361 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1365 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1366 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1367 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1368 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1369 		MISC_CMD, mrt_ioctl},
1370 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1371 		MISC_CMD, mrt_ioctl},
1372 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1373 		MISC_CMD, mrt_ioctl}
1374 };
1375 
1376 int ip_misc_ioctl_count =
1377     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1378 
1379 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1380 					/* Settable in /etc/system */
1381 /* Defined in ip_ire.c */
1382 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1383 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1384 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1385 
1386 static nv_t	ire_nv_arr[] = {
1387 	{ IRE_BROADCAST, "BROADCAST" },
1388 	{ IRE_LOCAL, "LOCAL" },
1389 	{ IRE_LOOPBACK, "LOOPBACK" },
1390 	{ IRE_CACHE, "CACHE" },
1391 	{ IRE_DEFAULT, "DEFAULT" },
1392 	{ IRE_PREFIX, "PREFIX" },
1393 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1394 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1395 	{ IRE_HOST, "HOST" },
1396 	{ 0 }
1397 };
1398 
1399 nv_t	*ire_nv_tbl = ire_nv_arr;
1400 
1401 /* Simple ICMP IP Header Template */
1402 static ipha_t icmp_ipha = {
1403 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1404 };
1405 
1406 struct module_info ip_mod_info = {
1407 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1408 	IP_MOD_LOWAT
1409 };
1410 
1411 /*
1412  * Duplicate static symbols within a module confuses mdb; so we avoid the
1413  * problem by making the symbols here distinct from those in udp.c.
1414  */
1415 
1416 /*
1417  * Entry points for IP as a device and as a module.
1418  * FIXME: down the road we might want a separate module and driver qinit.
1419  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1420  */
1421 static struct qinit iprinitv4 = {
1422 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1423 	&ip_mod_info
1424 };
1425 
1426 struct qinit iprinitv6 = {
1427 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1428 	&ip_mod_info
1429 };
1430 
1431 static struct qinit ipwinitv4 = {
1432 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1433 	&ip_mod_info
1434 };
1435 
1436 struct qinit ipwinitv6 = {
1437 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1438 	&ip_mod_info
1439 };
1440 
1441 static struct qinit iplrinit = {
1442 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1443 	&ip_mod_info
1444 };
1445 
1446 static struct qinit iplwinit = {
1447 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1448 	&ip_mod_info
1449 };
1450 
1451 /* For AF_INET aka /dev/ip */
1452 struct streamtab ipinfov4 = {
1453 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1454 };
1455 
1456 /* For AF_INET6 aka /dev/ip6 */
1457 struct streamtab ipinfov6 = {
1458 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1459 };
1460 
1461 #ifdef	DEBUG
1462 static boolean_t skip_sctp_cksum = B_FALSE;
1463 #endif
1464 
1465 /*
1466  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1467  * ip_rput_v6(), ip_output(), etc.  If the message
1468  * block already has a M_CTL at the front of it, then simply set the zoneid
1469  * appropriately.
1470  */
1471 mblk_t *
1472 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1473 {
1474 	mblk_t		*first_mp;
1475 	ipsec_out_t	*io;
1476 
1477 	ASSERT(zoneid != ALL_ZONES);
1478 	if (mp->b_datap->db_type == M_CTL) {
1479 		io = (ipsec_out_t *)mp->b_rptr;
1480 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1481 		io->ipsec_out_zoneid = zoneid;
1482 		return (mp);
1483 	}
1484 
1485 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1486 	if (first_mp == NULL)
1487 		return (NULL);
1488 	io = (ipsec_out_t *)first_mp->b_rptr;
1489 	/* This is not a secure packet */
1490 	io->ipsec_out_secure = B_FALSE;
1491 	io->ipsec_out_zoneid = zoneid;
1492 	first_mp->b_cont = mp;
1493 	return (first_mp);
1494 }
1495 
1496 /*
1497  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1498  */
1499 mblk_t *
1500 ip_copymsg(mblk_t *mp)
1501 {
1502 	mblk_t *nmp;
1503 	ipsec_info_t *in;
1504 
1505 	if (mp->b_datap->db_type != M_CTL)
1506 		return (copymsg(mp));
1507 
1508 	in = (ipsec_info_t *)mp->b_rptr;
1509 
1510 	/*
1511 	 * Note that M_CTL is also used for delivering ICMP error messages
1512 	 * upstream to transport layers.
1513 	 */
1514 	if (in->ipsec_info_type != IPSEC_OUT &&
1515 	    in->ipsec_info_type != IPSEC_IN)
1516 		return (copymsg(mp));
1517 
1518 	nmp = copymsg(mp->b_cont);
1519 
1520 	if (in->ipsec_info_type == IPSEC_OUT) {
1521 		return (ipsec_out_tag(mp, nmp,
1522 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1523 	} else {
1524 		return (ipsec_in_tag(mp, nmp,
1525 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1526 	}
1527 }
1528 
1529 /* Generate an ICMP fragmentation needed message. */
1530 static void
1531 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1532     ip_stack_t *ipst)
1533 {
1534 	icmph_t	icmph;
1535 	mblk_t *first_mp;
1536 	boolean_t mctl_present;
1537 
1538 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1539 
1540 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1541 		if (mctl_present)
1542 			freeb(first_mp);
1543 		return;
1544 	}
1545 
1546 	bzero(&icmph, sizeof (icmph_t));
1547 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1548 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1549 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1550 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1551 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1552 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1553 	    ipst);
1554 }
1555 
1556 /*
1557  * icmp_inbound deals with ICMP messages in the following ways.
1558  *
1559  * 1) It needs to send a reply back and possibly delivering it
1560  *    to the "interested" upper clients.
1561  * 2) It needs to send it to the upper clients only.
1562  * 3) It needs to change some values in IP only.
1563  * 4) It needs to change some values in IP and upper layers e.g TCP.
1564  *
1565  * We need to accomodate icmp messages coming in clear until we get
1566  * everything secure from the wire. If icmp_accept_clear_messages
1567  * is zero we check with the global policy and act accordingly. If
1568  * it is non-zero, we accept the message without any checks. But
1569  * *this does not mean* that this will be delivered to the upper
1570  * clients. By accepting we might send replies back, change our MTU
1571  * value etc. but delivery to the ULP/clients depends on their policy
1572  * dispositions.
1573  *
1574  * We handle the above 4 cases in the context of IPsec in the
1575  * following way :
1576  *
1577  * 1) Send the reply back in the same way as the request came in.
1578  *    If it came in encrypted, it goes out encrypted. If it came in
1579  *    clear, it goes out in clear. Thus, this will prevent chosen
1580  *    plain text attack.
1581  * 2) The client may or may not expect things to come in secure.
1582  *    If it comes in secure, the policy constraints are checked
1583  *    before delivering it to the upper layers. If it comes in
1584  *    clear, ipsec_inbound_accept_clear will decide whether to
1585  *    accept this in clear or not. In both the cases, if the returned
1586  *    message (IP header + 8 bytes) that caused the icmp message has
1587  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1588  *    sending up. If there are only 8 bytes of returned message, then
1589  *    upper client will not be notified.
1590  * 3) Check with global policy to see whether it matches the constaints.
1591  *    But this will be done only if icmp_accept_messages_in_clear is
1592  *    zero.
1593  * 4) If we need to change both in IP and ULP, then the decision taken
1594  *    while affecting the values in IP and while delivering up to TCP
1595  *    should be the same.
1596  *
1597  * 	There are two cases.
1598  *
1599  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1600  *	   failed), we will not deliver it to the ULP, even though they
1601  *	   are *willing* to accept in *clear*. This is fine as our global
1602  *	   disposition to icmp messages asks us reject the datagram.
1603  *
1604  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1605  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1606  *	   to deliver it to ULP (policy failed), it can lead to
1607  *	   consistency problems. The cases known at this time are
1608  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1609  *	   values :
1610  *
1611  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1612  *	     and Upper layer rejects. Then the communication will
1613  *	     come to a stop. This is solved by making similar decisions
1614  *	     at both levels. Currently, when we are unable to deliver
1615  *	     to the Upper Layer (due to policy failures) while IP has
1616  *	     adjusted ire_max_frag, the next outbound datagram would
1617  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1618  *	     will be with the right level of protection. Thus the right
1619  *	     value will be communicated even if we are not able to
1620  *	     communicate when we get from the wire initially. But this
1621  *	     assumes there would be at least one outbound datagram after
1622  *	     IP has adjusted its ire_max_frag value. To make things
1623  *	     simpler, we accept in clear after the validation of
1624  *	     AH/ESP headers.
1625  *
1626  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1627  *	     upper layer depending on the level of protection the upper
1628  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1629  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1630  *	     should be accepted in clear when the Upper layer expects secure.
1631  *	     Thus the communication may get aborted by some bad ICMP
1632  *	     packets.
1633  *
1634  * IPQoS Notes:
1635  * The only instance when a packet is sent for processing is when there
1636  * isn't an ICMP client and if we are interested in it.
1637  * If there is a client, IPPF processing will take place in the
1638  * ip_fanout_proto routine.
1639  *
1640  * Zones notes:
1641  * The packet is only processed in the context of the specified zone: typically
1642  * only this zone will reply to an echo request, and only interested clients in
1643  * this zone will receive a copy of the packet. This means that the caller must
1644  * call icmp_inbound() for each relevant zone.
1645  */
1646 static void
1647 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1648     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1649     ill_t *recv_ill, zoneid_t zoneid)
1650 {
1651 	icmph_t	*icmph;
1652 	ipha_t	*ipha;
1653 	int	iph_hdr_length;
1654 	int	hdr_length;
1655 	boolean_t	interested;
1656 	uint32_t	ts;
1657 	uchar_t	*wptr;
1658 	ipif_t	*ipif;
1659 	mblk_t *first_mp;
1660 	ipsec_in_t *ii;
1661 	timestruc_t now;
1662 	uint32_t ill_index;
1663 	ip_stack_t *ipst;
1664 
1665 	ASSERT(ill != NULL);
1666 	ipst = ill->ill_ipst;
1667 
1668 	first_mp = mp;
1669 	if (mctl_present) {
1670 		mp = first_mp->b_cont;
1671 		ASSERT(mp != NULL);
1672 	}
1673 
1674 	ipha = (ipha_t *)mp->b_rptr;
1675 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1676 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1677 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1678 		if (first_mp == NULL)
1679 			return;
1680 	}
1681 
1682 	/*
1683 	 * On a labeled system, we have to check whether the zone itself is
1684 	 * permitted to receive raw traffic.
1685 	 */
1686 	if (is_system_labeled()) {
1687 		if (zoneid == ALL_ZONES)
1688 			zoneid = tsol_packet_to_zoneid(mp);
1689 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1690 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1691 			    zoneid));
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1693 			freemsg(first_mp);
1694 			return;
1695 		}
1696 	}
1697 
1698 	/*
1699 	 * We have accepted the ICMP message. It means that we will
1700 	 * respond to the packet if needed. It may not be delivered
1701 	 * to the upper client depending on the policy constraints
1702 	 * and the disposition in ipsec_inbound_accept_clear.
1703 	 */
1704 
1705 	ASSERT(ill != NULL);
1706 
1707 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1708 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1709 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1710 		/* Last chance to get real. */
1711 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1712 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1713 			freemsg(first_mp);
1714 			return;
1715 		}
1716 		/* Refresh iph following the pullup. */
1717 		ipha = (ipha_t *)mp->b_rptr;
1718 	}
1719 	/* ICMP header checksum, including checksum field, should be zero. */
1720 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1721 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1723 		freemsg(first_mp);
1724 		return;
1725 	}
1726 	/* The IP header will always be a multiple of four bytes */
1727 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1728 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1729 	    icmph->icmph_code));
1730 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1731 	/* We will set "interested" to "true" if we want a copy */
1732 	interested = B_FALSE;
1733 	switch (icmph->icmph_type) {
1734 	case ICMP_ECHO_REPLY:
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1736 		break;
1737 	case ICMP_DEST_UNREACHABLE:
1738 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1739 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1740 		interested = B_TRUE;	/* Pass up to transport */
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1742 		break;
1743 	case ICMP_SOURCE_QUENCH:
1744 		interested = B_TRUE;	/* Pass up to transport */
1745 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1746 		break;
1747 	case ICMP_REDIRECT:
1748 		if (!ipst->ips_ip_ignore_redirect)
1749 			interested = B_TRUE;
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1751 		break;
1752 	case ICMP_ECHO_REQUEST:
1753 		/*
1754 		 * Whether to respond to echo requests that come in as IP
1755 		 * broadcasts or as IP multicast is subject to debate
1756 		 * (what isn't?).  We aim to please, you pick it.
1757 		 * Default is do it.
1758 		 */
1759 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1760 			/* unicast: always respond */
1761 			interested = B_TRUE;
1762 		} else if (CLASSD(ipha->ipha_dst)) {
1763 			/* multicast: respond based on tunable */
1764 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1765 		} else if (broadcast) {
1766 			/* broadcast: respond based on tunable */
1767 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1768 		}
1769 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1770 		break;
1771 	case ICMP_ROUTER_ADVERTISEMENT:
1772 	case ICMP_ROUTER_SOLICITATION:
1773 		break;
1774 	case ICMP_TIME_EXCEEDED:
1775 		interested = B_TRUE;	/* Pass up to transport */
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1777 		break;
1778 	case ICMP_PARAM_PROBLEM:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1781 		break;
1782 	case ICMP_TIME_STAMP_REQUEST:
1783 		/* Response to Time Stamp Requests is local policy. */
1784 		if (ipst->ips_ip_g_resp_to_timestamp &&
1785 		    /* So is whether to respond if it was an IP broadcast. */
1786 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1787 			int tstamp_len = 3 * sizeof (uint32_t);
1788 
1789 			if (wptr +  tstamp_len > mp->b_wptr) {
1790 				if (!pullupmsg(mp, wptr + tstamp_len -
1791 				    mp->b_rptr)) {
1792 					BUMP_MIB(ill->ill_ip_mib,
1793 					    ipIfStatsInDiscards);
1794 					freemsg(first_mp);
1795 					return;
1796 				}
1797 				/* Refresh ipha following the pullup. */
1798 				ipha = (ipha_t *)mp->b_rptr;
1799 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1800 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1801 			}
1802 			interested = B_TRUE;
1803 		}
1804 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1805 		break;
1806 	case ICMP_TIME_STAMP_REPLY:
1807 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1808 		break;
1809 	case ICMP_INFO_REQUEST:
1810 		/* Per RFC 1122 3.2.2.7, ignore this. */
1811 	case ICMP_INFO_REPLY:
1812 		break;
1813 	case ICMP_ADDRESS_MASK_REQUEST:
1814 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1815 		    !broadcast) &&
1816 		    /* TODO m_pullup of complete header? */
1817 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1818 			interested = B_TRUE;
1819 		}
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1821 		break;
1822 	case ICMP_ADDRESS_MASK_REPLY:
1823 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1824 		break;
1825 	default:
1826 		interested = B_TRUE;	/* Pass up to transport */
1827 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1828 		break;
1829 	}
1830 	/* See if there is an ICMP client. */
1831 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1832 		/* If there is an ICMP client and we want one too, copy it. */
1833 		mblk_t *first_mp1;
1834 
1835 		if (!interested) {
1836 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1837 			    ip_policy, recv_ill, zoneid);
1838 			return;
1839 		}
1840 		first_mp1 = ip_copymsg(first_mp);
1841 		if (first_mp1 != NULL) {
1842 			ip_fanout_proto(q, first_mp1, ill, ipha,
1843 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1844 		}
1845 	} else if (!interested) {
1846 		freemsg(first_mp);
1847 		return;
1848 	} else {
1849 		/*
1850 		 * Initiate policy processing for this packet if ip_policy
1851 		 * is true.
1852 		 */
1853 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1854 			ill_index = ill->ill_phyint->phyint_ifindex;
1855 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1856 			if (mp == NULL) {
1857 				if (mctl_present) {
1858 					freeb(first_mp);
1859 				}
1860 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1861 				return;
1862 			}
1863 		}
1864 	}
1865 	/* We want to do something with it. */
1866 	/* Check db_ref to make sure we can modify the packet. */
1867 	if (mp->b_datap->db_ref > 1) {
1868 		mblk_t	*first_mp1;
1869 
1870 		first_mp1 = ip_copymsg(first_mp);
1871 		freemsg(first_mp);
1872 		if (!first_mp1) {
1873 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1874 			return;
1875 		}
1876 		first_mp = first_mp1;
1877 		if (mctl_present) {
1878 			mp = first_mp->b_cont;
1879 			ASSERT(mp != NULL);
1880 		} else {
1881 			mp = first_mp;
1882 		}
1883 		ipha = (ipha_t *)mp->b_rptr;
1884 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1885 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1886 	}
1887 	switch (icmph->icmph_type) {
1888 	case ICMP_ADDRESS_MASK_REQUEST:
1889 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1890 		if (ipif == NULL) {
1891 			freemsg(first_mp);
1892 			return;
1893 		}
1894 		/*
1895 		 * outging interface must be IPv4
1896 		 */
1897 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1898 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1899 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1900 		ipif_refrele(ipif);
1901 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1902 		break;
1903 	case ICMP_ECHO_REQUEST:
1904 		icmph->icmph_type = ICMP_ECHO_REPLY;
1905 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1906 		break;
1907 	case ICMP_TIME_STAMP_REQUEST: {
1908 		uint32_t *tsp;
1909 
1910 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1911 		tsp = (uint32_t *)wptr;
1912 		tsp++;		/* Skip past 'originate time' */
1913 		/* Compute # of milliseconds since midnight */
1914 		gethrestime(&now);
1915 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1916 		    now.tv_nsec / (NANOSEC / MILLISEC);
1917 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1918 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1919 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1920 		break;
1921 	}
1922 	default:
1923 		ipha = (ipha_t *)&icmph[1];
1924 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1925 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1926 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1927 				freemsg(first_mp);
1928 				return;
1929 			}
1930 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1931 			ipha = (ipha_t *)&icmph[1];
1932 		}
1933 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1935 			freemsg(first_mp);
1936 			return;
1937 		}
1938 		hdr_length = IPH_HDR_LENGTH(ipha);
1939 		if (hdr_length < sizeof (ipha_t)) {
1940 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1941 			freemsg(first_mp);
1942 			return;
1943 		}
1944 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1945 			if (!pullupmsg(mp,
1946 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1947 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 				freemsg(first_mp);
1949 				return;
1950 			}
1951 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1952 			ipha = (ipha_t *)&icmph[1];
1953 		}
1954 		switch (icmph->icmph_type) {
1955 		case ICMP_REDIRECT:
1956 			/*
1957 			 * As there is no upper client to deliver, we don't
1958 			 * need the first_mp any more.
1959 			 */
1960 			if (mctl_present) {
1961 				freeb(first_mp);
1962 			}
1963 			icmp_redirect(ill, mp);
1964 			return;
1965 		case ICMP_DEST_UNREACHABLE:
1966 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1967 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1968 				    zoneid, mp, iph_hdr_length, ipst)) {
1969 					freemsg(first_mp);
1970 					return;
1971 				}
1972 				/*
1973 				 * icmp_inbound_too_big() may alter mp.
1974 				 * Resynch ipha and icmph accordingly.
1975 				 */
1976 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1977 				ipha = (ipha_t *)&icmph[1];
1978 			}
1979 			/* FALLTHRU */
1980 		default :
1981 			/*
1982 			 * IPQoS notes: Since we have already done IPQoS
1983 			 * processing we don't want to do it again in
1984 			 * the fanout routines called by
1985 			 * icmp_inbound_error_fanout, hence the last
1986 			 * argument, ip_policy, is B_FALSE.
1987 			 */
1988 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1989 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1990 			    B_FALSE, recv_ill, zoneid);
1991 		}
1992 		return;
1993 	}
1994 	/* Send out an ICMP packet */
1995 	icmph->icmph_checksum = 0;
1996 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1997 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1998 		ipif_t	*ipif_chosen;
1999 		/*
2000 		 * Make it look like it was directed to us, so we don't look
2001 		 * like a fool with a broadcast or multicast source address.
2002 		 */
2003 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2004 		/*
2005 		 * Make sure that we haven't grabbed an interface that's DOWN.
2006 		 */
2007 		if (ipif != NULL) {
2008 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2009 			    ipha->ipha_src, zoneid);
2010 			if (ipif_chosen != NULL) {
2011 				ipif_refrele(ipif);
2012 				ipif = ipif_chosen;
2013 			}
2014 		}
2015 		if (ipif == NULL) {
2016 			ip0dbg(("icmp_inbound: "
2017 			    "No source for broadcast/multicast:\n"
2018 			    "\tsrc 0x%x dst 0x%x ill %p "
2019 			    "ipif_lcl_addr 0x%x\n",
2020 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2021 			    (void *)ill,
2022 			    ill->ill_ipif->ipif_lcl_addr));
2023 			freemsg(first_mp);
2024 			return;
2025 		}
2026 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2027 		ipha->ipha_dst = ipif->ipif_src_addr;
2028 		ipif_refrele(ipif);
2029 	}
2030 	/* Reset time to live. */
2031 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2032 	{
2033 		/* Swap source and destination addresses */
2034 		ipaddr_t tmp;
2035 
2036 		tmp = ipha->ipha_src;
2037 		ipha->ipha_src = ipha->ipha_dst;
2038 		ipha->ipha_dst = tmp;
2039 	}
2040 	ipha->ipha_ident = 0;
2041 	if (!IS_SIMPLE_IPH(ipha))
2042 		icmp_options_update(ipha);
2043 
2044 	if (!mctl_present) {
2045 		/*
2046 		 * This packet should go out the same way as it
2047 		 * came in i.e in clear. To make sure that global
2048 		 * policy will not be applied to this in ip_wput_ire,
2049 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2050 		 */
2051 		ASSERT(first_mp == mp);
2052 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2053 		if (first_mp == NULL) {
2054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 			freemsg(mp);
2056 			return;
2057 		}
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 
2060 		/* This is not a secure packet */
2061 		ii->ipsec_in_secure = B_FALSE;
2062 		first_mp->b_cont = mp;
2063 	} else {
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	}
2067 	ii->ipsec_in_zoneid = zoneid;
2068 	ASSERT(zoneid != ALL_ZONES);
2069 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2071 		return;
2072 	}
2073 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2074 	put(WR(q), first_mp);
2075 }
2076 
2077 static ipaddr_t
2078 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2079 {
2080 	conn_t *connp;
2081 	connf_t *connfp;
2082 	ipaddr_t nexthop_addr = INADDR_ANY;
2083 	int hdr_length = IPH_HDR_LENGTH(ipha);
2084 	uint16_t *up;
2085 	uint32_t ports;
2086 	ip_stack_t *ipst = ill->ill_ipst;
2087 
2088 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2089 	switch (ipha->ipha_protocol) {
2090 		case IPPROTO_TCP:
2091 		{
2092 			tcph_t *tcph;
2093 
2094 			/* do a reverse lookup */
2095 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2096 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2097 			    TCPS_LISTEN, ipst);
2098 			break;
2099 		}
2100 		case IPPROTO_UDP:
2101 		{
2102 			uint32_t dstport, srcport;
2103 
2104 			((uint16_t *)&ports)[0] = up[1];
2105 			((uint16_t *)&ports)[1] = up[0];
2106 
2107 			/* Extract ports in net byte order */
2108 			dstport = htons(ntohl(ports) & 0xFFFF);
2109 			srcport = htons(ntohl(ports) >> 16);
2110 
2111 			connfp = &ipst->ips_ipcl_udp_fanout[
2112 			    IPCL_UDP_HASH(dstport, ipst)];
2113 			mutex_enter(&connfp->connf_lock);
2114 			connp = connfp->connf_head;
2115 
2116 			/* do a reverse lookup */
2117 			while ((connp != NULL) &&
2118 			    (!IPCL_UDP_MATCH(connp, dstport,
2119 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2120 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2121 				connp = connp->conn_next;
2122 			}
2123 			if (connp != NULL)
2124 				CONN_INC_REF(connp);
2125 			mutex_exit(&connfp->connf_lock);
2126 			break;
2127 		}
2128 		case IPPROTO_SCTP:
2129 		{
2130 			in6_addr_t map_src, map_dst;
2131 
2132 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2133 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2134 			((uint16_t *)&ports)[0] = up[1];
2135 			((uint16_t *)&ports)[1] = up[0];
2136 
2137 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2138 			    zoneid, ipst->ips_netstack->netstack_sctp);
2139 			if (connp == NULL) {
2140 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2141 				    zoneid, ports, ipha, ipst);
2142 			} else {
2143 				CONN_INC_REF(connp);
2144 				SCTP_REFRELE(CONN2SCTP(connp));
2145 			}
2146 			break;
2147 		}
2148 		default:
2149 		{
2150 			ipha_t ripha;
2151 
2152 			ripha.ipha_src = ipha->ipha_dst;
2153 			ripha.ipha_dst = ipha->ipha_src;
2154 			ripha.ipha_protocol = ipha->ipha_protocol;
2155 
2156 			connfp = &ipst->ips_ipcl_proto_fanout[
2157 			    ipha->ipha_protocol];
2158 			mutex_enter(&connfp->connf_lock);
2159 			connp = connfp->connf_head;
2160 			for (connp = connfp->connf_head; connp != NULL;
2161 			    connp = connp->conn_next) {
2162 				if (IPCL_PROTO_MATCH(connp,
2163 				    ipha->ipha_protocol, &ripha, ill,
2164 				    0, zoneid)) {
2165 					CONN_INC_REF(connp);
2166 					break;
2167 				}
2168 			}
2169 			mutex_exit(&connfp->connf_lock);
2170 		}
2171 	}
2172 	if (connp != NULL) {
2173 		if (connp->conn_nexthop_set)
2174 			nexthop_addr = connp->conn_nexthop_v4;
2175 		CONN_DEC_REF(connp);
2176 	}
2177 	return (nexthop_addr);
2178 }
2179 
2180 /* Table from RFC 1191 */
2181 static int icmp_frag_size_table[] =
2182 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2183 
2184 /*
2185  * Process received ICMP Packet too big.
2186  * After updating any IRE it does the fanout to any matching transport streams.
2187  * Assumes the message has been pulled up till the IP header that caused
2188  * the error.
2189  *
2190  * Returns B_FALSE on failure and B_TRUE on success.
2191  */
2192 static boolean_t
2193 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2194     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2195     ip_stack_t *ipst)
2196 {
2197 	ire_t	*ire, *first_ire;
2198 	int	mtu, orig_mtu;
2199 	int	hdr_length;
2200 	ipaddr_t nexthop_addr;
2201 	boolean_t disable_pmtud;
2202 
2203 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2204 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2205 	ASSERT(ill != NULL);
2206 
2207 	hdr_length = IPH_HDR_LENGTH(ipha);
2208 
2209 	/* Drop if the original packet contained a source route */
2210 	if (ip_source_route_included(ipha)) {
2211 		return (B_FALSE);
2212 	}
2213 	/*
2214 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2215 	 * header.
2216 	 */
2217 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2218 	    mp->b_wptr) {
2219 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2220 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2222 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2223 			return (B_FALSE);
2224 		}
2225 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2226 		ipha = (ipha_t *)&icmph[1];
2227 	}
2228 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2229 	if (nexthop_addr != INADDR_ANY) {
2230 		/* nexthop set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2232 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2233 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2234 	} else {
2235 		/* nexthop not set */
2236 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2237 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2238 	}
2239 
2240 	if (!first_ire) {
2241 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2242 		    ntohl(ipha->ipha_dst)));
2243 		return (B_FALSE);
2244 	}
2245 
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	orig_mtu = mtu;
2249 	disable_pmtud = B_FALSE;
2250 
2251 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2252 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2253 	    ire = ire->ire_next) {
2254 		/*
2255 		 * Look for the connection to which this ICMP message is
2256 		 * directed. If it has the IP_NEXTHOP option set, then the
2257 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2258 		 * option. Else the search is limited to regular IREs.
2259 		 */
2260 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2262 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2263 		    (nexthop_addr != INADDR_ANY)))
2264 			continue;
2265 
2266 		mutex_enter(&ire->ire_lock);
2267 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2268 			uint32_t length;
2269 			int	i;
2270 
2271 			/*
2272 			 * Use the table from RFC 1191 to figure out
2273 			 * the next "plateau" based on the length in
2274 			 * the original IP packet.
2275 			 */
2276 			length = ntohs(ipha->ipha_length);
2277 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2278 			    uint32_t, length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				length -= hdr_length;
2287 			}
2288 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2289 				if (length > icmp_frag_size_table[i])
2290 					break;
2291 			}
2292 			if (i == A_CNT(icmp_frag_size_table)) {
2293 				/* Smaller than 68! */
2294 				disable_pmtud = B_TRUE;
2295 				mtu = ipst->ips_ip_pmtu_min;
2296 			} else {
2297 				mtu = icmp_frag_size_table[i];
2298 				if (mtu < ipst->ips_ip_pmtu_min) {
2299 					mtu = ipst->ips_ip_pmtu_min;
2300 					disable_pmtud = B_TRUE;
2301 				}
2302 			}
2303 			/* Fool the ULP into believing our guessed PMTU. */
2304 			icmph->icmph_du_zero = 0;
2305 			icmph->icmph_du_mtu = htons(mtu);
2306 		}
2307 		if (disable_pmtud)
2308 			ire->ire_frag_flag = 0;
2309 		/* Reduce the IRE max frag value as advised. */
2310 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2311 		if (ire->ire_max_frag == mtu) {
2312 			/* Decreased it */
2313 			ire->ire_marks |= IRE_MARK_PMTU;
2314 		}
2315 		mutex_exit(&ire->ire_lock);
2316 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2317 		    ire, int, orig_mtu, int, mtu);
2318 	}
2319 	rw_exit(&first_ire->ire_bucket->irb_lock);
2320 	ire_refrele(first_ire);
2321 	return (B_TRUE);
2322 }
2323 
2324 /*
2325  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2326  * calls this function.
2327  */
2328 static mblk_t *
2329 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2330 {
2331 	ipha_t *ipha;
2332 	icmph_t *icmph;
2333 	ipha_t *in_ipha;
2334 	int length;
2335 
2336 	ASSERT(mp->b_datap->db_type == M_DATA);
2337 
2338 	/*
2339 	 * For Self-encapsulated packets, we added an extra IP header
2340 	 * without the options. Inner IP header is the one from which
2341 	 * the outer IP header was formed. Thus, we need to remove the
2342 	 * outer IP header. To do this, we pullup the whole message
2343 	 * and overlay whatever follows the outer IP header over the
2344 	 * outer IP header.
2345 	 */
2346 
2347 	if (!pullupmsg(mp, -1))
2348 		return (NULL);
2349 
2350 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2351 	ipha = (ipha_t *)&icmph[1];
2352 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2353 
2354 	/*
2355 	 * The length that we want to overlay is following the inner
2356 	 * IP header. Subtracting the IP header + icmp header + outer
2357 	 * IP header's length should give us the length that we want to
2358 	 * overlay.
2359 	 */
2360 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2361 	    hdr_length;
2362 	/*
2363 	 * Overlay whatever follows the inner header over the
2364 	 * outer header.
2365 	 */
2366 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2367 
2368 	/* Set the wptr to account for the outer header */
2369 	mp->b_wptr -= hdr_length;
2370 	return (mp);
2371 }
2372 
2373 /*
2374  * Try to pass the ICMP message upstream in case the ULP cares.
2375  *
2376  * If the packet that caused the ICMP error is secure, we send
2377  * it to AH/ESP to make sure that the attached packet has a
2378  * valid association. ipha in the code below points to the
2379  * IP header of the packet that caused the error.
2380  *
2381  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2382  * in the context of IPsec. Normally we tell the upper layer
2383  * whenever we send the ire (including ip_bind), the IPsec header
2384  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2385  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2386  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2387  * same thing. As TCP has the IPsec options size that needs to be
2388  * adjusted, we just pass the MTU unchanged.
2389  *
2390  * IFN could have been generated locally or by some router.
2391  *
2392  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2393  *	    This happens because IP adjusted its value of MTU on an
2394  *	    earlier IFN message and could not tell the upper layer,
2395  *	    the new adjusted value of MTU e.g. Packet was encrypted
2396  *	    or there was not enough information to fanout to upper
2397  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2398  *	    generates the IFN, where IPsec processing has *not* been
2399  *	    done.
2400  *
2401  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2402  *	    could have generated this. This happens because ire_max_frag
2403  *	    value in IP was set to a new value, while the IPsec processing
2404  *	    was being done and after we made the fragmentation check in
2405  *	    ip_wput_ire. Thus on return from IPsec processing,
2406  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2407  *	    and generates the IFN. As IPsec processing is over, we fanout
2408  *	    to AH/ESP to remove the header.
2409  *
2410  *	    In both these cases, ipsec_in_loopback will be set indicating
2411  *	    that IFN was generated locally.
2412  *
2413  * ROUTER : IFN could be secure or non-secure.
2414  *
2415  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2416  *	      packet in error has AH/ESP headers to validate the AH/ESP
2417  *	      headers. AH/ESP will verify whether there is a valid SA or
2418  *	      not and send it back. We will fanout again if we have more
2419  *	      data in the packet.
2420  *
2421  *	      If the packet in error does not have AH/ESP, we handle it
2422  *	      like any other case.
2423  *
2424  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2425  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2426  *	      for validation. AH/ESP will verify whether there is a
2427  *	      valid SA or not and send it back. We will fanout again if
2428  *	      we have more 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 static void
2434 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2435     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2436     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2437     zoneid_t zoneid)
2438 {
2439 	uint16_t *up;	/* Pointer to ports in ULP header */
2440 	uint32_t ports;	/* reversed ports for fanout */
2441 	ipha_t ripha;	/* With reversed addresses */
2442 	mblk_t *first_mp;
2443 	ipsec_in_t *ii;
2444 	tcph_t	*tcph;
2445 	conn_t	*connp;
2446 	ip_stack_t *ipst;
2447 
2448 	ASSERT(ill != NULL);
2449 
2450 	ASSERT(recv_ill != NULL);
2451 	ipst = recv_ill->ill_ipst;
2452 
2453 	first_mp = mp;
2454 	if (mctl_present) {
2455 		mp = first_mp->b_cont;
2456 		ASSERT(mp != NULL);
2457 
2458 		ii = (ipsec_in_t *)first_mp->b_rptr;
2459 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2460 	} else {
2461 		ii = NULL;
2462 	}
2463 
2464 	switch (ipha->ipha_protocol) {
2465 	case IPPROTO_UDP:
2466 		/*
2467 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2468 		 * transport header.
2469 		 */
2470 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2471 		    mp->b_wptr) {
2472 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2473 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2474 				goto discard_pkt;
2475 			}
2476 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2477 			ipha = (ipha_t *)&icmph[1];
2478 		}
2479 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2480 
2481 		/*
2482 		 * Attempt to find a client stream based on port.
2483 		 * Note that we do a reverse lookup since the header is
2484 		 * in the form we sent it out.
2485 		 * The ripha header is only used for the IP_UDP_MATCH and we
2486 		 * only set the src and dst addresses and protocol.
2487 		 */
2488 		ripha.ipha_src = ipha->ipha_dst;
2489 		ripha.ipha_dst = ipha->ipha_src;
2490 		ripha.ipha_protocol = ipha->ipha_protocol;
2491 		((uint16_t *)&ports)[0] = up[1];
2492 		((uint16_t *)&ports)[1] = up[0];
2493 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2494 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2495 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2496 		    icmph->icmph_type, icmph->icmph_code));
2497 
2498 		/* Have to change db_type after any pullupmsg */
2499 		DB_TYPE(mp) = M_CTL;
2500 
2501 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2502 		    mctl_present, ip_policy, recv_ill, zoneid);
2503 		return;
2504 
2505 	case IPPROTO_TCP:
2506 		/*
2507 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2508 		 * transport header.
2509 		 */
2510 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2511 		    mp->b_wptr) {
2512 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2513 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2514 				goto discard_pkt;
2515 			}
2516 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2517 			ipha = (ipha_t *)&icmph[1];
2518 		}
2519 		/*
2520 		 * Find a TCP client stream for this packet.
2521 		 * Note that we do a reverse lookup since the header is
2522 		 * in the form we sent it out.
2523 		 */
2524 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2525 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2526 		    ipst);
2527 		if (connp == NULL)
2528 			goto discard_pkt;
2529 
2530 		/* Have to change db_type after any pullupmsg */
2531 		DB_TYPE(mp) = M_CTL;
2532 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2533 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2534 		return;
2535 
2536 	case IPPROTO_SCTP:
2537 		/*
2538 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2539 		 * transport header.
2540 		 */
2541 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2542 		    mp->b_wptr) {
2543 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2544 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2545 				goto discard_pkt;
2546 			}
2547 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2548 			ipha = (ipha_t *)&icmph[1];
2549 		}
2550 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2551 		/*
2552 		 * Find a SCTP client stream for this packet.
2553 		 * Note that we do a reverse lookup since the header is
2554 		 * in the form we sent it out.
2555 		 * The ripha header is only used for the matching and we
2556 		 * only set the src and dst addresses, protocol, and version.
2557 		 */
2558 		ripha.ipha_src = ipha->ipha_dst;
2559 		ripha.ipha_dst = ipha->ipha_src;
2560 		ripha.ipha_protocol = ipha->ipha_protocol;
2561 		ripha.ipha_version_and_hdr_length =
2562 		    ipha->ipha_version_and_hdr_length;
2563 		((uint16_t *)&ports)[0] = up[1];
2564 		((uint16_t *)&ports)[1] = up[0];
2565 
2566 		/* Have to change db_type after any pullupmsg */
2567 		DB_TYPE(mp) = M_CTL;
2568 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2569 		    mctl_present, ip_policy, zoneid);
2570 		return;
2571 
2572 	case IPPROTO_ESP:
2573 	case IPPROTO_AH: {
2574 		int ipsec_rc;
2575 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2576 
2577 		/*
2578 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2579 		 * We will re-use the IPSEC_IN if it is already present as
2580 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2581 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2582 		 * one and attach it in the front.
2583 		 */
2584 		if (ii != NULL) {
2585 			/*
2586 			 * ip_fanout_proto_again converts the ICMP errors
2587 			 * that come back from AH/ESP to M_DATA so that
2588 			 * if it is non-AH/ESP and we do a pullupmsg in
2589 			 * this function, it would work. Convert it back
2590 			 * to M_CTL before we send up as this is a ICMP
2591 			 * error. This could have been generated locally or
2592 			 * by some router. Validate the inner IPsec
2593 			 * headers.
2594 			 *
2595 			 * NOTE : ill_index is used by ip_fanout_proto_again
2596 			 * to locate the ill.
2597 			 */
2598 			ASSERT(ill != NULL);
2599 			ii->ipsec_in_ill_index =
2600 			    ill->ill_phyint->phyint_ifindex;
2601 			ii->ipsec_in_rill_index =
2602 			    recv_ill->ill_phyint->phyint_ifindex;
2603 			DB_TYPE(first_mp->b_cont) = M_CTL;
2604 		} else {
2605 			/*
2606 			 * IPSEC_IN is not present. We attach a ipsec_in
2607 			 * message and send up to IPsec for validating
2608 			 * and removing the IPsec headers. Clear
2609 			 * ipsec_in_secure so that when we return
2610 			 * from IPsec, we don't mistakenly think that this
2611 			 * is a secure packet came from the network.
2612 			 *
2613 			 * NOTE : ill_index is used by ip_fanout_proto_again
2614 			 * to locate the ill.
2615 			 */
2616 			ASSERT(first_mp == mp);
2617 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2618 			if (first_mp == NULL) {
2619 				freemsg(mp);
2620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2621 				return;
2622 			}
2623 			ii = (ipsec_in_t *)first_mp->b_rptr;
2624 
2625 			/* This is not a secure packet */
2626 			ii->ipsec_in_secure = B_FALSE;
2627 			first_mp->b_cont = mp;
2628 			DB_TYPE(mp) = M_CTL;
2629 			ASSERT(ill != NULL);
2630 			ii->ipsec_in_ill_index =
2631 			    ill->ill_phyint->phyint_ifindex;
2632 			ii->ipsec_in_rill_index =
2633 			    recv_ill->ill_phyint->phyint_ifindex;
2634 		}
2635 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2636 
2637 		if (!ipsec_loaded(ipss)) {
2638 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2639 			return;
2640 		}
2641 
2642 		if (ipha->ipha_protocol == IPPROTO_ESP)
2643 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2644 		else
2645 			ipsec_rc = ipsecah_icmp_error(first_mp);
2646 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2647 			return;
2648 
2649 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2650 		return;
2651 	}
2652 	default:
2653 		/*
2654 		 * The ripha header is only used for the lookup and we
2655 		 * only set the src and dst addresses and protocol.
2656 		 */
2657 		ripha.ipha_src = ipha->ipha_dst;
2658 		ripha.ipha_dst = ipha->ipha_src;
2659 		ripha.ipha_protocol = ipha->ipha_protocol;
2660 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2661 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2662 		    ntohl(ipha->ipha_dst),
2663 		    icmph->icmph_type, icmph->icmph_code));
2664 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2665 			ipha_t *in_ipha;
2666 
2667 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2668 			    mp->b_wptr) {
2669 				if (!pullupmsg(mp, (uchar_t *)ipha +
2670 				    hdr_length + sizeof (ipha_t) -
2671 				    mp->b_rptr)) {
2672 					goto discard_pkt;
2673 				}
2674 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2675 				ipha = (ipha_t *)&icmph[1];
2676 			}
2677 			/*
2678 			 * Caller has verified that length has to be
2679 			 * at least the size of IP header.
2680 			 */
2681 			ASSERT(hdr_length >= sizeof (ipha_t));
2682 			/*
2683 			 * Check the sanity of the inner IP header like
2684 			 * we did for the outer header.
2685 			 */
2686 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2687 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2688 				goto discard_pkt;
2689 			}
2690 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2691 				goto discard_pkt;
2692 			}
2693 			/* Check for Self-encapsulated tunnels */
2694 			if (in_ipha->ipha_src == ipha->ipha_src &&
2695 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2696 
2697 				mp = icmp_inbound_self_encap_error(mp,
2698 				    iph_hdr_length, hdr_length);
2699 				if (mp == NULL)
2700 					goto discard_pkt;
2701 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2702 				ipha = (ipha_t *)&icmph[1];
2703 				hdr_length = IPH_HDR_LENGTH(ipha);
2704 				/*
2705 				 * The packet in error is self-encapsualted.
2706 				 * And we are finding it further encapsulated
2707 				 * which we could not have possibly generated.
2708 				 */
2709 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2710 					goto discard_pkt;
2711 				}
2712 				icmp_inbound_error_fanout(q, ill, first_mp,
2713 				    icmph, ipha, iph_hdr_length, hdr_length,
2714 				    mctl_present, ip_policy, recv_ill, zoneid);
2715 				return;
2716 			}
2717 		}
2718 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2719 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2720 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2721 		    ii != NULL &&
2722 		    ii->ipsec_in_loopback &&
2723 		    ii->ipsec_in_secure) {
2724 			/*
2725 			 * For IP tunnels that get a looped-back
2726 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2727 			 * reported new MTU to take into account the IPsec
2728 			 * headers protecting this configured tunnel.
2729 			 *
2730 			 * This allows the tunnel module (tun.c) to blindly
2731 			 * accept the MTU reported in an ICMP "too big"
2732 			 * message.
2733 			 *
2734 			 * Non-looped back ICMP messages will just be
2735 			 * handled by the security protocols (if needed),
2736 			 * and the first subsequent packet will hit this
2737 			 * path.
2738 			 */
2739 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2740 			    ipsec_in_extra_length(first_mp));
2741 		}
2742 		/* Have to change db_type after any pullupmsg */
2743 		DB_TYPE(mp) = M_CTL;
2744 
2745 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2746 		    ip_policy, recv_ill, zoneid);
2747 		return;
2748 	}
2749 	/* NOTREACHED */
2750 discard_pkt:
2751 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2752 drop_pkt:;
2753 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2754 	freemsg(first_mp);
2755 }
2756 
2757 /*
2758  * Common IP options parser.
2759  *
2760  * Setup routine: fill in *optp with options-parsing state, then
2761  * tail-call ipoptp_next to return the first option.
2762  */
2763 uint8_t
2764 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2765 {
2766 	uint32_t totallen; /* total length of all options */
2767 
2768 	totallen = ipha->ipha_version_and_hdr_length -
2769 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2770 	totallen <<= 2;
2771 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2772 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2773 	optp->ipoptp_flags = 0;
2774 	return (ipoptp_next(optp));
2775 }
2776 
2777 /*
2778  * Common IP options parser: extract next option.
2779  */
2780 uint8_t
2781 ipoptp_next(ipoptp_t *optp)
2782 {
2783 	uint8_t *end = optp->ipoptp_end;
2784 	uint8_t *cur = optp->ipoptp_next;
2785 	uint8_t opt, len, pointer;
2786 
2787 	/*
2788 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2789 	 * has been corrupted.
2790 	 */
2791 	ASSERT(cur <= end);
2792 
2793 	if (cur == end)
2794 		return (IPOPT_EOL);
2795 
2796 	opt = cur[IPOPT_OPTVAL];
2797 
2798 	/*
2799 	 * Skip any NOP options.
2800 	 */
2801 	while (opt == IPOPT_NOP) {
2802 		cur++;
2803 		if (cur == end)
2804 			return (IPOPT_EOL);
2805 		opt = cur[IPOPT_OPTVAL];
2806 	}
2807 
2808 	if (opt == IPOPT_EOL)
2809 		return (IPOPT_EOL);
2810 
2811 	/*
2812 	 * Option requiring a length.
2813 	 */
2814 	if ((cur + 1) >= end) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	len = cur[IPOPT_OLEN];
2819 	if (len < 2) {
2820 		optp->ipoptp_flags |= IPOPTP_ERROR;
2821 		return (IPOPT_EOL);
2822 	}
2823 	optp->ipoptp_cur = cur;
2824 	optp->ipoptp_len = len;
2825 	optp->ipoptp_next = cur + len;
2826 	if (cur + len > end) {
2827 		optp->ipoptp_flags |= IPOPTP_ERROR;
2828 		return (IPOPT_EOL);
2829 	}
2830 
2831 	/*
2832 	 * For the options which require a pointer field, make sure
2833 	 * its there, and make sure it points to either something
2834 	 * inside this option, or the end of the option.
2835 	 */
2836 	switch (opt) {
2837 	case IPOPT_RR:
2838 	case IPOPT_TS:
2839 	case IPOPT_LSRR:
2840 	case IPOPT_SSRR:
2841 		if (len <= IPOPT_OFFSET) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		pointer = cur[IPOPT_OFFSET];
2846 		if (pointer - 1 > len) {
2847 			optp->ipoptp_flags |= IPOPTP_ERROR;
2848 			return (opt);
2849 		}
2850 		break;
2851 	}
2852 
2853 	/*
2854 	 * Sanity check the pointer field based on the type of the
2855 	 * option.
2856 	 */
2857 	switch (opt) {
2858 	case IPOPT_RR:
2859 	case IPOPT_SSRR:
2860 	case IPOPT_LSRR:
2861 		if (pointer < IPOPT_MINOFF_SR)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		break;
2864 	case IPOPT_TS:
2865 		if (pointer < IPOPT_MINOFF_IT)
2866 			optp->ipoptp_flags |= IPOPTP_ERROR;
2867 		/*
2868 		 * Note that the Internet Timestamp option also
2869 		 * contains two four bit fields (the Overflow field,
2870 		 * and the Flag field), which follow the pointer
2871 		 * field.  We don't need to check that these fields
2872 		 * fall within the length of the option because this
2873 		 * was implicitely done above.  We've checked that the
2874 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2875 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2876 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2877 		 */
2878 		ASSERT(len > IPOPT_POS_OV_FLG);
2879 		break;
2880 	}
2881 
2882 	return (opt);
2883 }
2884 
2885 /*
2886  * Use the outgoing IP header to create an IP_OPTIONS option the way
2887  * it was passed down from the application.
2888  */
2889 int
2890 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2891 {
2892 	ipoptp_t	opts;
2893 	const uchar_t	*opt;
2894 	uint8_t		optval;
2895 	uint8_t		optlen;
2896 	uint32_t	len = 0;
2897 	uchar_t	*buf1 = buf;
2898 
2899 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2900 	len += IP_ADDR_LEN;
2901 	bzero(buf1, IP_ADDR_LEN);
2902 
2903 	/*
2904 	 * OK to cast away const here, as we don't store through the returned
2905 	 * opts.ipoptp_cur pointer.
2906 	 */
2907 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2908 	    optval != IPOPT_EOL;
2909 	    optval = ipoptp_next(&opts)) {
2910 		int	off;
2911 
2912 		opt = opts.ipoptp_cur;
2913 		optlen = opts.ipoptp_len;
2914 		switch (optval) {
2915 		case IPOPT_SSRR:
2916 		case IPOPT_LSRR:
2917 
2918 			/*
2919 			 * Insert ipha_dst as the first entry in the source
2920 			 * route and move down the entries on step.
2921 			 * The last entry gets placed at buf1.
2922 			 */
2923 			buf[IPOPT_OPTVAL] = optval;
2924 			buf[IPOPT_OLEN] = optlen;
2925 			buf[IPOPT_OFFSET] = optlen;
2926 
2927 			off = optlen - IP_ADDR_LEN;
2928 			if (off < 0) {
2929 				/* No entries in source route */
2930 				break;
2931 			}
2932 			/* Last entry in source route */
2933 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2934 			off -= IP_ADDR_LEN;
2935 
2936 			while (off > 0) {
2937 				bcopy(opt + off,
2938 				    buf + off + IP_ADDR_LEN,
2939 				    IP_ADDR_LEN);
2940 				off -= IP_ADDR_LEN;
2941 			}
2942 			/* ipha_dst into first slot */
2943 			bcopy(&ipha->ipha_dst,
2944 			    buf + off + IP_ADDR_LEN,
2945 			    IP_ADDR_LEN);
2946 			buf += optlen;
2947 			len += optlen;
2948 			break;
2949 
2950 		case IPOPT_COMSEC:
2951 		case IPOPT_SECURITY:
2952 			/* if passing up a label is not ok, then remove */
2953 			if (is_system_labeled())
2954 				break;
2955 			/* FALLTHROUGH */
2956 		default:
2957 			bcopy(opt, buf, optlen);
2958 			buf += optlen;
2959 			len += optlen;
2960 			break;
2961 		}
2962 	}
2963 done:
2964 	/* Pad the resulting options */
2965 	while (len & 0x3) {
2966 		*buf++ = IPOPT_EOL;
2967 		len++;
2968 	}
2969 	return (len);
2970 }
2971 
2972 /*
2973  * Update any record route or timestamp options to include this host.
2974  * Reverse any source route option.
2975  * This routine assumes that the options are well formed i.e. that they
2976  * have already been checked.
2977  */
2978 static void
2979 icmp_options_update(ipha_t *ipha)
2980 {
2981 	ipoptp_t	opts;
2982 	uchar_t		*opt;
2983 	uint8_t		optval;
2984 	ipaddr_t	src;		/* Our local address */
2985 	ipaddr_t	dst;
2986 
2987 	ip2dbg(("icmp_options_update\n"));
2988 	src = ipha->ipha_src;
2989 	dst = ipha->ipha_dst;
2990 
2991 	for (optval = ipoptp_first(&opts, ipha);
2992 	    optval != IPOPT_EOL;
2993 	    optval = ipoptp_next(&opts)) {
2994 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2995 		opt = opts.ipoptp_cur;
2996 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2997 		    optval, opts.ipoptp_len));
2998 		switch (optval) {
2999 			int off1, off2;
3000 		case IPOPT_SSRR:
3001 		case IPOPT_LSRR:
3002 			/*
3003 			 * Reverse the source route.  The first entry
3004 			 * should be the next to last one in the current
3005 			 * source route (the last entry is our address).
3006 			 * The last entry should be the final destination.
3007 			 */
3008 			off1 = IPOPT_MINOFF_SR - 1;
3009 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3010 			if (off2 < 0) {
3011 				/* No entries in source route */
3012 				ip1dbg((
3013 				    "icmp_options_update: bad src route\n"));
3014 				break;
3015 			}
3016 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3017 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3018 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3019 			off2 -= IP_ADDR_LEN;
3020 
3021 			while (off1 < off2) {
3022 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3023 				bcopy((char *)opt + off2, (char *)opt + off1,
3024 				    IP_ADDR_LEN);
3025 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3026 				off1 += IP_ADDR_LEN;
3027 				off2 -= IP_ADDR_LEN;
3028 			}
3029 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3030 			break;
3031 		}
3032 	}
3033 }
3034 
3035 /*
3036  * Process received ICMP Redirect messages.
3037  */
3038 static void
3039 icmp_redirect(ill_t *ill, mblk_t *mp)
3040 {
3041 	ipha_t	*ipha;
3042 	int	iph_hdr_length;
3043 	icmph_t	*icmph;
3044 	ipha_t	*ipha_err;
3045 	ire_t	*ire;
3046 	ire_t	*prev_ire;
3047 	ire_t	*save_ire;
3048 	ipaddr_t  src, dst, gateway;
3049 	iulp_t	ulp_info = { 0 };
3050 	int	error;
3051 	ip_stack_t *ipst;
3052 
3053 	ASSERT(ill != NULL);
3054 	ipst = ill->ill_ipst;
3055 
3056 	ipha = (ipha_t *)mp->b_rptr;
3057 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3058 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3059 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3060 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3061 		freemsg(mp);
3062 		return;
3063 	}
3064 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3065 	ipha_err = (ipha_t *)&icmph[1];
3066 	src = ipha->ipha_src;
3067 	dst = ipha_err->ipha_dst;
3068 	gateway = icmph->icmph_rd_gateway;
3069 	/* Make sure the new gateway is reachable somehow. */
3070 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3071 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3072 	/*
3073 	 * Make sure we had a route for the dest in question and that
3074 	 * that route was pointing to the old gateway (the source of the
3075 	 * redirect packet.)
3076 	 */
3077 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3078 	    NULL, MATCH_IRE_GW, ipst);
3079 	/*
3080 	 * Check that
3081 	 *	the redirect was not from ourselves
3082 	 *	the new gateway and the old gateway are directly reachable
3083 	 */
3084 	if (!prev_ire ||
3085 	    !ire ||
3086 	    ire->ire_type == IRE_LOCAL) {
3087 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3088 		freemsg(mp);
3089 		if (ire != NULL)
3090 			ire_refrele(ire);
3091 		if (prev_ire != NULL)
3092 			ire_refrele(prev_ire);
3093 		return;
3094 	}
3095 
3096 	/*
3097 	 * Should we use the old ULP info to create the new gateway?  From
3098 	 * a user's perspective, we should inherit the info so that it
3099 	 * is a "smooth" transition.  If we do not do that, then new
3100 	 * connections going thru the new gateway will have no route metrics,
3101 	 * which is counter-intuitive to user.  From a network point of
3102 	 * view, this may or may not make sense even though the new gateway
3103 	 * is still directly connected to us so the route metrics should not
3104 	 * change much.
3105 	 *
3106 	 * But if the old ire_uinfo is not initialized, we do another
3107 	 * recursive lookup on the dest using the new gateway.  There may
3108 	 * be a route to that.  If so, use it to initialize the redirect
3109 	 * route.
3110 	 */
3111 	if (prev_ire->ire_uinfo.iulp_set) {
3112 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3113 	} else {
3114 		ire_t *tmp_ire;
3115 		ire_t *sire;
3116 
3117 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3118 		    ALL_ZONES, 0, NULL,
3119 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3120 		    ipst);
3121 		if (sire != NULL) {
3122 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3123 			/*
3124 			 * If sire != NULL, ire_ftable_lookup() should not
3125 			 * return a NULL value.
3126 			 */
3127 			ASSERT(tmp_ire != NULL);
3128 			ire_refrele(tmp_ire);
3129 			ire_refrele(sire);
3130 		} else if (tmp_ire != NULL) {
3131 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3132 			    sizeof (iulp_t));
3133 			ire_refrele(tmp_ire);
3134 		}
3135 	}
3136 	if (prev_ire->ire_type == IRE_CACHE)
3137 		ire_delete(prev_ire);
3138 	ire_refrele(prev_ire);
3139 	/*
3140 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3141 	 * require TOS routing
3142 	 */
3143 	switch (icmph->icmph_code) {
3144 	case 0:
3145 	case 1:
3146 		/* TODO: TOS specificity for cases 2 and 3 */
3147 	case 2:
3148 	case 3:
3149 		break;
3150 	default:
3151 		freemsg(mp);
3152 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3153 		ire_refrele(ire);
3154 		return;
3155 	}
3156 	/*
3157 	 * Create a Route Association.  This will allow us to remember that
3158 	 * someone we believe told us to use the particular gateway.
3159 	 */
3160 	save_ire = ire;
3161 	ire = ire_create(
3162 	    (uchar_t *)&dst,			/* dest addr */
3163 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3164 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3165 	    (uchar_t *)&gateway,		/* gateway addr */
3166 	    &save_ire->ire_max_frag,		/* max frag */
3167 	    NULL,				/* no src nce */
3168 	    NULL,				/* no rfq */
3169 	    NULL,				/* no stq */
3170 	    IRE_HOST,
3171 	    NULL,				/* ipif */
3172 	    0,					/* cmask */
3173 	    0,					/* phandle */
3174 	    0,					/* ihandle */
3175 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3176 	    &ulp_info,
3177 	    NULL,				/* tsol_gc_t */
3178 	    NULL,				/* gcgrp */
3179 	    ipst);
3180 
3181 	if (ire == NULL) {
3182 		freemsg(mp);
3183 		ire_refrele(save_ire);
3184 		return;
3185 	}
3186 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3187 	ire_refrele(save_ire);
3188 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3189 
3190 	if (error == 0) {
3191 		ire_refrele(ire);		/* Held in ire_add_v4 */
3192 		/* tell routing sockets that we received a redirect */
3193 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3194 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3195 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3196 	}
3197 
3198 	/*
3199 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3200 	 * This together with the added IRE has the effect of
3201 	 * modifying an existing redirect.
3202 	 */
3203 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3204 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3205 	if (prev_ire != NULL) {
3206 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3207 			ire_delete(prev_ire);
3208 		ire_refrele(prev_ire);
3209 	}
3210 
3211 	freemsg(mp);
3212 }
3213 
3214 /*
3215  * Generate an ICMP parameter problem message.
3216  */
3217 static void
3218 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3219 	ip_stack_t *ipst)
3220 {
3221 	icmph_t	icmph;
3222 	boolean_t mctl_present;
3223 	mblk_t *first_mp;
3224 
3225 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3226 
3227 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3228 		if (mctl_present)
3229 			freeb(first_mp);
3230 		return;
3231 	}
3232 
3233 	bzero(&icmph, sizeof (icmph_t));
3234 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3235 	icmph.icmph_pp_ptr = ptr;
3236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3237 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3238 	    ipst);
3239 }
3240 
3241 /*
3242  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3243  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3244  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3245  * an icmp error packet can be sent.
3246  * Assigns an appropriate source address to the packet. If ipha_dst is
3247  * one of our addresses use it for source. Otherwise pick a source based
3248  * on a route lookup back to ipha_src.
3249  * Note that ipha_src must be set here since the
3250  * packet is likely to arrive on an ill queue in ip_wput() which will
3251  * not set a source address.
3252  */
3253 static void
3254 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3255     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3256 {
3257 	ipaddr_t dst;
3258 	icmph_t	*icmph;
3259 	ipha_t	*ipha;
3260 	uint_t	len_needed;
3261 	size_t	msg_len;
3262 	mblk_t	*mp1;
3263 	ipaddr_t src;
3264 	ire_t	*ire;
3265 	mblk_t *ipsec_mp;
3266 	ipsec_out_t	*io = NULL;
3267 
3268 	if (mctl_present) {
3269 		/*
3270 		 * If it is :
3271 		 *
3272 		 * 1) a IPSEC_OUT, then this is caused by outbound
3273 		 *    datagram originating on this host. IPsec processing
3274 		 *    may or may not have been done. Refer to comments above
3275 		 *    icmp_inbound_error_fanout for details.
3276 		 *
3277 		 * 2) a IPSEC_IN if we are generating a icmp_message
3278 		 *    for an incoming datagram destined for us i.e called
3279 		 *    from ip_fanout_send_icmp.
3280 		 */
3281 		ipsec_info_t *in;
3282 		ipsec_mp = mp;
3283 		mp = ipsec_mp->b_cont;
3284 
3285 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3286 		ipha = (ipha_t *)mp->b_rptr;
3287 
3288 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3289 		    in->ipsec_info_type == IPSEC_IN);
3290 
3291 		if (in->ipsec_info_type == IPSEC_IN) {
3292 			/*
3293 			 * Convert the IPSEC_IN to IPSEC_OUT.
3294 			 */
3295 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3296 				BUMP_MIB(&ipst->ips_ip_mib,
3297 				    ipIfStatsOutDiscards);
3298 				return;
3299 			}
3300 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3301 		} else {
3302 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3303 			io = (ipsec_out_t *)in;
3304 			/*
3305 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3306 			 * ire lookup.
3307 			 */
3308 			io->ipsec_out_proc_begin = B_FALSE;
3309 		}
3310 		ASSERT(zoneid != ALL_ZONES);
3311 		/*
3312 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3313 		 * initialized.  We need to do that now.
3314 		 */
3315 		io->ipsec_out_zoneid = zoneid;
3316 	} else {
3317 		/*
3318 		 * This is in clear. The icmp message we are building
3319 		 * here should go out in clear.
3320 		 *
3321 		 * Pardon the convolution of it all, but it's easier to
3322 		 * allocate a "use cleartext" IPSEC_IN message and convert
3323 		 * it than it is to allocate a new one.
3324 		 */
3325 		ipsec_in_t *ii;
3326 		ASSERT(DB_TYPE(mp) == M_DATA);
3327 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3328 		if (ipsec_mp == NULL) {
3329 			freemsg(mp);
3330 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3331 			return;
3332 		}
3333 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3334 
3335 		/* This is not a secure packet */
3336 		ii->ipsec_in_secure = B_FALSE;
3337 		/*
3338 		 * For trusted extensions using a shared IP address we can
3339 		 * send using any zoneid.
3340 		 */
3341 		if (zoneid == ALL_ZONES)
3342 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3343 		else
3344 			ii->ipsec_in_zoneid = zoneid;
3345 		ipsec_mp->b_cont = mp;
3346 		ipha = (ipha_t *)mp->b_rptr;
3347 		/*
3348 		 * Convert the IPSEC_IN to IPSEC_OUT.
3349 		 */
3350 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3351 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3352 			return;
3353 		}
3354 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3355 	}
3356 
3357 	/* Remember our eventual destination */
3358 	dst = ipha->ipha_src;
3359 
3360 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3361 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3362 	if (ire != NULL &&
3363 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3364 		src = ipha->ipha_dst;
3365 	} else {
3366 		if (ire != NULL)
3367 			ire_refrele(ire);
3368 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3369 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3370 		    ipst);
3371 		if (ire == NULL) {
3372 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3373 			freemsg(ipsec_mp);
3374 			return;
3375 		}
3376 		src = ire->ire_src_addr;
3377 	}
3378 
3379 	if (ire != NULL)
3380 		ire_refrele(ire);
3381 
3382 	/*
3383 	 * Check if we can send back more then 8 bytes in addition to
3384 	 * the IP header.  We try to send 64 bytes of data and the internal
3385 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3386 	 */
3387 	len_needed = IPH_HDR_LENGTH(ipha);
3388 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3389 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3390 
3391 		if (!pullupmsg(mp, -1)) {
3392 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3393 			freemsg(ipsec_mp);
3394 			return;
3395 		}
3396 		ipha = (ipha_t *)mp->b_rptr;
3397 
3398 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3399 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3400 			    len_needed));
3401 		} else {
3402 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3403 
3404 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3405 			len_needed += ip_hdr_length_v6(mp, ip6h);
3406 		}
3407 	}
3408 	len_needed += ipst->ips_ip_icmp_return;
3409 	msg_len = msgdsize(mp);
3410 	if (msg_len > len_needed) {
3411 		(void) adjmsg(mp, len_needed - msg_len);
3412 		msg_len = len_needed;
3413 	}
3414 	/* Make sure we propagate the cred/label for TX */
3415 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3416 	if (mp1 == NULL) {
3417 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3418 		freemsg(ipsec_mp);
3419 		return;
3420 	}
3421 	mp1->b_cont = mp;
3422 	mp = mp1;
3423 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3424 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3425 	    io->ipsec_out_type == IPSEC_OUT);
3426 	ipsec_mp->b_cont = mp;
3427 
3428 	/*
3429 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3430 	 * node generates be accepted in peace by all on-host destinations.
3431 	 * If we do NOT assume that all on-host destinations trust
3432 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3433 	 * (Look for ipsec_out_icmp_loopback).
3434 	 */
3435 	io->ipsec_out_icmp_loopback = B_TRUE;
3436 
3437 	ipha = (ipha_t *)mp->b_rptr;
3438 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3439 	*ipha = icmp_ipha;
3440 	ipha->ipha_src = src;
3441 	ipha->ipha_dst = dst;
3442 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3443 	msg_len += sizeof (icmp_ipha) + len;
3444 	if (msg_len > IP_MAXPACKET) {
3445 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3446 		msg_len = IP_MAXPACKET;
3447 	}
3448 	ipha->ipha_length = htons((uint16_t)msg_len);
3449 	icmph = (icmph_t *)&ipha[1];
3450 	bcopy(stuff, icmph, len);
3451 	icmph->icmph_checksum = 0;
3452 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3453 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3454 	put(q, ipsec_mp);
3455 }
3456 
3457 /*
3458  * Determine if an ICMP error packet can be sent given the rate limit.
3459  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3460  * in milliseconds) and a burst size. Burst size number of packets can
3461  * be sent arbitrarely closely spaced.
3462  * The state is tracked using two variables to implement an approximate
3463  * token bucket filter:
3464  *	icmp_pkt_err_last - lbolt value when the last burst started
3465  *	icmp_pkt_err_sent - number of packets sent in current burst
3466  */
3467 boolean_t
3468 icmp_err_rate_limit(ip_stack_t *ipst)
3469 {
3470 	clock_t now = TICK_TO_MSEC(lbolt);
3471 	uint_t refilled; /* Number of packets refilled in tbf since last */
3472 	/* Guard against changes by loading into local variable */
3473 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3474 
3475 	if (err_interval == 0)
3476 		return (B_FALSE);
3477 
3478 	if (ipst->ips_icmp_pkt_err_last > now) {
3479 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3480 		ipst->ips_icmp_pkt_err_last = 0;
3481 		ipst->ips_icmp_pkt_err_sent = 0;
3482 	}
3483 	/*
3484 	 * If we are in a burst update the token bucket filter.
3485 	 * Update the "last" time to be close to "now" but make sure
3486 	 * we don't loose precision.
3487 	 */
3488 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3489 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3490 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3491 			ipst->ips_icmp_pkt_err_sent = 0;
3492 		} else {
3493 			ipst->ips_icmp_pkt_err_sent -= refilled;
3494 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3495 		}
3496 	}
3497 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3498 		/* Start of new burst */
3499 		ipst->ips_icmp_pkt_err_last = now;
3500 	}
3501 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3502 		ipst->ips_icmp_pkt_err_sent++;
3503 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3504 		    ipst->ips_icmp_pkt_err_sent));
3505 		return (B_FALSE);
3506 	}
3507 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3508 	return (B_TRUE);
3509 }
3510 
3511 /*
3512  * Check if it is ok to send an IPv4 ICMP error packet in
3513  * response to the IPv4 packet in mp.
3514  * Free the message and return null if no
3515  * ICMP error packet should be sent.
3516  */
3517 static mblk_t *
3518 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3519 {
3520 	icmph_t	*icmph;
3521 	ipha_t	*ipha;
3522 	uint_t	len_needed;
3523 	ire_t	*src_ire;
3524 	ire_t	*dst_ire;
3525 
3526 	if (!mp)
3527 		return (NULL);
3528 	ipha = (ipha_t *)mp->b_rptr;
3529 	if (ip_csum_hdr(ipha)) {
3530 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3531 		freemsg(mp);
3532 		return (NULL);
3533 	}
3534 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3535 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3536 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3537 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3538 	if (src_ire != NULL || dst_ire != NULL ||
3539 	    CLASSD(ipha->ipha_dst) ||
3540 	    CLASSD(ipha->ipha_src) ||
3541 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3542 		/* Note: only errors to the fragment with offset 0 */
3543 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3544 		freemsg(mp);
3545 		if (src_ire != NULL)
3546 			ire_refrele(src_ire);
3547 		if (dst_ire != NULL)
3548 			ire_refrele(dst_ire);
3549 		return (NULL);
3550 	}
3551 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3552 		/*
3553 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3554 		 * errors in response to any ICMP errors.
3555 		 */
3556 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3557 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3558 			if (!pullupmsg(mp, len_needed)) {
3559 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3560 				freemsg(mp);
3561 				return (NULL);
3562 			}
3563 			ipha = (ipha_t *)mp->b_rptr;
3564 		}
3565 		icmph = (icmph_t *)
3566 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3567 		switch (icmph->icmph_type) {
3568 		case ICMP_DEST_UNREACHABLE:
3569 		case ICMP_SOURCE_QUENCH:
3570 		case ICMP_TIME_EXCEEDED:
3571 		case ICMP_PARAM_PROBLEM:
3572 		case ICMP_REDIRECT:
3573 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3574 			freemsg(mp);
3575 			return (NULL);
3576 		default:
3577 			break;
3578 		}
3579 	}
3580 	/*
3581 	 * If this is a labeled system, then check to see if we're allowed to
3582 	 * send a response to this particular sender.  If not, then just drop.
3583 	 */
3584 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3585 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3586 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3587 		freemsg(mp);
3588 		return (NULL);
3589 	}
3590 	if (icmp_err_rate_limit(ipst)) {
3591 		/*
3592 		 * Only send ICMP error packets every so often.
3593 		 * This should be done on a per port/source basis,
3594 		 * but for now this will suffice.
3595 		 */
3596 		freemsg(mp);
3597 		return (NULL);
3598 	}
3599 	return (mp);
3600 }
3601 
3602 /*
3603  * Generate an ICMP redirect message.
3604  */
3605 static void
3606 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3607 {
3608 	icmph_t	icmph;
3609 
3610 	/*
3611 	 * We are called from ip_rput where we could
3612 	 * not have attached an IPSEC_IN.
3613 	 */
3614 	ASSERT(mp->b_datap->db_type == M_DATA);
3615 
3616 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3617 		return;
3618 	}
3619 
3620 	bzero(&icmph, sizeof (icmph_t));
3621 	icmph.icmph_type = ICMP_REDIRECT;
3622 	icmph.icmph_code = 1;
3623 	icmph.icmph_rd_gateway = gateway;
3624 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3625 	/* Redirects sent by router, and router is global zone */
3626 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3627 }
3628 
3629 /*
3630  * Generate an ICMP time exceeded message.
3631  */
3632 void
3633 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3634     ip_stack_t *ipst)
3635 {
3636 	icmph_t	icmph;
3637 	boolean_t mctl_present;
3638 	mblk_t *first_mp;
3639 
3640 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3641 
3642 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3643 		if (mctl_present)
3644 			freeb(first_mp);
3645 		return;
3646 	}
3647 
3648 	bzero(&icmph, sizeof (icmph_t));
3649 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3650 	icmph.icmph_code = code;
3651 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3652 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3653 	    ipst);
3654 }
3655 
3656 /*
3657  * Generate an ICMP unreachable message.
3658  */
3659 void
3660 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3661     ip_stack_t *ipst)
3662 {
3663 	icmph_t	icmph;
3664 	mblk_t *first_mp;
3665 	boolean_t mctl_present;
3666 
3667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3668 
3669 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3670 		if (mctl_present)
3671 			freeb(first_mp);
3672 		return;
3673 	}
3674 
3675 	bzero(&icmph, sizeof (icmph_t));
3676 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3677 	icmph.icmph_code = code;
3678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3679 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3680 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3681 	    zoneid, ipst);
3682 }
3683 
3684 /*
3685  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3686  * duplicate.  As long as someone else holds the address, the interface will
3687  * stay down.  When that conflict goes away, the interface is brought back up.
3688  * This is done so that accidental shutdowns of addresses aren't made
3689  * permanent.  Your server will recover from a failure.
3690  *
3691  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3692  * user space process (dhcpagent).
3693  *
3694  * Recovery completes if ARP reports that the address is now ours (via
3695  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3696  *
3697  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3698  */
3699 static void
3700 ipif_dup_recovery(void *arg)
3701 {
3702 	ipif_t *ipif = arg;
3703 	ill_t *ill = ipif->ipif_ill;
3704 	mblk_t *arp_add_mp;
3705 	mblk_t *arp_del_mp;
3706 	ip_stack_t *ipst = ill->ill_ipst;
3707 
3708 	ipif->ipif_recovery_id = 0;
3709 
3710 	/*
3711 	 * No lock needed for moving or condemned check, as this is just an
3712 	 * optimization.
3713 	 */
3714 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3715 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3716 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3717 		/* No reason to try to bring this address back. */
3718 		return;
3719 	}
3720 
3721 	/* ACE_F_UNVERIFIED restarts DAD */
3722 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3723 		goto alloc_fail;
3724 
3725 	if (ipif->ipif_arp_del_mp == NULL) {
3726 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3727 			goto alloc_fail;
3728 		ipif->ipif_arp_del_mp = arp_del_mp;
3729 	}
3730 
3731 	putnext(ill->ill_rq, arp_add_mp);
3732 	return;
3733 
3734 alloc_fail:
3735 	/*
3736 	 * On allocation failure, just restart the timer.  Note that the ipif
3737 	 * is down here, so no other thread could be trying to start a recovery
3738 	 * timer.  The ill_lock protects the condemned flag and the recovery
3739 	 * timer ID.
3740 	 */
3741 	freemsg(arp_add_mp);
3742 	mutex_enter(&ill->ill_lock);
3743 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3744 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3745 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3746 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3747 	}
3748 	mutex_exit(&ill->ill_lock);
3749 }
3750 
3751 /*
3752  * This is for exclusive changes due to ARP.  Either tear down an interface due
3753  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3754  */
3755 /* ARGSUSED */
3756 static void
3757 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3758 {
3759 	ill_t	*ill = rq->q_ptr;
3760 	arh_t *arh;
3761 	ipaddr_t src;
3762 	ipif_t	*ipif;
3763 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3764 	char hbuf[MAC_STR_LEN];
3765 	char sbuf[INET_ADDRSTRLEN];
3766 	const char *failtype;
3767 	boolean_t bring_up;
3768 	ip_stack_t *ipst = ill->ill_ipst;
3769 
3770 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3771 	case AR_CN_READY:
3772 		failtype = NULL;
3773 		bring_up = B_TRUE;
3774 		break;
3775 	case AR_CN_FAILED:
3776 		failtype = "in use";
3777 		bring_up = B_FALSE;
3778 		break;
3779 	default:
3780 		failtype = "claimed";
3781 		bring_up = B_FALSE;
3782 		break;
3783 	}
3784 
3785 	arh = (arh_t *)mp->b_cont->b_rptr;
3786 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3787 
3788 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3789 	    sizeof (hbuf));
3790 	(void) ip_dot_addr(src, sbuf);
3791 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3792 
3793 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3794 		    ipif->ipif_lcl_addr != src) {
3795 			continue;
3796 		}
3797 
3798 		/*
3799 		 * If we failed on a recovery probe, then restart the timer to
3800 		 * try again later.
3801 		 */
3802 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3803 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3804 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3805 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3806 		    ipst->ips_ip_dup_recovery > 0 &&
3807 		    ipif->ipif_recovery_id == 0) {
3808 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3809 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If what we're trying to do has already been done, then do
3815 		 * nothing.
3816 		 */
3817 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3818 			continue;
3819 
3820 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3821 
3822 		if (failtype == NULL) {
3823 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3824 			    ibuf);
3825 		} else {
3826 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3827 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3828 		}
3829 
3830 		if (bring_up) {
3831 			ASSERT(ill->ill_dl_up);
3832 			/*
3833 			 * Free up the ARP delete message so we can allocate
3834 			 * a fresh one through the normal path.
3835 			 */
3836 			freemsg(ipif->ipif_arp_del_mp);
3837 			ipif->ipif_arp_del_mp = NULL;
3838 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3839 			    EINPROGRESS) {
3840 				ipif->ipif_addr_ready = 1;
3841 				(void) ipif_up_done(ipif);
3842 				ASSERT(ill->ill_move_ipif == NULL);
3843 			}
3844 			continue;
3845 		}
3846 
3847 		mutex_enter(&ill->ill_lock);
3848 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3849 		ipif->ipif_flags |= IPIF_DUPLICATE;
3850 		ill->ill_ipif_dup_count++;
3851 		mutex_exit(&ill->ill_lock);
3852 		/*
3853 		 * Already exclusive on the ill; no need to handle deferred
3854 		 * processing here.
3855 		 */
3856 		(void) ipif_down(ipif, NULL, NULL);
3857 		ipif_down_tail(ipif);
3858 		mutex_enter(&ill->ill_lock);
3859 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3860 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3861 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3862 		    ipst->ips_ip_dup_recovery > 0) {
3863 			ASSERT(ipif->ipif_recovery_id == 0);
3864 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3865 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3866 		}
3867 		mutex_exit(&ill->ill_lock);
3868 	}
3869 	freemsg(mp);
3870 }
3871 
3872 /* ARGSUSED */
3873 static void
3874 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3875 {
3876 	ill_t	*ill = rq->q_ptr;
3877 	arh_t *arh;
3878 	ipaddr_t src;
3879 	ipif_t	*ipif;
3880 
3881 	arh = (arh_t *)mp->b_cont->b_rptr;
3882 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3883 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3884 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3885 			(void) ipif_resolver_up(ipif, Res_act_defend);
3886 	}
3887 	freemsg(mp);
3888 }
3889 
3890 /*
3891  * News from ARP.  ARP sends notification of interesting events down
3892  * to its clients using M_CTL messages with the interesting ARP packet
3893  * attached via b_cont.
3894  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3895  * queue as opposed to ARP sending the message to all the clients, i.e. all
3896  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3897  * table if a cache IRE is found to delete all the entries for the address in
3898  * the packet.
3899  */
3900 static void
3901 ip_arp_news(queue_t *q, mblk_t *mp)
3902 {
3903 	arcn_t		*arcn;
3904 	arh_t		*arh;
3905 	ire_t		*ire = NULL;
3906 	char		hbuf[MAC_STR_LEN];
3907 	char		sbuf[INET_ADDRSTRLEN];
3908 	ipaddr_t	src;
3909 	in6_addr_t	v6src;
3910 	boolean_t	isv6 = B_FALSE;
3911 	ipif_t		*ipif;
3912 	ill_t		*ill;
3913 	ip_stack_t	*ipst;
3914 
3915 	if (CONN_Q(q)) {
3916 		conn_t *connp = Q_TO_CONN(q);
3917 
3918 		ipst = connp->conn_netstack->netstack_ip;
3919 	} else {
3920 		ill_t *ill = (ill_t *)q->q_ptr;
3921 
3922 		ipst = ill->ill_ipst;
3923 	}
3924 
3925 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3926 		if (q->q_next) {
3927 			putnext(q, mp);
3928 		} else
3929 			freemsg(mp);
3930 		return;
3931 	}
3932 	arh = (arh_t *)mp->b_cont->b_rptr;
3933 	/* Is it one we are interested in? */
3934 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3935 		isv6 = B_TRUE;
3936 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3937 		    IPV6_ADDR_LEN);
3938 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3939 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3940 		    IP_ADDR_LEN);
3941 	} else {
3942 		freemsg(mp);
3943 		return;
3944 	}
3945 
3946 	ill = q->q_ptr;
3947 
3948 	arcn = (arcn_t *)mp->b_rptr;
3949 	switch (arcn->arcn_code) {
3950 	case AR_CN_BOGON:
3951 		/*
3952 		 * Someone is sending ARP packets with a source protocol
3953 		 * address that we have published and for which we believe our
3954 		 * entry is authoritative and (when ill_arp_extend is set)
3955 		 * verified to be unique on the network.
3956 		 *
3957 		 * The ARP module internally handles the cases where the sender
3958 		 * is just probing (for DAD) and where the hardware address of
3959 		 * a non-authoritative entry has changed.  Thus, these are the
3960 		 * real conflicts, and we have to do resolution.
3961 		 *
3962 		 * We back away quickly from the address if it's from DHCP or
3963 		 * otherwise temporary and hasn't been used recently (or at
3964 		 * all).  We'd like to include "deprecated" addresses here as
3965 		 * well (as there's no real reason to defend something we're
3966 		 * discarding), but IPMP "reuses" this flag to mean something
3967 		 * other than the standard meaning.
3968 		 *
3969 		 * If the ARP module above is not extended (meaning that it
3970 		 * doesn't know how to defend the address), then we just log
3971 		 * the problem as we always did and continue on.  It's not
3972 		 * right, but there's little else we can do, and those old ATM
3973 		 * users are going away anyway.
3974 		 */
3975 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3976 		    hbuf, sizeof (hbuf));
3977 		(void) ip_dot_addr(src, sbuf);
3978 		if (isv6) {
3979 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3980 			    ipst);
3981 		} else {
3982 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3983 		}
3984 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3985 			uint32_t now;
3986 			uint32_t maxage;
3987 			clock_t lused;
3988 			uint_t maxdefense;
3989 			uint_t defs;
3990 
3991 			/*
3992 			 * First, figure out if this address hasn't been used
3993 			 * in a while.  If it hasn't, then it's a better
3994 			 * candidate for abandoning.
3995 			 */
3996 			ipif = ire->ire_ipif;
3997 			ASSERT(ipif != NULL);
3998 			now = gethrestime_sec();
3999 			maxage = now - ire->ire_create_time;
4000 			if (maxage > ipst->ips_ip_max_temp_idle)
4001 				maxage = ipst->ips_ip_max_temp_idle;
4002 			lused = drv_hztousec(ddi_get_lbolt() -
4003 			    ire->ire_last_used_time) / MICROSEC + 1;
4004 			if (lused >= maxage && (ipif->ipif_flags &
4005 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4006 				maxdefense = ipst->ips_ip_max_temp_defend;
4007 			else
4008 				maxdefense = ipst->ips_ip_max_defend;
4009 
4010 			/*
4011 			 * Now figure out how many times we've defended
4012 			 * ourselves.  Ignore defenses that happened long in
4013 			 * the past.
4014 			 */
4015 			mutex_enter(&ire->ire_lock);
4016 			if ((defs = ire->ire_defense_count) > 0 &&
4017 			    now - ire->ire_defense_time >
4018 			    ipst->ips_ip_defend_interval) {
4019 				ire->ire_defense_count = defs = 0;
4020 			}
4021 			ire->ire_defense_count++;
4022 			ire->ire_defense_time = now;
4023 			mutex_exit(&ire->ire_lock);
4024 			ill_refhold(ill);
4025 			ire_refrele(ire);
4026 
4027 			/*
4028 			 * If we've defended ourselves too many times already,
4029 			 * then give up and tear down the interface(s) using
4030 			 * this address.  Otherwise, defend by sending out a
4031 			 * gratuitous ARP.
4032 			 */
4033 			if (defs >= maxdefense && ill->ill_arp_extend) {
4034 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4035 				    B_FALSE);
4036 			} else {
4037 				cmn_err(CE_WARN,
4038 				    "node %s is using our IP address %s on %s",
4039 				    hbuf, sbuf, ill->ill_name);
4040 				/*
4041 				 * If this is an old (ATM) ARP module, then
4042 				 * don't try to defend the address.  Remain
4043 				 * compatible with the old behavior.  Defend
4044 				 * only with new ARP.
4045 				 */
4046 				if (ill->ill_arp_extend) {
4047 					qwriter_ip(ill, q, mp, ip_arp_defend,
4048 					    NEW_OP, B_FALSE);
4049 				} else {
4050 					ill_refrele(ill);
4051 				}
4052 			}
4053 			return;
4054 		}
4055 		cmn_err(CE_WARN,
4056 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4057 		    hbuf, sbuf, ill->ill_name);
4058 		if (ire != NULL)
4059 			ire_refrele(ire);
4060 		break;
4061 	case AR_CN_ANNOUNCE:
4062 		if (isv6) {
4063 			/*
4064 			 * For XRESOLV interfaces.
4065 			 * Delete the IRE cache entry and NCE for this
4066 			 * v6 address
4067 			 */
4068 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4069 			/*
4070 			 * If v6src is a non-zero, it's a router address
4071 			 * as below. Do the same sort of thing to clean
4072 			 * out off-net IRE_CACHE entries that go through
4073 			 * the router.
4074 			 */
4075 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4076 				ire_walk_v6(ire_delete_cache_gw_v6,
4077 				    (char *)&v6src, ALL_ZONES, ipst);
4078 			}
4079 		} else {
4080 			nce_hw_map_t hwm;
4081 
4082 			/*
4083 			 * ARP gives us a copy of any packet where it thinks
4084 			 * the address has changed, so that we can update our
4085 			 * caches.  We're responsible for caching known answers
4086 			 * in the current design.  We check whether the
4087 			 * hardware address really has changed in all of our
4088 			 * entries that have cached this mapping, and if so, we
4089 			 * blow them away.  This way we will immediately pick
4090 			 * up the rare case of a host changing hardware
4091 			 * address.
4092 			 */
4093 			if (src == 0)
4094 				break;
4095 			hwm.hwm_addr = src;
4096 			hwm.hwm_hwlen = arh->arh_hlen;
4097 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4098 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4099 			ndp_walk_common(ipst->ips_ndp4, NULL,
4100 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4101 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4102 		}
4103 		break;
4104 	case AR_CN_READY:
4105 		/* No external v6 resolver has a contract to use this */
4106 		if (isv6)
4107 			break;
4108 		/* If the link is down, we'll retry this later */
4109 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4110 			break;
4111 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4112 		    NULL, NULL, ipst);
4113 		if (ipif != NULL) {
4114 			/*
4115 			 * If this is a duplicate recovery, then we now need to
4116 			 * go exclusive to bring this thing back up.
4117 			 */
4118 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4119 			    IPIF_DUPLICATE) {
4120 				ipif_refrele(ipif);
4121 				ill_refhold(ill);
4122 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4123 				    B_FALSE);
4124 				return;
4125 			}
4126 			/*
4127 			 * If this is the first notice that this address is
4128 			 * ready, then let the user know now.
4129 			 */
4130 			if ((ipif->ipif_flags & IPIF_UP) &&
4131 			    !ipif->ipif_addr_ready) {
4132 				ipif_mask_reply(ipif);
4133 				ipif_up_notify(ipif);
4134 			}
4135 			ipif->ipif_addr_ready = 1;
4136 			ipif_refrele(ipif);
4137 		}
4138 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4139 		if (ire != NULL) {
4140 			ire->ire_defense_count = 0;
4141 			ire_refrele(ire);
4142 		}
4143 		break;
4144 	case AR_CN_FAILED:
4145 		/* No external v6 resolver has a contract to use this */
4146 		if (isv6)
4147 			break;
4148 		if (!ill->ill_arp_extend) {
4149 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4150 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4151 			(void) ip_dot_addr(src, sbuf);
4152 
4153 			cmn_err(CE_WARN,
4154 			    "node %s is using our IP address %s on %s",
4155 			    hbuf, sbuf, ill->ill_name);
4156 			break;
4157 		}
4158 		ill_refhold(ill);
4159 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4160 		return;
4161 	}
4162 	freemsg(mp);
4163 }
4164 
4165 /*
4166  * Create a mblk suitable for carrying the interface index and/or source link
4167  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4168  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4169  * application.
4170  */
4171 mblk_t *
4172 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4173     ip_stack_t *ipst)
4174 {
4175 	mblk_t		*mp;
4176 	ip_pktinfo_t	*pinfo;
4177 	ipha_t 		*ipha;
4178 	struct ether_header *pether;
4179 	boolean_t	ipmp_ill_held = B_FALSE;
4180 
4181 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4182 	if (mp == NULL) {
4183 		ip1dbg(("ip_add_info: allocation failure.\n"));
4184 		return (data_mp);
4185 	}
4186 
4187 	ipha = (ipha_t *)data_mp->b_rptr;
4188 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4189 	bzero(pinfo, sizeof (ip_pktinfo_t));
4190 	pinfo->ip_pkt_flags = (uchar_t)flags;
4191 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4192 
4193 	pether = (struct ether_header *)((char *)ipha
4194 	    - sizeof (struct ether_header));
4195 
4196 	/*
4197 	 * Make sure the interface is an ethernet type, since this option
4198 	 * is currently supported only on this type of interface. Also make
4199 	 * sure we are pointing correctly above db_base.
4200 	 */
4201 	if ((flags & IPF_RECVSLLA) &&
4202 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4203 	    (ill->ill_type == IFT_ETHER) &&
4204 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4205 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4206 		bcopy(pether->ether_shost.ether_addr_octet,
4207 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4208 	} else {
4209 		/*
4210 		 * Clear the bit. Indicate to upper layer that IP is not
4211 		 * sending this ancillary info.
4212 		 */
4213 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4214 	}
4215 
4216 	/*
4217 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4218 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4219 	 * IPF_RECVADDR support on test addresses is not needed.)
4220 	 *
4221 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4222 	 * processing a packet looped back to an IPMP data address
4223 	 * (since those IRE_LOCALs are tied to IPMP ills).
4224 	 */
4225 	if (IS_UNDER_IPMP(ill)) {
4226 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4227 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4228 			freemsg(mp);
4229 			return (data_mp);
4230 		}
4231 		ipmp_ill_held = B_TRUE;
4232 	}
4233 
4234 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4235 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4236 	if (flags & IPF_RECVADDR) {
4237 		ipif_t	*ipif;
4238 		ire_t	*ire;
4239 
4240 		/*
4241 		 * Only valid for V4
4242 		 */
4243 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4244 		    (IPV4_VERSION << 4));
4245 
4246 		ipif = ipif_get_next_ipif(NULL, ill);
4247 		if (ipif != NULL) {
4248 			/*
4249 			 * Since a decision has already been made to deliver the
4250 			 * packet, there is no need to test for SECATTR and
4251 			 * ZONEONLY.
4252 			 * When a multicast packet is transmitted
4253 			 * a cache entry is created for the multicast address.
4254 			 * When delivering a copy of the packet or when new
4255 			 * packets are received we do not want to match on the
4256 			 * cached entry so explicitly match on
4257 			 * IRE_LOCAL and IRE_LOOPBACK
4258 			 */
4259 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4260 			    IRE_LOCAL | IRE_LOOPBACK,
4261 			    ipif, zoneid, NULL,
4262 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4263 			if (ire == NULL) {
4264 				/*
4265 				 * packet must have come on a different
4266 				 * interface.
4267 				 * Since a decision has already been made to
4268 				 * deliver the packet, there is no need to test
4269 				 * for SECATTR and ZONEONLY.
4270 				 * Only match on local and broadcast ire's.
4271 				 * See detailed comment above.
4272 				 */
4273 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4274 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4275 				    NULL, MATCH_IRE_TYPE, ipst);
4276 			}
4277 
4278 			if (ire == NULL) {
4279 				/*
4280 				 * This is either a multicast packet or
4281 				 * the address has been removed since
4282 				 * the packet was received.
4283 				 * Return INADDR_ANY so that normal source
4284 				 * selection occurs for the response.
4285 				 */
4286 
4287 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4288 			} else {
4289 				pinfo->ip_pkt_match_addr.s_addr =
4290 				    ire->ire_src_addr;
4291 				ire_refrele(ire);
4292 			}
4293 			ipif_refrele(ipif);
4294 		} else {
4295 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4296 		}
4297 	}
4298 
4299 	if (ipmp_ill_held)
4300 		ill_refrele(ill);
4301 
4302 	mp->b_datap->db_type = M_CTL;
4303 	mp->b_wptr += sizeof (ip_pktinfo_t);
4304 	mp->b_cont = data_mp;
4305 
4306 	return (mp);
4307 }
4308 
4309 /*
4310  * Used to determine the most accurate cred_t to use for TX.
4311  * First priority is SCM_UCRED having set the label in the message,
4312  * which is used for MLP on UDP. Second priority is the open credentials
4313  * with the peer's label (aka conn_effective_cred), which is needed for
4314  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4315  */
4316 cred_t *
4317 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4318 {
4319 	cred_t *cr;
4320 
4321 	cr = msg_getcred(mp, pidp);
4322 	if (cr != NULL && crgetlabel(cr) != NULL)
4323 		return (cr);
4324 	*pidp = NOPID;
4325 	return (CONN_CRED(connp));
4326 }
4327 
4328 /*
4329  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4330  * part of the bind request.
4331  */
4332 
4333 boolean_t
4334 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4335 {
4336 	ipsec_in_t *ii;
4337 
4338 	ASSERT(policy_mp != NULL);
4339 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4340 
4341 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4342 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4343 
4344 	connp->conn_policy = ii->ipsec_in_policy;
4345 	ii->ipsec_in_policy = NULL;
4346 
4347 	if (ii->ipsec_in_action != NULL) {
4348 		if (connp->conn_latch == NULL) {
4349 			connp->conn_latch = iplatch_create();
4350 			if (connp->conn_latch == NULL)
4351 				return (B_FALSE);
4352 		}
4353 		ipsec_latch_inbound(connp->conn_latch, ii);
4354 	}
4355 	return (B_TRUE);
4356 }
4357 
4358 static void
4359 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4360 {
4361 	/*
4362 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4363 	 * We can't do this in ip_bind_get_ire because the policy
4364 	 * may not have been inherited at that point in time and hence
4365 	 * conn_out_enforce_policy may not be set.
4366 	 */
4367 	if (ire_requested && connp->conn_out_enforce_policy &&
4368 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4369 		ire_t *ire = (ire_t *)mp->b_rptr;
4370 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4371 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4372 	}
4373 }
4374 
4375 /*
4376  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4377  * and to arrange for power-fanout assist.  The ULP is identified by
4378  * adding a single byte at the end of the original bind message.
4379  * A ULP other than UDP or TCP that wishes to be recognized passes
4380  * down a bind with a zero length address.
4381  *
4382  * The binding works as follows:
4383  * - A zero byte address means just bind to the protocol.
4384  * - A four byte address is treated as a request to validate
4385  *   that the address is a valid local address, appropriate for
4386  *   an application to bind to. This does not affect any fanout
4387  *   information in IP.
4388  * - A sizeof sin_t byte address is used to bind to only the local address
4389  *   and port.
4390  * - A sizeof ipa_conn_t byte address contains complete fanout information
4391  *   consisting of local and remote addresses and ports.  In
4392  *   this case, the addresses are both validated as appropriate
4393  *   for this operation, and, if so, the information is retained
4394  *   for use in the inbound fanout.
4395  *
4396  * The ULP (except in the zero-length bind) can append an
4397  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4398  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4399  * a copy of the source or destination IRE (source for local bind;
4400  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4401  * policy information contained should be copied on to the conn.
4402  *
4403  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4404  */
4405 mblk_t *
4406 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4407 {
4408 	ssize_t		len;
4409 	struct T_bind_req	*tbr;
4410 	sin_t		*sin;
4411 	ipa_conn_t	*ac;
4412 	uchar_t		*ucp;
4413 	mblk_t		*mp1;
4414 	boolean_t	ire_requested;
4415 	int		error = 0;
4416 	int		protocol;
4417 	ipa_conn_x_t	*acx;
4418 	cred_t		*cr;
4419 
4420 	/*
4421 	 * All Solaris components should pass a db_credp
4422 	 * for this TPI message, hence we ASSERT.
4423 	 * But in case there is some other M_PROTO that looks
4424 	 * like a TPI message sent by some other kernel
4425 	 * component, we check and return an error.
4426 	 */
4427 	cr = msg_getcred(mp, NULL);
4428 	ASSERT(cr != NULL);
4429 	if (cr == NULL) {
4430 		error = EINVAL;
4431 		goto bad_addr;
4432 	}
4433 
4434 	ASSERT(!connp->conn_af_isv6);
4435 	connp->conn_pkt_isv6 = B_FALSE;
4436 
4437 	len = MBLKL(mp);
4438 	if (len < (sizeof (*tbr) + 1)) {
4439 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4440 		    "ip_bind: bogus msg, len %ld", len);
4441 		/* XXX: Need to return something better */
4442 		goto bad_addr;
4443 	}
4444 	/* Back up and extract the protocol identifier. */
4445 	mp->b_wptr--;
4446 	protocol = *mp->b_wptr & 0xFF;
4447 	tbr = (struct T_bind_req *)mp->b_rptr;
4448 	/* Reset the message type in preparation for shipping it back. */
4449 	DB_TYPE(mp) = M_PCPROTO;
4450 
4451 	connp->conn_ulp = (uint8_t)protocol;
4452 
4453 	/*
4454 	 * Check for a zero length address.  This is from a protocol that
4455 	 * wants to register to receive all packets of its type.
4456 	 */
4457 	if (tbr->ADDR_length == 0) {
4458 		/*
4459 		 * These protocols are now intercepted in ip_bind_v6().
4460 		 * Reject protocol-level binds here for now.
4461 		 *
4462 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4463 		 * so that the protocol type cannot be SCTP.
4464 		 */
4465 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4466 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4467 			goto bad_addr;
4468 		}
4469 
4470 		/*
4471 		 *
4472 		 * The udp module never sends down a zero-length address,
4473 		 * and allowing this on a labeled system will break MLP
4474 		 * functionality.
4475 		 */
4476 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4477 			goto bad_addr;
4478 
4479 		if (connp->conn_mac_exempt)
4480 			goto bad_addr;
4481 
4482 		/* No hash here really.  The table is big enough. */
4483 		connp->conn_srcv6 = ipv6_all_zeros;
4484 
4485 		ipcl_proto_insert(connp, protocol);
4486 
4487 		tbr->PRIM_type = T_BIND_ACK;
4488 		return (mp);
4489 	}
4490 
4491 	/* Extract the address pointer from the message. */
4492 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4493 	    tbr->ADDR_length);
4494 	if (ucp == NULL) {
4495 		ip1dbg(("ip_bind: no address\n"));
4496 		goto bad_addr;
4497 	}
4498 	if (!OK_32PTR(ucp)) {
4499 		ip1dbg(("ip_bind: unaligned address\n"));
4500 		goto bad_addr;
4501 	}
4502 	/*
4503 	 * Check for trailing mps.
4504 	 */
4505 
4506 	mp1 = mp->b_cont;
4507 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4508 
4509 	switch (tbr->ADDR_length) {
4510 	default:
4511 		ip1dbg(("ip_bind: bad address length %d\n",
4512 		    (int)tbr->ADDR_length));
4513 		goto bad_addr;
4514 
4515 	case IP_ADDR_LEN:
4516 		/* Verification of local address only */
4517 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4518 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4519 		break;
4520 
4521 	case sizeof (sin_t):
4522 		sin = (sin_t *)ucp;
4523 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4524 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4525 		break;
4526 
4527 	case sizeof (ipa_conn_t):
4528 		ac = (ipa_conn_t *)ucp;
4529 		/* For raw socket, the local port is not set. */
4530 		if (ac->ac_lport == 0)
4531 			ac->ac_lport = connp->conn_lport;
4532 		/* Always verify destination reachability. */
4533 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4534 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4535 		    B_TRUE, B_TRUE, cr);
4536 		break;
4537 
4538 	case sizeof (ipa_conn_x_t):
4539 		acx = (ipa_conn_x_t *)ucp;
4540 		/*
4541 		 * Whether or not to verify destination reachability depends
4542 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4543 		 */
4544 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4545 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4546 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4547 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4548 		break;
4549 	}
4550 	ASSERT(error != EINPROGRESS);
4551 	if (error != 0)
4552 		goto bad_addr;
4553 
4554 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4555 
4556 	/* Send it home. */
4557 	mp->b_datap->db_type = M_PCPROTO;
4558 	tbr->PRIM_type = T_BIND_ACK;
4559 	return (mp);
4560 
4561 bad_addr:
4562 	/*
4563 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4564 	 * a unix errno.
4565 	 */
4566 	if (error > 0)
4567 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4568 	else
4569 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4570 	return (mp);
4571 }
4572 
4573 /*
4574  * Here address is verified to be a valid local address.
4575  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4576  * address is also considered a valid local address.
4577  * In the case of a broadcast/multicast address, however, the
4578  * upper protocol is expected to reset the src address
4579  * to 0 if it sees a IRE_BROADCAST type returned so that
4580  * no packets are emitted with broadcast/multicast address as
4581  * source address (that violates hosts requirements RFC 1122)
4582  * The addresses valid for bind are:
4583  *	(1) - INADDR_ANY (0)
4584  *	(2) - IP address of an UP interface
4585  *	(3) - IP address of a DOWN interface
4586  *	(4) - valid local IP broadcast addresses. In this case
4587  *	the conn will only receive packets destined to
4588  *	the specified broadcast address.
4589  *	(5) - a multicast address. In this case
4590  *	the conn will only receive packets destined to
4591  *	the specified multicast address. Note: the
4592  *	application still has to issue an
4593  *	IP_ADD_MEMBERSHIP socket option.
4594  *
4595  * On error, return -1 for TBADADDR otherwise pass the
4596  * errno with TSYSERR reply.
4597  *
4598  * In all the above cases, the bound address must be valid in the current zone.
4599  * When the address is loopback, multicast or broadcast, there might be many
4600  * matching IREs so bind has to look up based on the zone.
4601  *
4602  * Note: lport is in network byte order.
4603  *
4604  */
4605 int
4606 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4607     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4608 {
4609 	int		error = 0;
4610 	ire_t		*src_ire;
4611 	zoneid_t	zoneid;
4612 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4613 	mblk_t		*mp = NULL;
4614 	boolean_t	ire_requested = B_FALSE;
4615 	boolean_t	ipsec_policy_set = B_FALSE;
4616 
4617 	if (mpp)
4618 		mp = *mpp;
4619 
4620 	if (mp != NULL) {
4621 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4622 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4623 	}
4624 
4625 	/*
4626 	 * If it was previously connected, conn_fully_bound would have
4627 	 * been set.
4628 	 */
4629 	connp->conn_fully_bound = B_FALSE;
4630 
4631 	src_ire = NULL;
4632 
4633 	zoneid = IPCL_ZONEID(connp);
4634 
4635 	if (src_addr) {
4636 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4637 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4638 		/*
4639 		 * If an address other than 0.0.0.0 is requested,
4640 		 * we verify that it is a valid address for bind
4641 		 * Note: Following code is in if-else-if form for
4642 		 * readability compared to a condition check.
4643 		 */
4644 		/* LINTED - statement has no consequence */
4645 		if (IRE_IS_LOCAL(src_ire)) {
4646 			/*
4647 			 * (2) Bind to address of local UP interface
4648 			 */
4649 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4650 			/*
4651 			 * (4) Bind to broadcast address
4652 			 * Note: permitted only from transports that
4653 			 * request IRE
4654 			 */
4655 			if (!ire_requested)
4656 				error = EADDRNOTAVAIL;
4657 		} else {
4658 			/*
4659 			 * (3) Bind to address of local DOWN interface
4660 			 * (ipif_lookup_addr() looks up all interfaces
4661 			 * but we do not get here for UP interfaces
4662 			 * - case (2) above)
4663 			 */
4664 			/* LINTED - statement has no consequent */
4665 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4666 				/* The address exists */
4667 			} else if (CLASSD(src_addr)) {
4668 				error = 0;
4669 				if (src_ire != NULL)
4670 					ire_refrele(src_ire);
4671 				/*
4672 				 * (5) bind to multicast address.
4673 				 * Fake out the IRE returned to upper
4674 				 * layer to be a broadcast IRE.
4675 				 */
4676 				src_ire = ire_ctable_lookup(
4677 				    INADDR_BROADCAST, INADDR_ANY,
4678 				    IRE_BROADCAST, NULL, zoneid, NULL,
4679 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4680 				    ipst);
4681 				if (src_ire == NULL || !ire_requested)
4682 					error = EADDRNOTAVAIL;
4683 			} else {
4684 				/*
4685 				 * Not a valid address for bind
4686 				 */
4687 				error = EADDRNOTAVAIL;
4688 			}
4689 		}
4690 		if (error) {
4691 			/* Red Alert!  Attempting to be a bogon! */
4692 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4693 			    ntohl(src_addr)));
4694 			goto bad_addr;
4695 		}
4696 	}
4697 
4698 	/*
4699 	 * Allow setting new policies. For example, disconnects come
4700 	 * down as ipa_t bind. As we would have set conn_policy_cached
4701 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4702 	 * can change after the disconnect.
4703 	 */
4704 	connp->conn_policy_cached = B_FALSE;
4705 
4706 	/*
4707 	 * If not fanout_insert this was just an address verification
4708 	 */
4709 	if (fanout_insert) {
4710 		/*
4711 		 * The addresses have been verified. Time to insert in
4712 		 * the correct fanout list.
4713 		 */
4714 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4715 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4716 		connp->conn_lport = lport;
4717 		connp->conn_fport = 0;
4718 		/*
4719 		 * Do we need to add a check to reject Multicast packets
4720 		 */
4721 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4722 	}
4723 
4724 	if (error == 0) {
4725 		if (ire_requested) {
4726 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4727 				error = -1;
4728 				/* Falls through to bad_addr */
4729 			}
4730 		} else if (ipsec_policy_set) {
4731 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4732 				error = -1;
4733 				/* Falls through to bad_addr */
4734 			}
4735 		}
4736 	}
4737 bad_addr:
4738 	if (error != 0) {
4739 		if (connp->conn_anon_port) {
4740 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4741 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4742 			    B_FALSE);
4743 		}
4744 		connp->conn_mlp_type = mlptSingle;
4745 	}
4746 	if (src_ire != NULL)
4747 		IRE_REFRELE(src_ire);
4748 	return (error);
4749 }
4750 
4751 int
4752 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4753     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4754 {
4755 	int error;
4756 	mblk_t	*mp = NULL;
4757 	boolean_t ire_requested;
4758 
4759 	if (ire_mpp)
4760 		mp = *ire_mpp;
4761 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4762 
4763 	ASSERT(!connp->conn_af_isv6);
4764 	connp->conn_pkt_isv6 = B_FALSE;
4765 	connp->conn_ulp = protocol;
4766 
4767 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4768 	    fanout_insert);
4769 	if (error == 0) {
4770 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4771 		    ire_requested);
4772 	} else if (error < 0) {
4773 		error = -TBADADDR;
4774 	}
4775 	return (error);
4776 }
4777 
4778 /*
4779  * Verify that both the source and destination addresses
4780  * are valid.  If verify_dst is false, then the destination address may be
4781  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4782  * destination reachability, while tunnels do not.
4783  * Note that we allow connect to broadcast and multicast
4784  * addresses when ire_requested is set. Thus the ULP
4785  * has to check for IRE_BROADCAST and multicast.
4786  *
4787  * Returns zero if ok.
4788  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4789  * (for use with TSYSERR reply).
4790  *
4791  * Note: lport and fport are in network byte order.
4792  */
4793 int
4794 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4795     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4796     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4797 {
4798 
4799 	ire_t		*src_ire;
4800 	ire_t		*dst_ire;
4801 	int		error = 0;
4802 	ire_t		*sire = NULL;
4803 	ire_t		*md_dst_ire = NULL;
4804 	ire_t		*lso_dst_ire = NULL;
4805 	ill_t		*ill = NULL;
4806 	zoneid_t	zoneid;
4807 	ipaddr_t	src_addr = *src_addrp;
4808 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4809 	mblk_t		*mp = NULL;
4810 	boolean_t	ire_requested = B_FALSE;
4811 	boolean_t	ipsec_policy_set = B_FALSE;
4812 	ts_label_t	*tsl = NULL;
4813 	cred_t		*effective_cred = NULL;
4814 
4815 	if (mpp)
4816 		mp = *mpp;
4817 
4818 	if (mp != NULL) {
4819 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4820 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4821 	}
4822 
4823 	src_ire = dst_ire = NULL;
4824 
4825 	/*
4826 	 * If we never got a disconnect before, clear it now.
4827 	 */
4828 	connp->conn_fully_bound = B_FALSE;
4829 
4830 	zoneid = IPCL_ZONEID(connp);
4831 
4832 	/*
4833 	 * Check whether Trusted Solaris policy allows communication with this
4834 	 * host, and pretend that the destination is unreachable if not.
4835 	 *
4836 	 * This is never a problem for TCP, since that transport is known to
4837 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4838 	 * handling.  If the remote is unreachable, it will be detected at that
4839 	 * point, so there's no reason to check it here.
4840 	 *
4841 	 * Note that for sendto (and other datagram-oriented friends), this
4842 	 * check is done as part of the data path label computation instead.
4843 	 * The check here is just to make non-TCP connect() report the right
4844 	 * error.
4845 	 */
4846 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4847 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4848 		    connp->conn_mac_exempt, &effective_cred)) != 0) {
4849 			if (ip_debug > 2) {
4850 				pr_addr_dbg(
4851 				    "ip_bind_connected_v4:"
4852 				    " no label for dst %s\n",
4853 				    AF_INET, &dst_addr);
4854 			}
4855 			goto bad_addr;
4856 		}
4857 
4858 		/*
4859 		 * tsol_check_dest() may have created a new cred with
4860 		 * a modified security label. Use that cred if it exists
4861 		 * for ire lookups.
4862 		 */
4863 		if (effective_cred == NULL) {
4864 			tsl = crgetlabel(cr);
4865 		} else {
4866 			tsl = crgetlabel(effective_cred);
4867 		}
4868 	}
4869 
4870 	if (CLASSD(dst_addr)) {
4871 		/* Pick up an IRE_BROADCAST */
4872 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4873 		    NULL, zoneid, tsl,
4874 		    (MATCH_IRE_RECURSIVE |
4875 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4876 		    MATCH_IRE_SECATTR), ipst);
4877 	} else {
4878 		/*
4879 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4880 		 * and onlink ipif is not found set ENETUNREACH error.
4881 		 */
4882 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4883 			ipif_t *ipif;
4884 
4885 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4886 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4887 			if (ipif == NULL) {
4888 				error = ENETUNREACH;
4889 				goto bad_addr;
4890 			}
4891 			ipif_refrele(ipif);
4892 		}
4893 
4894 		if (connp->conn_nexthop_set) {
4895 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4896 			    0, 0, NULL, NULL, zoneid, tsl,
4897 			    MATCH_IRE_SECATTR, ipst);
4898 		} else {
4899 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4900 			    &sire, zoneid, tsl,
4901 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4902 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4903 			    MATCH_IRE_SECATTR), ipst);
4904 		}
4905 	}
4906 	/*
4907 	 * dst_ire can't be a broadcast when not ire_requested.
4908 	 * We also prevent ire's with src address INADDR_ANY to
4909 	 * be used, which are created temporarily for
4910 	 * sending out packets from endpoints that have
4911 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4912 	 * reachable.  If verify_dst is false, the destination needn't be
4913 	 * reachable.
4914 	 *
4915 	 * If we match on a reject or black hole, then we've got a
4916 	 * local failure.  May as well fail out the connect() attempt,
4917 	 * since it's never going to succeed.
4918 	 */
4919 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4920 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4921 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4922 		/*
4923 		 * If we're verifying destination reachability, we always want
4924 		 * to complain here.
4925 		 *
4926 		 * If we're not verifying destination reachability but the
4927 		 * destination has a route, we still want to fail on the
4928 		 * temporary address and broadcast address tests.
4929 		 */
4930 		if (verify_dst || (dst_ire != NULL)) {
4931 			if (ip_debug > 2) {
4932 				pr_addr_dbg("ip_bind_connected_v4:"
4933 				    "bad connected dst %s\n",
4934 				    AF_INET, &dst_addr);
4935 			}
4936 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4937 				error = ENETUNREACH;
4938 			else
4939 				error = EHOSTUNREACH;
4940 			goto bad_addr;
4941 		}
4942 	}
4943 
4944 	/*
4945 	 * If the app does a connect(), it means that it will most likely
4946 	 * send more than 1 packet to the destination.  It makes sense
4947 	 * to clear the temporary flag.
4948 	 */
4949 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4950 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4951 		irb_t *irb = dst_ire->ire_bucket;
4952 
4953 		rw_enter(&irb->irb_lock, RW_WRITER);
4954 		/*
4955 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4956 		 * the lock to guarantee irb_tmp_ire_cnt.
4957 		 */
4958 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4959 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4960 			irb->irb_tmp_ire_cnt--;
4961 		}
4962 		rw_exit(&irb->irb_lock);
4963 	}
4964 
4965 	/*
4966 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4967 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4968 	 * eligibility tests for passive connects are handled separately
4969 	 * through tcp_adapt_ire().  We do this before the source address
4970 	 * selection, because dst_ire may change after a call to
4971 	 * ipif_select_source().  This is a best-effort check, as the
4972 	 * packet for this connection may not actually go through
4973 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4974 	 * calling ip_newroute().  This is why we further check on the
4975 	 * IRE during LSO/Multidata packet transmission in
4976 	 * tcp_lsosend()/tcp_multisend().
4977 	 */
4978 	if (!ipsec_policy_set && dst_ire != NULL &&
4979 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4980 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4981 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4982 			lso_dst_ire = dst_ire;
4983 			IRE_REFHOLD(lso_dst_ire);
4984 		} else if (ipst->ips_ip_multidata_outbound &&
4985 		    ILL_MDT_CAPABLE(ill)) {
4986 			md_dst_ire = dst_ire;
4987 			IRE_REFHOLD(md_dst_ire);
4988 		}
4989 	}
4990 
4991 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4992 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4993 		/*
4994 		 * If the IRE belongs to a different zone, look for a matching
4995 		 * route in the forwarding table and use the source address from
4996 		 * that route.
4997 		 */
4998 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4999 		    zoneid, 0, NULL,
5000 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
5001 		    MATCH_IRE_RJ_BHOLE, ipst);
5002 		if (src_ire == NULL) {
5003 			error = EHOSTUNREACH;
5004 			goto bad_addr;
5005 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5006 			if (!(src_ire->ire_type & IRE_HOST))
5007 				error = ENETUNREACH;
5008 			else
5009 				error = EHOSTUNREACH;
5010 			goto bad_addr;
5011 		}
5012 		if (src_addr == INADDR_ANY)
5013 			src_addr = src_ire->ire_src_addr;
5014 		ire_refrele(src_ire);
5015 		src_ire = NULL;
5016 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5017 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5018 			src_addr = sire->ire_src_addr;
5019 			ire_refrele(dst_ire);
5020 			dst_ire = sire;
5021 			sire = NULL;
5022 		} else {
5023 			/*
5024 			 * Pick a source address so that a proper inbound
5025 			 * load spreading would happen.
5026 			 */
5027 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5028 			ipif_t *src_ipif = NULL;
5029 			ire_t *ipif_ire;
5030 
5031 			/*
5032 			 * Supply a local source address such that inbound
5033 			 * load spreading happens.
5034 			 *
5035 			 * Determine the best source address on this ill for
5036 			 * the destination.
5037 			 *
5038 			 * 1) For broadcast, we should return a broadcast ire
5039 			 *    found above so that upper layers know that the
5040 			 *    destination address is a broadcast address.
5041 			 *
5042 			 * 2) If the ipif is DEPRECATED, select a better
5043 			 *    source address.  Similarly, if the ipif is on
5044 			 *    the IPMP meta-interface, pick a source address
5045 			 *    at random to improve inbound load spreading.
5046 			 *
5047 			 * 3) If the outgoing interface is part of a usesrc
5048 			 *    group, then try selecting a source address from
5049 			 *    the usesrc ILL.
5050 			 */
5051 			if ((dst_ire->ire_zoneid != zoneid &&
5052 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5053 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5054 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5055 			    (IS_IPMP(ire_ill) ||
5056 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5057 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5058 				/*
5059 				 * If the destination is reachable via a
5060 				 * given gateway, the selected source address
5061 				 * should be in the same subnet as the gateway.
5062 				 * Otherwise, the destination is not reachable.
5063 				 *
5064 				 * If there are no interfaces on the same subnet
5065 				 * as the destination, ipif_select_source gives
5066 				 * first non-deprecated interface which might be
5067 				 * on a different subnet than the gateway.
5068 				 * This is not desirable. Hence pass the dst_ire
5069 				 * source address to ipif_select_source.
5070 				 * It is sure that the destination is reachable
5071 				 * with the dst_ire source address subnet.
5072 				 * So passing dst_ire source address to
5073 				 * ipif_select_source will make sure that the
5074 				 * selected source will be on the same subnet
5075 				 * as dst_ire source address.
5076 				 */
5077 				ipaddr_t saddr =
5078 				    dst_ire->ire_ipif->ipif_src_addr;
5079 				src_ipif = ipif_select_source(ire_ill,
5080 				    saddr, zoneid);
5081 				if (src_ipif != NULL) {
5082 					if (IS_VNI(src_ipif->ipif_ill)) {
5083 						/*
5084 						 * For VNI there is no
5085 						 * interface route
5086 						 */
5087 						src_addr =
5088 						    src_ipif->ipif_src_addr;
5089 					} else {
5090 						ipif_ire =
5091 						    ipif_to_ire(src_ipif);
5092 						if (ipif_ire != NULL) {
5093 							IRE_REFRELE(dst_ire);
5094 							dst_ire = ipif_ire;
5095 						}
5096 						src_addr =
5097 						    dst_ire->ire_src_addr;
5098 					}
5099 					ipif_refrele(src_ipif);
5100 				} else {
5101 					src_addr = dst_ire->ire_src_addr;
5102 				}
5103 			} else {
5104 				src_addr = dst_ire->ire_src_addr;
5105 			}
5106 		}
5107 	}
5108 
5109 	/*
5110 	 * We do ire_route_lookup() here (and not
5111 	 * interface lookup as we assert that
5112 	 * src_addr should only come from an
5113 	 * UP interface for hard binding.
5114 	 */
5115 	ASSERT(src_ire == NULL);
5116 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5117 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5118 	/* src_ire must be a local|loopback */
5119 	if (!IRE_IS_LOCAL(src_ire)) {
5120 		if (ip_debug > 2) {
5121 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5122 			    "src %s\n", AF_INET, &src_addr);
5123 		}
5124 		error = EADDRNOTAVAIL;
5125 		goto bad_addr;
5126 	}
5127 
5128 	/*
5129 	 * If the source address is a loopback address, the
5130 	 * destination had best be local or multicast.
5131 	 * The transports that can't handle multicast will reject
5132 	 * those addresses.
5133 	 */
5134 	if (src_ire->ire_type == IRE_LOOPBACK &&
5135 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5136 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5137 		error = -1;
5138 		goto bad_addr;
5139 	}
5140 
5141 	/*
5142 	 * Allow setting new policies. For example, disconnects come
5143 	 * down as ipa_t bind. As we would have set conn_policy_cached
5144 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5145 	 * can change after the disconnect.
5146 	 */
5147 	connp->conn_policy_cached = B_FALSE;
5148 
5149 	/*
5150 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5151 	 * can handle their passed-in conn's.
5152 	 */
5153 
5154 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5155 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5156 	connp->conn_lport = lport;
5157 	connp->conn_fport = fport;
5158 	*src_addrp = src_addr;
5159 
5160 	ASSERT(!(ipsec_policy_set && ire_requested));
5161 	if (ire_requested) {
5162 		iulp_t *ulp_info = NULL;
5163 
5164 		/*
5165 		 * Note that sire will not be NULL if this is an off-link
5166 		 * connection and there is not cache for that dest yet.
5167 		 *
5168 		 * XXX Because of an existing bug, if there are multiple
5169 		 * default routes, the IRE returned now may not be the actual
5170 		 * default route used (default routes are chosen in a
5171 		 * round robin fashion).  So if the metrics for different
5172 		 * default routes are different, we may return the wrong
5173 		 * metrics.  This will not be a problem if the existing
5174 		 * bug is fixed.
5175 		 */
5176 		if (sire != NULL) {
5177 			ulp_info = &(sire->ire_uinfo);
5178 		}
5179 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5180 			error = -1;
5181 			goto bad_addr;
5182 		}
5183 		mp = *mpp;
5184 	} else if (ipsec_policy_set) {
5185 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5186 			error = -1;
5187 			goto bad_addr;
5188 		}
5189 	}
5190 
5191 	/*
5192 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5193 	 * we'll cache that.  If we don't, we'll inherit global policy.
5194 	 *
5195 	 * We can't insert until the conn reflects the policy. Note that
5196 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5197 	 * connections where we don't have a policy. This is to prevent
5198 	 * global policy lookups in the inbound path.
5199 	 *
5200 	 * If we insert before we set conn_policy_cached,
5201 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5202 	 * because global policy cound be non-empty. We normally call
5203 	 * ipsec_check_policy() for conn_policy_cached connections only if
5204 	 * ipc_in_enforce_policy is set. But in this case,
5205 	 * conn_policy_cached can get set anytime since we made the
5206 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5207 	 * called, which will make the above assumption false.  Thus, we
5208 	 * need to insert after we set conn_policy_cached.
5209 	 */
5210 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5211 		goto bad_addr;
5212 
5213 	if (fanout_insert) {
5214 		/*
5215 		 * The addresses have been verified. Time to insert in
5216 		 * the correct fanout list.
5217 		 */
5218 		error = ipcl_conn_insert(connp, protocol, src_addr,
5219 		    dst_addr, connp->conn_ports);
5220 	}
5221 
5222 	if (error == 0) {
5223 		connp->conn_fully_bound = B_TRUE;
5224 		/*
5225 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5226 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5227 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5228 		 * ip_xxinfo_return(), which performs further checks
5229 		 * against them and upon success, returns the LSO/MDT info
5230 		 * mblk which we will attach to the bind acknowledgment.
5231 		 */
5232 		if (lso_dst_ire != NULL) {
5233 			mblk_t *lsoinfo_mp;
5234 
5235 			ASSERT(ill->ill_lso_capab != NULL);
5236 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5237 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5238 				if (mp == NULL) {
5239 					*mpp = lsoinfo_mp;
5240 				} else {
5241 					linkb(mp, lsoinfo_mp);
5242 				}
5243 			}
5244 		} else if (md_dst_ire != NULL) {
5245 			mblk_t *mdinfo_mp;
5246 
5247 			ASSERT(ill->ill_mdt_capab != NULL);
5248 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5249 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5250 				if (mp == NULL) {
5251 					*mpp = mdinfo_mp;
5252 				} else {
5253 					linkb(mp, mdinfo_mp);
5254 				}
5255 			}
5256 		}
5257 	}
5258 bad_addr:
5259 	if (ipsec_policy_set) {
5260 		ASSERT(mp != NULL);
5261 		freeb(mp);
5262 		/*
5263 		 * As of now assume that nothing else accompanies
5264 		 * IPSEC_POLICY_SET.
5265 		 */
5266 		*mpp = NULL;
5267 	}
5268 	if (src_ire != NULL)
5269 		IRE_REFRELE(src_ire);
5270 	if (dst_ire != NULL)
5271 		IRE_REFRELE(dst_ire);
5272 	if (sire != NULL)
5273 		IRE_REFRELE(sire);
5274 	if (md_dst_ire != NULL)
5275 		IRE_REFRELE(md_dst_ire);
5276 	if (lso_dst_ire != NULL)
5277 		IRE_REFRELE(lso_dst_ire);
5278 	if (effective_cred != NULL)
5279 		crfree(effective_cred);
5280 	return (error);
5281 }
5282 
5283 int
5284 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5285     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5286     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5287 {
5288 	int error;
5289 	mblk_t	*mp = NULL;
5290 	boolean_t ire_requested;
5291 
5292 	if (ire_mpp)
5293 		mp = *ire_mpp;
5294 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5295 
5296 	ASSERT(!connp->conn_af_isv6);
5297 	connp->conn_pkt_isv6 = B_FALSE;
5298 	connp->conn_ulp = protocol;
5299 
5300 	/* For raw socket, the local port is not set. */
5301 	if (lport == 0)
5302 		lport = connp->conn_lport;
5303 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5304 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5305 	if (error == 0) {
5306 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5307 		    ire_requested);
5308 	} else if (error < 0) {
5309 		error = -TBADADDR;
5310 	}
5311 	return (error);
5312 }
5313 
5314 /*
5315  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5316  * Prefers dst_ire over src_ire.
5317  */
5318 static boolean_t
5319 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5320 {
5321 	mblk_t	*mp = *mpp;
5322 	ire_t	*ret_ire;
5323 
5324 	ASSERT(mp != NULL);
5325 
5326 	if (ire != NULL) {
5327 		/*
5328 		 * mp initialized above to IRE_DB_REQ_TYPE
5329 		 * appended mblk. Its <upper protocol>'s
5330 		 * job to make sure there is room.
5331 		 */
5332 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5333 			return (B_FALSE);
5334 
5335 		mp->b_datap->db_type = IRE_DB_TYPE;
5336 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5337 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5338 		ret_ire = (ire_t *)mp->b_rptr;
5339 		/*
5340 		 * Pass the latest setting of the ip_path_mtu_discovery and
5341 		 * copy the ulp info if any.
5342 		 */
5343 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5344 		    IPH_DF : 0;
5345 		if (ulp_info != NULL) {
5346 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5347 			    sizeof (iulp_t));
5348 		}
5349 		ret_ire->ire_mp = mp;
5350 	} else {
5351 		/*
5352 		 * No IRE was found. Remove IRE mblk.
5353 		 */
5354 		*mpp = mp->b_cont;
5355 		freeb(mp);
5356 	}
5357 	return (B_TRUE);
5358 }
5359 
5360 /*
5361  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5362  * the final piece where we don't.  Return a pointer to the first mblk in the
5363  * result, and update the pointer to the next mblk to chew on.  If anything
5364  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5365  * NULL pointer.
5366  */
5367 mblk_t *
5368 ip_carve_mp(mblk_t **mpp, ssize_t len)
5369 {
5370 	mblk_t	*mp0;
5371 	mblk_t	*mp1;
5372 	mblk_t	*mp2;
5373 
5374 	if (!len || !mpp || !(mp0 = *mpp))
5375 		return (NULL);
5376 	/* If we aren't going to consume the first mblk, we need a dup. */
5377 	if (mp0->b_wptr - mp0->b_rptr > len) {
5378 		mp1 = dupb(mp0);
5379 		if (mp1) {
5380 			/* Partition the data between the two mblks. */
5381 			mp1->b_wptr = mp1->b_rptr + len;
5382 			mp0->b_rptr = mp1->b_wptr;
5383 			/*
5384 			 * after adjustments if mblk not consumed is now
5385 			 * unaligned, try to align it. If this fails free
5386 			 * all messages and let upper layer recover.
5387 			 */
5388 			if (!OK_32PTR(mp0->b_rptr)) {
5389 				if (!pullupmsg(mp0, -1)) {
5390 					freemsg(mp0);
5391 					freemsg(mp1);
5392 					*mpp = NULL;
5393 					return (NULL);
5394 				}
5395 			}
5396 		}
5397 		return (mp1);
5398 	}
5399 	/* Eat through as many mblks as we need to get len bytes. */
5400 	len -= mp0->b_wptr - mp0->b_rptr;
5401 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5402 		if (mp2->b_wptr - mp2->b_rptr > len) {
5403 			/*
5404 			 * We won't consume the entire last mblk.  Like
5405 			 * above, dup and partition it.
5406 			 */
5407 			mp1->b_cont = dupb(mp2);
5408 			mp1 = mp1->b_cont;
5409 			if (!mp1) {
5410 				/*
5411 				 * Trouble.  Rather than go to a lot of
5412 				 * trouble to clean up, we free the messages.
5413 				 * This won't be any worse than losing it on
5414 				 * the wire.
5415 				 */
5416 				freemsg(mp0);
5417 				freemsg(mp2);
5418 				*mpp = NULL;
5419 				return (NULL);
5420 			}
5421 			mp1->b_wptr = mp1->b_rptr + len;
5422 			mp2->b_rptr = mp1->b_wptr;
5423 			/*
5424 			 * after adjustments if mblk not consumed is now
5425 			 * unaligned, try to align it. If this fails free
5426 			 * all messages and let upper layer recover.
5427 			 */
5428 			if (!OK_32PTR(mp2->b_rptr)) {
5429 				if (!pullupmsg(mp2, -1)) {
5430 					freemsg(mp0);
5431 					freemsg(mp2);
5432 					*mpp = NULL;
5433 					return (NULL);
5434 				}
5435 			}
5436 			*mpp = mp2;
5437 			return (mp0);
5438 		}
5439 		/* Decrement len by the amount we just got. */
5440 		len -= mp2->b_wptr - mp2->b_rptr;
5441 	}
5442 	/*
5443 	 * len should be reduced to zero now.  If not our caller has
5444 	 * screwed up.
5445 	 */
5446 	if (len) {
5447 		/* Shouldn't happen! */
5448 		freemsg(mp0);
5449 		*mpp = NULL;
5450 		return (NULL);
5451 	}
5452 	/*
5453 	 * We consumed up to exactly the end of an mblk.  Detach the part
5454 	 * we are returning from the rest of the chain.
5455 	 */
5456 	mp1->b_cont = NULL;
5457 	*mpp = mp2;
5458 	return (mp0);
5459 }
5460 
5461 /* The ill stream is being unplumbed. Called from ip_close */
5462 int
5463 ip_modclose(ill_t *ill)
5464 {
5465 	boolean_t success;
5466 	ipsq_t	*ipsq;
5467 	ipif_t	*ipif;
5468 	queue_t	*q = ill->ill_rq;
5469 	ip_stack_t	*ipst = ill->ill_ipst;
5470 	int	i;
5471 
5472 	/*
5473 	 * The punlink prior to this may have initiated a capability
5474 	 * negotiation. But ipsq_enter will block until that finishes or
5475 	 * times out.
5476 	 */
5477 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5478 
5479 	/*
5480 	 * Open/close/push/pop is guaranteed to be single threaded
5481 	 * per stream by STREAMS. FS guarantees that all references
5482 	 * from top are gone before close is called. So there can't
5483 	 * be another close thread that has set CONDEMNED on this ill.
5484 	 * and cause ipsq_enter to return failure.
5485 	 */
5486 	ASSERT(success);
5487 	ipsq = ill->ill_phyint->phyint_ipsq;
5488 
5489 	/*
5490 	 * Mark it condemned. No new reference will be made to this ill.
5491 	 * Lookup functions will return an error. Threads that try to
5492 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5493 	 * that the refcnt will drop down to zero.
5494 	 */
5495 	mutex_enter(&ill->ill_lock);
5496 	ill->ill_state_flags |= ILL_CONDEMNED;
5497 	for (ipif = ill->ill_ipif; ipif != NULL;
5498 	    ipif = ipif->ipif_next) {
5499 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5500 	}
5501 	/*
5502 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5503 	 * returns  error if ILL_CONDEMNED is set
5504 	 */
5505 	cv_broadcast(&ill->ill_cv);
5506 	mutex_exit(&ill->ill_lock);
5507 
5508 	/*
5509 	 * Send all the deferred DLPI messages downstream which came in
5510 	 * during the small window right before ipsq_enter(). We do this
5511 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5512 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5513 	 */
5514 	ill_dlpi_send_deferred(ill);
5515 
5516 	/*
5517 	 * Shut down fragmentation reassembly.
5518 	 * ill_frag_timer won't start a timer again.
5519 	 * Now cancel any existing timer
5520 	 */
5521 	(void) untimeout(ill->ill_frag_timer_id);
5522 	(void) ill_frag_timeout(ill, 0);
5523 
5524 	/*
5525 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5526 	 * this ill. Then wait for the refcnts to drop to zero.
5527 	 * ill_is_freeable checks whether the ill is really quiescent.
5528 	 * Then make sure that threads that are waiting to enter the
5529 	 * ipsq have seen the error returned by ipsq_enter and have
5530 	 * gone away. Then we call ill_delete_tail which does the
5531 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5532 	 */
5533 	ill_delete(ill);
5534 	mutex_enter(&ill->ill_lock);
5535 	while (!ill_is_freeable(ill))
5536 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5537 	while (ill->ill_waiters)
5538 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5539 
5540 	mutex_exit(&ill->ill_lock);
5541 
5542 	/*
5543 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5544 	 * it held until the end of the function since the cleanup
5545 	 * below needs to be able to use the ip_stack_t.
5546 	 */
5547 	netstack_hold(ipst->ips_netstack);
5548 
5549 	/* qprocsoff is done via ill_delete_tail */
5550 	ill_delete_tail(ill);
5551 	ASSERT(ill->ill_ipst == NULL);
5552 
5553 	/*
5554 	 * Walk through all upper (conn) streams and qenable
5555 	 * those that have queued data.
5556 	 * close synchronization needs this to
5557 	 * be done to ensure that all upper layers blocked
5558 	 * due to flow control to the closing device
5559 	 * get unblocked.
5560 	 */
5561 	ip1dbg(("ip_wsrv: walking\n"));
5562 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5563 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5564 	}
5565 
5566 	mutex_enter(&ipst->ips_ip_mi_lock);
5567 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5568 	mutex_exit(&ipst->ips_ip_mi_lock);
5569 
5570 	/*
5571 	 * credp could be null if the open didn't succeed and ip_modopen
5572 	 * itself calls ip_close.
5573 	 */
5574 	if (ill->ill_credp != NULL)
5575 		crfree(ill->ill_credp);
5576 
5577 	/*
5578 	 * Now we are done with the module close pieces that
5579 	 * need the netstack_t.
5580 	 */
5581 	netstack_rele(ipst->ips_netstack);
5582 
5583 	mi_close_free((IDP)ill);
5584 	q->q_ptr = WR(q)->q_ptr = NULL;
5585 
5586 	ipsq_exit(ipsq);
5587 
5588 	return (0);
5589 }
5590 
5591 /*
5592  * This is called as part of close() for IP, UDP, ICMP, and RTS
5593  * in order to quiesce the conn.
5594  */
5595 void
5596 ip_quiesce_conn(conn_t *connp)
5597 {
5598 	boolean_t	drain_cleanup_reqd = B_FALSE;
5599 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5600 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5601 	ip_stack_t	*ipst;
5602 
5603 	ASSERT(!IPCL_IS_TCP(connp));
5604 	ipst = connp->conn_netstack->netstack_ip;
5605 
5606 	/*
5607 	 * Mark the conn as closing, and this conn must not be
5608 	 * inserted in future into any list. Eg. conn_drain_insert(),
5609 	 * won't insert this conn into the conn_drain_list.
5610 	 * Similarly ill_pending_mp_add() will not add any mp to
5611 	 * the pending mp list, after this conn has started closing.
5612 	 *
5613 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5614 	 * cannot get set henceforth.
5615 	 */
5616 	mutex_enter(&connp->conn_lock);
5617 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5618 	connp->conn_state_flags |= CONN_CLOSING;
5619 	if (connp->conn_idl != NULL)
5620 		drain_cleanup_reqd = B_TRUE;
5621 	if (connp->conn_oper_pending_ill != NULL)
5622 		conn_ioctl_cleanup_reqd = B_TRUE;
5623 	if (connp->conn_dhcpinit_ill != NULL) {
5624 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5625 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5626 		connp->conn_dhcpinit_ill = NULL;
5627 	}
5628 	if (connp->conn_ilg_inuse != 0)
5629 		ilg_cleanup_reqd = B_TRUE;
5630 	mutex_exit(&connp->conn_lock);
5631 
5632 	if (conn_ioctl_cleanup_reqd)
5633 		conn_ioctl_cleanup(connp);
5634 
5635 	if (is_system_labeled() && connp->conn_anon_port) {
5636 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5637 		    connp->conn_mlp_type, connp->conn_ulp,
5638 		    ntohs(connp->conn_lport), B_FALSE);
5639 		connp->conn_anon_port = 0;
5640 	}
5641 	connp->conn_mlp_type = mlptSingle;
5642 
5643 	/*
5644 	 * Remove this conn from any fanout list it is on.
5645 	 * and then wait for any threads currently operating
5646 	 * on this endpoint to finish
5647 	 */
5648 	ipcl_hash_remove(connp);
5649 
5650 	/*
5651 	 * Remove this conn from the drain list, and do
5652 	 * any other cleanup that may be required.
5653 	 * (Only non-tcp streams may have a non-null conn_idl.
5654 	 * TCP streams are never flow controlled, and
5655 	 * conn_idl will be null)
5656 	 */
5657 	if (drain_cleanup_reqd)
5658 		conn_drain_tail(connp, B_TRUE);
5659 
5660 	if (connp == ipst->ips_ip_g_mrouter)
5661 		(void) ip_mrouter_done(NULL, ipst);
5662 
5663 	if (ilg_cleanup_reqd)
5664 		ilg_delete_all(connp);
5665 
5666 	conn_delete_ire(connp, NULL);
5667 
5668 	/*
5669 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5670 	 * callers from write side can't be there now because close
5671 	 * is in progress. The only other caller is ipcl_walk
5672 	 * which checks for the condemned flag.
5673 	 */
5674 	mutex_enter(&connp->conn_lock);
5675 	connp->conn_state_flags |= CONN_CONDEMNED;
5676 	while (connp->conn_ref != 1)
5677 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5678 	connp->conn_state_flags |= CONN_QUIESCED;
5679 	mutex_exit(&connp->conn_lock);
5680 }
5681 
5682 /* ARGSUSED */
5683 int
5684 ip_close(queue_t *q, int flags)
5685 {
5686 	conn_t		*connp;
5687 
5688 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5689 
5690 	/*
5691 	 * Call the appropriate delete routine depending on whether this is
5692 	 * a module or device.
5693 	 */
5694 	if (WR(q)->q_next != NULL) {
5695 		/* This is a module close */
5696 		return (ip_modclose((ill_t *)q->q_ptr));
5697 	}
5698 
5699 	connp = q->q_ptr;
5700 	ip_quiesce_conn(connp);
5701 
5702 	qprocsoff(q);
5703 
5704 	/*
5705 	 * Now we are truly single threaded on this stream, and can
5706 	 * delete the things hanging off the connp, and finally the connp.
5707 	 * We removed this connp from the fanout list, it cannot be
5708 	 * accessed thru the fanouts, and we already waited for the
5709 	 * conn_ref to drop to 0. We are already in close, so
5710 	 * there cannot be any other thread from the top. qprocsoff
5711 	 * has completed, and service has completed or won't run in
5712 	 * future.
5713 	 */
5714 	ASSERT(connp->conn_ref == 1);
5715 
5716 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5717 
5718 	connp->conn_ref--;
5719 	ipcl_conn_destroy(connp);
5720 
5721 	q->q_ptr = WR(q)->q_ptr = NULL;
5722 	return (0);
5723 }
5724 
5725 /*
5726  * Wapper around putnext() so that ip_rts_request can merely use
5727  * conn_recv.
5728  */
5729 /*ARGSUSED2*/
5730 static void
5731 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5732 {
5733 	conn_t *connp = (conn_t *)arg1;
5734 
5735 	putnext(connp->conn_rq, mp);
5736 }
5737 
5738 /*
5739  * Called when the module is about to be unloaded
5740  */
5741 void
5742 ip_ddi_destroy(void)
5743 {
5744 	tnet_fini();
5745 
5746 	icmp_ddi_g_destroy();
5747 	rts_ddi_g_destroy();
5748 	udp_ddi_g_destroy();
5749 	sctp_ddi_g_destroy();
5750 	tcp_ddi_g_destroy();
5751 	ipsec_policy_g_destroy();
5752 	ipcl_g_destroy();
5753 	ip_net_g_destroy();
5754 	ip_ire_g_fini();
5755 	inet_minor_destroy(ip_minor_arena_sa);
5756 #if defined(_LP64)
5757 	inet_minor_destroy(ip_minor_arena_la);
5758 #endif
5759 
5760 #ifdef DEBUG
5761 	list_destroy(&ip_thread_list);
5762 	rw_destroy(&ip_thread_rwlock);
5763 	tsd_destroy(&ip_thread_data);
5764 #endif
5765 
5766 	netstack_unregister(NS_IP);
5767 }
5768 
5769 /*
5770  * First step in cleanup.
5771  */
5772 /* ARGSUSED */
5773 static void
5774 ip_stack_shutdown(netstackid_t stackid, void *arg)
5775 {
5776 	ip_stack_t *ipst = (ip_stack_t *)arg;
5777 
5778 #ifdef NS_DEBUG
5779 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5780 #endif
5781 
5782 	/* Get rid of loopback interfaces and their IREs */
5783 	ip_loopback_cleanup(ipst);
5784 
5785 	/*
5786 	 * The *_hook_shutdown()s start the process of notifying any
5787 	 * consumers that things are going away.... nothing is destroyed.
5788 	 */
5789 	ipv4_hook_shutdown(ipst);
5790 	ipv6_hook_shutdown(ipst);
5791 
5792 	mutex_enter(&ipst->ips_capab_taskq_lock);
5793 	ipst->ips_capab_taskq_quit = B_TRUE;
5794 	cv_signal(&ipst->ips_capab_taskq_cv);
5795 	mutex_exit(&ipst->ips_capab_taskq_lock);
5796 
5797 	mutex_enter(&ipst->ips_mrt_lock);
5798 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5799 	cv_signal(&ipst->ips_mrt_cv);
5800 	mutex_exit(&ipst->ips_mrt_lock);
5801 }
5802 
5803 /*
5804  * Free the IP stack instance.
5805  */
5806 static void
5807 ip_stack_fini(netstackid_t stackid, void *arg)
5808 {
5809 	ip_stack_t *ipst = (ip_stack_t *)arg;
5810 	int ret;
5811 
5812 #ifdef NS_DEBUG
5813 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5814 #endif
5815 	/*
5816 	 * At this point, all of the notifications that the events and
5817 	 * protocols are going away have been run, meaning that we can
5818 	 * now set about starting to clean things up.
5819 	 */
5820 	ipv4_hook_destroy(ipst);
5821 	ipv6_hook_destroy(ipst);
5822 	ip_net_destroy(ipst);
5823 
5824 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5825 	cv_destroy(&ipst->ips_capab_taskq_cv);
5826 	list_destroy(&ipst->ips_capab_taskq_list);
5827 
5828 	mutex_enter(&ipst->ips_mrt_lock);
5829 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5830 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5831 	mutex_destroy(&ipst->ips_mrt_lock);
5832 	cv_destroy(&ipst->ips_mrt_cv);
5833 	cv_destroy(&ipst->ips_mrt_done_cv);
5834 
5835 	ipmp_destroy(ipst);
5836 	rw_destroy(&ipst->ips_srcid_lock);
5837 
5838 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5839 	ipst->ips_ip_mibkp = NULL;
5840 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5841 	ipst->ips_icmp_mibkp = NULL;
5842 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5843 	ipst->ips_ip_kstat = NULL;
5844 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5845 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5846 	ipst->ips_ip6_kstat = NULL;
5847 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5848 
5849 	nd_free(&ipst->ips_ip_g_nd);
5850 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5851 	ipst->ips_param_arr = NULL;
5852 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5853 	ipst->ips_ndp_arr = NULL;
5854 
5855 	ip_mrouter_stack_destroy(ipst);
5856 
5857 	mutex_destroy(&ipst->ips_ip_mi_lock);
5858 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5859 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5860 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5861 
5862 	ret = untimeout(ipst->ips_igmp_timeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5867 		ipst->ips_igmp_timeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5874 		ipst->ips_igmp_slowtimeout_id = 0;
5875 	}
5876 	ret = untimeout(ipst->ips_mld_timeout_id);
5877 	if (ret == -1) {
5878 		ASSERT(ipst->ips_mld_timeout_id == 0);
5879 	} else {
5880 		ASSERT(ipst->ips_mld_timeout_id != 0);
5881 		ipst->ips_mld_timeout_id = 0;
5882 	}
5883 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5884 	if (ret == -1) {
5885 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5886 	} else {
5887 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5888 		ipst->ips_mld_slowtimeout_id = 0;
5889 	}
5890 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5891 	if (ret == -1) {
5892 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5893 	} else {
5894 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5895 		ipst->ips_ip_ire_expire_id = 0;
5896 	}
5897 
5898 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5899 	mutex_destroy(&ipst->ips_mld_timer_lock);
5900 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5901 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5902 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5903 	rw_destroy(&ipst->ips_ill_g_lock);
5904 
5905 	ipobs_fini(ipst);
5906 	ip_ire_fini(ipst);
5907 	ip6_asp_free(ipst);
5908 	conn_drain_fini(ipst);
5909 	ipcl_destroy(ipst);
5910 
5911 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5912 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5913 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5914 	ipst->ips_ndp4 = NULL;
5915 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5916 	ipst->ips_ndp6 = NULL;
5917 
5918 	if (ipst->ips_loopback_ksp != NULL) {
5919 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5920 		ipst->ips_loopback_ksp = NULL;
5921 	}
5922 
5923 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5924 	ipst->ips_phyint_g_list = NULL;
5925 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5926 	ipst->ips_ill_g_heads = NULL;
5927 
5928 	ldi_ident_release(ipst->ips_ldi_ident);
5929 	kmem_free(ipst, sizeof (*ipst));
5930 }
5931 
5932 /*
5933  * This function is called from the TSD destructor, and is used to debug
5934  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5935  * details.
5936  */
5937 static void
5938 ip_thread_exit(void *phash)
5939 {
5940 	th_hash_t *thh = phash;
5941 
5942 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5943 	list_remove(&ip_thread_list, thh);
5944 	rw_exit(&ip_thread_rwlock);
5945 	mod_hash_destroy_hash(thh->thh_hash);
5946 	kmem_free(thh, sizeof (*thh));
5947 }
5948 
5949 /*
5950  * Called when the IP kernel module is loaded into the kernel
5951  */
5952 void
5953 ip_ddi_init(void)
5954 {
5955 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5956 
5957 	/*
5958 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5959 	 * initial devices: ip, ip6, tcp, tcp6.
5960 	 */
5961 	/*
5962 	 * If this is a 64-bit kernel, then create two separate arenas -
5963 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5964 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5965 	 */
5966 	ip_minor_arena_la = NULL;
5967 	ip_minor_arena_sa = NULL;
5968 #if defined(_LP64)
5969 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5970 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5971 		cmn_err(CE_PANIC,
5972 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5973 	}
5974 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5975 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5976 		cmn_err(CE_PANIC,
5977 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5978 	}
5979 #else
5980 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5981 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5982 		cmn_err(CE_PANIC,
5983 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5984 	}
5985 #endif
5986 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5987 
5988 	ipcl_g_init();
5989 	ip_ire_g_init();
5990 	ip_net_g_init();
5991 
5992 #ifdef DEBUG
5993 	tsd_create(&ip_thread_data, ip_thread_exit);
5994 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5995 	list_create(&ip_thread_list, sizeof (th_hash_t),
5996 	    offsetof(th_hash_t, thh_link));
5997 #endif
5998 
5999 	/*
6000 	 * We want to be informed each time a stack is created or
6001 	 * destroyed in the kernel, so we can maintain the
6002 	 * set of udp_stack_t's.
6003 	 */
6004 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
6005 	    ip_stack_fini);
6006 
6007 	ipsec_policy_g_init();
6008 	tcp_ddi_g_init();
6009 	sctp_ddi_g_init();
6010 
6011 	tnet_init();
6012 
6013 	udp_ddi_g_init();
6014 	rts_ddi_g_init();
6015 	icmp_ddi_g_init();
6016 }
6017 
6018 /*
6019  * Initialize the IP stack instance.
6020  */
6021 static void *
6022 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6023 {
6024 	ip_stack_t	*ipst;
6025 	ipparam_t	*pa;
6026 	ipndp_t		*na;
6027 	major_t		major;
6028 
6029 #ifdef NS_DEBUG
6030 	printf("ip_stack_init(stack %d)\n", stackid);
6031 #endif
6032 
6033 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6034 	ipst->ips_netstack = ns;
6035 
6036 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6037 	    KM_SLEEP);
6038 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6039 	    KM_SLEEP);
6040 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6041 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6042 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6043 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6044 
6045 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6046 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	ipst->ips_igmp_deferred_next = INFINITY;
6048 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6049 	ipst->ips_mld_deferred_next = INFINITY;
6050 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6051 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6052 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6053 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6054 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6055 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6056 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6057 
6058 	ipcl_init(ipst);
6059 	ip_ire_init(ipst);
6060 	ip6_asp_init(ipst);
6061 	ipif_init(ipst);
6062 	conn_drain_init(ipst);
6063 	ip_mrouter_stack_init(ipst);
6064 
6065 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6066 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6067 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
6068 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
6069 
6070 	ipst->ips_ip_multirt_log_interval = 1000;
6071 
6072 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6073 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6074 	ipst->ips_ill_index = 1;
6075 
6076 	ipst->ips_saved_ip_g_forward = -1;
6077 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6078 
6079 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6080 	ipst->ips_param_arr = pa;
6081 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6082 
6083 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6084 	ipst->ips_ndp_arr = na;
6085 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6086 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6087 	    (caddr_t)&ipst->ips_ip_g_forward;
6088 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6089 	    (caddr_t)&ipst->ips_ipv6_forward;
6090 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6091 	    "ip_cgtp_filter") == 0);
6092 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6093 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6094 
6095 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6096 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6097 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6098 
6099 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6100 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6101 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6102 	ipst->ips_ip6_kstat =
6103 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6104 
6105 	ipst->ips_ip_src_id = 1;
6106 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6107 
6108 	ipobs_init(ipst);
6109 	ip_net_init(ipst, ns);
6110 	ipv4_hook_init(ipst);
6111 	ipv6_hook_init(ipst);
6112 	ipmp_init(ipst);
6113 
6114 	/*
6115 	 * Create the taskq dispatcher thread and initialize related stuff.
6116 	 */
6117 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6118 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6119 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6120 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6121 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6122 	    offsetof(mblk_t, b_next));
6123 
6124 	/*
6125 	 * Create the mcast_restart_timers_thread() worker thread.
6126 	 */
6127 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6128 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6129 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6130 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6131 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6132 
6133 	major = mod_name_to_major(INET_NAME);
6134 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6135 	return (ipst);
6136 }
6137 
6138 /*
6139  * Allocate and initialize a DLPI template of the specified length.  (May be
6140  * called as writer.)
6141  */
6142 mblk_t *
6143 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6144 {
6145 	mblk_t	*mp;
6146 
6147 	mp = allocb(len, BPRI_MED);
6148 	if (!mp)
6149 		return (NULL);
6150 
6151 	/*
6152 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6153 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6154 	 * that other DLPI are M_PROTO.
6155 	 */
6156 	if (prim == DL_INFO_REQ) {
6157 		mp->b_datap->db_type = M_PCPROTO;
6158 	} else {
6159 		mp->b_datap->db_type = M_PROTO;
6160 	}
6161 
6162 	mp->b_wptr = mp->b_rptr + len;
6163 	bzero(mp->b_rptr, len);
6164 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6165 	return (mp);
6166 }
6167 
6168 /*
6169  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6170  */
6171 mblk_t *
6172 ip_dlnotify_alloc(uint_t notification, uint_t data)
6173 {
6174 	dl_notify_ind_t	*notifyp;
6175 	mblk_t		*mp;
6176 
6177 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6178 		return (NULL);
6179 
6180 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6181 	notifyp->dl_notification = notification;
6182 	notifyp->dl_data = data;
6183 	return (mp);
6184 }
6185 
6186 /*
6187  * Debug formatting routine.  Returns a character string representation of the
6188  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6189  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6190  *
6191  * Once the ndd table-printing interfaces are removed, this can be changed to
6192  * standard dotted-decimal form.
6193  */
6194 char *
6195 ip_dot_addr(ipaddr_t addr, char *buf)
6196 {
6197 	uint8_t *ap = (uint8_t *)&addr;
6198 
6199 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6200 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6201 	return (buf);
6202 }
6203 
6204 /*
6205  * Write the given MAC address as a printable string in the usual colon-
6206  * separated format.
6207  */
6208 const char *
6209 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6210 {
6211 	char *bp;
6212 
6213 	if (alen == 0 || buflen < 4)
6214 		return ("?");
6215 	bp = buf;
6216 	for (;;) {
6217 		/*
6218 		 * If there are more MAC address bytes available, but we won't
6219 		 * have any room to print them, then add "..." to the string
6220 		 * instead.  See below for the 'magic number' explanation.
6221 		 */
6222 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6223 			(void) strcpy(bp, "...");
6224 			break;
6225 		}
6226 		(void) sprintf(bp, "%02x", *addr++);
6227 		bp += 2;
6228 		if (--alen == 0)
6229 			break;
6230 		*bp++ = ':';
6231 		buflen -= 3;
6232 		/*
6233 		 * At this point, based on the first 'if' statement above,
6234 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6235 		 * buflen >= 4.  The first case leaves room for the final "xx"
6236 		 * number and trailing NUL byte.  The second leaves room for at
6237 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6238 		 * that statement.
6239 		 */
6240 	}
6241 	return (buf);
6242 }
6243 
6244 /*
6245  * Send an ICMP error after patching up the packet appropriately.  Returns
6246  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6247  */
6248 static boolean_t
6249 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6250     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6251     zoneid_t zoneid, ip_stack_t *ipst)
6252 {
6253 	ipha_t *ipha;
6254 	mblk_t *first_mp;
6255 	boolean_t secure;
6256 	unsigned char db_type;
6257 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6258 
6259 	first_mp = mp;
6260 	if (mctl_present) {
6261 		mp = mp->b_cont;
6262 		secure = ipsec_in_is_secure(first_mp);
6263 		ASSERT(mp != NULL);
6264 	} else {
6265 		/*
6266 		 * If this is an ICMP error being reported - which goes
6267 		 * up as M_CTLs, we need to convert them to M_DATA till
6268 		 * we finish checking with global policy because
6269 		 * ipsec_check_global_policy() assumes M_DATA as clear
6270 		 * and M_CTL as secure.
6271 		 */
6272 		db_type = DB_TYPE(mp);
6273 		DB_TYPE(mp) = M_DATA;
6274 		secure = B_FALSE;
6275 	}
6276 	/*
6277 	 * We are generating an icmp error for some inbound packet.
6278 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6279 	 * Before we generate an error, check with global policy
6280 	 * to see whether this is allowed to enter the system. As
6281 	 * there is no "conn", we are checking with global policy.
6282 	 */
6283 	ipha = (ipha_t *)mp->b_rptr;
6284 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6285 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6286 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6287 		if (first_mp == NULL)
6288 			return (B_FALSE);
6289 	}
6290 
6291 	if (!mctl_present)
6292 		DB_TYPE(mp) = db_type;
6293 
6294 	if (flags & IP_FF_SEND_ICMP) {
6295 		if (flags & IP_FF_HDR_COMPLETE) {
6296 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6297 				freemsg(first_mp);
6298 				return (B_TRUE);
6299 			}
6300 		}
6301 		if (flags & IP_FF_CKSUM) {
6302 			/*
6303 			 * Have to correct checksum since
6304 			 * the packet might have been
6305 			 * fragmented and the reassembly code in ip_rput
6306 			 * does not restore the IP checksum.
6307 			 */
6308 			ipha->ipha_hdr_checksum = 0;
6309 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6310 		}
6311 		switch (icmp_type) {
6312 		case ICMP_DEST_UNREACHABLE:
6313 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6314 			    ipst);
6315 			break;
6316 		default:
6317 			freemsg(first_mp);
6318 			break;
6319 		}
6320 	} else {
6321 		freemsg(first_mp);
6322 		return (B_FALSE);
6323 	}
6324 
6325 	return (B_TRUE);
6326 }
6327 
6328 /*
6329  * Used to send an ICMP error message when a packet is received for
6330  * a protocol that is not supported. The mblk passed as argument
6331  * is consumed by this function.
6332  */
6333 void
6334 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6335     ip_stack_t *ipst)
6336 {
6337 	mblk_t *mp;
6338 	ipha_t *ipha;
6339 	ill_t *ill;
6340 	ipsec_in_t *ii;
6341 
6342 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6343 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6344 
6345 	mp = ipsec_mp->b_cont;
6346 	ipsec_mp->b_cont = NULL;
6347 	ipha = (ipha_t *)mp->b_rptr;
6348 	/* Get ill from index in ipsec_in_t. */
6349 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6350 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6351 	    ipst);
6352 	if (ill != NULL) {
6353 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6354 			if (ip_fanout_send_icmp(q, mp, flags,
6355 			    ICMP_DEST_UNREACHABLE,
6356 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6357 				BUMP_MIB(ill->ill_ip_mib,
6358 				    ipIfStatsInUnknownProtos);
6359 			}
6360 		} else {
6361 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6362 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6363 			    0, B_FALSE, zoneid, ipst)) {
6364 				BUMP_MIB(ill->ill_ip_mib,
6365 				    ipIfStatsInUnknownProtos);
6366 			}
6367 		}
6368 		ill_refrele(ill);
6369 	} else { /* re-link for the freemsg() below. */
6370 		ipsec_mp->b_cont = mp;
6371 	}
6372 
6373 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6374 	freemsg(ipsec_mp);
6375 }
6376 
6377 /*
6378  * See if the inbound datagram has had IPsec processing applied to it.
6379  */
6380 boolean_t
6381 ipsec_in_is_secure(mblk_t *ipsec_mp)
6382 {
6383 	ipsec_in_t *ii;
6384 
6385 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6386 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6387 
6388 	if (ii->ipsec_in_loopback) {
6389 		return (ii->ipsec_in_secure);
6390 	} else {
6391 		return (ii->ipsec_in_ah_sa != NULL ||
6392 		    ii->ipsec_in_esp_sa != NULL ||
6393 		    ii->ipsec_in_decaps);
6394 	}
6395 }
6396 
6397 /*
6398  * Handle protocols with which IP is less intimate.  There
6399  * can be more than one stream bound to a particular
6400  * protocol.  When this is the case, normally each one gets a copy
6401  * of any incoming packets.
6402  *
6403  * IPsec NOTE :
6404  *
6405  * Don't allow a secure packet going up a non-secure connection.
6406  * We don't allow this because
6407  *
6408  * 1) Reply might go out in clear which will be dropped at
6409  *    the sending side.
6410  * 2) If the reply goes out in clear it will give the
6411  *    adversary enough information for getting the key in
6412  *    most of the cases.
6413  *
6414  * Moreover getting a secure packet when we expect clear
6415  * implies that SA's were added without checking for
6416  * policy on both ends. This should not happen once ISAKMP
6417  * is used to negotiate SAs as SAs will be added only after
6418  * verifying the policy.
6419  *
6420  * NOTE : If the packet was tunneled and not multicast we only send
6421  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6422  * back to delivering packets to AF_INET6 raw sockets.
6423  *
6424  * IPQoS Notes:
6425  * Once we have determined the client, invoke IPPF processing.
6426  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6427  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6428  * ip_policy will be false.
6429  *
6430  * Zones notes:
6431  * Currently only applications in the global zone can create raw sockets for
6432  * protocols other than ICMP. So unlike the broadcast / multicast case of
6433  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6434  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6435  */
6436 static void
6437 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6438     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6439     zoneid_t zoneid)
6440 {
6441 	queue_t	*rq;
6442 	mblk_t	*mp1, *first_mp1;
6443 	uint_t	protocol = ipha->ipha_protocol;
6444 	ipaddr_t dst;
6445 	boolean_t one_only;
6446 	mblk_t *first_mp = mp;
6447 	boolean_t secure;
6448 	uint32_t ill_index;
6449 	conn_t	*connp, *first_connp, *next_connp;
6450 	connf_t	*connfp;
6451 	boolean_t shared_addr;
6452 	mib2_ipIfStatsEntry_t *mibptr;
6453 	ip_stack_t *ipst = recv_ill->ill_ipst;
6454 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6455 
6456 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6457 	if (mctl_present) {
6458 		mp = first_mp->b_cont;
6459 		secure = ipsec_in_is_secure(first_mp);
6460 		ASSERT(mp != NULL);
6461 	} else {
6462 		secure = B_FALSE;
6463 	}
6464 	dst = ipha->ipha_dst;
6465 	/*
6466 	 * If the packet was tunneled and not multicast we only send to it
6467 	 * the first match.
6468 	 */
6469 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6470 	    !CLASSD(dst));
6471 
6472 	shared_addr = (zoneid == ALL_ZONES);
6473 	if (shared_addr) {
6474 		/*
6475 		 * We don't allow multilevel ports for raw IP, so no need to
6476 		 * check for that here.
6477 		 */
6478 		zoneid = tsol_packet_to_zoneid(mp);
6479 	}
6480 
6481 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6482 	mutex_enter(&connfp->connf_lock);
6483 	connp = connfp->connf_head;
6484 	for (connp = connfp->connf_head; connp != NULL;
6485 	    connp = connp->conn_next) {
6486 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6487 		    zoneid) &&
6488 		    (!is_system_labeled() ||
6489 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6490 		    connp))) {
6491 			break;
6492 		}
6493 	}
6494 
6495 	if (connp == NULL) {
6496 		/*
6497 		 * No one bound to these addresses.  Is
6498 		 * there a client that wants all
6499 		 * unclaimed datagrams?
6500 		 */
6501 		mutex_exit(&connfp->connf_lock);
6502 		/*
6503 		 * Check for IPPROTO_ENCAP...
6504 		 */
6505 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6506 			/*
6507 			 * If an IPsec mblk is here on a multicast
6508 			 * tunnel (using ip_mroute stuff), check policy here,
6509 			 * THEN ship off to ip_mroute_decap().
6510 			 *
6511 			 * BTW,  If I match a configured IP-in-IP
6512 			 * tunnel, this path will not be reached, and
6513 			 * ip_mroute_decap will never be called.
6514 			 */
6515 			first_mp = ipsec_check_global_policy(first_mp, connp,
6516 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6517 			if (first_mp != NULL) {
6518 				if (mctl_present)
6519 					freeb(first_mp);
6520 				ip_mroute_decap(q, mp, ill);
6521 			} /* Else we already freed everything! */
6522 		} else {
6523 			/*
6524 			 * Otherwise send an ICMP protocol unreachable.
6525 			 */
6526 			if (ip_fanout_send_icmp(q, first_mp, flags,
6527 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6528 			    mctl_present, zoneid, ipst)) {
6529 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6530 			}
6531 		}
6532 		return;
6533 	}
6534 
6535 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6536 
6537 	CONN_INC_REF(connp);
6538 	first_connp = connp;
6539 
6540 	/*
6541 	 * Only send message to one tunnel driver by immediately
6542 	 * terminating the loop.
6543 	 */
6544 	connp = one_only ? NULL : connp->conn_next;
6545 
6546 	for (;;) {
6547 		while (connp != NULL) {
6548 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6549 			    flags, zoneid) &&
6550 			    (!is_system_labeled() ||
6551 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6552 			    shared_addr, connp)))
6553 				break;
6554 			connp = connp->conn_next;
6555 		}
6556 
6557 		/*
6558 		 * Copy the packet.
6559 		 */
6560 		if (connp == NULL ||
6561 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6562 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6563 			/*
6564 			 * No more interested clients or memory
6565 			 * allocation failed
6566 			 */
6567 			connp = first_connp;
6568 			break;
6569 		}
6570 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6571 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6572 		CONN_INC_REF(connp);
6573 		mutex_exit(&connfp->connf_lock);
6574 		rq = connp->conn_rq;
6575 
6576 		/*
6577 		 * Check flow control
6578 		 */
6579 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6580 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6581 			if (flags & IP_FF_RAWIP) {
6582 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6583 			} else {
6584 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6585 			}
6586 
6587 			freemsg(first_mp1);
6588 		} else {
6589 			/*
6590 			 * Don't enforce here if we're an actual tunnel -
6591 			 * let "tun" do it instead.
6592 			 */
6593 			if (!IPCL_IS_IPTUN(connp) &&
6594 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6595 			    secure)) {
6596 				first_mp1 = ipsec_check_inbound_policy
6597 				    (first_mp1, connp, ipha, NULL,
6598 				    mctl_present);
6599 			}
6600 			if (first_mp1 != NULL) {
6601 				int in_flags = 0;
6602 				/*
6603 				 * ip_fanout_proto also gets called from
6604 				 * icmp_inbound_error_fanout, in which case
6605 				 * the msg type is M_CTL.  Don't add info
6606 				 * in this case for the time being. In future
6607 				 * when there is a need for knowing the
6608 				 * inbound iface index for ICMP error msgs,
6609 				 * then this can be changed.
6610 				 */
6611 				if (connp->conn_recvif)
6612 					in_flags = IPF_RECVIF;
6613 				/*
6614 				 * The ULP may support IP_RECVPKTINFO for both
6615 				 * IP v4 and v6 so pass the appropriate argument
6616 				 * based on conn IP version.
6617 				 */
6618 				if (connp->conn_ip_recvpktinfo) {
6619 					if (connp->conn_af_isv6) {
6620 						/*
6621 						 * V6 only needs index
6622 						 */
6623 						in_flags |= IPF_RECVIF;
6624 					} else {
6625 						/*
6626 						 * V4 needs index +
6627 						 * matching address.
6628 						 */
6629 						in_flags |= IPF_RECVADDR;
6630 					}
6631 				}
6632 				if ((in_flags != 0) &&
6633 				    (mp->b_datap->db_type != M_CTL)) {
6634 					/*
6635 					 * the actual data will be
6636 					 * contained in b_cont upon
6637 					 * successful return of the
6638 					 * following call else
6639 					 * original mblk is returned
6640 					 */
6641 					ASSERT(recv_ill != NULL);
6642 					mp1 = ip_add_info(mp1, recv_ill,
6643 					    in_flags, IPCL_ZONEID(connp), ipst);
6644 				}
6645 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6646 				if (mctl_present)
6647 					freeb(first_mp1);
6648 				(connp->conn_recv)(connp, mp1, NULL);
6649 			}
6650 		}
6651 		mutex_enter(&connfp->connf_lock);
6652 		/* Follow the next pointer before releasing the conn. */
6653 		next_connp = connp->conn_next;
6654 		CONN_DEC_REF(connp);
6655 		connp = next_connp;
6656 	}
6657 
6658 	/* Last one.  Send it upstream. */
6659 	mutex_exit(&connfp->connf_lock);
6660 
6661 	/*
6662 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6663 	 * will be set to false.
6664 	 */
6665 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6666 		ill_index = ill->ill_phyint->phyint_ifindex;
6667 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6668 		if (mp == NULL) {
6669 			CONN_DEC_REF(connp);
6670 			if (mctl_present) {
6671 				freeb(first_mp);
6672 			}
6673 			return;
6674 		}
6675 	}
6676 
6677 	rq = connp->conn_rq;
6678 	/*
6679 	 * Check flow control
6680 	 */
6681 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6682 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6683 		if (flags & IP_FF_RAWIP) {
6684 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6685 		} else {
6686 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6687 		}
6688 
6689 		freemsg(first_mp);
6690 	} else {
6691 		if (IPCL_IS_IPTUN(connp)) {
6692 			/*
6693 			 * Tunneled packet.  We enforce policy in the tunnel
6694 			 * module itself.
6695 			 *
6696 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6697 			 * a policy check.
6698 			 * FIXME to use conn_recv for tun later.
6699 			 */
6700 			putnext(rq, first_mp);
6701 			CONN_DEC_REF(connp);
6702 			return;
6703 		}
6704 
6705 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6706 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6707 			    ipha, NULL, mctl_present);
6708 		}
6709 
6710 		if (first_mp != NULL) {
6711 			int in_flags = 0;
6712 
6713 			/*
6714 			 * ip_fanout_proto also gets called
6715 			 * from icmp_inbound_error_fanout, in
6716 			 * which case the msg type is M_CTL.
6717 			 * Don't add info in this case for time
6718 			 * being. In future when there is a
6719 			 * need for knowing the inbound iface
6720 			 * index for ICMP error msgs, then this
6721 			 * can be changed
6722 			 */
6723 			if (connp->conn_recvif)
6724 				in_flags = IPF_RECVIF;
6725 			if (connp->conn_ip_recvpktinfo) {
6726 				if (connp->conn_af_isv6) {
6727 					/*
6728 					 * V6 only needs index
6729 					 */
6730 					in_flags |= IPF_RECVIF;
6731 				} else {
6732 					/*
6733 					 * V4 needs index +
6734 					 * matching address.
6735 					 */
6736 					in_flags |= IPF_RECVADDR;
6737 				}
6738 			}
6739 			if ((in_flags != 0) &&
6740 			    (mp->b_datap->db_type != M_CTL)) {
6741 
6742 				/*
6743 				 * the actual data will be contained in
6744 				 * b_cont upon successful return
6745 				 * of the following call else original
6746 				 * mblk is returned
6747 				 */
6748 				ASSERT(recv_ill != NULL);
6749 				mp = ip_add_info(mp, recv_ill,
6750 				    in_flags, IPCL_ZONEID(connp), ipst);
6751 			}
6752 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6753 			(connp->conn_recv)(connp, mp, NULL);
6754 			if (mctl_present)
6755 				freeb(first_mp);
6756 		}
6757 	}
6758 	CONN_DEC_REF(connp);
6759 }
6760 
6761 /*
6762  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6763  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6764  * the correct squeue, in this case the same squeue as a valid listener with
6765  * no current connection state for the packet we are processing. The function
6766  * is called for synchronizing both IPv4 and IPv6.
6767  */
6768 void
6769 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6770     tcp_stack_t *tcps, conn_t *connp)
6771 {
6772 	mblk_t *rst_mp;
6773 	tcp_xmit_reset_event_t *eventp;
6774 
6775 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6776 
6777 	if (rst_mp == NULL) {
6778 		freemsg(mp);
6779 		return;
6780 	}
6781 
6782 	rst_mp->b_datap->db_type = M_PROTO;
6783 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6784 
6785 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6786 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6787 	eventp->tcp_xre_iphdrlen = hdrlen;
6788 	eventp->tcp_xre_zoneid = zoneid;
6789 	eventp->tcp_xre_tcps = tcps;
6790 
6791 	rst_mp->b_cont = mp;
6792 	mp = rst_mp;
6793 
6794 	/*
6795 	 * Increment the connref, this ref will be released by the squeue
6796 	 * framework.
6797 	 */
6798 	CONN_INC_REF(connp);
6799 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6800 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6801 }
6802 
6803 /*
6804  * Fanout for TCP packets
6805  * The caller puts <fport, lport> in the ports parameter.
6806  *
6807  * IPQoS Notes
6808  * Before sending it to the client, invoke IPPF processing.
6809  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6810  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6811  * ip_policy is false.
6812  */
6813 static void
6814 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6815     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6816 {
6817 	mblk_t  *first_mp;
6818 	boolean_t secure;
6819 	uint32_t ill_index;
6820 	int	ip_hdr_len;
6821 	tcph_t	*tcph;
6822 	boolean_t syn_present = B_FALSE;
6823 	conn_t	*connp;
6824 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6825 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6826 
6827 	ASSERT(recv_ill != NULL);
6828 
6829 	first_mp = mp;
6830 	if (mctl_present) {
6831 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6832 		mp = first_mp->b_cont;
6833 		secure = ipsec_in_is_secure(first_mp);
6834 		ASSERT(mp != NULL);
6835 	} else {
6836 		secure = B_FALSE;
6837 	}
6838 
6839 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6840 
6841 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6842 	    zoneid, ipst)) == NULL) {
6843 		/*
6844 		 * No connected connection or listener. Send a
6845 		 * TH_RST via tcp_xmit_listeners_reset.
6846 		 */
6847 
6848 		/* Initiate IPPf processing, if needed. */
6849 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6850 			uint32_t ill_index;
6851 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6852 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6853 			if (first_mp == NULL)
6854 				return;
6855 		}
6856 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6857 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6858 		    zoneid));
6859 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6860 		    ipst->ips_netstack->netstack_tcp, NULL);
6861 		return;
6862 	}
6863 
6864 	/*
6865 	 * Allocate the SYN for the TCP connection here itself
6866 	 */
6867 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6868 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6869 		if (IPCL_IS_TCP(connp)) {
6870 			squeue_t *sqp;
6871 
6872 			/*
6873 			 * If the queue belongs to a conn, and fused tcp
6874 			 * loopback is enabled, assign the eager's squeue
6875 			 * to be that of the active connect's. Note that
6876 			 * we don't check for IP_FF_LOOPBACK here since this
6877 			 * routine gets called only for loopback (unlike the
6878 			 * IPv6 counterpart).
6879 			 */
6880 			if (do_tcp_fusion &&
6881 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6882 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6883 			    !secure &&
6884 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6885 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6886 				sqp = Q_TO_CONN(q)->conn_sqp;
6887 			} else {
6888 				sqp = IP_SQUEUE_GET(lbolt);
6889 			}
6890 
6891 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6892 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6893 			syn_present = B_TRUE;
6894 		}
6895 	}
6896 
6897 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6898 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6899 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6900 		if ((flags & TH_RST) || (flags & TH_URG)) {
6901 			CONN_DEC_REF(connp);
6902 			freemsg(first_mp);
6903 			return;
6904 		}
6905 		if (flags & TH_ACK) {
6906 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6907 			    ipst->ips_netstack->netstack_tcp, connp);
6908 			CONN_DEC_REF(connp);
6909 			return;
6910 		}
6911 
6912 		CONN_DEC_REF(connp);
6913 		freemsg(first_mp);
6914 		return;
6915 	}
6916 
6917 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6918 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6919 		    NULL, mctl_present);
6920 		if (first_mp == NULL) {
6921 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6922 			CONN_DEC_REF(connp);
6923 			return;
6924 		}
6925 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6926 			ASSERT(syn_present);
6927 			if (mctl_present) {
6928 				ASSERT(first_mp != mp);
6929 				first_mp->b_datap->db_struioflag |=
6930 				    STRUIO_POLICY;
6931 			} else {
6932 				ASSERT(first_mp == mp);
6933 				mp->b_datap->db_struioflag &=
6934 				    ~STRUIO_EAGER;
6935 				mp->b_datap->db_struioflag |=
6936 				    STRUIO_POLICY;
6937 			}
6938 		} else {
6939 			/*
6940 			 * Discard first_mp early since we're dealing with a
6941 			 * fully-connected conn_t and tcp doesn't do policy in
6942 			 * this case.
6943 			 */
6944 			if (mctl_present) {
6945 				freeb(first_mp);
6946 				mctl_present = B_FALSE;
6947 			}
6948 			first_mp = mp;
6949 		}
6950 	}
6951 
6952 	/*
6953 	 * Initiate policy processing here if needed. If we get here from
6954 	 * icmp_inbound_error_fanout, ip_policy is false.
6955 	 */
6956 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6957 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6958 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6959 		if (mp == NULL) {
6960 			CONN_DEC_REF(connp);
6961 			if (mctl_present)
6962 				freeb(first_mp);
6963 			return;
6964 		} else if (mctl_present) {
6965 			ASSERT(first_mp != mp);
6966 			first_mp->b_cont = mp;
6967 		} else {
6968 			first_mp = mp;
6969 		}
6970 	}
6971 
6972 	/* Handle socket options. */
6973 	if (!syn_present &&
6974 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6975 		/* Add header */
6976 		ASSERT(recv_ill != NULL);
6977 		/*
6978 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6979 		 * IPF_RECVIF.
6980 		 */
6981 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6982 		    ipst);
6983 		if (mp == NULL) {
6984 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6985 			CONN_DEC_REF(connp);
6986 			if (mctl_present)
6987 				freeb(first_mp);
6988 			return;
6989 		} else if (mctl_present) {
6990 			/*
6991 			 * ip_add_info might return a new mp.
6992 			 */
6993 			ASSERT(first_mp != mp);
6994 			first_mp->b_cont = mp;
6995 		} else {
6996 			first_mp = mp;
6997 		}
6998 	}
6999 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
7000 	if (IPCL_IS_TCP(connp)) {
7001 		/* do not drain, certain use cases can blow the stack */
7002 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
7003 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
7004 	} else {
7005 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
7006 		(connp->conn_recv)(connp, first_mp, NULL);
7007 		CONN_DEC_REF(connp);
7008 	}
7009 }
7010 
7011 /*
7012  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
7013  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
7014  * is not consumed.
7015  *
7016  * One of four things can happen, all of which affect the passed-in mblk:
7017  *
7018  * 1.) ICMP messages that go through here just get returned TRUE.
7019  *
7020  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7021  *
7022  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7023  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7024  *
7025  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7026  */
7027 static boolean_t
7028 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7029     ipsec_stack_t *ipss)
7030 {
7031 	int shift, plen, iph_len;
7032 	ipha_t *ipha;
7033 	udpha_t *udpha;
7034 	uint32_t *spi;
7035 	uint32_t esp_ports;
7036 	uint8_t *orptr;
7037 	boolean_t free_ire;
7038 
7039 	if (DB_TYPE(mp) == M_CTL) {
7040 		/*
7041 		 * ICMP message with UDP inside.  Don't bother stripping, just
7042 		 * send it up.
7043 		 *
7044 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7045 		 * to ignore errors set by ICMP anyway ('cause they might be
7046 		 * forged), but that's the app's decision, not ours.
7047 		 */
7048 
7049 		/* Bunch of reality checks for DEBUG kernels... */
7050 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7051 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7052 
7053 		return (B_TRUE);
7054 	}
7055 
7056 	ipha = (ipha_t *)mp->b_rptr;
7057 	iph_len = IPH_HDR_LENGTH(ipha);
7058 	plen = ntohs(ipha->ipha_length);
7059 
7060 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7061 		/*
7062 		 * Most likely a keepalive for the benefit of an intervening
7063 		 * NAT.  These aren't for us, per se, so drop it.
7064 		 *
7065 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7066 		 * byte packets (keepalives are 1-byte), but we'll drop them
7067 		 * also.
7068 		 */
7069 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7070 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7071 		return (B_FALSE);
7072 	}
7073 
7074 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7075 		/* might as well pull it all up - it might be ESP. */
7076 		if (!pullupmsg(mp, -1)) {
7077 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7078 			    DROPPER(ipss, ipds_esp_nomem),
7079 			    &ipss->ipsec_dropper);
7080 			return (B_FALSE);
7081 		}
7082 
7083 		ipha = (ipha_t *)mp->b_rptr;
7084 	}
7085 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7086 	if (*spi == 0) {
7087 		/* UDP packet - remove 0-spi. */
7088 		shift = sizeof (uint32_t);
7089 	} else {
7090 		/* ESP-in-UDP packet - reduce to ESP. */
7091 		ipha->ipha_protocol = IPPROTO_ESP;
7092 		shift = sizeof (udpha_t);
7093 	}
7094 
7095 	/* Fix IP header */
7096 	ipha->ipha_length = htons(plen - shift);
7097 	ipha->ipha_hdr_checksum = 0;
7098 
7099 	orptr = mp->b_rptr;
7100 	mp->b_rptr += shift;
7101 
7102 	udpha = (udpha_t *)(orptr + iph_len);
7103 	if (*spi == 0) {
7104 		ASSERT((uint8_t *)ipha == orptr);
7105 		udpha->uha_length = htons(plen - shift - iph_len);
7106 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7107 		esp_ports = 0;
7108 	} else {
7109 		esp_ports = *((uint32_t *)udpha);
7110 		ASSERT(esp_ports != 0);
7111 	}
7112 	ovbcopy(orptr, orptr + shift, iph_len);
7113 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7114 		ipha = (ipha_t *)(orptr + shift);
7115 
7116 		free_ire = (ire == NULL);
7117 		if (free_ire) {
7118 			/* Re-acquire ire. */
7119 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7120 			    ipss->ipsec_netstack->netstack_ip);
7121 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7122 				if (ire != NULL)
7123 					ire_refrele(ire);
7124 				/*
7125 				 * Do a regular freemsg(), as this is an IP
7126 				 * error (no local route) not an IPsec one.
7127 				 */
7128 				freemsg(mp);
7129 			}
7130 		}
7131 
7132 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7133 		if (free_ire)
7134 			ire_refrele(ire);
7135 	}
7136 
7137 	return (esp_ports == 0);
7138 }
7139 
7140 /*
7141  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7142  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7143  * Caller is responsible for dropping references to the conn, and freeing
7144  * first_mp.
7145  *
7146  * IPQoS Notes
7147  * Before sending it to the client, invoke IPPF processing. Policy processing
7148  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7149  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7150  * ip_wput_local, ip_policy is false.
7151  */
7152 static void
7153 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7154     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7155     boolean_t ip_policy)
7156 {
7157 	boolean_t	mctl_present = (first_mp != NULL);
7158 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7159 	uint32_t	ill_index;
7160 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7161 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7162 
7163 	ASSERT(ill != NULL);
7164 
7165 	if (mctl_present)
7166 		first_mp->b_cont = mp;
7167 	else
7168 		first_mp = mp;
7169 
7170 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7171 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7172 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7173 		freemsg(first_mp);
7174 		return;
7175 	}
7176 
7177 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7178 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7179 		    NULL, mctl_present);
7180 		/* Freed by ipsec_check_inbound_policy(). */
7181 		if (first_mp == NULL) {
7182 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7183 			return;
7184 		}
7185 	}
7186 	if (mctl_present)
7187 		freeb(first_mp);
7188 
7189 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7190 	if (connp->conn_udp->udp_nat_t_endpoint) {
7191 		if (mctl_present) {
7192 			/* mctl_present *shouldn't* happen. */
7193 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7194 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7195 			    &ipss->ipsec_dropper);
7196 			return;
7197 		}
7198 
7199 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7200 			return;
7201 	}
7202 
7203 	/* Handle options. */
7204 	if (connp->conn_recvif)
7205 		in_flags = IPF_RECVIF;
7206 	/*
7207 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7208 	 * passed to ip_add_info is based on IP version of connp.
7209 	 */
7210 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7211 		if (connp->conn_af_isv6) {
7212 			/*
7213 			 * V6 only needs index
7214 			 */
7215 			in_flags |= IPF_RECVIF;
7216 		} else {
7217 			/*
7218 			 * V4 needs index + matching address.
7219 			 */
7220 			in_flags |= IPF_RECVADDR;
7221 		}
7222 	}
7223 
7224 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7225 		in_flags |= IPF_RECVSLLA;
7226 
7227 	/*
7228 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7229 	 * freed if the packet is dropped. The caller will do so.
7230 	 */
7231 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7232 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7233 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7234 		if (mp == NULL) {
7235 			return;
7236 		}
7237 	}
7238 	if ((in_flags != 0) &&
7239 	    (mp->b_datap->db_type != M_CTL)) {
7240 		/*
7241 		 * The actual data will be contained in b_cont
7242 		 * upon successful return of the following call
7243 		 * else original mblk is returned
7244 		 */
7245 		ASSERT(recv_ill != NULL);
7246 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7247 		    ipst);
7248 	}
7249 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7250 	/* Send it upstream */
7251 	(connp->conn_recv)(connp, mp, NULL);
7252 }
7253 
7254 /*
7255  * Fanout for UDP packets.
7256  * The caller puts <fport, lport> in the ports parameter.
7257  *
7258  * If SO_REUSEADDR is set all multicast and broadcast packets
7259  * will be delivered to all streams bound to the same port.
7260  *
7261  * Zones notes:
7262  * Multicast and broadcast packets will be distributed to streams in all zones.
7263  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7264  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7265  * packets. To maintain this behavior with multiple zones, the conns are grouped
7266  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7267  * each zone. If unset, all the following conns in the same zone are skipped.
7268  */
7269 static void
7270 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7271     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7272     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7273 {
7274 	uint32_t	dstport, srcport;
7275 	ipaddr_t	dst;
7276 	mblk_t		*first_mp;
7277 	boolean_t	secure;
7278 	in6_addr_t	v6src;
7279 	conn_t		*connp;
7280 	connf_t		*connfp;
7281 	conn_t		*first_connp;
7282 	conn_t		*next_connp;
7283 	mblk_t		*mp1, *first_mp1;
7284 	ipaddr_t	src;
7285 	zoneid_t	last_zoneid;
7286 	boolean_t	reuseaddr;
7287 	boolean_t	shared_addr;
7288 	boolean_t	unlabeled;
7289 	ip_stack_t	*ipst;
7290 
7291 	ASSERT(recv_ill != NULL);
7292 	ipst = recv_ill->ill_ipst;
7293 
7294 	first_mp = mp;
7295 	if (mctl_present) {
7296 		mp = first_mp->b_cont;
7297 		first_mp->b_cont = NULL;
7298 		secure = ipsec_in_is_secure(first_mp);
7299 		ASSERT(mp != NULL);
7300 	} else {
7301 		first_mp = NULL;
7302 		secure = B_FALSE;
7303 	}
7304 
7305 	/* Extract ports in net byte order */
7306 	dstport = htons(ntohl(ports) & 0xFFFF);
7307 	srcport = htons(ntohl(ports) >> 16);
7308 	dst = ipha->ipha_dst;
7309 	src = ipha->ipha_src;
7310 
7311 	unlabeled = B_FALSE;
7312 	if (is_system_labeled())
7313 		/* Cred cannot be null on IPv4 */
7314 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7315 		    TSLF_UNLABELED) != 0;
7316 	shared_addr = (zoneid == ALL_ZONES);
7317 	if (shared_addr) {
7318 		/*
7319 		 * No need to handle exclusive-stack zones since ALL_ZONES
7320 		 * only applies to the shared stack.
7321 		 */
7322 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7323 		/*
7324 		 * If no shared MLP is found, tsol_mlp_findzone returns
7325 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7326 		 * search for the zone based on the packet label.
7327 		 *
7328 		 * If there is such a zone, we prefer to find a
7329 		 * connection in it.  Otherwise, we look for a
7330 		 * MAC-exempt connection in any zone whose label
7331 		 * dominates the default label on the packet.
7332 		 */
7333 		if (zoneid == ALL_ZONES)
7334 			zoneid = tsol_packet_to_zoneid(mp);
7335 		else
7336 			unlabeled = B_FALSE;
7337 	}
7338 
7339 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7340 	mutex_enter(&connfp->connf_lock);
7341 	connp = connfp->connf_head;
7342 	if (!broadcast && !CLASSD(dst)) {
7343 		/*
7344 		 * Not broadcast or multicast. Send to the one (first)
7345 		 * client we find. No need to check conn_wantpacket()
7346 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7347 		 * IPv4 unicast packets.
7348 		 */
7349 		while ((connp != NULL) &&
7350 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7351 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7352 		    !(unlabeled && connp->conn_mac_exempt && shared_addr)))) {
7353 			/*
7354 			 * We keep searching since the conn did not match,
7355 			 * or its zone did not match and it is not either
7356 			 * an allzones conn or a mac exempt conn (if the
7357 			 * sender is unlabeled.)
7358 			 */
7359 			connp = connp->conn_next;
7360 		}
7361 
7362 		if (connp == NULL ||
7363 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7364 			goto notfound;
7365 
7366 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7367 
7368 		if (is_system_labeled() &&
7369 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7370 		    connp))
7371 			goto notfound;
7372 
7373 		CONN_INC_REF(connp);
7374 		mutex_exit(&connfp->connf_lock);
7375 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7376 		    flags, recv_ill, ip_policy);
7377 		IP_STAT(ipst, ip_udp_fannorm);
7378 		CONN_DEC_REF(connp);
7379 		return;
7380 	}
7381 
7382 	/*
7383 	 * Broadcast and multicast case
7384 	 *
7385 	 * Need to check conn_wantpacket().
7386 	 * If SO_REUSEADDR has been set on the first we send the
7387 	 * packet to all clients that have joined the group and
7388 	 * match the port.
7389 	 */
7390 
7391 	while (connp != NULL) {
7392 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7393 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7394 		    (!is_system_labeled() ||
7395 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7396 		    connp)))
7397 			break;
7398 		connp = connp->conn_next;
7399 	}
7400 
7401 	if (connp == NULL ||
7402 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7403 		goto notfound;
7404 
7405 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7406 
7407 	first_connp = connp;
7408 	/*
7409 	 * When SO_REUSEADDR is not set, send the packet only to the first
7410 	 * matching connection in its zone by keeping track of the zoneid.
7411 	 */
7412 	reuseaddr = first_connp->conn_reuseaddr;
7413 	last_zoneid = first_connp->conn_zoneid;
7414 
7415 	CONN_INC_REF(connp);
7416 	connp = connp->conn_next;
7417 	for (;;) {
7418 		while (connp != NULL) {
7419 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7420 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7421 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7422 			    (!is_system_labeled() ||
7423 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7424 			    shared_addr, connp)))
7425 				break;
7426 			connp = connp->conn_next;
7427 		}
7428 		/*
7429 		 * Just copy the data part alone. The mctl part is
7430 		 * needed just for verifying policy and it is never
7431 		 * sent up.
7432 		 */
7433 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7434 		    ((mp1 = copymsg(mp)) == NULL))) {
7435 			/*
7436 			 * No more interested clients or memory
7437 			 * allocation failed
7438 			 */
7439 			connp = first_connp;
7440 			break;
7441 		}
7442 		if (connp->conn_zoneid != last_zoneid) {
7443 			/*
7444 			 * Update the zoneid so that the packet isn't sent to
7445 			 * any more conns in the same zone unless SO_REUSEADDR
7446 			 * is set.
7447 			 */
7448 			reuseaddr = connp->conn_reuseaddr;
7449 			last_zoneid = connp->conn_zoneid;
7450 		}
7451 		if (first_mp != NULL) {
7452 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7453 			    ipsec_info_type == IPSEC_IN);
7454 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7455 			    ipst->ips_netstack);
7456 			if (first_mp1 == NULL) {
7457 				freemsg(mp1);
7458 				connp = first_connp;
7459 				break;
7460 			}
7461 		} else {
7462 			first_mp1 = NULL;
7463 		}
7464 		CONN_INC_REF(connp);
7465 		mutex_exit(&connfp->connf_lock);
7466 		/*
7467 		 * IPQoS notes: We don't send the packet for policy
7468 		 * processing here, will do it for the last one (below).
7469 		 * i.e. we do it per-packet now, but if we do policy
7470 		 * processing per-conn, then we would need to do it
7471 		 * here too.
7472 		 */
7473 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7474 		    ipha, flags, recv_ill, B_FALSE);
7475 		mutex_enter(&connfp->connf_lock);
7476 		/* Follow the next pointer before releasing the conn. */
7477 		next_connp = connp->conn_next;
7478 		IP_STAT(ipst, ip_udp_fanmb);
7479 		CONN_DEC_REF(connp);
7480 		connp = next_connp;
7481 	}
7482 
7483 	/* Last one.  Send it upstream. */
7484 	mutex_exit(&connfp->connf_lock);
7485 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7486 	    recv_ill, ip_policy);
7487 	IP_STAT(ipst, ip_udp_fanmb);
7488 	CONN_DEC_REF(connp);
7489 	return;
7490 
7491 notfound:
7492 
7493 	mutex_exit(&connfp->connf_lock);
7494 	IP_STAT(ipst, ip_udp_fanothers);
7495 	/*
7496 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7497 	 * have already been matched above, since they live in the IPv4
7498 	 * fanout tables. This implies we only need to
7499 	 * check for IPv6 in6addr_any endpoints here.
7500 	 * Thus we compare using ipv6_all_zeros instead of the destination
7501 	 * address, except for the multicast group membership lookup which
7502 	 * uses the IPv4 destination.
7503 	 */
7504 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7505 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7506 	mutex_enter(&connfp->connf_lock);
7507 	connp = connfp->connf_head;
7508 	if (!broadcast && !CLASSD(dst)) {
7509 		while (connp != NULL) {
7510 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7511 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7512 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7513 			    !connp->conn_ipv6_v6only)
7514 				break;
7515 			connp = connp->conn_next;
7516 		}
7517 
7518 		if (connp != NULL && is_system_labeled() &&
7519 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7520 		    connp))
7521 			connp = NULL;
7522 
7523 		if (connp == NULL ||
7524 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7525 			/*
7526 			 * No one bound to this port.  Is
7527 			 * there a client that wants all
7528 			 * unclaimed datagrams?
7529 			 */
7530 			mutex_exit(&connfp->connf_lock);
7531 
7532 			if (mctl_present)
7533 				first_mp->b_cont = mp;
7534 			else
7535 				first_mp = mp;
7536 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7537 			    connf_head != NULL) {
7538 				ip_fanout_proto(q, first_mp, ill, ipha,
7539 				    flags | IP_FF_RAWIP, mctl_present,
7540 				    ip_policy, recv_ill, zoneid);
7541 			} else {
7542 				if (ip_fanout_send_icmp(q, first_mp, flags,
7543 				    ICMP_DEST_UNREACHABLE,
7544 				    ICMP_PORT_UNREACHABLE,
7545 				    mctl_present, zoneid, ipst)) {
7546 					BUMP_MIB(ill->ill_ip_mib,
7547 					    udpIfStatsNoPorts);
7548 				}
7549 			}
7550 			return;
7551 		}
7552 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7553 
7554 		CONN_INC_REF(connp);
7555 		mutex_exit(&connfp->connf_lock);
7556 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7557 		    flags, recv_ill, ip_policy);
7558 		CONN_DEC_REF(connp);
7559 		return;
7560 	}
7561 	/*
7562 	 * IPv4 multicast packet being delivered to an AF_INET6
7563 	 * in6addr_any endpoint.
7564 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7565 	 * and not conn_wantpacket_v6() since any multicast membership is
7566 	 * for an IPv4-mapped multicast address.
7567 	 * The packet is sent to all clients in all zones that have joined the
7568 	 * group and match the port.
7569 	 */
7570 	while (connp != NULL) {
7571 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7572 		    srcport, v6src) &&
7573 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7574 		    (!is_system_labeled() ||
7575 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7576 		    connp)))
7577 			break;
7578 		connp = connp->conn_next;
7579 	}
7580 
7581 	if (connp == NULL ||
7582 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7583 		/*
7584 		 * No one bound to this port.  Is
7585 		 * there a client that wants all
7586 		 * unclaimed datagrams?
7587 		 */
7588 		mutex_exit(&connfp->connf_lock);
7589 
7590 		if (mctl_present)
7591 			first_mp->b_cont = mp;
7592 		else
7593 			first_mp = mp;
7594 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7595 		    NULL) {
7596 			ip_fanout_proto(q, first_mp, ill, ipha,
7597 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7598 			    recv_ill, zoneid);
7599 		} else {
7600 			/*
7601 			 * We used to attempt to send an icmp error here, but
7602 			 * since this is known to be a multicast packet
7603 			 * and we don't send icmp errors in response to
7604 			 * multicast, just drop the packet and give up sooner.
7605 			 */
7606 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7607 			freemsg(first_mp);
7608 		}
7609 		return;
7610 	}
7611 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7612 
7613 	first_connp = connp;
7614 
7615 	CONN_INC_REF(connp);
7616 	connp = connp->conn_next;
7617 	for (;;) {
7618 		while (connp != NULL) {
7619 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7620 			    ipv6_all_zeros, srcport, v6src) &&
7621 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7622 			    (!is_system_labeled() ||
7623 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7624 			    shared_addr, connp)))
7625 				break;
7626 			connp = connp->conn_next;
7627 		}
7628 		/*
7629 		 * Just copy the data part alone. The mctl part is
7630 		 * needed just for verifying policy and it is never
7631 		 * sent up.
7632 		 */
7633 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7634 		    ((mp1 = copymsg(mp)) == NULL))) {
7635 			/*
7636 			 * No more intested clients or memory
7637 			 * allocation failed
7638 			 */
7639 			connp = first_connp;
7640 			break;
7641 		}
7642 		if (first_mp != NULL) {
7643 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7644 			    ipsec_info_type == IPSEC_IN);
7645 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7646 			    ipst->ips_netstack);
7647 			if (first_mp1 == NULL) {
7648 				freemsg(mp1);
7649 				connp = first_connp;
7650 				break;
7651 			}
7652 		} else {
7653 			first_mp1 = NULL;
7654 		}
7655 		CONN_INC_REF(connp);
7656 		mutex_exit(&connfp->connf_lock);
7657 		/*
7658 		 * IPQoS notes: We don't send the packet for policy
7659 		 * processing here, will do it for the last one (below).
7660 		 * i.e. we do it per-packet now, but if we do policy
7661 		 * processing per-conn, then we would need to do it
7662 		 * here too.
7663 		 */
7664 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7665 		    ipha, flags, recv_ill, B_FALSE);
7666 		mutex_enter(&connfp->connf_lock);
7667 		/* Follow the next pointer before releasing the conn. */
7668 		next_connp = connp->conn_next;
7669 		CONN_DEC_REF(connp);
7670 		connp = next_connp;
7671 	}
7672 
7673 	/* Last one.  Send it upstream. */
7674 	mutex_exit(&connfp->connf_lock);
7675 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7676 	    recv_ill, ip_policy);
7677 	CONN_DEC_REF(connp);
7678 }
7679 
7680 /*
7681  * Complete the ip_wput header so that it
7682  * is possible to generate ICMP
7683  * errors.
7684  */
7685 int
7686 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7687 {
7688 	ire_t *ire;
7689 
7690 	if (ipha->ipha_src == INADDR_ANY) {
7691 		ire = ire_lookup_local(zoneid, ipst);
7692 		if (ire == NULL) {
7693 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7694 			return (1);
7695 		}
7696 		ipha->ipha_src = ire->ire_addr;
7697 		ire_refrele(ire);
7698 	}
7699 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7700 	ipha->ipha_hdr_checksum = 0;
7701 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7702 	return (0);
7703 }
7704 
7705 /*
7706  * Nobody should be sending
7707  * packets up this stream
7708  */
7709 static void
7710 ip_lrput(queue_t *q, mblk_t *mp)
7711 {
7712 	mblk_t *mp1;
7713 
7714 	switch (mp->b_datap->db_type) {
7715 	case M_FLUSH:
7716 		/* Turn around */
7717 		if (*mp->b_rptr & FLUSHW) {
7718 			*mp->b_rptr &= ~FLUSHR;
7719 			qreply(q, mp);
7720 			return;
7721 		}
7722 		break;
7723 	}
7724 	/* Could receive messages that passed through ar_rput */
7725 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7726 		mp1->b_prev = mp1->b_next = NULL;
7727 	freemsg(mp);
7728 }
7729 
7730 /* Nobody should be sending packets down this stream */
7731 /* ARGSUSED */
7732 void
7733 ip_lwput(queue_t *q, mblk_t *mp)
7734 {
7735 	freemsg(mp);
7736 }
7737 
7738 /*
7739  * Move the first hop in any source route to ipha_dst and remove that part of
7740  * the source route.  Called by other protocols.  Errors in option formatting
7741  * are ignored - will be handled by ip_wput_options Return the final
7742  * destination (either ipha_dst or the last entry in a source route.)
7743  */
7744 ipaddr_t
7745 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7746 {
7747 	ipoptp_t	opts;
7748 	uchar_t		*opt;
7749 	uint8_t		optval;
7750 	uint8_t		optlen;
7751 	ipaddr_t	dst;
7752 	int		i;
7753 	ire_t		*ire;
7754 	ip_stack_t	*ipst = ns->netstack_ip;
7755 
7756 	ip2dbg(("ip_massage_options\n"));
7757 	dst = ipha->ipha_dst;
7758 	for (optval = ipoptp_first(&opts, ipha);
7759 	    optval != IPOPT_EOL;
7760 	    optval = ipoptp_next(&opts)) {
7761 		opt = opts.ipoptp_cur;
7762 		switch (optval) {
7763 			uint8_t off;
7764 		case IPOPT_SSRR:
7765 		case IPOPT_LSRR:
7766 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7767 				ip1dbg(("ip_massage_options: bad src route\n"));
7768 				break;
7769 			}
7770 			optlen = opts.ipoptp_len;
7771 			off = opt[IPOPT_OFFSET];
7772 			off--;
7773 		redo_srr:
7774 			if (optlen < IP_ADDR_LEN ||
7775 			    off > optlen - IP_ADDR_LEN) {
7776 				/* End of source route */
7777 				ip1dbg(("ip_massage_options: end of SR\n"));
7778 				break;
7779 			}
7780 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7781 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7782 			    ntohl(dst)));
7783 			/*
7784 			 * Check if our address is present more than
7785 			 * once as consecutive hops in source route.
7786 			 * XXX verify per-interface ip_forwarding
7787 			 * for source route?
7788 			 */
7789 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7790 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7791 			if (ire != NULL) {
7792 				ire_refrele(ire);
7793 				off += IP_ADDR_LEN;
7794 				goto redo_srr;
7795 			}
7796 			if (dst == htonl(INADDR_LOOPBACK)) {
7797 				ip1dbg(("ip_massage_options: loopback addr in "
7798 				    "source route!\n"));
7799 				break;
7800 			}
7801 			/*
7802 			 * Update ipha_dst to be the first hop and remove the
7803 			 * first hop from the source route (by overwriting
7804 			 * part of the option with NOP options).
7805 			 */
7806 			ipha->ipha_dst = dst;
7807 			/* Put the last entry in dst */
7808 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7809 			    3;
7810 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7811 
7812 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7813 			    ntohl(dst)));
7814 			/* Move down and overwrite */
7815 			opt[IP_ADDR_LEN] = opt[0];
7816 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7817 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7818 			for (i = 0; i < IP_ADDR_LEN; i++)
7819 				opt[i] = IPOPT_NOP;
7820 			break;
7821 		}
7822 	}
7823 	return (dst);
7824 }
7825 
7826 /*
7827  * Return the network mask
7828  * associated with the specified address.
7829  */
7830 ipaddr_t
7831 ip_net_mask(ipaddr_t addr)
7832 {
7833 	uchar_t	*up = (uchar_t *)&addr;
7834 	ipaddr_t mask = 0;
7835 	uchar_t	*maskp = (uchar_t *)&mask;
7836 
7837 #if defined(__i386) || defined(__amd64)
7838 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7839 #endif
7840 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7841 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7842 #endif
7843 	if (CLASSD(addr)) {
7844 		maskp[0] = 0xF0;
7845 		return (mask);
7846 	}
7847 
7848 	/* We assume Class E default netmask to be 32 */
7849 	if (CLASSE(addr))
7850 		return (0xffffffffU);
7851 
7852 	if (addr == 0)
7853 		return (0);
7854 	maskp[0] = 0xFF;
7855 	if ((up[0] & 0x80) == 0)
7856 		return (mask);
7857 
7858 	maskp[1] = 0xFF;
7859 	if ((up[0] & 0xC0) == 0x80)
7860 		return (mask);
7861 
7862 	maskp[2] = 0xFF;
7863 	if ((up[0] & 0xE0) == 0xC0)
7864 		return (mask);
7865 
7866 	/* Otherwise return no mask */
7867 	return ((ipaddr_t)0);
7868 }
7869 
7870 /*
7871  * Helper ill lookup function used by IPsec.
7872  */
7873 ill_t *
7874 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7875 {
7876 	ill_t *ret_ill;
7877 
7878 	ASSERT(ifindex != 0);
7879 
7880 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7881 	    ipst);
7882 	if (ret_ill == NULL) {
7883 		if (isv6) {
7884 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7885 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7886 			    ifindex));
7887 		} else {
7888 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7889 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7890 			    ifindex));
7891 		}
7892 		freemsg(first_mp);
7893 		return (NULL);
7894 	}
7895 	return (ret_ill);
7896 }
7897 
7898 /*
7899  * IPv4 -
7900  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7901  * out a packet to a destination address for which we do not have specific
7902  * (or sufficient) routing information.
7903  *
7904  * NOTE : These are the scopes of some of the variables that point at IRE,
7905  *	  which needs to be followed while making any future modifications
7906  *	  to avoid memory leaks.
7907  *
7908  *	- ire and sire are the entries looked up initially by
7909  *	  ire_ftable_lookup.
7910  *	- ipif_ire is used to hold the interface ire associated with
7911  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7912  *	  it before branching out to error paths.
7913  *	- save_ire is initialized before ire_create, so that ire returned
7914  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7915  *	  before breaking out of the switch.
7916  *
7917  *	Thus on failures, we have to REFRELE only ire and sire, if they
7918  *	are not NULL.
7919  */
7920 void
7921 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7922     zoneid_t zoneid, ip_stack_t *ipst)
7923 {
7924 	areq_t	*areq;
7925 	ipaddr_t gw = 0;
7926 	ire_t	*ire = NULL;
7927 	mblk_t	*res_mp;
7928 	ipaddr_t *addrp;
7929 	ipaddr_t nexthop_addr;
7930 	ipif_t  *src_ipif = NULL;
7931 	ill_t	*dst_ill = NULL;
7932 	ipha_t  *ipha;
7933 	ire_t	*sire = NULL;
7934 	mblk_t	*first_mp;
7935 	ire_t	*save_ire;
7936 	ushort_t ire_marks = 0;
7937 	boolean_t mctl_present;
7938 	ipsec_out_t *io;
7939 	mblk_t	*saved_mp;
7940 	mblk_t	*copy_mp = NULL;
7941 	mblk_t	*xmit_mp = NULL;
7942 	ipaddr_t save_dst;
7943 	uint32_t multirt_flags =
7944 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7945 	boolean_t multirt_is_resolvable;
7946 	boolean_t multirt_resolve_next;
7947 	boolean_t unspec_src;
7948 	boolean_t ip_nexthop = B_FALSE;
7949 	tsol_ire_gw_secattr_t *attrp = NULL;
7950 	tsol_gcgrp_t *gcgrp = NULL;
7951 	tsol_gcgrp_addr_t ga;
7952 	int multirt_res_failures = 0;
7953 	int multirt_res_attempts = 0;
7954 	int multirt_already_resolved = 0;
7955 	boolean_t multirt_no_icmp_error = B_FALSE;
7956 
7957 	if (ip_debug > 2) {
7958 		/* ip1dbg */
7959 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7960 	}
7961 
7962 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7963 	if (mctl_present) {
7964 		io = (ipsec_out_t *)first_mp->b_rptr;
7965 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7966 		ASSERT(zoneid == io->ipsec_out_zoneid);
7967 		ASSERT(zoneid != ALL_ZONES);
7968 	}
7969 
7970 	ipha = (ipha_t *)mp->b_rptr;
7971 
7972 	/* All multicast lookups come through ip_newroute_ipif() */
7973 	if (CLASSD(dst)) {
7974 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7975 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7976 		freemsg(first_mp);
7977 		return;
7978 	}
7979 
7980 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7981 		ip_nexthop = B_TRUE;
7982 		nexthop_addr = io->ipsec_out_nexthop_addr;
7983 	}
7984 	/*
7985 	 * If this IRE is created for forwarding or it is not for
7986 	 * traffic for congestion controlled protocols, mark it as temporary.
7987 	 */
7988 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7989 		ire_marks |= IRE_MARK_TEMPORARY;
7990 
7991 	/*
7992 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7993 	 * chain until it gets the most specific information available.
7994 	 * For example, we know that there is no IRE_CACHE for this dest,
7995 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7996 	 * ire_ftable_lookup will look up the gateway, etc.
7997 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7998 	 * to the destination, of equal netmask length in the forward table,
7999 	 * will be recursively explored. If no information is available
8000 	 * for the final gateway of that route, we force the returned ire
8001 	 * to be equal to sire using MATCH_IRE_PARENT.
8002 	 * At least, in this case we have a starting point (in the buckets)
8003 	 * to look for other routes to the destination in the forward table.
8004 	 * This is actually used only for multirouting, where a list
8005 	 * of routes has to be processed in sequence.
8006 	 *
8007 	 * In the process of coming up with the most specific information,
8008 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8009 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8010 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8011 	 * Two caveats when handling incomplete ire's in ip_newroute:
8012 	 * - we should be careful when accessing its ire_nce (specifically
8013 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8014 	 * - not all legacy code path callers are prepared to handle
8015 	 *   incomplete ire's, so we should not create/add incomplete
8016 	 *   ire_cache entries here. (See discussion about temporary solution
8017 	 *   further below).
8018 	 *
8019 	 * In order to minimize packet dropping, and to preserve existing
8020 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8021 	 * gateway, and instead use the IF_RESOLVER ire to send out
8022 	 * another request to ARP (this is achieved by passing the
8023 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8024 	 * arp response comes back in ip_wput_nondata, we will create
8025 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8026 	 *
8027 	 * Note that this is a temporary solution; the correct solution is
8028 	 * to create an incomplete  per-dst ire_cache entry, and send the
8029 	 * packet out when the gw's nce is resolved. In order to achieve this,
8030 	 * all packet processing must have been completed prior to calling
8031 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8032 	 * to be modified to accomodate this solution.
8033 	 */
8034 	if (ip_nexthop) {
8035 		/*
8036 		 * The first time we come here, we look for an IRE_INTERFACE
8037 		 * entry for the specified nexthop, set the dst to be the
8038 		 * nexthop address and create an IRE_CACHE entry for the
8039 		 * nexthop. The next time around, we are able to find an
8040 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8041 		 * nexthop address and create an IRE_CACHE entry for the
8042 		 * destination address via the specified nexthop.
8043 		 */
8044 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8045 		    msg_getlabel(mp), ipst);
8046 		if (ire != NULL) {
8047 			gw = nexthop_addr;
8048 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8049 		} else {
8050 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8051 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8052 			    msg_getlabel(mp),
8053 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8054 			    ipst);
8055 			if (ire != NULL) {
8056 				dst = nexthop_addr;
8057 			}
8058 		}
8059 	} else {
8060 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8061 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8062 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8063 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8064 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8065 		    ipst);
8066 	}
8067 
8068 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8069 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8070 
8071 	/*
8072 	 * This loop is run only once in most cases.
8073 	 * We loop to resolve further routes only when the destination
8074 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8075 	 */
8076 	do {
8077 		/* Clear the previous iteration's values */
8078 		if (src_ipif != NULL) {
8079 			ipif_refrele(src_ipif);
8080 			src_ipif = NULL;
8081 		}
8082 		if (dst_ill != NULL) {
8083 			ill_refrele(dst_ill);
8084 			dst_ill = NULL;
8085 		}
8086 
8087 		multirt_resolve_next = B_FALSE;
8088 		/*
8089 		 * We check if packets have to be multirouted.
8090 		 * In this case, given the current <ire, sire> couple,
8091 		 * we look for the next suitable <ire, sire>.
8092 		 * This check is done in ire_multirt_lookup(),
8093 		 * which applies various criteria to find the next route
8094 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8095 		 * unchanged if it detects it has not been tried yet.
8096 		 */
8097 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8098 			ip3dbg(("ip_newroute: starting next_resolution "
8099 			    "with first_mp %p, tag %d\n",
8100 			    (void *)first_mp,
8101 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8102 
8103 			ASSERT(sire != NULL);
8104 			multirt_is_resolvable =
8105 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8106 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
8107 
8108 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8109 			    "multirt_already_resolved %d, "
8110 			    "multirt_res_attempts %d, multirt_res_failures %d, "
8111 			    "ire %p, sire %p\n", multirt_is_resolvable,
8112 			    multirt_already_resolved, multirt_res_attempts,
8113 			    multirt_res_failures, (void *)ire, (void *)sire));
8114 
8115 			if (!multirt_is_resolvable) {
8116 				/*
8117 				 * No more multirt route to resolve; give up
8118 				 * (all routes resolved or no more
8119 				 * resolvable routes).
8120 				 */
8121 				if (ire != NULL) {
8122 					ire_refrele(ire);
8123 					ire = NULL;
8124 				}
8125 				/*
8126 				 * Generate ICMP error only if all attempts to
8127 				 * resolve multirt route failed and there is no
8128 				 * already resolved one.  Don't generate ICMP
8129 				 * error when:
8130 				 *
8131 				 *  1) there was no attempt to resolve
8132 				 *  2) at least one attempt passed
8133 				 *  3) a multirt route is already resolved
8134 				 *
8135 				 *  Case 1) may occur due to multiple
8136 				 *    resolution attempts during single
8137 				 *    ip_multirt_resolution_interval.
8138 				 *
8139 				 *  Case 2-3) means that CGTP destination is
8140 				 *    reachable via one link so we don't want to
8141 				 *    generate ICMP host unreachable error.
8142 				 */
8143 				if (multirt_res_attempts == 0 ||
8144 				    multirt_res_failures <
8145 				    multirt_res_attempts ||
8146 				    multirt_already_resolved > 0)
8147 					multirt_no_icmp_error = B_TRUE;
8148 			} else {
8149 				ASSERT(sire != NULL);
8150 				ASSERT(ire != NULL);
8151 
8152 				multirt_res_attempts++;
8153 			}
8154 		}
8155 
8156 		if (ire == NULL) {
8157 			if (ip_debug > 3) {
8158 				/* ip2dbg */
8159 				pr_addr_dbg("ip_newroute: "
8160 				    "can't resolve %s\n", AF_INET, &dst);
8161 			}
8162 			ip3dbg(("ip_newroute: "
8163 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8164 			    (void *)ire, (void *)sire,
8165 			    (int)multirt_no_icmp_error));
8166 
8167 			if (sire != NULL) {
8168 				ire_refrele(sire);
8169 				sire = NULL;
8170 			}
8171 
8172 			if (multirt_no_icmp_error) {
8173 				/* There is no need to report an ICMP error. */
8174 				MULTIRT_DEBUG_UNTAG(first_mp);
8175 				freemsg(first_mp);
8176 				return;
8177 			}
8178 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8179 			    RTA_DST, ipst);
8180 			goto icmp_err_ret;
8181 		}
8182 
8183 		/*
8184 		 * Verify that the returned IRE does not have either
8185 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8186 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8187 		 */
8188 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8189 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8190 			goto icmp_err_ret;
8191 		}
8192 		/*
8193 		 * Increment the ire_ob_pkt_count field for ire if it is an
8194 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8195 		 * increment the same for the parent IRE, sire, if it is some
8196 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8197 		 */
8198 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8199 			UPDATE_OB_PKT_COUNT(ire);
8200 			ire->ire_last_used_time = lbolt;
8201 		}
8202 
8203 		if (sire != NULL) {
8204 			gw = sire->ire_gateway_addr;
8205 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8206 			    IRE_INTERFACE)) == 0);
8207 			UPDATE_OB_PKT_COUNT(sire);
8208 			sire->ire_last_used_time = lbolt;
8209 		}
8210 		/*
8211 		 * We have a route to reach the destination.  Find the
8212 		 * appropriate ill, then get a source address using
8213 		 * ipif_select_source().
8214 		 *
8215 		 * If we are here trying to create an IRE_CACHE for an offlink
8216 		 * destination and have an IRE_CACHE entry for VNI, then use
8217 		 * ire_stq instead since VNI's queue is a black hole.
8218 		 */
8219 		if ((ire->ire_type == IRE_CACHE) &&
8220 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8221 			dst_ill = ire->ire_stq->q_ptr;
8222 			ill_refhold(dst_ill);
8223 		} else {
8224 			ill_t *ill = ire->ire_ipif->ipif_ill;
8225 
8226 			if (IS_IPMP(ill)) {
8227 				dst_ill =
8228 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8229 			} else {
8230 				dst_ill = ill;
8231 				ill_refhold(dst_ill);
8232 			}
8233 		}
8234 
8235 		if (dst_ill == NULL) {
8236 			if (ip_debug > 2) {
8237 				pr_addr_dbg("ip_newroute: no dst "
8238 				    "ill for dst %s\n", AF_INET, &dst);
8239 			}
8240 			goto icmp_err_ret;
8241 		}
8242 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8243 
8244 		/*
8245 		 * Pick the best source address from dst_ill.
8246 		 *
8247 		 * 1) Try to pick the source address from the destination
8248 		 *    route. Clustering assumes that when we have multiple
8249 		 *    prefixes hosted on an interface, the prefix of the
8250 		 *    source address matches the prefix of the destination
8251 		 *    route. We do this only if the address is not
8252 		 *    DEPRECATED.
8253 		 *
8254 		 * 2) If the conn is in a different zone than the ire, we
8255 		 *    need to pick a source address from the right zone.
8256 		 */
8257 		ASSERT(src_ipif == NULL);
8258 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8259 			/*
8260 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8261 			 * Check that the ipif matching the requested source
8262 			 * address still exists.
8263 			 */
8264 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8265 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8266 		}
8267 
8268 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8269 
8270 		if (src_ipif == NULL &&
8271 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8272 			ire_marks |= IRE_MARK_USESRC_CHECK;
8273 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8274 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8275 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8276 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8277 			    ire->ire_zoneid != ALL_ZONES) ||
8278 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8279 				/*
8280 				 * If the destination is reachable via a
8281 				 * given gateway, the selected source address
8282 				 * should be in the same subnet as the gateway.
8283 				 * Otherwise, the destination is not reachable.
8284 				 *
8285 				 * If there are no interfaces on the same subnet
8286 				 * as the destination, ipif_select_source gives
8287 				 * first non-deprecated interface which might be
8288 				 * on a different subnet than the gateway.
8289 				 * This is not desirable. Hence pass the dst_ire
8290 				 * source address to ipif_select_source.
8291 				 * It is sure that the destination is reachable
8292 				 * with the dst_ire source address subnet.
8293 				 * So passing dst_ire source address to
8294 				 * ipif_select_source will make sure that the
8295 				 * selected source will be on the same subnet
8296 				 * as dst_ire source address.
8297 				 */
8298 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8299 
8300 				src_ipif = ipif_select_source(dst_ill, saddr,
8301 				    zoneid);
8302 				if (src_ipif == NULL) {
8303 					/*
8304 					 * In the case of multirouting, it may
8305 					 * happen that ipif_select_source fails
8306 					 * as DAD may disallow use of the
8307 					 * particular source interface.  Anyway,
8308 					 * we need to continue and attempt to
8309 					 * resolve other multirt routes.
8310 					 */
8311 					if ((sire != NULL) &&
8312 					    (sire->ire_flags & RTF_MULTIRT)) {
8313 						ire_refrele(ire);
8314 						ire = NULL;
8315 						multirt_resolve_next = B_TRUE;
8316 						multirt_res_failures++;
8317 						continue;
8318 					}
8319 
8320 					if (ip_debug > 2) {
8321 						pr_addr_dbg("ip_newroute: "
8322 						    "no src for dst %s ",
8323 						    AF_INET, &dst);
8324 						printf("on interface %s\n",
8325 						    dst_ill->ill_name);
8326 					}
8327 					goto icmp_err_ret;
8328 				}
8329 			} else {
8330 				src_ipif = ire->ire_ipif;
8331 				ASSERT(src_ipif != NULL);
8332 				/* hold src_ipif for uniformity */
8333 				ipif_refhold(src_ipif);
8334 			}
8335 		}
8336 
8337 		/*
8338 		 * Assign a source address while we have the conn.
8339 		 * We can't have ip_wput_ire pick a source address when the
8340 		 * packet returns from arp since we need to look at
8341 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8342 		 * going through arp.
8343 		 *
8344 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8345 		 *	  it uses ip6i to store this information.
8346 		 */
8347 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8348 			ipha->ipha_src = src_ipif->ipif_src_addr;
8349 
8350 		if (ip_debug > 3) {
8351 			/* ip2dbg */
8352 			pr_addr_dbg("ip_newroute: first hop %s\n",
8353 			    AF_INET, &gw);
8354 		}
8355 		ip2dbg(("\tire type %s (%d)\n",
8356 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8357 
8358 		/*
8359 		 * The TTL of multirouted packets is bounded by the
8360 		 * ip_multirt_ttl ndd variable.
8361 		 */
8362 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8363 			/* Force TTL of multirouted packets */
8364 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8365 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8366 				ip2dbg(("ip_newroute: forcing multirt TTL "
8367 				    "to %d (was %d), dst 0x%08x\n",
8368 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8369 				    ntohl(sire->ire_addr)));
8370 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8371 			}
8372 		}
8373 		/*
8374 		 * At this point in ip_newroute(), ire is either the
8375 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8376 		 * destination or an IRE_INTERFACE type that should be used
8377 		 * to resolve an on-subnet destination or an on-subnet
8378 		 * next-hop gateway.
8379 		 *
8380 		 * In the IRE_CACHE case, we have the following :
8381 		 *
8382 		 * 1) src_ipif - used for getting a source address.
8383 		 *
8384 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8385 		 *    means packets using this IRE_CACHE will go out on
8386 		 *    dst_ill.
8387 		 *
8388 		 * 3) The IRE sire will point to the prefix that is the
8389 		 *    longest  matching route for the destination. These
8390 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8391 		 *
8392 		 *    The newly created IRE_CACHE entry for the off-subnet
8393 		 *    destination is tied to both the prefix route and the
8394 		 *    interface route used to resolve the next-hop gateway
8395 		 *    via the ire_phandle and ire_ihandle fields,
8396 		 *    respectively.
8397 		 *
8398 		 * In the IRE_INTERFACE case, we have the following :
8399 		 *
8400 		 * 1) src_ipif - used for getting a source address.
8401 		 *
8402 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8403 		 *    means packets using the IRE_CACHE that we will build
8404 		 *    here will go out on dst_ill.
8405 		 *
8406 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8407 		 *    to be created will only be tied to the IRE_INTERFACE
8408 		 *    that was derived from the ire_ihandle field.
8409 		 *
8410 		 *    If sire is non-NULL, it means the destination is
8411 		 *    off-link and we will first create the IRE_CACHE for the
8412 		 *    gateway. Next time through ip_newroute, we will create
8413 		 *    the IRE_CACHE for the final destination as described
8414 		 *    above.
8415 		 *
8416 		 * In both cases, after the current resolution has been
8417 		 * completed (or possibly initialised, in the IRE_INTERFACE
8418 		 * case), the loop may be re-entered to attempt the resolution
8419 		 * of another RTF_MULTIRT route.
8420 		 *
8421 		 * When an IRE_CACHE entry for the off-subnet destination is
8422 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8423 		 * for further processing in emission loops.
8424 		 */
8425 		save_ire = ire;
8426 		switch (ire->ire_type) {
8427 		case IRE_CACHE: {
8428 			ire_t	*ipif_ire;
8429 
8430 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8431 			if (gw == 0)
8432 				gw = ire->ire_gateway_addr;
8433 			/*
8434 			 * We need 3 ire's to create a new cache ire for an
8435 			 * off-link destination from the cache ire of the
8436 			 * gateway.
8437 			 *
8438 			 *	1. The prefix ire 'sire' (Note that this does
8439 			 *	   not apply to the conn_nexthop_set case)
8440 			 *	2. The cache ire of the gateway 'ire'
8441 			 *	3. The interface ire 'ipif_ire'
8442 			 *
8443 			 * We have (1) and (2). We lookup (3) below.
8444 			 *
8445 			 * If there is no interface route to the gateway,
8446 			 * it is a race condition, where we found the cache
8447 			 * but the interface route has been deleted.
8448 			 */
8449 			if (ip_nexthop) {
8450 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8451 			} else {
8452 				ipif_ire =
8453 				    ire_ihandle_lookup_offlink(ire, sire);
8454 			}
8455 			if (ipif_ire == NULL) {
8456 				ip1dbg(("ip_newroute: "
8457 				    "ire_ihandle_lookup_offlink failed\n"));
8458 				goto icmp_err_ret;
8459 			}
8460 
8461 			/*
8462 			 * Check cached gateway IRE for any security
8463 			 * attributes; if found, associate the gateway
8464 			 * credentials group to the destination IRE.
8465 			 */
8466 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8467 				mutex_enter(&attrp->igsa_lock);
8468 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8469 					GCGRP_REFHOLD(gcgrp);
8470 				mutex_exit(&attrp->igsa_lock);
8471 			}
8472 
8473 			/*
8474 			 * XXX For the source of the resolver mp,
8475 			 * we are using the same DL_UNITDATA_REQ
8476 			 * (from save_ire->ire_nce->nce_res_mp)
8477 			 * though the save_ire is not pointing at the same ill.
8478 			 * This is incorrect. We need to send it up to the
8479 			 * resolver to get the right res_mp. For ethernets
8480 			 * this may be okay (ill_type == DL_ETHER).
8481 			 */
8482 
8483 			ire = ire_create(
8484 			    (uchar_t *)&dst,		/* dest address */
8485 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8486 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8487 			    (uchar_t *)&gw,		/* gateway address */
8488 			    &save_ire->ire_max_frag,
8489 			    save_ire->ire_nce,		/* src nce */
8490 			    dst_ill->ill_rq,		/* recv-from queue */
8491 			    dst_ill->ill_wq,		/* send-to queue */
8492 			    IRE_CACHE,			/* IRE type */
8493 			    src_ipif,
8494 			    (sire != NULL) ?
8495 			    sire->ire_mask : 0, 	/* Parent mask */
8496 			    (sire != NULL) ?
8497 			    sire->ire_phandle : 0,	/* Parent handle */
8498 			    ipif_ire->ire_ihandle,	/* Interface handle */
8499 			    (sire != NULL) ? (sire->ire_flags &
8500 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8501 			    (sire != NULL) ?
8502 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8503 			    NULL,
8504 			    gcgrp,
8505 			    ipst);
8506 
8507 			if (ire == NULL) {
8508 				if (gcgrp != NULL) {
8509 					GCGRP_REFRELE(gcgrp);
8510 					gcgrp = NULL;
8511 				}
8512 				ire_refrele(ipif_ire);
8513 				ire_refrele(save_ire);
8514 				break;
8515 			}
8516 
8517 			/* reference now held by IRE */
8518 			gcgrp = NULL;
8519 
8520 			ire->ire_marks |= ire_marks;
8521 
8522 			/*
8523 			 * Prevent sire and ipif_ire from getting deleted.
8524 			 * The newly created ire is tied to both of them via
8525 			 * the phandle and ihandle respectively.
8526 			 */
8527 			if (sire != NULL) {
8528 				IRB_REFHOLD(sire->ire_bucket);
8529 				/* Has it been removed already ? */
8530 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8531 					IRB_REFRELE(sire->ire_bucket);
8532 					ire_refrele(ipif_ire);
8533 					ire_refrele(save_ire);
8534 					break;
8535 				}
8536 			}
8537 
8538 			IRB_REFHOLD(ipif_ire->ire_bucket);
8539 			/* Has it been removed already ? */
8540 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8541 				IRB_REFRELE(ipif_ire->ire_bucket);
8542 				if (sire != NULL)
8543 					IRB_REFRELE(sire->ire_bucket);
8544 				ire_refrele(ipif_ire);
8545 				ire_refrele(save_ire);
8546 				break;
8547 			}
8548 
8549 			xmit_mp = first_mp;
8550 			/*
8551 			 * In the case of multirouting, a copy
8552 			 * of the packet is done before its sending.
8553 			 * The copy is used to attempt another
8554 			 * route resolution, in a next loop.
8555 			 */
8556 			if (ire->ire_flags & RTF_MULTIRT) {
8557 				copy_mp = copymsg(first_mp);
8558 				if (copy_mp != NULL) {
8559 					xmit_mp = copy_mp;
8560 					MULTIRT_DEBUG_TAG(first_mp);
8561 				}
8562 			}
8563 
8564 			ire_add_then_send(q, ire, xmit_mp);
8565 			ire_refrele(save_ire);
8566 
8567 			/* Assert that sire is not deleted yet. */
8568 			if (sire != NULL) {
8569 				ASSERT(sire->ire_ptpn != NULL);
8570 				IRB_REFRELE(sire->ire_bucket);
8571 			}
8572 
8573 			/* Assert that ipif_ire is not deleted yet. */
8574 			ASSERT(ipif_ire->ire_ptpn != NULL);
8575 			IRB_REFRELE(ipif_ire->ire_bucket);
8576 			ire_refrele(ipif_ire);
8577 
8578 			/*
8579 			 * If copy_mp is not NULL, multirouting was
8580 			 * requested. We loop to initiate a next
8581 			 * route resolution attempt, starting from sire.
8582 			 */
8583 			if (copy_mp != NULL) {
8584 				/*
8585 				 * Search for the next unresolved
8586 				 * multirt route.
8587 				 */
8588 				copy_mp = NULL;
8589 				ipif_ire = NULL;
8590 				ire = NULL;
8591 				multirt_resolve_next = B_TRUE;
8592 				continue;
8593 			}
8594 			if (sire != NULL)
8595 				ire_refrele(sire);
8596 			ipif_refrele(src_ipif);
8597 			ill_refrele(dst_ill);
8598 			return;
8599 		}
8600 		case IRE_IF_NORESOLVER: {
8601 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8602 			    dst_ill->ill_resolver_mp == NULL) {
8603 				ip1dbg(("ip_newroute: dst_ill %p "
8604 				    "for IRE_IF_NORESOLVER ire %p has "
8605 				    "no ill_resolver_mp\n",
8606 				    (void *)dst_ill, (void *)ire));
8607 				break;
8608 			}
8609 
8610 			/*
8611 			 * TSol note: We are creating the ire cache for the
8612 			 * destination 'dst'. If 'dst' is offlink, going
8613 			 * through the first hop 'gw', the security attributes
8614 			 * of 'dst' must be set to point to the gateway
8615 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8616 			 * is possible that 'dst' is a potential gateway that is
8617 			 * referenced by some route that has some security
8618 			 * attributes. Thus in the former case, we need to do a
8619 			 * gcgrp_lookup of 'gw' while in the latter case we
8620 			 * need to do gcgrp_lookup of 'dst' itself.
8621 			 */
8622 			ga.ga_af = AF_INET;
8623 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8624 			    &ga.ga_addr);
8625 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8626 
8627 			ire = ire_create(
8628 			    (uchar_t *)&dst,		/* dest address */
8629 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8630 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8631 			    (uchar_t *)&gw,		/* gateway address */
8632 			    &save_ire->ire_max_frag,
8633 			    NULL,			/* no src nce */
8634 			    dst_ill->ill_rq,		/* recv-from queue */
8635 			    dst_ill->ill_wq,		/* send-to queue */
8636 			    IRE_CACHE,
8637 			    src_ipif,
8638 			    save_ire->ire_mask,		/* Parent mask */
8639 			    (sire != NULL) ?		/* Parent handle */
8640 			    sire->ire_phandle : 0,
8641 			    save_ire->ire_ihandle,	/* Interface handle */
8642 			    (sire != NULL) ? sire->ire_flags &
8643 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8644 			    &(save_ire->ire_uinfo),
8645 			    NULL,
8646 			    gcgrp,
8647 			    ipst);
8648 
8649 			if (ire == NULL) {
8650 				if (gcgrp != NULL) {
8651 					GCGRP_REFRELE(gcgrp);
8652 					gcgrp = NULL;
8653 				}
8654 				ire_refrele(save_ire);
8655 				break;
8656 			}
8657 
8658 			/* reference now held by IRE */
8659 			gcgrp = NULL;
8660 
8661 			ire->ire_marks |= ire_marks;
8662 
8663 			/* Prevent save_ire from getting deleted */
8664 			IRB_REFHOLD(save_ire->ire_bucket);
8665 			/* Has it been removed already ? */
8666 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8667 				IRB_REFRELE(save_ire->ire_bucket);
8668 				ire_refrele(save_ire);
8669 				break;
8670 			}
8671 
8672 			/*
8673 			 * In the case of multirouting, a copy
8674 			 * of the packet is made before it is sent.
8675 			 * The copy is used in the next
8676 			 * loop to attempt another resolution.
8677 			 */
8678 			xmit_mp = first_mp;
8679 			if ((sire != NULL) &&
8680 			    (sire->ire_flags & RTF_MULTIRT)) {
8681 				copy_mp = copymsg(first_mp);
8682 				if (copy_mp != NULL) {
8683 					xmit_mp = copy_mp;
8684 					MULTIRT_DEBUG_TAG(first_mp);
8685 				}
8686 			}
8687 			ire_add_then_send(q, ire, xmit_mp);
8688 
8689 			/* Assert that it is not deleted yet. */
8690 			ASSERT(save_ire->ire_ptpn != NULL);
8691 			IRB_REFRELE(save_ire->ire_bucket);
8692 			ire_refrele(save_ire);
8693 
8694 			if (copy_mp != NULL) {
8695 				/*
8696 				 * If we found a (no)resolver, we ignore any
8697 				 * trailing top priority IRE_CACHE in further
8698 				 * loops. This ensures that we do not omit any
8699 				 * (no)resolver.
8700 				 * This IRE_CACHE, if any, will be processed
8701 				 * by another thread entering ip_newroute().
8702 				 * IRE_CACHE entries, if any, will be processed
8703 				 * by another thread entering ip_newroute(),
8704 				 * (upon resolver response, for instance).
8705 				 * This aims to force parallel multirt
8706 				 * resolutions as soon as a packet must be sent.
8707 				 * In the best case, after the tx of only one
8708 				 * packet, all reachable routes are resolved.
8709 				 * Otherwise, the resolution of all RTF_MULTIRT
8710 				 * routes would require several emissions.
8711 				 */
8712 				multirt_flags &= ~MULTIRT_CACHEGW;
8713 
8714 				/*
8715 				 * Search for the next unresolved multirt
8716 				 * route.
8717 				 */
8718 				copy_mp = NULL;
8719 				save_ire = NULL;
8720 				ire = NULL;
8721 				multirt_resolve_next = B_TRUE;
8722 				continue;
8723 			}
8724 
8725 			/*
8726 			 * Don't need sire anymore
8727 			 */
8728 			if (sire != NULL)
8729 				ire_refrele(sire);
8730 
8731 			ipif_refrele(src_ipif);
8732 			ill_refrele(dst_ill);
8733 			return;
8734 		}
8735 		case IRE_IF_RESOLVER:
8736 			/*
8737 			 * We can't build an IRE_CACHE yet, but at least we
8738 			 * found a resolver that can help.
8739 			 */
8740 			res_mp = dst_ill->ill_resolver_mp;
8741 			if (!OK_RESOLVER_MP(res_mp))
8742 				break;
8743 
8744 			/*
8745 			 * To be at this point in the code with a non-zero gw
8746 			 * means that dst is reachable through a gateway that
8747 			 * we have never resolved.  By changing dst to the gw
8748 			 * addr we resolve the gateway first.
8749 			 * When ire_add_then_send() tries to put the IP dg
8750 			 * to dst, it will reenter ip_newroute() at which
8751 			 * time we will find the IRE_CACHE for the gw and
8752 			 * create another IRE_CACHE in case IRE_CACHE above.
8753 			 */
8754 			if (gw != INADDR_ANY) {
8755 				/*
8756 				 * The source ipif that was determined above was
8757 				 * relative to the destination address, not the
8758 				 * gateway's. If src_ipif was not taken out of
8759 				 * the IRE_IF_RESOLVER entry, we'll need to call
8760 				 * ipif_select_source() again.
8761 				 */
8762 				if (src_ipif != ire->ire_ipif) {
8763 					ipif_refrele(src_ipif);
8764 					src_ipif = ipif_select_source(dst_ill,
8765 					    gw, zoneid);
8766 					/*
8767 					 * In the case of multirouting, it may
8768 					 * happen that ipif_select_source fails
8769 					 * as DAD may disallow use of the
8770 					 * particular source interface.  Anyway,
8771 					 * we need to continue and attempt to
8772 					 * resolve other multirt routes.
8773 					 */
8774 					if (src_ipif == NULL) {
8775 						if (sire != NULL &&
8776 						    (sire->ire_flags &
8777 						    RTF_MULTIRT)) {
8778 							ire_refrele(ire);
8779 							ire = NULL;
8780 							multirt_resolve_next =
8781 							    B_TRUE;
8782 							multirt_res_failures++;
8783 							continue;
8784 						}
8785 						if (ip_debug > 2) {
8786 							pr_addr_dbg(
8787 							    "ip_newroute: no "
8788 							    "src for gw %s ",
8789 							    AF_INET, &gw);
8790 							printf("on "
8791 							    "interface %s\n",
8792 							    dst_ill->ill_name);
8793 						}
8794 						goto icmp_err_ret;
8795 					}
8796 				}
8797 				save_dst = dst;
8798 				dst = gw;
8799 				gw = INADDR_ANY;
8800 			}
8801 
8802 			/*
8803 			 * We obtain a partial IRE_CACHE which we will pass
8804 			 * along with the resolver query.  When the response
8805 			 * comes back it will be there ready for us to add.
8806 			 * The ire_max_frag is atomically set under the
8807 			 * irebucket lock in ire_add_v[46].
8808 			 */
8809 
8810 			ire = ire_create_mp(
8811 			    (uchar_t *)&dst,		/* dest address */
8812 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8813 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8814 			    (uchar_t *)&gw,		/* gateway address */
8815 			    NULL,			/* ire_max_frag */
8816 			    NULL,			/* no src nce */
8817 			    dst_ill->ill_rq,		/* recv-from queue */
8818 			    dst_ill->ill_wq,		/* send-to queue */
8819 			    IRE_CACHE,
8820 			    src_ipif,			/* Interface ipif */
8821 			    save_ire->ire_mask,		/* Parent mask */
8822 			    0,
8823 			    save_ire->ire_ihandle,	/* Interface handle */
8824 			    0,				/* flags if any */
8825 			    &(save_ire->ire_uinfo),
8826 			    NULL,
8827 			    NULL,
8828 			    ipst);
8829 
8830 			if (ire == NULL) {
8831 				ire_refrele(save_ire);
8832 				break;
8833 			}
8834 
8835 			if ((sire != NULL) &&
8836 			    (sire->ire_flags & RTF_MULTIRT)) {
8837 				copy_mp = copymsg(first_mp);
8838 				if (copy_mp != NULL)
8839 					MULTIRT_DEBUG_TAG(copy_mp);
8840 			}
8841 
8842 			ire->ire_marks |= ire_marks;
8843 
8844 			/*
8845 			 * Construct message chain for the resolver
8846 			 * of the form:
8847 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8848 			 * Packet could contain a IPSEC_OUT mp.
8849 			 *
8850 			 * NOTE : ire will be added later when the response
8851 			 * comes back from ARP. If the response does not
8852 			 * come back, ARP frees the packet. For this reason,
8853 			 * we can't REFHOLD the bucket of save_ire to prevent
8854 			 * deletions. We may not be able to REFRELE the bucket
8855 			 * if the response never comes back. Thus, before
8856 			 * adding the ire, ire_add_v4 will make sure that the
8857 			 * interface route does not get deleted. This is the
8858 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8859 			 * where we can always prevent deletions because of
8860 			 * the synchronous nature of adding IRES i.e
8861 			 * ire_add_then_send is called after creating the IRE.
8862 			 */
8863 			ASSERT(ire->ire_mp != NULL);
8864 			ire->ire_mp->b_cont = first_mp;
8865 			/* Have saved_mp handy, for cleanup if canput fails */
8866 			saved_mp = mp;
8867 			mp = copyb(res_mp);
8868 			if (mp == NULL) {
8869 				/* Prepare for cleanup */
8870 				mp = saved_mp; /* pkt */
8871 				ire_delete(ire); /* ire_mp */
8872 				ire = NULL;
8873 				ire_refrele(save_ire);
8874 				if (copy_mp != NULL) {
8875 					MULTIRT_DEBUG_UNTAG(copy_mp);
8876 					freemsg(copy_mp);
8877 					copy_mp = NULL;
8878 				}
8879 				break;
8880 			}
8881 			linkb(mp, ire->ire_mp);
8882 
8883 			/*
8884 			 * Fill in the source and dest addrs for the resolver.
8885 			 * NOTE: this depends on memory layouts imposed by
8886 			 * ill_init().
8887 			 */
8888 			areq = (areq_t *)mp->b_rptr;
8889 			addrp = (ipaddr_t *)((char *)areq +
8890 			    areq->areq_sender_addr_offset);
8891 			*addrp = save_ire->ire_src_addr;
8892 
8893 			ire_refrele(save_ire);
8894 			addrp = (ipaddr_t *)((char *)areq +
8895 			    areq->areq_target_addr_offset);
8896 			*addrp = dst;
8897 			/* Up to the resolver. */
8898 			if (canputnext(dst_ill->ill_rq) &&
8899 			    !(dst_ill->ill_arp_closing)) {
8900 				putnext(dst_ill->ill_rq, mp);
8901 				ire = NULL;
8902 				if (copy_mp != NULL) {
8903 					/*
8904 					 * If we found a resolver, we ignore
8905 					 * any trailing top priority IRE_CACHE
8906 					 * in the further loops. This ensures
8907 					 * that we do not omit any resolver.
8908 					 * IRE_CACHE entries, if any, will be
8909 					 * processed next time we enter
8910 					 * ip_newroute().
8911 					 */
8912 					multirt_flags &= ~MULTIRT_CACHEGW;
8913 					/*
8914 					 * Search for the next unresolved
8915 					 * multirt route.
8916 					 */
8917 					first_mp = copy_mp;
8918 					copy_mp = NULL;
8919 					/* Prepare the next resolution loop. */
8920 					mp = first_mp;
8921 					EXTRACT_PKT_MP(mp, first_mp,
8922 					    mctl_present);
8923 					if (mctl_present)
8924 						io = (ipsec_out_t *)
8925 						    first_mp->b_rptr;
8926 					ipha = (ipha_t *)mp->b_rptr;
8927 
8928 					ASSERT(sire != NULL);
8929 
8930 					dst = save_dst;
8931 					multirt_resolve_next = B_TRUE;
8932 					continue;
8933 				}
8934 
8935 				if (sire != NULL)
8936 					ire_refrele(sire);
8937 
8938 				/*
8939 				 * The response will come back in ip_wput
8940 				 * with db_type IRE_DB_TYPE.
8941 				 */
8942 				ipif_refrele(src_ipif);
8943 				ill_refrele(dst_ill);
8944 				return;
8945 			} else {
8946 				/* Prepare for cleanup */
8947 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8948 				    mp);
8949 				mp->b_cont = NULL;
8950 				freeb(mp); /* areq */
8951 				/*
8952 				 * this is an ire that is not added to the
8953 				 * cache. ire_freemblk will handle the release
8954 				 * of any resources associated with the ire.
8955 				 */
8956 				ire_delete(ire); /* ire_mp */
8957 				mp = saved_mp; /* pkt */
8958 				ire = NULL;
8959 				if (copy_mp != NULL) {
8960 					MULTIRT_DEBUG_UNTAG(copy_mp);
8961 					freemsg(copy_mp);
8962 					copy_mp = NULL;
8963 				}
8964 				break;
8965 			}
8966 		default:
8967 			break;
8968 		}
8969 	} while (multirt_resolve_next);
8970 
8971 	ip1dbg(("ip_newroute: dropped\n"));
8972 	/* Did this packet originate externally? */
8973 	if (mp->b_prev) {
8974 		mp->b_next = NULL;
8975 		mp->b_prev = NULL;
8976 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8977 	} else {
8978 		if (dst_ill != NULL) {
8979 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8980 		} else {
8981 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8982 		}
8983 	}
8984 	ASSERT(copy_mp == NULL);
8985 	MULTIRT_DEBUG_UNTAG(first_mp);
8986 	freemsg(first_mp);
8987 	if (ire != NULL)
8988 		ire_refrele(ire);
8989 	if (sire != NULL)
8990 		ire_refrele(sire);
8991 	if (src_ipif != NULL)
8992 		ipif_refrele(src_ipif);
8993 	if (dst_ill != NULL)
8994 		ill_refrele(dst_ill);
8995 	return;
8996 
8997 icmp_err_ret:
8998 	ip1dbg(("ip_newroute: no route\n"));
8999 	if (src_ipif != NULL)
9000 		ipif_refrele(src_ipif);
9001 	if (dst_ill != NULL)
9002 		ill_refrele(dst_ill);
9003 	if (sire != NULL)
9004 		ire_refrele(sire);
9005 	/* Did this packet originate externally? */
9006 	if (mp->b_prev) {
9007 		mp->b_next = NULL;
9008 		mp->b_prev = NULL;
9009 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9010 		q = WR(q);
9011 	} else {
9012 		/*
9013 		 * There is no outgoing ill, so just increment the
9014 		 * system MIB.
9015 		 */
9016 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9017 		/*
9018 		 * Since ip_wput() isn't close to finished, we fill
9019 		 * in enough of the header for credible error reporting.
9020 		 */
9021 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9022 			/* Failed */
9023 			MULTIRT_DEBUG_UNTAG(first_mp);
9024 			freemsg(first_mp);
9025 			if (ire != NULL)
9026 				ire_refrele(ire);
9027 			return;
9028 		}
9029 	}
9030 
9031 	/*
9032 	 * At this point we will have ire only if RTF_BLACKHOLE
9033 	 * or RTF_REJECT flags are set on the IRE. It will not
9034 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9035 	 */
9036 	if (ire != NULL) {
9037 		if (ire->ire_flags & RTF_BLACKHOLE) {
9038 			ire_refrele(ire);
9039 			MULTIRT_DEBUG_UNTAG(first_mp);
9040 			freemsg(first_mp);
9041 			return;
9042 		}
9043 		ire_refrele(ire);
9044 	}
9045 	if (ip_source_routed(ipha, ipst)) {
9046 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9047 		    zoneid, ipst);
9048 		return;
9049 	}
9050 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9051 }
9052 
9053 ip_opt_info_t zero_info;
9054 
9055 /*
9056  * IPv4 -
9057  * ip_newroute_ipif is called by ip_wput_multicast and
9058  * ip_rput_forward_multicast whenever we need to send
9059  * out a packet to a destination address for which we do not have specific
9060  * routing information. It is used when the packet will be sent out
9061  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9062  * socket option is set or icmp error message wants to go out on a particular
9063  * interface for a unicast packet.
9064  *
9065  * In most cases, the destination address is resolved thanks to the ipif
9066  * intrinsic resolver. However, there are some cases where the call to
9067  * ip_newroute_ipif must take into account the potential presence of
9068  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9069  * that uses the interface. This is specified through flags,
9070  * which can be a combination of:
9071  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9072  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9073  *   and flags. Additionally, the packet source address has to be set to
9074  *   the specified address. The caller is thus expected to set this flag
9075  *   if the packet has no specific source address yet.
9076  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9077  *   flag, the resulting ire will inherit the flag. All unresolved routes
9078  *   to the destination must be explored in the same call to
9079  *   ip_newroute_ipif().
9080  */
9081 static void
9082 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9083     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9084 {
9085 	areq_t	*areq;
9086 	ire_t	*ire = NULL;
9087 	mblk_t	*res_mp;
9088 	ipaddr_t *addrp;
9089 	mblk_t *first_mp;
9090 	ire_t	*save_ire = NULL;
9091 	ipif_t	*src_ipif = NULL;
9092 	ushort_t ire_marks = 0;
9093 	ill_t	*dst_ill = NULL;
9094 	ipha_t *ipha;
9095 	mblk_t	*saved_mp;
9096 	ire_t   *fire = NULL;
9097 	mblk_t  *copy_mp = NULL;
9098 	boolean_t multirt_resolve_next;
9099 	boolean_t unspec_src;
9100 	ipaddr_t ipha_dst;
9101 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9102 
9103 	/*
9104 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9105 	 * here for uniformity
9106 	 */
9107 	ipif_refhold(ipif);
9108 
9109 	/*
9110 	 * This loop is run only once in most cases.
9111 	 * We loop to resolve further routes only when the destination
9112 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9113 	 */
9114 	do {
9115 		if (dst_ill != NULL) {
9116 			ill_refrele(dst_ill);
9117 			dst_ill = NULL;
9118 		}
9119 		if (src_ipif != NULL) {
9120 			ipif_refrele(src_ipif);
9121 			src_ipif = NULL;
9122 		}
9123 		multirt_resolve_next = B_FALSE;
9124 
9125 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9126 		    ipif->ipif_ill->ill_name));
9127 
9128 		first_mp = mp;
9129 		if (DB_TYPE(mp) == M_CTL)
9130 			mp = mp->b_cont;
9131 		ipha = (ipha_t *)mp->b_rptr;
9132 
9133 		/*
9134 		 * Save the packet destination address, we may need it after
9135 		 * the packet has been consumed.
9136 		 */
9137 		ipha_dst = ipha->ipha_dst;
9138 
9139 		/*
9140 		 * If the interface is a pt-pt interface we look for an
9141 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9142 		 * local_address and the pt-pt destination address. Otherwise
9143 		 * we just match the local address.
9144 		 * NOTE: dst could be different than ipha->ipha_dst in case
9145 		 * of sending igmp multicast packets over a point-to-point
9146 		 * connection.
9147 		 * Thus we must be careful enough to check ipha_dst to be a
9148 		 * multicast address, otherwise it will take xmit_if path for
9149 		 * multicast packets resulting into kernel stack overflow by
9150 		 * repeated calls to ip_newroute_ipif from ire_send().
9151 		 */
9152 		if (CLASSD(ipha_dst) &&
9153 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9154 			goto err_ret;
9155 		}
9156 
9157 		/*
9158 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9159 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9160 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9161 		 * propagate its flags to the new ire.
9162 		 */
9163 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9164 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9165 			ip2dbg(("ip_newroute_ipif: "
9166 			    "ipif_lookup_multi_ire("
9167 			    "ipif %p, dst %08x) = fire %p\n",
9168 			    (void *)ipif, ntohl(dst), (void *)fire));
9169 		}
9170 
9171 		/*
9172 		 * Note: While we pick a dst_ill we are really only
9173 		 * interested in the ill for load spreading. The source
9174 		 * ipif is determined by source address selection below.
9175 		 */
9176 		if (IS_IPMP(ipif->ipif_ill)) {
9177 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9178 
9179 			if (CLASSD(ipha_dst))
9180 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9181 			else
9182 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9183 		} else {
9184 			dst_ill = ipif->ipif_ill;
9185 			ill_refhold(dst_ill);
9186 		}
9187 
9188 		if (dst_ill == NULL) {
9189 			if (ip_debug > 2) {
9190 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9191 				    "for dst %s\n", AF_INET, &dst);
9192 			}
9193 			goto err_ret;
9194 		}
9195 
9196 		/*
9197 		 * Pick a source address preferring non-deprecated ones.
9198 		 * Unlike ip_newroute, we don't do any source address
9199 		 * selection here since for multicast it really does not help
9200 		 * in inbound load spreading as in the unicast case.
9201 		 */
9202 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9203 		    (fire->ire_flags & RTF_SETSRC)) {
9204 			/*
9205 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9206 			 * on that interface. This ire has RTF_SETSRC flag, so
9207 			 * the source address of the packet must be changed.
9208 			 * Check that the ipif matching the requested source
9209 			 * address still exists.
9210 			 */
9211 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9212 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9213 		}
9214 
9215 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9216 
9217 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9218 		    (IS_IPMP(ipif->ipif_ill) ||
9219 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9220 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9221 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9222 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9223 		    (src_ipif == NULL) &&
9224 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9225 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9226 			if (src_ipif == NULL) {
9227 				if (ip_debug > 2) {
9228 					/* ip1dbg */
9229 					pr_addr_dbg("ip_newroute_ipif: "
9230 					    "no src for dst %s",
9231 					    AF_INET, &dst);
9232 				}
9233 				ip1dbg((" on interface %s\n",
9234 				    dst_ill->ill_name));
9235 				goto err_ret;
9236 			}
9237 			ipif_refrele(ipif);
9238 			ipif = src_ipif;
9239 			ipif_refhold(ipif);
9240 		}
9241 		if (src_ipif == NULL) {
9242 			src_ipif = ipif;
9243 			ipif_refhold(src_ipif);
9244 		}
9245 
9246 		/*
9247 		 * Assign a source address while we have the conn.
9248 		 * We can't have ip_wput_ire pick a source address when the
9249 		 * packet returns from arp since conn_unspec_src might be set
9250 		 * and we lose the conn when going through arp.
9251 		 */
9252 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9253 			ipha->ipha_src = src_ipif->ipif_src_addr;
9254 
9255 		/*
9256 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9257 		 * that the outgoing interface does not have an interface ire.
9258 		 */
9259 		if (CLASSD(ipha_dst) && (connp == NULL ||
9260 		    connp->conn_outgoing_ill == NULL) &&
9261 		    infop->ip_opt_ill_index == 0) {
9262 			/* ipif_to_ire returns an held ire */
9263 			ire = ipif_to_ire(ipif);
9264 			if (ire == NULL)
9265 				goto err_ret;
9266 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9267 				goto err_ret;
9268 			save_ire = ire;
9269 
9270 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9271 			    "flags %04x\n",
9272 			    (void *)ire, (void *)ipif, flags));
9273 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9274 			    (fire->ire_flags & RTF_MULTIRT)) {
9275 				/*
9276 				 * As requested by flags, an IRE_OFFSUBNET was
9277 				 * looked up on that interface. This ire has
9278 				 * RTF_MULTIRT flag, so the resolution loop will
9279 				 * be re-entered to resolve additional routes on
9280 				 * other interfaces. For that purpose, a copy of
9281 				 * the packet is performed at this point.
9282 				 */
9283 				fire->ire_last_used_time = lbolt;
9284 				copy_mp = copymsg(first_mp);
9285 				if (copy_mp) {
9286 					MULTIRT_DEBUG_TAG(copy_mp);
9287 				}
9288 			}
9289 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9290 			    (fire->ire_flags & RTF_SETSRC)) {
9291 				/*
9292 				 * As requested by flags, an IRE_OFFSUBET was
9293 				 * looked up on that interface. This ire has
9294 				 * RTF_SETSRC flag, so the source address of the
9295 				 * packet must be changed.
9296 				 */
9297 				ipha->ipha_src = fire->ire_src_addr;
9298 			}
9299 		} else {
9300 			/*
9301 			 * The only ways we can come here are:
9302 			 * 1) IP_BOUND_IF socket option is set
9303 			 * 2) SO_DONTROUTE socket option is set
9304 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9305 			 * In all cases, the new ire will not be added
9306 			 * into cache table.
9307 			 */
9308 			ASSERT(connp == NULL || connp->conn_dontroute ||
9309 			    connp->conn_outgoing_ill != NULL ||
9310 			    infop->ip_opt_ill_index != 0);
9311 			ire_marks |= IRE_MARK_NOADD;
9312 		}
9313 
9314 		switch (ipif->ipif_net_type) {
9315 		case IRE_IF_NORESOLVER: {
9316 			/* We have what we need to build an IRE_CACHE. */
9317 
9318 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9319 			    (dst_ill->ill_resolver_mp == NULL)) {
9320 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9321 				    "for IRE_IF_NORESOLVER ire %p has "
9322 				    "no ill_resolver_mp\n",
9323 				    (void *)dst_ill, (void *)ire));
9324 				break;
9325 			}
9326 
9327 			/*
9328 			 * The new ire inherits the IRE_OFFSUBNET flags
9329 			 * and source address, if this was requested.
9330 			 */
9331 			ire = ire_create(
9332 			    (uchar_t *)&dst,		/* dest address */
9333 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9334 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9335 			    NULL,			/* gateway address */
9336 			    &ipif->ipif_mtu,
9337 			    NULL,			/* no src nce */
9338 			    dst_ill->ill_rq,		/* recv-from queue */
9339 			    dst_ill->ill_wq,		/* send-to queue */
9340 			    IRE_CACHE,
9341 			    src_ipif,
9342 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9343 			    (fire != NULL) ?		/* Parent handle */
9344 			    fire->ire_phandle : 0,
9345 			    (save_ire != NULL) ?	/* Interface handle */
9346 			    save_ire->ire_ihandle : 0,
9347 			    (fire != NULL) ?
9348 			    (fire->ire_flags &
9349 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9350 			    (save_ire == NULL ? &ire_uinfo_null :
9351 			    &save_ire->ire_uinfo),
9352 			    NULL,
9353 			    NULL,
9354 			    ipst);
9355 
9356 			if (ire == NULL) {
9357 				if (save_ire != NULL)
9358 					ire_refrele(save_ire);
9359 				break;
9360 			}
9361 
9362 			ire->ire_marks |= ire_marks;
9363 
9364 			/*
9365 			 * If IRE_MARK_NOADD is set then we need to convert
9366 			 * the max_fragp to a useable value now. This is
9367 			 * normally done in ire_add_v[46]. We also need to
9368 			 * associate the ire with an nce (normally would be
9369 			 * done in ip_wput_nondata()).
9370 			 *
9371 			 * Note that IRE_MARK_NOADD packets created here
9372 			 * do not have a non-null ire_mp pointer. The null
9373 			 * value of ire_bucket indicates that they were
9374 			 * never added.
9375 			 */
9376 			if (ire->ire_marks & IRE_MARK_NOADD) {
9377 				uint_t  max_frag;
9378 
9379 				max_frag = *ire->ire_max_fragp;
9380 				ire->ire_max_fragp = NULL;
9381 				ire->ire_max_frag = max_frag;
9382 
9383 				if ((ire->ire_nce = ndp_lookup_v4(
9384 				    ire_to_ill(ire),
9385 				    (ire->ire_gateway_addr != INADDR_ANY ?
9386 				    &ire->ire_gateway_addr : &ire->ire_addr),
9387 				    B_FALSE)) == NULL) {
9388 					if (save_ire != NULL)
9389 						ire_refrele(save_ire);
9390 					break;
9391 				}
9392 				ASSERT(ire->ire_nce->nce_state ==
9393 				    ND_REACHABLE);
9394 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9395 			}
9396 
9397 			/* Prevent save_ire from getting deleted */
9398 			if (save_ire != NULL) {
9399 				IRB_REFHOLD(save_ire->ire_bucket);
9400 				/* Has it been removed already ? */
9401 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9402 					IRB_REFRELE(save_ire->ire_bucket);
9403 					ire_refrele(save_ire);
9404 					break;
9405 				}
9406 			}
9407 
9408 			ire_add_then_send(q, ire, first_mp);
9409 
9410 			/* Assert that save_ire is not deleted yet. */
9411 			if (save_ire != NULL) {
9412 				ASSERT(save_ire->ire_ptpn != NULL);
9413 				IRB_REFRELE(save_ire->ire_bucket);
9414 				ire_refrele(save_ire);
9415 				save_ire = NULL;
9416 			}
9417 			if (fire != NULL) {
9418 				ire_refrele(fire);
9419 				fire = NULL;
9420 			}
9421 
9422 			/*
9423 			 * the resolution loop is re-entered if this
9424 			 * was requested through flags and if we
9425 			 * actually are in a multirouting case.
9426 			 */
9427 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9428 				boolean_t need_resolve =
9429 				    ire_multirt_need_resolve(ipha_dst,
9430 				    msg_getlabel(copy_mp), ipst);
9431 				if (!need_resolve) {
9432 					MULTIRT_DEBUG_UNTAG(copy_mp);
9433 					freemsg(copy_mp);
9434 					copy_mp = NULL;
9435 				} else {
9436 					/*
9437 					 * ipif_lookup_group() calls
9438 					 * ire_lookup_multi() that uses
9439 					 * ire_ftable_lookup() to find
9440 					 * an IRE_INTERFACE for the group.
9441 					 * In the multirt case,
9442 					 * ire_lookup_multi() then invokes
9443 					 * ire_multirt_lookup() to find
9444 					 * the next resolvable ire.
9445 					 * As a result, we obtain an new
9446 					 * interface, derived from the
9447 					 * next ire.
9448 					 */
9449 					ipif_refrele(ipif);
9450 					ipif = ipif_lookup_group(ipha_dst,
9451 					    zoneid, ipst);
9452 					ip2dbg(("ip_newroute_ipif: "
9453 					    "multirt dst %08x, ipif %p\n",
9454 					    htonl(dst), (void *)ipif));
9455 					if (ipif != NULL) {
9456 						mp = copy_mp;
9457 						copy_mp = NULL;
9458 						multirt_resolve_next = B_TRUE;
9459 						continue;
9460 					} else {
9461 						freemsg(copy_mp);
9462 					}
9463 				}
9464 			}
9465 			if (ipif != NULL)
9466 				ipif_refrele(ipif);
9467 			ill_refrele(dst_ill);
9468 			ipif_refrele(src_ipif);
9469 			return;
9470 		}
9471 		case IRE_IF_RESOLVER:
9472 			/*
9473 			 * We can't build an IRE_CACHE yet, but at least
9474 			 * we found a resolver that can help.
9475 			 */
9476 			res_mp = dst_ill->ill_resolver_mp;
9477 			if (!OK_RESOLVER_MP(res_mp))
9478 				break;
9479 
9480 			/*
9481 			 * We obtain a partial IRE_CACHE which we will pass
9482 			 * along with the resolver query.  When the response
9483 			 * comes back it will be there ready for us to add.
9484 			 * The new ire inherits the IRE_OFFSUBNET flags
9485 			 * and source address, if this was requested.
9486 			 * The ire_max_frag is atomically set under the
9487 			 * irebucket lock in ire_add_v[46]. Only in the
9488 			 * case of IRE_MARK_NOADD, we set it here itself.
9489 			 */
9490 			ire = ire_create_mp(
9491 			    (uchar_t *)&dst,		/* dest address */
9492 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9493 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9494 			    NULL,			/* gateway address */
9495 			    (ire_marks & IRE_MARK_NOADD) ?
9496 			    ipif->ipif_mtu : 0,		/* max_frag */
9497 			    NULL,			/* no src nce */
9498 			    dst_ill->ill_rq,		/* recv-from queue */
9499 			    dst_ill->ill_wq,		/* send-to queue */
9500 			    IRE_CACHE,
9501 			    src_ipif,
9502 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9503 			    (fire != NULL) ?		/* Parent handle */
9504 			    fire->ire_phandle : 0,
9505 			    (save_ire != NULL) ?	/* Interface handle */
9506 			    save_ire->ire_ihandle : 0,
9507 			    (fire != NULL) ?		/* flags if any */
9508 			    (fire->ire_flags &
9509 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9510 			    (save_ire == NULL ? &ire_uinfo_null :
9511 			    &save_ire->ire_uinfo),
9512 			    NULL,
9513 			    NULL,
9514 			    ipst);
9515 
9516 			if (save_ire != NULL) {
9517 				ire_refrele(save_ire);
9518 				save_ire = NULL;
9519 			}
9520 			if (ire == NULL)
9521 				break;
9522 
9523 			ire->ire_marks |= ire_marks;
9524 			/*
9525 			 * Construct message chain for the resolver of the
9526 			 * form:
9527 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9528 			 *
9529 			 * NOTE : ire will be added later when the response
9530 			 * comes back from ARP. If the response does not
9531 			 * come back, ARP frees the packet. For this reason,
9532 			 * we can't REFHOLD the bucket of save_ire to prevent
9533 			 * deletions. We may not be able to REFRELE the
9534 			 * bucket if the response never comes back.
9535 			 * Thus, before adding the ire, ire_add_v4 will make
9536 			 * sure that the interface route does not get deleted.
9537 			 * This is the only case unlike ip_newroute_v6,
9538 			 * ip_newroute_ipif_v6 where we can always prevent
9539 			 * deletions because ire_add_then_send is called after
9540 			 * creating the IRE.
9541 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9542 			 * does not add this IRE into the IRE CACHE.
9543 			 */
9544 			ASSERT(ire->ire_mp != NULL);
9545 			ire->ire_mp->b_cont = first_mp;
9546 			/* Have saved_mp handy, for cleanup if canput fails */
9547 			saved_mp = mp;
9548 			mp = copyb(res_mp);
9549 			if (mp == NULL) {
9550 				/* Prepare for cleanup */
9551 				mp = saved_mp; /* pkt */
9552 				ire_delete(ire); /* ire_mp */
9553 				ire = NULL;
9554 				if (copy_mp != NULL) {
9555 					MULTIRT_DEBUG_UNTAG(copy_mp);
9556 					freemsg(copy_mp);
9557 					copy_mp = NULL;
9558 				}
9559 				break;
9560 			}
9561 			linkb(mp, ire->ire_mp);
9562 
9563 			/*
9564 			 * Fill in the source and dest addrs for the resolver.
9565 			 * NOTE: this depends on memory layouts imposed by
9566 			 * ill_init().  There are corner cases above where we
9567 			 * might've created the IRE with an INADDR_ANY source
9568 			 * address (e.g., if the zeroth ipif on an underlying
9569 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9570 			 * on the ill has a usable test address).  If so, tell
9571 			 * ARP to use ipha_src as its sender address.
9572 			 */
9573 			areq = (areq_t *)mp->b_rptr;
9574 			addrp = (ipaddr_t *)((char *)areq +
9575 			    areq->areq_sender_addr_offset);
9576 			if (ire->ire_src_addr != INADDR_ANY)
9577 				*addrp = ire->ire_src_addr;
9578 			else
9579 				*addrp = ipha->ipha_src;
9580 			addrp = (ipaddr_t *)((char *)areq +
9581 			    areq->areq_target_addr_offset);
9582 			*addrp = dst;
9583 			/* Up to the resolver. */
9584 			if (canputnext(dst_ill->ill_rq) &&
9585 			    !(dst_ill->ill_arp_closing)) {
9586 				putnext(dst_ill->ill_rq, mp);
9587 				/*
9588 				 * The response will come back in ip_wput
9589 				 * with db_type IRE_DB_TYPE.
9590 				 */
9591 			} else {
9592 				mp->b_cont = NULL;
9593 				freeb(mp); /* areq */
9594 				ire_delete(ire); /* ire_mp */
9595 				saved_mp->b_next = NULL;
9596 				saved_mp->b_prev = NULL;
9597 				freemsg(first_mp); /* pkt */
9598 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9599 			}
9600 
9601 			if (fire != NULL) {
9602 				ire_refrele(fire);
9603 				fire = NULL;
9604 			}
9605 
9606 			/*
9607 			 * The resolution loop is re-entered if this was
9608 			 * requested through flags and we actually are
9609 			 * in a multirouting case.
9610 			 */
9611 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9612 				boolean_t need_resolve =
9613 				    ire_multirt_need_resolve(ipha_dst,
9614 				    msg_getlabel(copy_mp), ipst);
9615 				if (!need_resolve) {
9616 					MULTIRT_DEBUG_UNTAG(copy_mp);
9617 					freemsg(copy_mp);
9618 					copy_mp = NULL;
9619 				} else {
9620 					/*
9621 					 * ipif_lookup_group() calls
9622 					 * ire_lookup_multi() that uses
9623 					 * ire_ftable_lookup() to find
9624 					 * an IRE_INTERFACE for the group.
9625 					 * In the multirt case,
9626 					 * ire_lookup_multi() then invokes
9627 					 * ire_multirt_lookup() to find
9628 					 * the next resolvable ire.
9629 					 * As a result, we obtain an new
9630 					 * interface, derived from the
9631 					 * next ire.
9632 					 */
9633 					ipif_refrele(ipif);
9634 					ipif = ipif_lookup_group(ipha_dst,
9635 					    zoneid, ipst);
9636 					if (ipif != NULL) {
9637 						mp = copy_mp;
9638 						copy_mp = NULL;
9639 						multirt_resolve_next = B_TRUE;
9640 						continue;
9641 					} else {
9642 						freemsg(copy_mp);
9643 					}
9644 				}
9645 			}
9646 			if (ipif != NULL)
9647 				ipif_refrele(ipif);
9648 			ill_refrele(dst_ill);
9649 			ipif_refrele(src_ipif);
9650 			return;
9651 		default:
9652 			break;
9653 		}
9654 	} while (multirt_resolve_next);
9655 
9656 err_ret:
9657 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9658 	if (fire != NULL)
9659 		ire_refrele(fire);
9660 	ipif_refrele(ipif);
9661 	/* Did this packet originate externally? */
9662 	if (dst_ill != NULL)
9663 		ill_refrele(dst_ill);
9664 	if (src_ipif != NULL)
9665 		ipif_refrele(src_ipif);
9666 	if (mp->b_prev || mp->b_next) {
9667 		mp->b_next = NULL;
9668 		mp->b_prev = NULL;
9669 	} else {
9670 		/*
9671 		 * Since ip_wput() isn't close to finished, we fill
9672 		 * in enough of the header for credible error reporting.
9673 		 */
9674 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9675 			/* Failed */
9676 			freemsg(first_mp);
9677 			if (ire != NULL)
9678 				ire_refrele(ire);
9679 			return;
9680 		}
9681 	}
9682 	/*
9683 	 * At this point we will have ire only if RTF_BLACKHOLE
9684 	 * or RTF_REJECT flags are set on the IRE. It will not
9685 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9686 	 */
9687 	if (ire != NULL) {
9688 		if (ire->ire_flags & RTF_BLACKHOLE) {
9689 			ire_refrele(ire);
9690 			freemsg(first_mp);
9691 			return;
9692 		}
9693 		ire_refrele(ire);
9694 	}
9695 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9696 }
9697 
9698 /* Name/Value Table Lookup Routine */
9699 char *
9700 ip_nv_lookup(nv_t *nv, int value)
9701 {
9702 	if (!nv)
9703 		return (NULL);
9704 	for (; nv->nv_name; nv++) {
9705 		if (nv->nv_value == value)
9706 			return (nv->nv_name);
9707 	}
9708 	return ("unknown");
9709 }
9710 
9711 /*
9712  * This is a module open, i.e. this is a control stream for access
9713  * to a DLPI device.  We allocate an ill_t as the instance data in
9714  * this case.
9715  */
9716 int
9717 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9718 {
9719 	ill_t	*ill;
9720 	int	err;
9721 	zoneid_t zoneid;
9722 	netstack_t *ns;
9723 	ip_stack_t *ipst;
9724 
9725 	/*
9726 	 * Prevent unprivileged processes from pushing IP so that
9727 	 * they can't send raw IP.
9728 	 */
9729 	if (secpolicy_net_rawaccess(credp) != 0)
9730 		return (EPERM);
9731 
9732 	ns = netstack_find_by_cred(credp);
9733 	ASSERT(ns != NULL);
9734 	ipst = ns->netstack_ip;
9735 	ASSERT(ipst != NULL);
9736 
9737 	/*
9738 	 * For exclusive stacks we set the zoneid to zero
9739 	 * to make IP operate as if in the global zone.
9740 	 */
9741 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9742 		zoneid = GLOBAL_ZONEID;
9743 	else
9744 		zoneid = crgetzoneid(credp);
9745 
9746 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9747 	q->q_ptr = WR(q)->q_ptr = ill;
9748 	ill->ill_ipst = ipst;
9749 	ill->ill_zoneid = zoneid;
9750 
9751 	/*
9752 	 * ill_init initializes the ill fields and then sends down
9753 	 * down a DL_INFO_REQ after calling qprocson.
9754 	 */
9755 	err = ill_init(q, ill);
9756 	if (err != 0) {
9757 		mi_free(ill);
9758 		netstack_rele(ipst->ips_netstack);
9759 		q->q_ptr = NULL;
9760 		WR(q)->q_ptr = NULL;
9761 		return (err);
9762 	}
9763 
9764 	/* ill_init initializes the ipsq marking this thread as writer */
9765 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9766 	/* Wait for the DL_INFO_ACK */
9767 	mutex_enter(&ill->ill_lock);
9768 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9769 		/*
9770 		 * Return value of 0 indicates a pending signal.
9771 		 */
9772 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9773 		if (err == 0) {
9774 			mutex_exit(&ill->ill_lock);
9775 			(void) ip_close(q, 0);
9776 			return (EINTR);
9777 		}
9778 	}
9779 	mutex_exit(&ill->ill_lock);
9780 
9781 	/*
9782 	 * ip_rput_other could have set an error  in ill_error on
9783 	 * receipt of M_ERROR.
9784 	 */
9785 
9786 	err = ill->ill_error;
9787 	if (err != 0) {
9788 		(void) ip_close(q, 0);
9789 		return (err);
9790 	}
9791 
9792 	ill->ill_credp = credp;
9793 	crhold(credp);
9794 
9795 	mutex_enter(&ipst->ips_ip_mi_lock);
9796 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9797 	    credp);
9798 	mutex_exit(&ipst->ips_ip_mi_lock);
9799 	if (err) {
9800 		(void) ip_close(q, 0);
9801 		return (err);
9802 	}
9803 	return (0);
9804 }
9805 
9806 /* For /dev/ip aka AF_INET open */
9807 int
9808 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9809 {
9810 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9811 }
9812 
9813 /* For /dev/ip6 aka AF_INET6 open */
9814 int
9815 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9816 {
9817 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9818 }
9819 
9820 /* IP open routine. */
9821 int
9822 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9823     boolean_t isv6)
9824 {
9825 	conn_t 		*connp;
9826 	major_t		maj;
9827 	zoneid_t	zoneid;
9828 	netstack_t	*ns;
9829 	ip_stack_t	*ipst;
9830 
9831 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9832 
9833 	/* Allow reopen. */
9834 	if (q->q_ptr != NULL)
9835 		return (0);
9836 
9837 	if (sflag & MODOPEN) {
9838 		/* This is a module open */
9839 		return (ip_modopen(q, devp, flag, sflag, credp));
9840 	}
9841 
9842 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9843 		/*
9844 		 * Non streams based socket looking for a stream
9845 		 * to access IP
9846 		 */
9847 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9848 		    credp, isv6));
9849 	}
9850 
9851 	ns = netstack_find_by_cred(credp);
9852 	ASSERT(ns != NULL);
9853 	ipst = ns->netstack_ip;
9854 	ASSERT(ipst != NULL);
9855 
9856 	/*
9857 	 * For exclusive stacks we set the zoneid to zero
9858 	 * to make IP operate as if in the global zone.
9859 	 */
9860 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9861 		zoneid = GLOBAL_ZONEID;
9862 	else
9863 		zoneid = crgetzoneid(credp);
9864 
9865 	/*
9866 	 * We are opening as a device. This is an IP client stream, and we
9867 	 * allocate an conn_t as the instance data.
9868 	 */
9869 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9870 
9871 	/*
9872 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9873 	 * done by netstack_find_by_cred()
9874 	 */
9875 	netstack_rele(ipst->ips_netstack);
9876 
9877 	connp->conn_zoneid = zoneid;
9878 	connp->conn_sqp = NULL;
9879 	connp->conn_initial_sqp = NULL;
9880 	connp->conn_final_sqp = NULL;
9881 
9882 	connp->conn_upq = q;
9883 	q->q_ptr = WR(q)->q_ptr = connp;
9884 
9885 	if (flag & SO_SOCKSTR)
9886 		connp->conn_flags |= IPCL_SOCKET;
9887 
9888 	/* Minor tells us which /dev entry was opened */
9889 	if (isv6) {
9890 		connp->conn_flags |= IPCL_ISV6;
9891 		connp->conn_af_isv6 = B_TRUE;
9892 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9893 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9894 	} else {
9895 		connp->conn_af_isv6 = B_FALSE;
9896 		connp->conn_pkt_isv6 = B_FALSE;
9897 	}
9898 
9899 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9900 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9901 		connp->conn_minor_arena = ip_minor_arena_la;
9902 	} else {
9903 		/*
9904 		 * Either minor numbers in the large arena were exhausted
9905 		 * or a non socket application is doing the open.
9906 		 * Try to allocate from the small arena.
9907 		 */
9908 		if ((connp->conn_dev =
9909 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9910 			/* CONN_DEC_REF takes care of netstack_rele() */
9911 			q->q_ptr = WR(q)->q_ptr = NULL;
9912 			CONN_DEC_REF(connp);
9913 			return (EBUSY);
9914 		}
9915 		connp->conn_minor_arena = ip_minor_arena_sa;
9916 	}
9917 
9918 	maj = getemajor(*devp);
9919 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9920 
9921 	/*
9922 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9923 	 */
9924 	connp->conn_cred = credp;
9925 
9926 	/*
9927 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9928 	 */
9929 	connp->conn_recv = ip_conn_input;
9930 
9931 	crhold(connp->conn_cred);
9932 
9933 	/*
9934 	 * If the caller has the process-wide flag set, then default to MAC
9935 	 * exempt mode.  This allows read-down to unlabeled hosts.
9936 	 */
9937 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9938 		connp->conn_mac_exempt = B_TRUE;
9939 
9940 	connp->conn_rq = q;
9941 	connp->conn_wq = WR(q);
9942 
9943 	/* Non-zero default values */
9944 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9945 
9946 	/*
9947 	 * Make the conn globally visible to walkers
9948 	 */
9949 	ASSERT(connp->conn_ref == 1);
9950 	mutex_enter(&connp->conn_lock);
9951 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9952 	mutex_exit(&connp->conn_lock);
9953 
9954 	qprocson(q);
9955 
9956 	return (0);
9957 }
9958 
9959 /*
9960  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9961  * Note that there is no race since either ip_output function works - it
9962  * is just an optimization to enter the best ip_output routine directly.
9963  */
9964 void
9965 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9966     ip_stack_t *ipst)
9967 {
9968 	if (isv6)  {
9969 		if (bump_mib) {
9970 			BUMP_MIB(&ipst->ips_ip6_mib,
9971 			    ipIfStatsOutSwitchIPVersion);
9972 		}
9973 		connp->conn_send = ip_output_v6;
9974 		connp->conn_pkt_isv6 = B_TRUE;
9975 	} else {
9976 		if (bump_mib) {
9977 			BUMP_MIB(&ipst->ips_ip_mib,
9978 			    ipIfStatsOutSwitchIPVersion);
9979 		}
9980 		connp->conn_send = ip_output;
9981 		connp->conn_pkt_isv6 = B_FALSE;
9982 	}
9983 
9984 }
9985 
9986 /*
9987  * See if IPsec needs loading because of the options in mp.
9988  */
9989 static boolean_t
9990 ipsec_opt_present(mblk_t *mp)
9991 {
9992 	uint8_t *optcp, *next_optcp, *opt_endcp;
9993 	struct opthdr *opt;
9994 	struct T_opthdr *topt;
9995 	int opthdr_len;
9996 	t_uscalar_t optname, optlevel;
9997 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9998 	ipsec_req_t *ipsr;
9999 
10000 	/*
10001 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10002 	 * return TRUE.
10003 	 */
10004 
10005 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10006 	opt_endcp = optcp + tor->OPT_length;
10007 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10008 		opthdr_len = sizeof (struct T_opthdr);
10009 	} else {		/* O_OPTMGMT_REQ */
10010 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10011 		opthdr_len = sizeof (struct opthdr);
10012 	}
10013 	for (; optcp < opt_endcp; optcp = next_optcp) {
10014 		if (optcp + opthdr_len > opt_endcp)
10015 			return (B_FALSE);	/* Not enough option header. */
10016 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10017 			topt = (struct T_opthdr *)optcp;
10018 			optlevel = topt->level;
10019 			optname = topt->name;
10020 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10021 		} else {
10022 			opt = (struct opthdr *)optcp;
10023 			optlevel = opt->level;
10024 			optname = opt->name;
10025 			next_optcp = optcp + opthdr_len +
10026 			    _TPI_ALIGN_OPT(opt->len);
10027 		}
10028 		if ((next_optcp < optcp) || /* wraparound pointer space */
10029 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10030 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10031 			return (B_FALSE); /* bad option buffer */
10032 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10033 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10034 			/*
10035 			 * Check to see if it's an all-bypass or all-zeroes
10036 			 * IPsec request.  Don't bother loading IPsec if
10037 			 * the socket doesn't want to use it.  (A good example
10038 			 * is a bypass request.)
10039 			 *
10040 			 * Basically, if any of the non-NEVER bits are set,
10041 			 * load IPsec.
10042 			 */
10043 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10044 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10045 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10046 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10047 			    != 0)
10048 				return (B_TRUE);
10049 		}
10050 	}
10051 	return (B_FALSE);
10052 }
10053 
10054 /*
10055  * If conn is is waiting for ipsec to finish loading, kick it.
10056  */
10057 /* ARGSUSED */
10058 static void
10059 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10060 {
10061 	t_scalar_t	optreq_prim;
10062 	mblk_t		*mp;
10063 	cred_t		*cr;
10064 	int		err = 0;
10065 
10066 	/*
10067 	 * This function is called, after ipsec loading is complete.
10068 	 * Since IP checks exclusively and atomically (i.e it prevents
10069 	 * ipsec load from completing until ip_optcom_req completes)
10070 	 * whether ipsec load is complete, there cannot be a race with IP
10071 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10072 	 */
10073 	mutex_enter(&connp->conn_lock);
10074 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10075 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10076 		mp = connp->conn_ipsec_opt_mp;
10077 		connp->conn_ipsec_opt_mp = NULL;
10078 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10079 		mutex_exit(&connp->conn_lock);
10080 
10081 		/*
10082 		 * All Solaris components should pass a db_credp
10083 		 * for this TPI message, hence we ASSERT.
10084 		 * But in case there is some other M_PROTO that looks
10085 		 * like a TPI message sent by some other kernel
10086 		 * component, we check and return an error.
10087 		 */
10088 		cr = msg_getcred(mp, NULL);
10089 		ASSERT(cr != NULL);
10090 		if (cr == NULL) {
10091 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10092 			if (mp != NULL)
10093 				qreply(connp->conn_wq, mp);
10094 			return;
10095 		}
10096 
10097 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10098 
10099 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10100 		if (optreq_prim == T_OPTMGMT_REQ) {
10101 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10102 			    &ip_opt_obj, B_FALSE);
10103 		} else {
10104 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10105 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10106 			    &ip_opt_obj, B_FALSE);
10107 		}
10108 		if (err != EINPROGRESS)
10109 			CONN_OPER_PENDING_DONE(connp);
10110 		return;
10111 	}
10112 	mutex_exit(&connp->conn_lock);
10113 }
10114 
10115 /*
10116  * Called from the ipsec_loader thread, outside any perimeter, to tell
10117  * ip qenable any of the queues waiting for the ipsec loader to
10118  * complete.
10119  */
10120 void
10121 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10122 {
10123 	netstack_t *ns = ipss->ipsec_netstack;
10124 
10125 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10126 }
10127 
10128 /*
10129  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10130  * determines the grp on which it has to become exclusive, queues the mp
10131  * and IPSQ draining restarts the optmgmt
10132  */
10133 static boolean_t
10134 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10135 {
10136 	conn_t *connp = Q_TO_CONN(q);
10137 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10138 
10139 	/*
10140 	 * Take IPsec requests and treat them special.
10141 	 */
10142 	if (ipsec_opt_present(mp)) {
10143 		/* First check if IPsec is loaded. */
10144 		mutex_enter(&ipss->ipsec_loader_lock);
10145 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10146 			mutex_exit(&ipss->ipsec_loader_lock);
10147 			return (B_FALSE);
10148 		}
10149 		mutex_enter(&connp->conn_lock);
10150 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10151 
10152 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10153 		connp->conn_ipsec_opt_mp = mp;
10154 		mutex_exit(&connp->conn_lock);
10155 		mutex_exit(&ipss->ipsec_loader_lock);
10156 
10157 		ipsec_loader_loadnow(ipss);
10158 		return (B_TRUE);
10159 	}
10160 	return (B_FALSE);
10161 }
10162 
10163 /*
10164  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10165  * all of them are copied to the conn_t. If the req is "zero", the policy is
10166  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10167  * fields.
10168  * We keep only the latest setting of the policy and thus policy setting
10169  * is not incremental/cumulative.
10170  *
10171  * Requests to set policies with multiple alternative actions will
10172  * go through a different API.
10173  */
10174 int
10175 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10176 {
10177 	uint_t ah_req = 0;
10178 	uint_t esp_req = 0;
10179 	uint_t se_req = 0;
10180 	ipsec_selkey_t sel;
10181 	ipsec_act_t *actp = NULL;
10182 	uint_t nact;
10183 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10184 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10185 	ipsec_policy_root_t *pr;
10186 	ipsec_policy_head_t *ph;
10187 	int fam;
10188 	boolean_t is_pol_reset;
10189 	int error = 0;
10190 	netstack_t	*ns = connp->conn_netstack;
10191 	ip_stack_t	*ipst = ns->netstack_ip;
10192 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10193 
10194 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10195 
10196 	/*
10197 	 * The IP_SEC_OPT option does not allow variable length parameters,
10198 	 * hence a request cannot be NULL.
10199 	 */
10200 	if (req == NULL)
10201 		return (EINVAL);
10202 
10203 	ah_req = req->ipsr_ah_req;
10204 	esp_req = req->ipsr_esp_req;
10205 	se_req = req->ipsr_self_encap_req;
10206 
10207 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10208 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10209 		return (EINVAL);
10210 
10211 	/*
10212 	 * Are we dealing with a request to reset the policy (i.e.
10213 	 * zero requests).
10214 	 */
10215 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10216 	    (esp_req & REQ_MASK) == 0 &&
10217 	    (se_req & REQ_MASK) == 0);
10218 
10219 	if (!is_pol_reset) {
10220 		/*
10221 		 * If we couldn't load IPsec, fail with "protocol
10222 		 * not supported".
10223 		 * IPsec may not have been loaded for a request with zero
10224 		 * policies, so we don't fail in this case.
10225 		 */
10226 		mutex_enter(&ipss->ipsec_loader_lock);
10227 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10228 			mutex_exit(&ipss->ipsec_loader_lock);
10229 			return (EPROTONOSUPPORT);
10230 		}
10231 		mutex_exit(&ipss->ipsec_loader_lock);
10232 
10233 		/*
10234 		 * Test for valid requests. Invalid algorithms
10235 		 * need to be tested by IPsec code because new
10236 		 * algorithms can be added dynamically.
10237 		 */
10238 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10239 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10240 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10241 			return (EINVAL);
10242 		}
10243 
10244 		/*
10245 		 * Only privileged users can issue these
10246 		 * requests.
10247 		 */
10248 		if (((ah_req & IPSEC_PREF_NEVER) ||
10249 		    (esp_req & IPSEC_PREF_NEVER) ||
10250 		    (se_req & IPSEC_PREF_NEVER)) &&
10251 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10252 			return (EPERM);
10253 		}
10254 
10255 		/*
10256 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10257 		 * are mutually exclusive.
10258 		 */
10259 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10260 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10261 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10262 			/* Both of them are set */
10263 			return (EINVAL);
10264 		}
10265 	}
10266 
10267 	mutex_enter(&connp->conn_lock);
10268 
10269 	/*
10270 	 * If we have already cached policies in ip_bind_connected*(), don't
10271 	 * let them change now. We cache policies for connections
10272 	 * whose src,dst [addr, port] is known.
10273 	 */
10274 	if (connp->conn_policy_cached) {
10275 		mutex_exit(&connp->conn_lock);
10276 		return (EINVAL);
10277 	}
10278 
10279 	/*
10280 	 * We have a zero policies, reset the connection policy if already
10281 	 * set. This will cause the connection to inherit the
10282 	 * global policy, if any.
10283 	 */
10284 	if (is_pol_reset) {
10285 		if (connp->conn_policy != NULL) {
10286 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10287 			connp->conn_policy = NULL;
10288 		}
10289 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10290 		connp->conn_in_enforce_policy = B_FALSE;
10291 		connp->conn_out_enforce_policy = B_FALSE;
10292 		mutex_exit(&connp->conn_lock);
10293 		return (0);
10294 	}
10295 
10296 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10297 	    ipst->ips_netstack);
10298 	if (ph == NULL)
10299 		goto enomem;
10300 
10301 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10302 	if (actp == NULL)
10303 		goto enomem;
10304 
10305 	/*
10306 	 * Always allocate IPv4 policy entries, since they can also
10307 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10308 	 */
10309 	bzero(&sel, sizeof (sel));
10310 	sel.ipsl_valid = IPSL_IPV4;
10311 
10312 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10313 	    ipst->ips_netstack);
10314 	if (pin4 == NULL)
10315 		goto enomem;
10316 
10317 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10318 	    ipst->ips_netstack);
10319 	if (pout4 == NULL)
10320 		goto enomem;
10321 
10322 	if (connp->conn_af_isv6) {
10323 		/*
10324 		 * We're looking at a v6 socket, also allocate the
10325 		 * v6-specific entries...
10326 		 */
10327 		sel.ipsl_valid = IPSL_IPV6;
10328 		pin6 = ipsec_policy_create(&sel, actp, nact,
10329 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10330 		if (pin6 == NULL)
10331 			goto enomem;
10332 
10333 		pout6 = ipsec_policy_create(&sel, actp, nact,
10334 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10335 		if (pout6 == NULL)
10336 			goto enomem;
10337 
10338 		/*
10339 		 * .. and file them away in the right place.
10340 		 */
10341 		fam = IPSEC_AF_V6;
10342 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10343 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10344 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10345 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10346 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10347 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10348 	}
10349 
10350 	ipsec_actvec_free(actp, nact);
10351 
10352 	/*
10353 	 * File the v4 policies.
10354 	 */
10355 	fam = IPSEC_AF_V4;
10356 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10357 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10358 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10359 
10360 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10361 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10362 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10363 
10364 	/*
10365 	 * If the requests need security, set enforce_policy.
10366 	 * If the requests are IPSEC_PREF_NEVER, one should
10367 	 * still set conn_out_enforce_policy so that an ipsec_out
10368 	 * gets attached in ip_wput. This is needed so that
10369 	 * for connections that we don't cache policy in ip_bind,
10370 	 * if global policy matches in ip_wput_attach_policy, we
10371 	 * don't wrongly inherit global policy. Similarly, we need
10372 	 * to set conn_in_enforce_policy also so that we don't verify
10373 	 * policy wrongly.
10374 	 */
10375 	if ((ah_req & REQ_MASK) != 0 ||
10376 	    (esp_req & REQ_MASK) != 0 ||
10377 	    (se_req & REQ_MASK) != 0) {
10378 		connp->conn_in_enforce_policy = B_TRUE;
10379 		connp->conn_out_enforce_policy = B_TRUE;
10380 		connp->conn_flags |= IPCL_CHECK_POLICY;
10381 	}
10382 
10383 	mutex_exit(&connp->conn_lock);
10384 	return (error);
10385 #undef REQ_MASK
10386 
10387 	/*
10388 	 * Common memory-allocation-failure exit path.
10389 	 */
10390 enomem:
10391 	mutex_exit(&connp->conn_lock);
10392 	if (actp != NULL)
10393 		ipsec_actvec_free(actp, nact);
10394 	if (pin4 != NULL)
10395 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10396 	if (pout4 != NULL)
10397 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10398 	if (pin6 != NULL)
10399 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10400 	if (pout6 != NULL)
10401 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10402 	return (ENOMEM);
10403 }
10404 
10405 /*
10406  * Only for options that pass in an IP addr. Currently only V4 options
10407  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10408  * So this function assumes level is IPPROTO_IP
10409  */
10410 int
10411 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10412     mblk_t *first_mp)
10413 {
10414 	ipif_t *ipif = NULL;
10415 	int error;
10416 	ill_t *ill;
10417 	int zoneid;
10418 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10419 
10420 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10421 
10422 	if (addr != INADDR_ANY || checkonly) {
10423 		ASSERT(connp != NULL);
10424 		zoneid = IPCL_ZONEID(connp);
10425 		if (option == IP_NEXTHOP) {
10426 			ipif = ipif_lookup_onlink_addr(addr,
10427 			    connp->conn_zoneid, ipst);
10428 		} else {
10429 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10430 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10431 			    &error, ipst);
10432 		}
10433 		if (ipif == NULL) {
10434 			if (error == EINPROGRESS)
10435 				return (error);
10436 			if ((option == IP_MULTICAST_IF) ||
10437 			    (option == IP_NEXTHOP))
10438 				return (EHOSTUNREACH);
10439 			else
10440 				return (EINVAL);
10441 		} else if (checkonly) {
10442 			if (option == IP_MULTICAST_IF) {
10443 				ill = ipif->ipif_ill;
10444 				/* not supported by the virtual network iface */
10445 				if (IS_VNI(ill)) {
10446 					ipif_refrele(ipif);
10447 					return (EINVAL);
10448 				}
10449 			}
10450 			ipif_refrele(ipif);
10451 			return (0);
10452 		}
10453 		ill = ipif->ipif_ill;
10454 		mutex_enter(&connp->conn_lock);
10455 		mutex_enter(&ill->ill_lock);
10456 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10457 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10458 			mutex_exit(&ill->ill_lock);
10459 			mutex_exit(&connp->conn_lock);
10460 			ipif_refrele(ipif);
10461 			return (option == IP_MULTICAST_IF ?
10462 			    EHOSTUNREACH : EINVAL);
10463 		}
10464 	} else {
10465 		mutex_enter(&connp->conn_lock);
10466 	}
10467 
10468 	/* None of the options below are supported on the VNI */
10469 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10470 		mutex_exit(&ill->ill_lock);
10471 		mutex_exit(&connp->conn_lock);
10472 		ipif_refrele(ipif);
10473 		return (EINVAL);
10474 	}
10475 
10476 	switch (option) {
10477 	case IP_MULTICAST_IF:
10478 		connp->conn_multicast_ipif = ipif;
10479 		break;
10480 	case IP_NEXTHOP:
10481 		connp->conn_nexthop_v4 = addr;
10482 		connp->conn_nexthop_set = B_TRUE;
10483 		break;
10484 	}
10485 
10486 	if (ipif != NULL) {
10487 		mutex_exit(&ill->ill_lock);
10488 		mutex_exit(&connp->conn_lock);
10489 		ipif_refrele(ipif);
10490 		return (0);
10491 	}
10492 	mutex_exit(&connp->conn_lock);
10493 	/* We succeded in cleared the option */
10494 	return (0);
10495 }
10496 
10497 /*
10498  * For options that pass in an ifindex specifying the ill. V6 options always
10499  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10500  */
10501 int
10502 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10503     int level, int option, mblk_t *first_mp)
10504 {
10505 	ill_t *ill = NULL;
10506 	int error = 0;
10507 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10508 
10509 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10510 	if (ifindex != 0) {
10511 		ASSERT(connp != NULL);
10512 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10513 		    first_mp, ip_restart_optmgmt, &error, ipst);
10514 		if (ill != NULL) {
10515 			if (checkonly) {
10516 				/* not supported by the virtual network iface */
10517 				if (IS_VNI(ill)) {
10518 					ill_refrele(ill);
10519 					return (EINVAL);
10520 				}
10521 				ill_refrele(ill);
10522 				return (0);
10523 			}
10524 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10525 			    0, NULL)) {
10526 				ill_refrele(ill);
10527 				ill = NULL;
10528 				mutex_enter(&connp->conn_lock);
10529 				goto setit;
10530 			}
10531 			mutex_enter(&connp->conn_lock);
10532 			mutex_enter(&ill->ill_lock);
10533 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10534 				mutex_exit(&ill->ill_lock);
10535 				mutex_exit(&connp->conn_lock);
10536 				ill_refrele(ill);
10537 				ill = NULL;
10538 				mutex_enter(&connp->conn_lock);
10539 			}
10540 			goto setit;
10541 		} else if (error == EINPROGRESS) {
10542 			return (error);
10543 		} else {
10544 			error = 0;
10545 		}
10546 	}
10547 	mutex_enter(&connp->conn_lock);
10548 setit:
10549 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10550 
10551 	/*
10552 	 * The options below assume that the ILL (if any) transmits and/or
10553 	 * receives traffic. Neither of which is true for the virtual network
10554 	 * interface, so fail setting these on a VNI.
10555 	 */
10556 	if (IS_VNI(ill)) {
10557 		ASSERT(ill != NULL);
10558 		mutex_exit(&ill->ill_lock);
10559 		mutex_exit(&connp->conn_lock);
10560 		ill_refrele(ill);
10561 		return (EINVAL);
10562 	}
10563 
10564 	if (level == IPPROTO_IP) {
10565 		switch (option) {
10566 		case IP_BOUND_IF:
10567 			connp->conn_incoming_ill = ill;
10568 			connp->conn_outgoing_ill = ill;
10569 			break;
10570 
10571 		case IP_MULTICAST_IF:
10572 			/*
10573 			 * This option is an internal special. The socket
10574 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10575 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10576 			 * specifies an ifindex and we try first on V6 ill's.
10577 			 * If we don't find one, we they try using on v4 ill's
10578 			 * intenally and we come here.
10579 			 */
10580 			if (!checkonly && ill != NULL) {
10581 				ipif_t	*ipif;
10582 				ipif = ill->ill_ipif;
10583 
10584 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10585 					mutex_exit(&ill->ill_lock);
10586 					mutex_exit(&connp->conn_lock);
10587 					ill_refrele(ill);
10588 					ill = NULL;
10589 					mutex_enter(&connp->conn_lock);
10590 				} else {
10591 					connp->conn_multicast_ipif = ipif;
10592 				}
10593 			}
10594 			break;
10595 
10596 		case IP_DHCPINIT_IF:
10597 			if (connp->conn_dhcpinit_ill != NULL) {
10598 				/*
10599 				 * We've locked the conn so conn_cleanup_ill()
10600 				 * cannot clear conn_dhcpinit_ill -- so it's
10601 				 * safe to access the ill.
10602 				 */
10603 				ill_t *oill = connp->conn_dhcpinit_ill;
10604 
10605 				ASSERT(oill->ill_dhcpinit != 0);
10606 				atomic_dec_32(&oill->ill_dhcpinit);
10607 				connp->conn_dhcpinit_ill = NULL;
10608 			}
10609 
10610 			if (ill != NULL) {
10611 				connp->conn_dhcpinit_ill = ill;
10612 				atomic_inc_32(&ill->ill_dhcpinit);
10613 			}
10614 			break;
10615 		}
10616 	} else {
10617 		switch (option) {
10618 		case IPV6_BOUND_IF:
10619 			connp->conn_incoming_ill = ill;
10620 			connp->conn_outgoing_ill = ill;
10621 			break;
10622 
10623 		case IPV6_MULTICAST_IF:
10624 			/*
10625 			 * Set conn_multicast_ill to be the IPv6 ill.
10626 			 * Set conn_multicast_ipif to be an IPv4 ipif
10627 			 * for ifindex to make IPv4 mapped addresses
10628 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10629 			 * Even if no IPv6 ill exists for the ifindex
10630 			 * we need to check for an IPv4 ifindex in order
10631 			 * for this to work with mapped addresses. In that
10632 			 * case only set conn_multicast_ipif.
10633 			 */
10634 			if (!checkonly) {
10635 				if (ifindex == 0) {
10636 					connp->conn_multicast_ill = NULL;
10637 					connp->conn_multicast_ipif = NULL;
10638 				} else if (ill != NULL) {
10639 					connp->conn_multicast_ill = ill;
10640 				}
10641 			}
10642 			break;
10643 		}
10644 	}
10645 
10646 	if (ill != NULL) {
10647 		mutex_exit(&ill->ill_lock);
10648 		mutex_exit(&connp->conn_lock);
10649 		ill_refrele(ill);
10650 		return (0);
10651 	}
10652 	mutex_exit(&connp->conn_lock);
10653 	/*
10654 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10655 	 * locate the ill and could not set the option (ifindex != 0)
10656 	 */
10657 	return (ifindex == 0 ? 0 : EINVAL);
10658 }
10659 
10660 /* This routine sets socket options. */
10661 /* ARGSUSED */
10662 int
10663 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10664     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10665     void *dummy, cred_t *cr, mblk_t *first_mp)
10666 {
10667 	int		*i1 = (int *)invalp;
10668 	conn_t		*connp = Q_TO_CONN(q);
10669 	int		error = 0;
10670 	boolean_t	checkonly;
10671 	ire_t		*ire;
10672 	boolean_t	found;
10673 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10674 
10675 	switch (optset_context) {
10676 
10677 	case SETFN_OPTCOM_CHECKONLY:
10678 		checkonly = B_TRUE;
10679 		/*
10680 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10681 		 * inlen != 0 implies value supplied and
10682 		 * 	we have to "pretend" to set it.
10683 		 * inlen == 0 implies that there is no
10684 		 * 	value part in T_CHECK request and just validation
10685 		 * done elsewhere should be enough, we just return here.
10686 		 */
10687 		if (inlen == 0) {
10688 			*outlenp = 0;
10689 			return (0);
10690 		}
10691 		break;
10692 	case SETFN_OPTCOM_NEGOTIATE:
10693 	case SETFN_UD_NEGOTIATE:
10694 	case SETFN_CONN_NEGOTIATE:
10695 		checkonly = B_FALSE;
10696 		break;
10697 	default:
10698 		/*
10699 		 * We should never get here
10700 		 */
10701 		*outlenp = 0;
10702 		return (EINVAL);
10703 	}
10704 
10705 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10706 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10707 
10708 	/*
10709 	 * For fixed length options, no sanity check
10710 	 * of passed in length is done. It is assumed *_optcom_req()
10711 	 * routines do the right thing.
10712 	 */
10713 
10714 	switch (level) {
10715 	case SOL_SOCKET:
10716 		/*
10717 		 * conn_lock protects the bitfields, and is used to
10718 		 * set the fields atomically.
10719 		 */
10720 		switch (name) {
10721 		case SO_BROADCAST:
10722 			if (!checkonly) {
10723 				/* TODO: use value someplace? */
10724 				mutex_enter(&connp->conn_lock);
10725 				connp->conn_broadcast = *i1 ? 1 : 0;
10726 				mutex_exit(&connp->conn_lock);
10727 			}
10728 			break;	/* goto sizeof (int) option return */
10729 		case SO_USELOOPBACK:
10730 			if (!checkonly) {
10731 				/* TODO: use value someplace? */
10732 				mutex_enter(&connp->conn_lock);
10733 				connp->conn_loopback = *i1 ? 1 : 0;
10734 				mutex_exit(&connp->conn_lock);
10735 			}
10736 			break;	/* goto sizeof (int) option return */
10737 		case SO_DONTROUTE:
10738 			if (!checkonly) {
10739 				mutex_enter(&connp->conn_lock);
10740 				connp->conn_dontroute = *i1 ? 1 : 0;
10741 				mutex_exit(&connp->conn_lock);
10742 			}
10743 			break;	/* goto sizeof (int) option return */
10744 		case SO_REUSEADDR:
10745 			if (!checkonly) {
10746 				mutex_enter(&connp->conn_lock);
10747 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10748 				mutex_exit(&connp->conn_lock);
10749 			}
10750 			break;	/* goto sizeof (int) option return */
10751 		case SO_PROTOTYPE:
10752 			if (!checkonly) {
10753 				mutex_enter(&connp->conn_lock);
10754 				connp->conn_proto = *i1;
10755 				mutex_exit(&connp->conn_lock);
10756 			}
10757 			break;	/* goto sizeof (int) option return */
10758 		case SO_ALLZONES:
10759 			if (!checkonly) {
10760 				mutex_enter(&connp->conn_lock);
10761 				if (IPCL_IS_BOUND(connp)) {
10762 					mutex_exit(&connp->conn_lock);
10763 					return (EINVAL);
10764 				}
10765 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10766 				mutex_exit(&connp->conn_lock);
10767 			}
10768 			break;	/* goto sizeof (int) option return */
10769 		case SO_ANON_MLP:
10770 			if (!checkonly) {
10771 				mutex_enter(&connp->conn_lock);
10772 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10773 				mutex_exit(&connp->conn_lock);
10774 			}
10775 			break;	/* goto sizeof (int) option return */
10776 		case SO_MAC_EXEMPT:
10777 			if (secpolicy_net_mac_aware(cr) != 0 ||
10778 			    IPCL_IS_BOUND(connp))
10779 				return (EACCES);
10780 			if (!checkonly) {
10781 				mutex_enter(&connp->conn_lock);
10782 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		default:
10787 			/*
10788 			 * "soft" error (negative)
10789 			 * option not handled at this level
10790 			 * Note: Do not modify *outlenp
10791 			 */
10792 			return (-EINVAL);
10793 		}
10794 		break;
10795 	case IPPROTO_IP:
10796 		switch (name) {
10797 		case IP_NEXTHOP:
10798 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10799 				return (EPERM);
10800 			/* FALLTHRU */
10801 		case IP_MULTICAST_IF: {
10802 			ipaddr_t addr = *i1;
10803 
10804 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10805 			    first_mp);
10806 			if (error != 0)
10807 				return (error);
10808 			break;	/* goto sizeof (int) option return */
10809 		}
10810 
10811 		case IP_MULTICAST_TTL:
10812 			/* Recorded in transport above IP */
10813 			*outvalp = *invalp;
10814 			*outlenp = sizeof (uchar_t);
10815 			return (0);
10816 		case IP_MULTICAST_LOOP:
10817 			if (!checkonly) {
10818 				mutex_enter(&connp->conn_lock);
10819 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10820 				mutex_exit(&connp->conn_lock);
10821 			}
10822 			*outvalp = *invalp;
10823 			*outlenp = sizeof (uchar_t);
10824 			return (0);
10825 		case IP_ADD_MEMBERSHIP:
10826 		case MCAST_JOIN_GROUP:
10827 		case IP_DROP_MEMBERSHIP:
10828 		case MCAST_LEAVE_GROUP: {
10829 			struct ip_mreq *mreqp;
10830 			struct group_req *greqp;
10831 			ire_t *ire;
10832 			boolean_t done = B_FALSE;
10833 			ipaddr_t group, ifaddr;
10834 			struct sockaddr_in *sin;
10835 			uint32_t *ifindexp;
10836 			boolean_t mcast_opt = B_TRUE;
10837 			mcast_record_t fmode;
10838 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10839 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10840 
10841 			switch (name) {
10842 			case IP_ADD_MEMBERSHIP:
10843 				mcast_opt = B_FALSE;
10844 				/* FALLTHRU */
10845 			case MCAST_JOIN_GROUP:
10846 				fmode = MODE_IS_EXCLUDE;
10847 				optfn = ip_opt_add_group;
10848 				break;
10849 
10850 			case IP_DROP_MEMBERSHIP:
10851 				mcast_opt = B_FALSE;
10852 				/* FALLTHRU */
10853 			case MCAST_LEAVE_GROUP:
10854 				fmode = MODE_IS_INCLUDE;
10855 				optfn = ip_opt_delete_group;
10856 				break;
10857 			}
10858 
10859 			if (mcast_opt) {
10860 				greqp = (struct group_req *)i1;
10861 				sin = (struct sockaddr_in *)&greqp->gr_group;
10862 				if (sin->sin_family != AF_INET) {
10863 					*outlenp = 0;
10864 					return (ENOPROTOOPT);
10865 				}
10866 				group = (ipaddr_t)sin->sin_addr.s_addr;
10867 				ifaddr = INADDR_ANY;
10868 				ifindexp = &greqp->gr_interface;
10869 			} else {
10870 				mreqp = (struct ip_mreq *)i1;
10871 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10872 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10873 				ifindexp = NULL;
10874 			}
10875 
10876 			/*
10877 			 * In the multirouting case, we need to replicate
10878 			 * the request on all interfaces that will take part
10879 			 * in replication.  We do so because multirouting is
10880 			 * reflective, thus we will probably receive multi-
10881 			 * casts on those interfaces.
10882 			 * The ip_multirt_apply_membership() succeeds if the
10883 			 * operation succeeds on at least one interface.
10884 			 */
10885 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10886 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10887 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10888 			if (ire != NULL) {
10889 				if (ire->ire_flags & RTF_MULTIRT) {
10890 					error = ip_multirt_apply_membership(
10891 					    optfn, ire, connp, checkonly, group,
10892 					    fmode, INADDR_ANY, first_mp);
10893 					done = B_TRUE;
10894 				}
10895 				ire_refrele(ire);
10896 			}
10897 			if (!done) {
10898 				error = optfn(connp, checkonly, group, ifaddr,
10899 				    ifindexp, fmode, INADDR_ANY, first_mp);
10900 			}
10901 			if (error) {
10902 				/*
10903 				 * EINPROGRESS is a soft error, needs retry
10904 				 * so don't make *outlenp zero.
10905 				 */
10906 				if (error != EINPROGRESS)
10907 					*outlenp = 0;
10908 				return (error);
10909 			}
10910 			/* OK return - copy input buffer into output buffer */
10911 			if (invalp != outvalp) {
10912 				/* don't trust bcopy for identical src/dst */
10913 				bcopy(invalp, outvalp, inlen);
10914 			}
10915 			*outlenp = inlen;
10916 			return (0);
10917 		}
10918 		case IP_BLOCK_SOURCE:
10919 		case IP_UNBLOCK_SOURCE:
10920 		case IP_ADD_SOURCE_MEMBERSHIP:
10921 		case IP_DROP_SOURCE_MEMBERSHIP:
10922 		case MCAST_BLOCK_SOURCE:
10923 		case MCAST_UNBLOCK_SOURCE:
10924 		case MCAST_JOIN_SOURCE_GROUP:
10925 		case MCAST_LEAVE_SOURCE_GROUP: {
10926 			struct ip_mreq_source *imreqp;
10927 			struct group_source_req *gsreqp;
10928 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10929 			uint32_t ifindex = 0;
10930 			mcast_record_t fmode;
10931 			struct sockaddr_in *sin;
10932 			ire_t *ire;
10933 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10934 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10935 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10936 
10937 			switch (name) {
10938 			case IP_BLOCK_SOURCE:
10939 				mcast_opt = B_FALSE;
10940 				/* FALLTHRU */
10941 			case MCAST_BLOCK_SOURCE:
10942 				fmode = MODE_IS_EXCLUDE;
10943 				optfn = ip_opt_add_group;
10944 				break;
10945 
10946 			case IP_UNBLOCK_SOURCE:
10947 				mcast_opt = B_FALSE;
10948 				/* FALLTHRU */
10949 			case MCAST_UNBLOCK_SOURCE:
10950 				fmode = MODE_IS_EXCLUDE;
10951 				optfn = ip_opt_delete_group;
10952 				break;
10953 
10954 			case IP_ADD_SOURCE_MEMBERSHIP:
10955 				mcast_opt = B_FALSE;
10956 				/* FALLTHRU */
10957 			case MCAST_JOIN_SOURCE_GROUP:
10958 				fmode = MODE_IS_INCLUDE;
10959 				optfn = ip_opt_add_group;
10960 				break;
10961 
10962 			case IP_DROP_SOURCE_MEMBERSHIP:
10963 				mcast_opt = B_FALSE;
10964 				/* FALLTHRU */
10965 			case MCAST_LEAVE_SOURCE_GROUP:
10966 				fmode = MODE_IS_INCLUDE;
10967 				optfn = ip_opt_delete_group;
10968 				break;
10969 			}
10970 
10971 			if (mcast_opt) {
10972 				gsreqp = (struct group_source_req *)i1;
10973 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10974 					*outlenp = 0;
10975 					return (ENOPROTOOPT);
10976 				}
10977 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10978 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10979 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10980 				src = (ipaddr_t)sin->sin_addr.s_addr;
10981 				ifindex = gsreqp->gsr_interface;
10982 			} else {
10983 				imreqp = (struct ip_mreq_source *)i1;
10984 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10985 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10986 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10987 			}
10988 
10989 			/*
10990 			 * In the multirouting case, we need to replicate
10991 			 * the request as noted in the mcast cases above.
10992 			 */
10993 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10994 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10995 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10996 			if (ire != NULL) {
10997 				if (ire->ire_flags & RTF_MULTIRT) {
10998 					error = ip_multirt_apply_membership(
10999 					    optfn, ire, connp, checkonly, grp,
11000 					    fmode, src, first_mp);
11001 					done = B_TRUE;
11002 				}
11003 				ire_refrele(ire);
11004 			}
11005 			if (!done) {
11006 				error = optfn(connp, checkonly, grp, ifaddr,
11007 				    &ifindex, fmode, src, first_mp);
11008 			}
11009 			if (error != 0) {
11010 				/*
11011 				 * EINPROGRESS is a soft error, needs retry
11012 				 * so don't make *outlenp zero.
11013 				 */
11014 				if (error != EINPROGRESS)
11015 					*outlenp = 0;
11016 				return (error);
11017 			}
11018 			/* OK return - copy input buffer into output buffer */
11019 			if (invalp != outvalp) {
11020 				bcopy(invalp, outvalp, inlen);
11021 			}
11022 			*outlenp = inlen;
11023 			return (0);
11024 		}
11025 		case IP_SEC_OPT:
11026 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11027 			if (error != 0) {
11028 				*outlenp = 0;
11029 				return (error);
11030 			}
11031 			break;
11032 		case IP_HDRINCL:
11033 		case IP_OPTIONS:
11034 		case T_IP_OPTIONS:
11035 		case IP_TOS:
11036 		case T_IP_TOS:
11037 		case IP_TTL:
11038 		case IP_RECVDSTADDR:
11039 		case IP_RECVOPTS:
11040 			/* OK return - copy input buffer into output buffer */
11041 			if (invalp != outvalp) {
11042 				/* don't trust bcopy for identical src/dst */
11043 				bcopy(invalp, outvalp, inlen);
11044 			}
11045 			*outlenp = inlen;
11046 			return (0);
11047 		case IP_RECVIF:
11048 			/* Retrieve the inbound interface index */
11049 			if (!checkonly) {
11050 				mutex_enter(&connp->conn_lock);
11051 				connp->conn_recvif = *i1 ? 1 : 0;
11052 				mutex_exit(&connp->conn_lock);
11053 			}
11054 			break;	/* goto sizeof (int) option return */
11055 		case IP_RECVPKTINFO:
11056 			if (!checkonly) {
11057 				mutex_enter(&connp->conn_lock);
11058 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11059 				mutex_exit(&connp->conn_lock);
11060 			}
11061 			break;	/* goto sizeof (int) option return */
11062 		case IP_RECVSLLA:
11063 			/* Retrieve the source link layer address */
11064 			if (!checkonly) {
11065 				mutex_enter(&connp->conn_lock);
11066 				connp->conn_recvslla = *i1 ? 1 : 0;
11067 				mutex_exit(&connp->conn_lock);
11068 			}
11069 			break;	/* goto sizeof (int) option return */
11070 		case MRT_INIT:
11071 		case MRT_DONE:
11072 		case MRT_ADD_VIF:
11073 		case MRT_DEL_VIF:
11074 		case MRT_ADD_MFC:
11075 		case MRT_DEL_MFC:
11076 		case MRT_ASSERT:
11077 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11078 				*outlenp = 0;
11079 				return (error);
11080 			}
11081 			error = ip_mrouter_set((int)name, q, checkonly,
11082 			    (uchar_t *)invalp, inlen, first_mp);
11083 			if (error) {
11084 				*outlenp = 0;
11085 				return (error);
11086 			}
11087 			/* OK return - copy input buffer into output buffer */
11088 			if (invalp != outvalp) {
11089 				/* don't trust bcopy for identical src/dst */
11090 				bcopy(invalp, outvalp, inlen);
11091 			}
11092 			*outlenp = inlen;
11093 			return (0);
11094 		case IP_BOUND_IF:
11095 		case IP_DHCPINIT_IF:
11096 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11097 			    level, name, first_mp);
11098 			if (error != 0)
11099 				return (error);
11100 			break; 		/* goto sizeof (int) option return */
11101 
11102 		case IP_UNSPEC_SRC:
11103 			/* Allow sending with a zero source address */
11104 			if (!checkonly) {
11105 				mutex_enter(&connp->conn_lock);
11106 				connp->conn_unspec_src = *i1 ? 1 : 0;
11107 				mutex_exit(&connp->conn_lock);
11108 			}
11109 			break;	/* goto sizeof (int) option return */
11110 		default:
11111 			/*
11112 			 * "soft" error (negative)
11113 			 * option not handled at this level
11114 			 * Note: Do not modify *outlenp
11115 			 */
11116 			return (-EINVAL);
11117 		}
11118 		break;
11119 	case IPPROTO_IPV6:
11120 		switch (name) {
11121 		case IPV6_BOUND_IF:
11122 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11123 			    level, name, first_mp);
11124 			if (error != 0)
11125 				return (error);
11126 			break; 		/* goto sizeof (int) option return */
11127 
11128 		case IPV6_MULTICAST_IF:
11129 			/*
11130 			 * The only possible errors are EINPROGRESS and
11131 			 * EINVAL. EINPROGRESS will be restarted and is not
11132 			 * a hard error. We call this option on both V4 and V6
11133 			 * If both return EINVAL, then this call returns
11134 			 * EINVAL. If at least one of them succeeds we
11135 			 * return success.
11136 			 */
11137 			found = B_FALSE;
11138 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11139 			    level, name, first_mp);
11140 			if (error == EINPROGRESS)
11141 				return (error);
11142 			if (error == 0)
11143 				found = B_TRUE;
11144 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11145 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11146 			if (error == 0)
11147 				found = B_TRUE;
11148 			if (!found)
11149 				return (error);
11150 			break; 		/* goto sizeof (int) option return */
11151 
11152 		case IPV6_MULTICAST_HOPS:
11153 			/* Recorded in transport above IP */
11154 			break;	/* goto sizeof (int) option return */
11155 		case IPV6_MULTICAST_LOOP:
11156 			if (!checkonly) {
11157 				mutex_enter(&connp->conn_lock);
11158 				connp->conn_multicast_loop = *i1;
11159 				mutex_exit(&connp->conn_lock);
11160 			}
11161 			break;	/* goto sizeof (int) option return */
11162 		case IPV6_JOIN_GROUP:
11163 		case MCAST_JOIN_GROUP:
11164 		case IPV6_LEAVE_GROUP:
11165 		case MCAST_LEAVE_GROUP: {
11166 			struct ipv6_mreq *ip_mreqp;
11167 			struct group_req *greqp;
11168 			ire_t *ire;
11169 			boolean_t done = B_FALSE;
11170 			in6_addr_t groupv6;
11171 			uint32_t ifindex;
11172 			boolean_t mcast_opt = B_TRUE;
11173 			mcast_record_t fmode;
11174 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11175 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11176 
11177 			switch (name) {
11178 			case IPV6_JOIN_GROUP:
11179 				mcast_opt = B_FALSE;
11180 				/* FALLTHRU */
11181 			case MCAST_JOIN_GROUP:
11182 				fmode = MODE_IS_EXCLUDE;
11183 				optfn = ip_opt_add_group_v6;
11184 				break;
11185 
11186 			case IPV6_LEAVE_GROUP:
11187 				mcast_opt = B_FALSE;
11188 				/* FALLTHRU */
11189 			case MCAST_LEAVE_GROUP:
11190 				fmode = MODE_IS_INCLUDE;
11191 				optfn = ip_opt_delete_group_v6;
11192 				break;
11193 			}
11194 
11195 			if (mcast_opt) {
11196 				struct sockaddr_in *sin;
11197 				struct sockaddr_in6 *sin6;
11198 				greqp = (struct group_req *)i1;
11199 				if (greqp->gr_group.ss_family == AF_INET) {
11200 					sin = (struct sockaddr_in *)
11201 					    &(greqp->gr_group);
11202 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11203 					    &groupv6);
11204 				} else {
11205 					sin6 = (struct sockaddr_in6 *)
11206 					    &(greqp->gr_group);
11207 					groupv6 = sin6->sin6_addr;
11208 				}
11209 				ifindex = greqp->gr_interface;
11210 			} else {
11211 				ip_mreqp = (struct ipv6_mreq *)i1;
11212 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11213 				ifindex = ip_mreqp->ipv6mr_interface;
11214 			}
11215 			/*
11216 			 * In the multirouting case, we need to replicate
11217 			 * the request on all interfaces that will take part
11218 			 * in replication.  We do so because multirouting is
11219 			 * reflective, thus we will probably receive multi-
11220 			 * casts on those interfaces.
11221 			 * The ip_multirt_apply_membership_v6() succeeds if
11222 			 * the operation succeeds on at least one interface.
11223 			 */
11224 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11225 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11226 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11227 			if (ire != NULL) {
11228 				if (ire->ire_flags & RTF_MULTIRT) {
11229 					error = ip_multirt_apply_membership_v6(
11230 					    optfn, ire, connp, checkonly,
11231 					    &groupv6, fmode, &ipv6_all_zeros,
11232 					    first_mp);
11233 					done = B_TRUE;
11234 				}
11235 				ire_refrele(ire);
11236 			}
11237 			if (!done) {
11238 				error = optfn(connp, checkonly, &groupv6,
11239 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11240 			}
11241 			if (error) {
11242 				/*
11243 				 * EINPROGRESS is a soft error, needs retry
11244 				 * so don't make *outlenp zero.
11245 				 */
11246 				if (error != EINPROGRESS)
11247 					*outlenp = 0;
11248 				return (error);
11249 			}
11250 			/* OK return - copy input buffer into output buffer */
11251 			if (invalp != outvalp) {
11252 				/* don't trust bcopy for identical src/dst */
11253 				bcopy(invalp, outvalp, inlen);
11254 			}
11255 			*outlenp = inlen;
11256 			return (0);
11257 		}
11258 		case MCAST_BLOCK_SOURCE:
11259 		case MCAST_UNBLOCK_SOURCE:
11260 		case MCAST_JOIN_SOURCE_GROUP:
11261 		case MCAST_LEAVE_SOURCE_GROUP: {
11262 			struct group_source_req *gsreqp;
11263 			in6_addr_t v6grp, v6src;
11264 			uint32_t ifindex;
11265 			mcast_record_t fmode;
11266 			ire_t *ire;
11267 			boolean_t done = B_FALSE;
11268 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11269 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11270 
11271 			switch (name) {
11272 			case MCAST_BLOCK_SOURCE:
11273 				fmode = MODE_IS_EXCLUDE;
11274 				optfn = ip_opt_add_group_v6;
11275 				break;
11276 			case MCAST_UNBLOCK_SOURCE:
11277 				fmode = MODE_IS_EXCLUDE;
11278 				optfn = ip_opt_delete_group_v6;
11279 				break;
11280 			case MCAST_JOIN_SOURCE_GROUP:
11281 				fmode = MODE_IS_INCLUDE;
11282 				optfn = ip_opt_add_group_v6;
11283 				break;
11284 			case MCAST_LEAVE_SOURCE_GROUP:
11285 				fmode = MODE_IS_INCLUDE;
11286 				optfn = ip_opt_delete_group_v6;
11287 				break;
11288 			}
11289 
11290 			gsreqp = (struct group_source_req *)i1;
11291 			ifindex = gsreqp->gsr_interface;
11292 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11293 				struct sockaddr_in *s;
11294 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11295 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11296 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11297 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11298 			} else {
11299 				struct sockaddr_in6 *s6;
11300 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11301 				v6grp = s6->sin6_addr;
11302 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11303 				v6src = s6->sin6_addr;
11304 			}
11305 
11306 			/*
11307 			 * In the multirouting case, we need to replicate
11308 			 * the request as noted in the mcast cases above.
11309 			 */
11310 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11311 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11312 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11313 			if (ire != NULL) {
11314 				if (ire->ire_flags & RTF_MULTIRT) {
11315 					error = ip_multirt_apply_membership_v6(
11316 					    optfn, ire, connp, checkonly,
11317 					    &v6grp, fmode, &v6src, first_mp);
11318 					done = B_TRUE;
11319 				}
11320 				ire_refrele(ire);
11321 			}
11322 			if (!done) {
11323 				error = optfn(connp, checkonly, &v6grp,
11324 				    ifindex, fmode, &v6src, first_mp);
11325 			}
11326 			if (error != 0) {
11327 				/*
11328 				 * EINPROGRESS is a soft error, needs retry
11329 				 * so don't make *outlenp zero.
11330 				 */
11331 				if (error != EINPROGRESS)
11332 					*outlenp = 0;
11333 				return (error);
11334 			}
11335 			/* OK return - copy input buffer into output buffer */
11336 			if (invalp != outvalp) {
11337 				bcopy(invalp, outvalp, inlen);
11338 			}
11339 			*outlenp = inlen;
11340 			return (0);
11341 		}
11342 		case IPV6_UNICAST_HOPS:
11343 			/* Recorded in transport above IP */
11344 			break;	/* goto sizeof (int) option return */
11345 		case IPV6_UNSPEC_SRC:
11346 			/* Allow sending with a zero source address */
11347 			if (!checkonly) {
11348 				mutex_enter(&connp->conn_lock);
11349 				connp->conn_unspec_src = *i1 ? 1 : 0;
11350 				mutex_exit(&connp->conn_lock);
11351 			}
11352 			break;	/* goto sizeof (int) option return */
11353 		case IPV6_RECVPKTINFO:
11354 			if (!checkonly) {
11355 				mutex_enter(&connp->conn_lock);
11356 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11357 				mutex_exit(&connp->conn_lock);
11358 			}
11359 			break;	/* goto sizeof (int) option return */
11360 		case IPV6_RECVTCLASS:
11361 			if (!checkonly) {
11362 				if (*i1 < 0 || *i1 > 1) {
11363 					return (EINVAL);
11364 				}
11365 				mutex_enter(&connp->conn_lock);
11366 				connp->conn_ipv6_recvtclass = *i1;
11367 				mutex_exit(&connp->conn_lock);
11368 			}
11369 			break;
11370 		case IPV6_RECVPATHMTU:
11371 			if (!checkonly) {
11372 				if (*i1 < 0 || *i1 > 1) {
11373 					return (EINVAL);
11374 				}
11375 				mutex_enter(&connp->conn_lock);
11376 				connp->conn_ipv6_recvpathmtu = *i1;
11377 				mutex_exit(&connp->conn_lock);
11378 			}
11379 			break;
11380 		case IPV6_RECVHOPLIMIT:
11381 			if (!checkonly) {
11382 				mutex_enter(&connp->conn_lock);
11383 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11384 				mutex_exit(&connp->conn_lock);
11385 			}
11386 			break;	/* goto sizeof (int) option return */
11387 		case IPV6_RECVHOPOPTS:
11388 			if (!checkonly) {
11389 				mutex_enter(&connp->conn_lock);
11390 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11391 				mutex_exit(&connp->conn_lock);
11392 			}
11393 			break;	/* goto sizeof (int) option return */
11394 		case IPV6_RECVDSTOPTS:
11395 			if (!checkonly) {
11396 				mutex_enter(&connp->conn_lock);
11397 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11398 				mutex_exit(&connp->conn_lock);
11399 			}
11400 			break;	/* goto sizeof (int) option return */
11401 		case IPV6_RECVRTHDR:
11402 			if (!checkonly) {
11403 				mutex_enter(&connp->conn_lock);
11404 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11405 				mutex_exit(&connp->conn_lock);
11406 			}
11407 			break;	/* goto sizeof (int) option return */
11408 		case IPV6_RECVRTHDRDSTOPTS:
11409 			if (!checkonly) {
11410 				mutex_enter(&connp->conn_lock);
11411 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11412 				mutex_exit(&connp->conn_lock);
11413 			}
11414 			break;	/* goto sizeof (int) option return */
11415 		case IPV6_PKTINFO:
11416 			if (inlen == 0)
11417 				return (-EINVAL);	/* clearing option */
11418 			error = ip6_set_pktinfo(cr, connp,
11419 			    (struct in6_pktinfo *)invalp);
11420 			if (error != 0)
11421 				*outlenp = 0;
11422 			else
11423 				*outlenp = inlen;
11424 			return (error);
11425 		case IPV6_NEXTHOP: {
11426 			struct sockaddr_in6 *sin6;
11427 
11428 			/* Verify that the nexthop is reachable */
11429 			if (inlen == 0)
11430 				return (-EINVAL);	/* clearing option */
11431 
11432 			sin6 = (struct sockaddr_in6 *)invalp;
11433 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11434 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11435 			    NULL, MATCH_IRE_DEFAULT, ipst);
11436 
11437 			if (ire == NULL) {
11438 				*outlenp = 0;
11439 				return (EHOSTUNREACH);
11440 			}
11441 			ire_refrele(ire);
11442 			return (-EINVAL);
11443 		}
11444 		case IPV6_SEC_OPT:
11445 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11446 			if (error != 0) {
11447 				*outlenp = 0;
11448 				return (error);
11449 			}
11450 			break;
11451 		case IPV6_SRC_PREFERENCES: {
11452 			/*
11453 			 * This is implemented strictly in the ip module
11454 			 * (here and in tcp_opt_*() to accomodate tcp
11455 			 * sockets).  Modules above ip pass this option
11456 			 * down here since ip is the only one that needs to
11457 			 * be aware of source address preferences.
11458 			 *
11459 			 * This socket option only affects connected
11460 			 * sockets that haven't already bound to a specific
11461 			 * IPv6 address.  In other words, sockets that
11462 			 * don't call bind() with an address other than the
11463 			 * unspecified address and that call connect().
11464 			 * ip_bind_connected_v6() passes these preferences
11465 			 * to the ipif_select_source_v6() function.
11466 			 */
11467 			if (inlen != sizeof (uint32_t))
11468 				return (EINVAL);
11469 			error = ip6_set_src_preferences(connp,
11470 			    *(uint32_t *)invalp);
11471 			if (error != 0) {
11472 				*outlenp = 0;
11473 				return (error);
11474 			} else {
11475 				*outlenp = sizeof (uint32_t);
11476 			}
11477 			break;
11478 		}
11479 		case IPV6_V6ONLY:
11480 			if (*i1 < 0 || *i1 > 1) {
11481 				return (EINVAL);
11482 			}
11483 			mutex_enter(&connp->conn_lock);
11484 			connp->conn_ipv6_v6only = *i1;
11485 			mutex_exit(&connp->conn_lock);
11486 			break;
11487 		default:
11488 			return (-EINVAL);
11489 		}
11490 		break;
11491 	default:
11492 		/*
11493 		 * "soft" error (negative)
11494 		 * option not handled at this level
11495 		 * Note: Do not modify *outlenp
11496 		 */
11497 		return (-EINVAL);
11498 	}
11499 	/*
11500 	 * Common case of return from an option that is sizeof (int)
11501 	 */
11502 	*(int *)outvalp = *i1;
11503 	*outlenp = sizeof (int);
11504 	return (0);
11505 }
11506 
11507 /*
11508  * This routine gets default values of certain options whose default
11509  * values are maintained by protocol specific code
11510  */
11511 /* ARGSUSED */
11512 int
11513 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11514 {
11515 	int *i1 = (int *)ptr;
11516 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11517 
11518 	switch (level) {
11519 	case IPPROTO_IP:
11520 		switch (name) {
11521 		case IP_MULTICAST_TTL:
11522 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11523 			return (sizeof (uchar_t));
11524 		case IP_MULTICAST_LOOP:
11525 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11526 			return (sizeof (uchar_t));
11527 		default:
11528 			return (-1);
11529 		}
11530 	case IPPROTO_IPV6:
11531 		switch (name) {
11532 		case IPV6_UNICAST_HOPS:
11533 			*i1 = ipst->ips_ipv6_def_hops;
11534 			return (sizeof (int));
11535 		case IPV6_MULTICAST_HOPS:
11536 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11537 			return (sizeof (int));
11538 		case IPV6_MULTICAST_LOOP:
11539 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11540 			return (sizeof (int));
11541 		case IPV6_V6ONLY:
11542 			*i1 = 1;
11543 			return (sizeof (int));
11544 		default:
11545 			return (-1);
11546 		}
11547 	default:
11548 		return (-1);
11549 	}
11550 	/* NOTREACHED */
11551 }
11552 
11553 /*
11554  * Given a destination address and a pointer to where to put the information
11555  * this routine fills in the mtuinfo.
11556  */
11557 int
11558 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11559     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11560 {
11561 	ire_t *ire;
11562 	ip_stack_t	*ipst = ns->netstack_ip;
11563 
11564 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11565 		return (-1);
11566 
11567 	bzero(mtuinfo, sizeof (*mtuinfo));
11568 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11569 	mtuinfo->ip6m_addr.sin6_port = port;
11570 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11571 
11572 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11573 	if (ire != NULL) {
11574 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11575 		ire_refrele(ire);
11576 	} else {
11577 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11578 	}
11579 	return (sizeof (struct ip6_mtuinfo));
11580 }
11581 
11582 /*
11583  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11584  * checking of cred and that ip_g_mrouter is set should be done and
11585  * isn't.  This doesn't matter as the error checking is done properly for the
11586  * other MRT options coming in through ip_opt_set.
11587  */
11588 int
11589 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11590 {
11591 	conn_t		*connp = Q_TO_CONN(q);
11592 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11593 
11594 	switch (level) {
11595 	case IPPROTO_IP:
11596 		switch (name) {
11597 		case MRT_VERSION:
11598 		case MRT_ASSERT:
11599 			(void) ip_mrouter_get(name, q, ptr);
11600 			return (sizeof (int));
11601 		case IP_SEC_OPT:
11602 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11603 		case IP_NEXTHOP:
11604 			if (connp->conn_nexthop_set) {
11605 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11606 				return (sizeof (ipaddr_t));
11607 			} else
11608 				return (0);
11609 		case IP_RECVPKTINFO:
11610 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11611 			return (sizeof (int));
11612 		default:
11613 			break;
11614 		}
11615 		break;
11616 	case IPPROTO_IPV6:
11617 		switch (name) {
11618 		case IPV6_SEC_OPT:
11619 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11620 		case IPV6_SRC_PREFERENCES: {
11621 			return (ip6_get_src_preferences(connp,
11622 			    (uint32_t *)ptr));
11623 		}
11624 		case IPV6_V6ONLY:
11625 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11626 			return (sizeof (int));
11627 		case IPV6_PATHMTU:
11628 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11629 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11630 		default:
11631 			break;
11632 		}
11633 		break;
11634 	default:
11635 		break;
11636 	}
11637 	return (-1);
11638 }
11639 /* Named Dispatch routine to get a current value out of our parameter table. */
11640 /* ARGSUSED */
11641 static int
11642 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11643 {
11644 	ipparam_t *ippa = (ipparam_t *)cp;
11645 
11646 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11647 	return (0);
11648 }
11649 
11650 /* ARGSUSED */
11651 static int
11652 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11653 {
11654 
11655 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11656 	return (0);
11657 }
11658 
11659 /*
11660  * Set ip{,6}_forwarding values.  This means walking through all of the
11661  * ill's and toggling their forwarding values.
11662  */
11663 /* ARGSUSED */
11664 static int
11665 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11666 {
11667 	long new_value;
11668 	int *forwarding_value = (int *)cp;
11669 	ill_t *ill;
11670 	boolean_t isv6;
11671 	ill_walk_context_t ctx;
11672 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11673 
11674 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11675 
11676 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11677 	    new_value < 0 || new_value > 1) {
11678 		return (EINVAL);
11679 	}
11680 
11681 	*forwarding_value = new_value;
11682 
11683 	/*
11684 	 * Regardless of the current value of ip_forwarding, set all per-ill
11685 	 * values of ip_forwarding to the value being set.
11686 	 *
11687 	 * Bring all the ill's up to date with the new global value.
11688 	 */
11689 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11690 
11691 	if (isv6)
11692 		ill = ILL_START_WALK_V6(&ctx, ipst);
11693 	else
11694 		ill = ILL_START_WALK_V4(&ctx, ipst);
11695 
11696 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11697 		(void) ill_forward_set(ill, new_value != 0);
11698 
11699 	rw_exit(&ipst->ips_ill_g_lock);
11700 	return (0);
11701 }
11702 
11703 /*
11704  * Walk through the param array specified registering each element with the
11705  * Named Dispatch handler. This is called only during init. So it is ok
11706  * not to acquire any locks
11707  */
11708 static boolean_t
11709 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11710     ipndp_t *ipnd, size_t ipnd_cnt)
11711 {
11712 	for (; ippa_cnt-- > 0; ippa++) {
11713 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11714 			if (!nd_load(ndp, ippa->ip_param_name,
11715 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11716 				nd_free(ndp);
11717 				return (B_FALSE);
11718 			}
11719 		}
11720 	}
11721 
11722 	for (; ipnd_cnt-- > 0; ipnd++) {
11723 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11724 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11725 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11726 			    ipnd->ip_ndp_data)) {
11727 				nd_free(ndp);
11728 				return (B_FALSE);
11729 			}
11730 		}
11731 	}
11732 
11733 	return (B_TRUE);
11734 }
11735 
11736 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11737 /* ARGSUSED */
11738 static int
11739 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11740 {
11741 	long		new_value;
11742 	ipparam_t	*ippa = (ipparam_t *)cp;
11743 
11744 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11745 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11746 		return (EINVAL);
11747 	}
11748 	ippa->ip_param_value = new_value;
11749 	return (0);
11750 }
11751 
11752 /*
11753  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11754  * When an ipf is passed here for the first time, if
11755  * we already have in-order fragments on the queue, we convert from the fast-
11756  * path reassembly scheme to the hard-case scheme.  From then on, additional
11757  * fragments are reassembled here.  We keep track of the start and end offsets
11758  * of each piece, and the number of holes in the chain.  When the hole count
11759  * goes to zero, we are done!
11760  *
11761  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11762  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11763  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11764  * after the call to ip_reassemble().
11765  */
11766 int
11767 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11768     size_t msg_len)
11769 {
11770 	uint_t	end;
11771 	mblk_t	*next_mp;
11772 	mblk_t	*mp1;
11773 	uint_t	offset;
11774 	boolean_t incr_dups = B_TRUE;
11775 	boolean_t offset_zero_seen = B_FALSE;
11776 	boolean_t pkt_boundary_checked = B_FALSE;
11777 
11778 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11779 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11780 
11781 	/* Add in byte count */
11782 	ipf->ipf_count += msg_len;
11783 	if (ipf->ipf_end) {
11784 		/*
11785 		 * We were part way through in-order reassembly, but now there
11786 		 * is a hole.  We walk through messages already queued, and
11787 		 * mark them for hard case reassembly.  We know that up till
11788 		 * now they were in order starting from offset zero.
11789 		 */
11790 		offset = 0;
11791 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11792 			IP_REASS_SET_START(mp1, offset);
11793 			if (offset == 0) {
11794 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11795 				offset = -ipf->ipf_nf_hdr_len;
11796 			}
11797 			offset += mp1->b_wptr - mp1->b_rptr;
11798 			IP_REASS_SET_END(mp1, offset);
11799 		}
11800 		/* One hole at the end. */
11801 		ipf->ipf_hole_cnt = 1;
11802 		/* Brand it as a hard case, forever. */
11803 		ipf->ipf_end = 0;
11804 	}
11805 	/* Walk through all the new pieces. */
11806 	do {
11807 		end = start + (mp->b_wptr - mp->b_rptr);
11808 		/*
11809 		 * If start is 0, decrease 'end' only for the first mblk of
11810 		 * the fragment. Otherwise 'end' can get wrong value in the
11811 		 * second pass of the loop if first mblk is exactly the
11812 		 * size of ipf_nf_hdr_len.
11813 		 */
11814 		if (start == 0 && !offset_zero_seen) {
11815 			/* First segment */
11816 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11817 			end -= ipf->ipf_nf_hdr_len;
11818 			offset_zero_seen = B_TRUE;
11819 		}
11820 		next_mp = mp->b_cont;
11821 		/*
11822 		 * We are checking to see if there is any interesing data
11823 		 * to process.  If there isn't and the mblk isn't the
11824 		 * one which carries the unfragmentable header then we
11825 		 * drop it.  It's possible to have just the unfragmentable
11826 		 * header come through without any data.  That needs to be
11827 		 * saved.
11828 		 *
11829 		 * If the assert at the top of this function holds then the
11830 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11831 		 * is infrequently traveled enough that the test is left in
11832 		 * to protect against future code changes which break that
11833 		 * invariant.
11834 		 */
11835 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11836 			/* Empty.  Blast it. */
11837 			IP_REASS_SET_START(mp, 0);
11838 			IP_REASS_SET_END(mp, 0);
11839 			/*
11840 			 * If the ipf points to the mblk we are about to free,
11841 			 * update ipf to point to the next mblk (or NULL
11842 			 * if none).
11843 			 */
11844 			if (ipf->ipf_mp->b_cont == mp)
11845 				ipf->ipf_mp->b_cont = next_mp;
11846 			freeb(mp);
11847 			continue;
11848 		}
11849 		mp->b_cont = NULL;
11850 		IP_REASS_SET_START(mp, start);
11851 		IP_REASS_SET_END(mp, end);
11852 		if (!ipf->ipf_tail_mp) {
11853 			ipf->ipf_tail_mp = mp;
11854 			ipf->ipf_mp->b_cont = mp;
11855 			if (start == 0 || !more) {
11856 				ipf->ipf_hole_cnt = 1;
11857 				/*
11858 				 * if the first fragment comes in more than one
11859 				 * mblk, this loop will be executed for each
11860 				 * mblk. Need to adjust hole count so exiting
11861 				 * this routine will leave hole count at 1.
11862 				 */
11863 				if (next_mp)
11864 					ipf->ipf_hole_cnt++;
11865 			} else
11866 				ipf->ipf_hole_cnt = 2;
11867 			continue;
11868 		} else if (ipf->ipf_last_frag_seen && !more &&
11869 		    !pkt_boundary_checked) {
11870 			/*
11871 			 * We check datagram boundary only if this fragment
11872 			 * claims to be the last fragment and we have seen a
11873 			 * last fragment in the past too. We do this only
11874 			 * once for a given fragment.
11875 			 *
11876 			 * start cannot be 0 here as fragments with start=0
11877 			 * and MF=0 gets handled as a complete packet. These
11878 			 * fragments should not reach here.
11879 			 */
11880 
11881 			if (start + msgdsize(mp) !=
11882 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11883 				/*
11884 				 * We have two fragments both of which claim
11885 				 * to be the last fragment but gives conflicting
11886 				 * information about the whole datagram size.
11887 				 * Something fishy is going on. Drop the
11888 				 * fragment and free up the reassembly list.
11889 				 */
11890 				return (IP_REASS_FAILED);
11891 			}
11892 
11893 			/*
11894 			 * We shouldn't come to this code block again for this
11895 			 * particular fragment.
11896 			 */
11897 			pkt_boundary_checked = B_TRUE;
11898 		}
11899 
11900 		/* New stuff at or beyond tail? */
11901 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11902 		if (start >= offset) {
11903 			if (ipf->ipf_last_frag_seen) {
11904 				/* current fragment is beyond last fragment */
11905 				return (IP_REASS_FAILED);
11906 			}
11907 			/* Link it on end. */
11908 			ipf->ipf_tail_mp->b_cont = mp;
11909 			ipf->ipf_tail_mp = mp;
11910 			if (more) {
11911 				if (start != offset)
11912 					ipf->ipf_hole_cnt++;
11913 			} else if (start == offset && next_mp == NULL)
11914 					ipf->ipf_hole_cnt--;
11915 			continue;
11916 		}
11917 		mp1 = ipf->ipf_mp->b_cont;
11918 		offset = IP_REASS_START(mp1);
11919 		/* New stuff at the front? */
11920 		if (start < offset) {
11921 			if (start == 0) {
11922 				if (end >= offset) {
11923 					/* Nailed the hole at the begining. */
11924 					ipf->ipf_hole_cnt--;
11925 				}
11926 			} else if (end < offset) {
11927 				/*
11928 				 * A hole, stuff, and a hole where there used
11929 				 * to be just a hole.
11930 				 */
11931 				ipf->ipf_hole_cnt++;
11932 			}
11933 			mp->b_cont = mp1;
11934 			/* Check for overlap. */
11935 			while (end > offset) {
11936 				if (end < IP_REASS_END(mp1)) {
11937 					mp->b_wptr -= end - offset;
11938 					IP_REASS_SET_END(mp, offset);
11939 					BUMP_MIB(ill->ill_ip_mib,
11940 					    ipIfStatsReasmPartDups);
11941 					break;
11942 				}
11943 				/* Did we cover another hole? */
11944 				if ((mp1->b_cont &&
11945 				    IP_REASS_END(mp1) !=
11946 				    IP_REASS_START(mp1->b_cont) &&
11947 				    end >= IP_REASS_START(mp1->b_cont)) ||
11948 				    (!ipf->ipf_last_frag_seen && !more)) {
11949 					ipf->ipf_hole_cnt--;
11950 				}
11951 				/* Clip out mp1. */
11952 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11953 					/*
11954 					 * After clipping out mp1, this guy
11955 					 * is now hanging off the end.
11956 					 */
11957 					ipf->ipf_tail_mp = mp;
11958 				}
11959 				IP_REASS_SET_START(mp1, 0);
11960 				IP_REASS_SET_END(mp1, 0);
11961 				/* Subtract byte count */
11962 				ipf->ipf_count -= mp1->b_datap->db_lim -
11963 				    mp1->b_datap->db_base;
11964 				freeb(mp1);
11965 				BUMP_MIB(ill->ill_ip_mib,
11966 				    ipIfStatsReasmPartDups);
11967 				mp1 = mp->b_cont;
11968 				if (!mp1)
11969 					break;
11970 				offset = IP_REASS_START(mp1);
11971 			}
11972 			ipf->ipf_mp->b_cont = mp;
11973 			continue;
11974 		}
11975 		/*
11976 		 * The new piece starts somewhere between the start of the head
11977 		 * and before the end of the tail.
11978 		 */
11979 		for (; mp1; mp1 = mp1->b_cont) {
11980 			offset = IP_REASS_END(mp1);
11981 			if (start < offset) {
11982 				if (end <= offset) {
11983 					/* Nothing new. */
11984 					IP_REASS_SET_START(mp, 0);
11985 					IP_REASS_SET_END(mp, 0);
11986 					/* Subtract byte count */
11987 					ipf->ipf_count -= mp->b_datap->db_lim -
11988 					    mp->b_datap->db_base;
11989 					if (incr_dups) {
11990 						ipf->ipf_num_dups++;
11991 						incr_dups = B_FALSE;
11992 					}
11993 					freeb(mp);
11994 					BUMP_MIB(ill->ill_ip_mib,
11995 					    ipIfStatsReasmDuplicates);
11996 					break;
11997 				}
11998 				/*
11999 				 * Trim redundant stuff off beginning of new
12000 				 * piece.
12001 				 */
12002 				IP_REASS_SET_START(mp, offset);
12003 				mp->b_rptr += offset - start;
12004 				BUMP_MIB(ill->ill_ip_mib,
12005 				    ipIfStatsReasmPartDups);
12006 				start = offset;
12007 				if (!mp1->b_cont) {
12008 					/*
12009 					 * After trimming, this guy is now
12010 					 * hanging off the end.
12011 					 */
12012 					mp1->b_cont = mp;
12013 					ipf->ipf_tail_mp = mp;
12014 					if (!more) {
12015 						ipf->ipf_hole_cnt--;
12016 					}
12017 					break;
12018 				}
12019 			}
12020 			if (start >= IP_REASS_START(mp1->b_cont))
12021 				continue;
12022 			/* Fill a hole */
12023 			if (start > offset)
12024 				ipf->ipf_hole_cnt++;
12025 			mp->b_cont = mp1->b_cont;
12026 			mp1->b_cont = mp;
12027 			mp1 = mp->b_cont;
12028 			offset = IP_REASS_START(mp1);
12029 			if (end >= offset) {
12030 				ipf->ipf_hole_cnt--;
12031 				/* Check for overlap. */
12032 				while (end > offset) {
12033 					if (end < IP_REASS_END(mp1)) {
12034 						mp->b_wptr -= end - offset;
12035 						IP_REASS_SET_END(mp, offset);
12036 						/*
12037 						 * TODO we might bump
12038 						 * this up twice if there is
12039 						 * overlap at both ends.
12040 						 */
12041 						BUMP_MIB(ill->ill_ip_mib,
12042 						    ipIfStatsReasmPartDups);
12043 						break;
12044 					}
12045 					/* Did we cover another hole? */
12046 					if ((mp1->b_cont &&
12047 					    IP_REASS_END(mp1)
12048 					    != IP_REASS_START(mp1->b_cont) &&
12049 					    end >=
12050 					    IP_REASS_START(mp1->b_cont)) ||
12051 					    (!ipf->ipf_last_frag_seen &&
12052 					    !more)) {
12053 						ipf->ipf_hole_cnt--;
12054 					}
12055 					/* Clip out mp1. */
12056 					if ((mp->b_cont = mp1->b_cont) ==
12057 					    NULL) {
12058 						/*
12059 						 * After clipping out mp1,
12060 						 * this guy is now hanging
12061 						 * off the end.
12062 						 */
12063 						ipf->ipf_tail_mp = mp;
12064 					}
12065 					IP_REASS_SET_START(mp1, 0);
12066 					IP_REASS_SET_END(mp1, 0);
12067 					/* Subtract byte count */
12068 					ipf->ipf_count -=
12069 					    mp1->b_datap->db_lim -
12070 					    mp1->b_datap->db_base;
12071 					freeb(mp1);
12072 					BUMP_MIB(ill->ill_ip_mib,
12073 					    ipIfStatsReasmPartDups);
12074 					mp1 = mp->b_cont;
12075 					if (!mp1)
12076 						break;
12077 					offset = IP_REASS_START(mp1);
12078 				}
12079 			}
12080 			break;
12081 		}
12082 	} while (start = end, mp = next_mp);
12083 
12084 	/* Fragment just processed could be the last one. Remember this fact */
12085 	if (!more)
12086 		ipf->ipf_last_frag_seen = B_TRUE;
12087 
12088 	/* Still got holes? */
12089 	if (ipf->ipf_hole_cnt)
12090 		return (IP_REASS_PARTIAL);
12091 	/* Clean up overloaded fields to avoid upstream disasters. */
12092 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12093 		IP_REASS_SET_START(mp1, 0);
12094 		IP_REASS_SET_END(mp1, 0);
12095 	}
12096 	return (IP_REASS_COMPLETE);
12097 }
12098 
12099 /*
12100  * ipsec processing for the fast path, used for input UDP Packets
12101  * Returns true if ready for passup to UDP.
12102  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12103  * was an ESP-in-UDP packet, etc.).
12104  */
12105 static boolean_t
12106 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12107     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12108 {
12109 	uint32_t	ill_index;
12110 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12111 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12112 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12113 	udp_t		*udp = connp->conn_udp;
12114 
12115 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12116 	/* The ill_index of the incoming ILL */
12117 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12118 
12119 	/* pass packet up to the transport */
12120 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12121 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12122 		    NULL, mctl_present);
12123 		if (*first_mpp == NULL) {
12124 			return (B_FALSE);
12125 		}
12126 	}
12127 
12128 	/* Initiate IPPF processing for fastpath UDP */
12129 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12130 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12131 		if (*mpp == NULL) {
12132 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12133 			    "deferred/dropped during IPPF processing\n"));
12134 			return (B_FALSE);
12135 		}
12136 	}
12137 	/*
12138 	 * Remove 0-spi if it's 0, or move everything behind
12139 	 * the UDP header over it and forward to ESP via
12140 	 * ip_proto_input().
12141 	 */
12142 	if (udp->udp_nat_t_endpoint) {
12143 		if (mctl_present) {
12144 			/* mctl_present *shouldn't* happen. */
12145 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12146 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12147 			    &ipss->ipsec_dropper);
12148 			*first_mpp = NULL;
12149 			return (B_FALSE);
12150 		}
12151 
12152 		/* "ill" is "recv_ill" in actuality. */
12153 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12154 			return (B_FALSE);
12155 
12156 		/* Else continue like a normal UDP packet. */
12157 	}
12158 
12159 	/*
12160 	 * We make the checks as below since we are in the fast path
12161 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12162 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12163 	 */
12164 	if (connp->conn_recvif || connp->conn_recvslla ||
12165 	    connp->conn_ip_recvpktinfo) {
12166 		if (connp->conn_recvif) {
12167 			in_flags = IPF_RECVIF;
12168 		}
12169 		/*
12170 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12171 		 * so the flag passed to ip_add_info is based on IP version
12172 		 * of connp.
12173 		 */
12174 		if (connp->conn_ip_recvpktinfo) {
12175 			if (connp->conn_af_isv6) {
12176 				/*
12177 				 * V6 only needs index
12178 				 */
12179 				in_flags |= IPF_RECVIF;
12180 			} else {
12181 				/*
12182 				 * V4 needs index + matching address.
12183 				 */
12184 				in_flags |= IPF_RECVADDR;
12185 			}
12186 		}
12187 		if (connp->conn_recvslla) {
12188 			in_flags |= IPF_RECVSLLA;
12189 		}
12190 		/*
12191 		 * since in_flags are being set ill will be
12192 		 * referenced in ip_add_info, so it better not
12193 		 * be NULL.
12194 		 */
12195 		/*
12196 		 * the actual data will be contained in b_cont
12197 		 * upon successful return of the following call.
12198 		 * If the call fails then the original mblk is
12199 		 * returned.
12200 		 */
12201 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12202 		    ipst);
12203 	}
12204 
12205 	return (B_TRUE);
12206 }
12207 
12208 /*
12209  * Fragmentation reassembly.  Each ILL has a hash table for
12210  * queuing packets undergoing reassembly for all IPIFs
12211  * associated with the ILL.  The hash is based on the packet
12212  * IP ident field.  The ILL frag hash table was allocated
12213  * as a timer block at the time the ILL was created.  Whenever
12214  * there is anything on the reassembly queue, the timer will
12215  * be running.  Returns B_TRUE if successful else B_FALSE;
12216  * frees mp on failure.
12217  */
12218 static boolean_t
12219 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12220     uint32_t *cksum_val, uint16_t *cksum_flags)
12221 {
12222 	uint32_t	frag_offset_flags;
12223 	mblk_t		*mp = *mpp;
12224 	mblk_t		*t_mp;
12225 	ipaddr_t	dst;
12226 	uint8_t		proto = ipha->ipha_protocol;
12227 	uint32_t	sum_val;
12228 	uint16_t	sum_flags;
12229 	ipf_t		*ipf;
12230 	ipf_t		**ipfp;
12231 	ipfb_t		*ipfb;
12232 	uint16_t	ident;
12233 	uint32_t	offset;
12234 	ipaddr_t	src;
12235 	uint_t		hdr_length;
12236 	uint32_t	end;
12237 	mblk_t		*mp1;
12238 	mblk_t		*tail_mp;
12239 	size_t		count;
12240 	size_t		msg_len;
12241 	uint8_t		ecn_info = 0;
12242 	uint32_t	packet_size;
12243 	boolean_t	pruned = B_FALSE;
12244 	ip_stack_t *ipst = ill->ill_ipst;
12245 
12246 	if (cksum_val != NULL)
12247 		*cksum_val = 0;
12248 	if (cksum_flags != NULL)
12249 		*cksum_flags = 0;
12250 
12251 	/*
12252 	 * Drop the fragmented as early as possible, if
12253 	 * we don't have resource(s) to re-assemble.
12254 	 */
12255 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12256 		freemsg(mp);
12257 		return (B_FALSE);
12258 	}
12259 
12260 	/* Check for fragmentation offset; return if there's none */
12261 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12262 	    (IPH_MF | IPH_OFFSET)) == 0)
12263 		return (B_TRUE);
12264 
12265 	/*
12266 	 * We utilize hardware computed checksum info only for UDP since
12267 	 * IP fragmentation is a normal occurrence for the protocol.  In
12268 	 * addition, checksum offload support for IP fragments carrying
12269 	 * UDP payload is commonly implemented across network adapters.
12270 	 */
12271 	ASSERT(recv_ill != NULL);
12272 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12273 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12274 		mblk_t *mp1 = mp->b_cont;
12275 		int32_t len;
12276 
12277 		/* Record checksum information from the packet */
12278 		sum_val = (uint32_t)DB_CKSUM16(mp);
12279 		sum_flags = DB_CKSUMFLAGS(mp);
12280 
12281 		/* IP payload offset from beginning of mblk */
12282 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12283 
12284 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12285 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12286 		    offset >= DB_CKSUMSTART(mp) &&
12287 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12288 			uint32_t adj;
12289 			/*
12290 			 * Partial checksum has been calculated by hardware
12291 			 * and attached to the packet; in addition, any
12292 			 * prepended extraneous data is even byte aligned.
12293 			 * If any such data exists, we adjust the checksum;
12294 			 * this would also handle any postpended data.
12295 			 */
12296 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12297 			    mp, mp1, len, adj);
12298 
12299 			/* One's complement subtract extraneous checksum */
12300 			if (adj >= sum_val)
12301 				sum_val = ~(adj - sum_val) & 0xFFFF;
12302 			else
12303 				sum_val -= adj;
12304 		}
12305 	} else {
12306 		sum_val = 0;
12307 		sum_flags = 0;
12308 	}
12309 
12310 	/* Clear hardware checksumming flag */
12311 	DB_CKSUMFLAGS(mp) = 0;
12312 
12313 	ident = ipha->ipha_ident;
12314 	offset = (frag_offset_flags << 3) & 0xFFFF;
12315 	src = ipha->ipha_src;
12316 	dst = ipha->ipha_dst;
12317 	hdr_length = IPH_HDR_LENGTH(ipha);
12318 	end = ntohs(ipha->ipha_length) - hdr_length;
12319 
12320 	/* If end == 0 then we have a packet with no data, so just free it */
12321 	if (end == 0) {
12322 		freemsg(mp);
12323 		return (B_FALSE);
12324 	}
12325 
12326 	/* Record the ECN field info. */
12327 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12328 	if (offset != 0) {
12329 		/*
12330 		 * If this isn't the first piece, strip the header, and
12331 		 * add the offset to the end value.
12332 		 */
12333 		mp->b_rptr += hdr_length;
12334 		end += offset;
12335 	}
12336 
12337 	msg_len = MBLKSIZE(mp);
12338 	tail_mp = mp;
12339 	while (tail_mp->b_cont != NULL) {
12340 		tail_mp = tail_mp->b_cont;
12341 		msg_len += MBLKSIZE(tail_mp);
12342 	}
12343 
12344 	/* If the reassembly list for this ILL will get too big, prune it */
12345 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12346 	    ipst->ips_ip_reass_queue_bytes) {
12347 		ill_frag_prune(ill,
12348 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12349 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12350 		pruned = B_TRUE;
12351 	}
12352 
12353 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12354 	mutex_enter(&ipfb->ipfb_lock);
12355 
12356 	ipfp = &ipfb->ipfb_ipf;
12357 	/* Try to find an existing fragment queue for this packet. */
12358 	for (;;) {
12359 		ipf = ipfp[0];
12360 		if (ipf != NULL) {
12361 			/*
12362 			 * It has to match on ident and src/dst address.
12363 			 */
12364 			if (ipf->ipf_ident == ident &&
12365 			    ipf->ipf_src == src &&
12366 			    ipf->ipf_dst == dst &&
12367 			    ipf->ipf_protocol == proto) {
12368 				/*
12369 				 * If we have received too many
12370 				 * duplicate fragments for this packet
12371 				 * free it.
12372 				 */
12373 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12374 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12375 					freemsg(mp);
12376 					mutex_exit(&ipfb->ipfb_lock);
12377 					return (B_FALSE);
12378 				}
12379 				/* Found it. */
12380 				break;
12381 			}
12382 			ipfp = &ipf->ipf_hash_next;
12383 			continue;
12384 		}
12385 
12386 		/*
12387 		 * If we pruned the list, do we want to store this new
12388 		 * fragment?. We apply an optimization here based on the
12389 		 * fact that most fragments will be received in order.
12390 		 * So if the offset of this incoming fragment is zero,
12391 		 * it is the first fragment of a new packet. We will
12392 		 * keep it.  Otherwise drop the fragment, as we have
12393 		 * probably pruned the packet already (since the
12394 		 * packet cannot be found).
12395 		 */
12396 		if (pruned && offset != 0) {
12397 			mutex_exit(&ipfb->ipfb_lock);
12398 			freemsg(mp);
12399 			return (B_FALSE);
12400 		}
12401 
12402 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12403 			/*
12404 			 * Too many fragmented packets in this hash
12405 			 * bucket. Free the oldest.
12406 			 */
12407 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12408 		}
12409 
12410 		/* New guy.  Allocate a frag message. */
12411 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12412 		if (mp1 == NULL) {
12413 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12414 			freemsg(mp);
12415 reass_done:
12416 			mutex_exit(&ipfb->ipfb_lock);
12417 			return (B_FALSE);
12418 		}
12419 
12420 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12421 		mp1->b_cont = mp;
12422 
12423 		/* Initialize the fragment header. */
12424 		ipf = (ipf_t *)mp1->b_rptr;
12425 		ipf->ipf_mp = mp1;
12426 		ipf->ipf_ptphn = ipfp;
12427 		ipfp[0] = ipf;
12428 		ipf->ipf_hash_next = NULL;
12429 		ipf->ipf_ident = ident;
12430 		ipf->ipf_protocol = proto;
12431 		ipf->ipf_src = src;
12432 		ipf->ipf_dst = dst;
12433 		ipf->ipf_nf_hdr_len = 0;
12434 		/* Record reassembly start time. */
12435 		ipf->ipf_timestamp = gethrestime_sec();
12436 		/* Record ipf generation and account for frag header */
12437 		ipf->ipf_gen = ill->ill_ipf_gen++;
12438 		ipf->ipf_count = MBLKSIZE(mp1);
12439 		ipf->ipf_last_frag_seen = B_FALSE;
12440 		ipf->ipf_ecn = ecn_info;
12441 		ipf->ipf_num_dups = 0;
12442 		ipfb->ipfb_frag_pkts++;
12443 		ipf->ipf_checksum = 0;
12444 		ipf->ipf_checksum_flags = 0;
12445 
12446 		/* Store checksum value in fragment header */
12447 		if (sum_flags != 0) {
12448 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12449 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12450 			ipf->ipf_checksum = sum_val;
12451 			ipf->ipf_checksum_flags = sum_flags;
12452 		}
12453 
12454 		/*
12455 		 * We handle reassembly two ways.  In the easy case,
12456 		 * where all the fragments show up in order, we do
12457 		 * minimal bookkeeping, and just clip new pieces on
12458 		 * the end.  If we ever see a hole, then we go off
12459 		 * to ip_reassemble which has to mark the pieces and
12460 		 * keep track of the number of holes, etc.  Obviously,
12461 		 * the point of having both mechanisms is so we can
12462 		 * handle the easy case as efficiently as possible.
12463 		 */
12464 		if (offset == 0) {
12465 			/* Easy case, in-order reassembly so far. */
12466 			ipf->ipf_count += msg_len;
12467 			ipf->ipf_tail_mp = tail_mp;
12468 			/*
12469 			 * Keep track of next expected offset in
12470 			 * ipf_end.
12471 			 */
12472 			ipf->ipf_end = end;
12473 			ipf->ipf_nf_hdr_len = hdr_length;
12474 		} else {
12475 			/* Hard case, hole at the beginning. */
12476 			ipf->ipf_tail_mp = NULL;
12477 			/*
12478 			 * ipf_end == 0 means that we have given up
12479 			 * on easy reassembly.
12480 			 */
12481 			ipf->ipf_end = 0;
12482 
12483 			/* Forget checksum offload from now on */
12484 			ipf->ipf_checksum_flags = 0;
12485 
12486 			/*
12487 			 * ipf_hole_cnt is set by ip_reassemble.
12488 			 * ipf_count is updated by ip_reassemble.
12489 			 * No need to check for return value here
12490 			 * as we don't expect reassembly to complete
12491 			 * or fail for the first fragment itself.
12492 			 */
12493 			(void) ip_reassemble(mp, ipf,
12494 			    (frag_offset_flags & IPH_OFFSET) << 3,
12495 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12496 		}
12497 		/* Update per ipfb and ill byte counts */
12498 		ipfb->ipfb_count += ipf->ipf_count;
12499 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12500 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12501 		/* If the frag timer wasn't already going, start it. */
12502 		mutex_enter(&ill->ill_lock);
12503 		ill_frag_timer_start(ill);
12504 		mutex_exit(&ill->ill_lock);
12505 		goto reass_done;
12506 	}
12507 
12508 	/*
12509 	 * If the packet's flag has changed (it could be coming up
12510 	 * from an interface different than the previous, therefore
12511 	 * possibly different checksum capability), then forget about
12512 	 * any stored checksum states.  Otherwise add the value to
12513 	 * the existing one stored in the fragment header.
12514 	 */
12515 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12516 		sum_val += ipf->ipf_checksum;
12517 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12518 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12519 		ipf->ipf_checksum = sum_val;
12520 	} else if (ipf->ipf_checksum_flags != 0) {
12521 		/* Forget checksum offload from now on */
12522 		ipf->ipf_checksum_flags = 0;
12523 	}
12524 
12525 	/*
12526 	 * We have a new piece of a datagram which is already being
12527 	 * reassembled.  Update the ECN info if all IP fragments
12528 	 * are ECN capable.  If there is one which is not, clear
12529 	 * all the info.  If there is at least one which has CE
12530 	 * code point, IP needs to report that up to transport.
12531 	 */
12532 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12533 		if (ecn_info == IPH_ECN_CE)
12534 			ipf->ipf_ecn = IPH_ECN_CE;
12535 	} else {
12536 		ipf->ipf_ecn = IPH_ECN_NECT;
12537 	}
12538 	if (offset && ipf->ipf_end == offset) {
12539 		/* The new fragment fits at the end */
12540 		ipf->ipf_tail_mp->b_cont = mp;
12541 		/* Update the byte count */
12542 		ipf->ipf_count += msg_len;
12543 		/* Update per ipfb and ill byte counts */
12544 		ipfb->ipfb_count += msg_len;
12545 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12546 		atomic_add_32(&ill->ill_frag_count, msg_len);
12547 		if (frag_offset_flags & IPH_MF) {
12548 			/* More to come. */
12549 			ipf->ipf_end = end;
12550 			ipf->ipf_tail_mp = tail_mp;
12551 			goto reass_done;
12552 		}
12553 	} else {
12554 		/* Go do the hard cases. */
12555 		int ret;
12556 
12557 		if (offset == 0)
12558 			ipf->ipf_nf_hdr_len = hdr_length;
12559 
12560 		/* Save current byte count */
12561 		count = ipf->ipf_count;
12562 		ret = ip_reassemble(mp, ipf,
12563 		    (frag_offset_flags & IPH_OFFSET) << 3,
12564 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12565 		/* Count of bytes added and subtracted (freeb()ed) */
12566 		count = ipf->ipf_count - count;
12567 		if (count) {
12568 			/* Update per ipfb and ill byte counts */
12569 			ipfb->ipfb_count += count;
12570 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12571 			atomic_add_32(&ill->ill_frag_count, count);
12572 		}
12573 		if (ret == IP_REASS_PARTIAL) {
12574 			goto reass_done;
12575 		} else if (ret == IP_REASS_FAILED) {
12576 			/* Reassembly failed. Free up all resources */
12577 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12578 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12579 				IP_REASS_SET_START(t_mp, 0);
12580 				IP_REASS_SET_END(t_mp, 0);
12581 			}
12582 			freemsg(mp);
12583 			goto reass_done;
12584 		}
12585 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12586 	}
12587 	/*
12588 	 * We have completed reassembly.  Unhook the frag header from
12589 	 * the reassembly list.
12590 	 *
12591 	 * Before we free the frag header, record the ECN info
12592 	 * to report back to the transport.
12593 	 */
12594 	ecn_info = ipf->ipf_ecn;
12595 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12596 	ipfp = ipf->ipf_ptphn;
12597 
12598 	/* We need to supply these to caller */
12599 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12600 		sum_val = ipf->ipf_checksum;
12601 	else
12602 		sum_val = 0;
12603 
12604 	mp1 = ipf->ipf_mp;
12605 	count = ipf->ipf_count;
12606 	ipf = ipf->ipf_hash_next;
12607 	if (ipf != NULL)
12608 		ipf->ipf_ptphn = ipfp;
12609 	ipfp[0] = ipf;
12610 	atomic_add_32(&ill->ill_frag_count, -count);
12611 	ASSERT(ipfb->ipfb_count >= count);
12612 	ipfb->ipfb_count -= count;
12613 	ipfb->ipfb_frag_pkts--;
12614 	mutex_exit(&ipfb->ipfb_lock);
12615 	/* Ditch the frag header. */
12616 	mp = mp1->b_cont;
12617 
12618 	freeb(mp1);
12619 
12620 	/* Restore original IP length in header. */
12621 	packet_size = (uint32_t)msgdsize(mp);
12622 	if (packet_size > IP_MAXPACKET) {
12623 		freemsg(mp);
12624 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12625 		return (B_FALSE);
12626 	}
12627 
12628 	if (DB_REF(mp) > 1) {
12629 		mblk_t *mp2 = copymsg(mp);
12630 
12631 		freemsg(mp);
12632 		if (mp2 == NULL) {
12633 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12634 			return (B_FALSE);
12635 		}
12636 		mp = mp2;
12637 	}
12638 	ipha = (ipha_t *)mp->b_rptr;
12639 
12640 	ipha->ipha_length = htons((uint16_t)packet_size);
12641 	/* We're now complete, zip the frag state */
12642 	ipha->ipha_fragment_offset_and_flags = 0;
12643 	/* Record the ECN info. */
12644 	ipha->ipha_type_of_service &= 0xFC;
12645 	ipha->ipha_type_of_service |= ecn_info;
12646 	*mpp = mp;
12647 
12648 	/* Reassembly is successful; return checksum information if needed */
12649 	if (cksum_val != NULL)
12650 		*cksum_val = sum_val;
12651 	if (cksum_flags != NULL)
12652 		*cksum_flags = sum_flags;
12653 
12654 	return (B_TRUE);
12655 }
12656 
12657 /*
12658  * Perform ip header check sum update local options.
12659  * return B_TRUE if all is well, else return B_FALSE and release
12660  * the mp. caller is responsible for decrementing ire ref cnt.
12661  */
12662 static boolean_t
12663 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12664     ip_stack_t *ipst)
12665 {
12666 	mblk_t		*first_mp;
12667 	boolean_t	mctl_present;
12668 	uint16_t	sum;
12669 
12670 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12671 	/*
12672 	 * Don't do the checksum if it has gone through AH/ESP
12673 	 * processing.
12674 	 */
12675 	if (!mctl_present) {
12676 		sum = ip_csum_hdr(ipha);
12677 		if (sum != 0) {
12678 			if (ill != NULL) {
12679 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12680 			} else {
12681 				BUMP_MIB(&ipst->ips_ip_mib,
12682 				    ipIfStatsInCksumErrs);
12683 			}
12684 			freemsg(first_mp);
12685 			return (B_FALSE);
12686 		}
12687 	}
12688 
12689 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12690 		if (mctl_present)
12691 			freeb(first_mp);
12692 		return (B_FALSE);
12693 	}
12694 
12695 	return (B_TRUE);
12696 }
12697 
12698 /*
12699  * All udp packet are delivered to the local host via this routine.
12700  */
12701 void
12702 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12703     ill_t *recv_ill)
12704 {
12705 	uint32_t	sum;
12706 	uint32_t	u1;
12707 	boolean_t	mctl_present;
12708 	conn_t		*connp;
12709 	mblk_t		*first_mp;
12710 	uint16_t	*up;
12711 	ill_t		*ill = (ill_t *)q->q_ptr;
12712 	uint16_t	reass_hck_flags = 0;
12713 	ip_stack_t	*ipst;
12714 
12715 	ASSERT(recv_ill != NULL);
12716 	ipst = recv_ill->ill_ipst;
12717 
12718 #define	rptr    ((uchar_t *)ipha)
12719 
12720 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12721 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12722 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12723 	ASSERT(ill != NULL);
12724 
12725 	/*
12726 	 * FAST PATH for udp packets
12727 	 */
12728 
12729 	/* u1 is # words of IP options */
12730 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12731 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12732 
12733 	/* IP options present */
12734 	if (u1 != 0)
12735 		goto ipoptions;
12736 
12737 	/* Check the IP header checksum.  */
12738 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12739 		/* Clear the IP header h/w cksum flag */
12740 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12741 	} else if (!mctl_present) {
12742 		/*
12743 		 * Don't verify header checksum if this packet is coming
12744 		 * back from AH/ESP as we already did it.
12745 		 */
12746 #define	uph	((uint16_t *)ipha)
12747 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12748 		    uph[6] + uph[7] + uph[8] + uph[9];
12749 #undef	uph
12750 		/* finish doing IP checksum */
12751 		sum = (sum & 0xFFFF) + (sum >> 16);
12752 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12753 		if (sum != 0 && sum != 0xFFFF) {
12754 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12755 			freemsg(first_mp);
12756 			return;
12757 		}
12758 	}
12759 
12760 	/*
12761 	 * Count for SNMP of inbound packets for ire.
12762 	 * if mctl is present this might be a secure packet and
12763 	 * has already been counted for in ip_proto_input().
12764 	 */
12765 	if (!mctl_present) {
12766 		UPDATE_IB_PKT_COUNT(ire);
12767 		ire->ire_last_used_time = lbolt;
12768 	}
12769 
12770 	/* packet part of fragmented IP packet? */
12771 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12772 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12773 		goto fragmented;
12774 	}
12775 
12776 	/* u1 = IP header length (20 bytes) */
12777 	u1 = IP_SIMPLE_HDR_LENGTH;
12778 
12779 	/* packet does not contain complete IP & UDP headers */
12780 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12781 		goto udppullup;
12782 
12783 	/* up points to UDP header */
12784 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12785 #define	iphs    ((uint16_t *)ipha)
12786 
12787 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12788 	if (up[3] != 0) {
12789 		mblk_t *mp1 = mp->b_cont;
12790 		boolean_t cksum_err;
12791 		uint16_t hck_flags = 0;
12792 
12793 		/* Pseudo-header checksum */
12794 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12795 		    iphs[9] + up[2];
12796 
12797 		/*
12798 		 * Revert to software checksum calculation if the interface
12799 		 * isn't capable of checksum offload or if IPsec is present.
12800 		 */
12801 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12802 			hck_flags = DB_CKSUMFLAGS(mp);
12803 
12804 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12805 			IP_STAT(ipst, ip_in_sw_cksum);
12806 
12807 		IP_CKSUM_RECV(hck_flags, u1,
12808 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12809 		    (int32_t)((uchar_t *)up - rptr),
12810 		    mp, mp1, cksum_err);
12811 
12812 		if (cksum_err) {
12813 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12814 			if (hck_flags & HCK_FULLCKSUM)
12815 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12816 			else if (hck_flags & HCK_PARTIALCKSUM)
12817 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12818 			else
12819 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12820 
12821 			freemsg(first_mp);
12822 			return;
12823 		}
12824 	}
12825 
12826 	/* Non-fragmented broadcast or multicast packet? */
12827 	if (ire->ire_type == IRE_BROADCAST)
12828 		goto udpslowpath;
12829 
12830 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12831 	    ire->ire_zoneid, ipst)) != NULL) {
12832 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12833 		IP_STAT(ipst, ip_udp_fast_path);
12834 
12835 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12836 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12837 			freemsg(mp);
12838 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12839 		} else {
12840 			if (!mctl_present) {
12841 				BUMP_MIB(ill->ill_ip_mib,
12842 				    ipIfStatsHCInDelivers);
12843 			}
12844 			/*
12845 			 * mp and first_mp can change.
12846 			 */
12847 			if (ip_udp_check(q, connp, recv_ill,
12848 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12849 				/* Send it upstream */
12850 				(connp->conn_recv)(connp, mp, NULL);
12851 			}
12852 		}
12853 		/*
12854 		 * freeb() cannot deal with null mblk being passed
12855 		 * in and first_mp can be set to null in the call
12856 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12857 		 */
12858 		if (mctl_present && first_mp != NULL) {
12859 			freeb(first_mp);
12860 		}
12861 		CONN_DEC_REF(connp);
12862 		return;
12863 	}
12864 
12865 	/*
12866 	 * if we got here we know the packet is not fragmented and
12867 	 * has no options. The classifier could not find a conn_t and
12868 	 * most likely its an icmp packet so send it through slow path.
12869 	 */
12870 
12871 	goto udpslowpath;
12872 
12873 ipoptions:
12874 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12875 		goto slow_done;
12876 	}
12877 
12878 	UPDATE_IB_PKT_COUNT(ire);
12879 	ire->ire_last_used_time = lbolt;
12880 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12881 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12882 fragmented:
12883 		/*
12884 		 * "sum" and "reass_hck_flags" are non-zero if the
12885 		 * reassembled packet has a valid hardware computed
12886 		 * checksum information associated with it.
12887 		 */
12888 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12889 		    &reass_hck_flags)) {
12890 			goto slow_done;
12891 		}
12892 
12893 		/*
12894 		 * Make sure that first_mp points back to mp as
12895 		 * the mp we came in with could have changed in
12896 		 * ip_rput_fragment().
12897 		 */
12898 		ASSERT(!mctl_present);
12899 		ipha = (ipha_t *)mp->b_rptr;
12900 		first_mp = mp;
12901 	}
12902 
12903 	/* Now we have a complete datagram, destined for this machine. */
12904 	u1 = IPH_HDR_LENGTH(ipha);
12905 	/* Pull up the UDP header, if necessary. */
12906 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12907 udppullup:
12908 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12909 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12910 			freemsg(first_mp);
12911 			goto slow_done;
12912 		}
12913 		ipha = (ipha_t *)mp->b_rptr;
12914 	}
12915 
12916 	/*
12917 	 * Validate the checksum for the reassembled packet; for the
12918 	 * pullup case we calculate the payload checksum in software.
12919 	 */
12920 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12921 	if (up[3] != 0) {
12922 		boolean_t cksum_err;
12923 
12924 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12925 			IP_STAT(ipst, ip_in_sw_cksum);
12926 
12927 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12928 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12929 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12930 		    iphs[9] + up[2], sum, cksum_err);
12931 
12932 		if (cksum_err) {
12933 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12934 
12935 			if (reass_hck_flags & HCK_FULLCKSUM)
12936 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12937 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12938 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12939 			else
12940 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12941 
12942 			freemsg(first_mp);
12943 			goto slow_done;
12944 		}
12945 	}
12946 udpslowpath:
12947 
12948 	/* Clear hardware checksum flag to be safe */
12949 	DB_CKSUMFLAGS(mp) = 0;
12950 
12951 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12952 	    (ire->ire_type == IRE_BROADCAST),
12953 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12954 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12955 
12956 slow_done:
12957 	IP_STAT(ipst, ip_udp_slow_path);
12958 	return;
12959 
12960 #undef  iphs
12961 #undef  rptr
12962 }
12963 
12964 /* ARGSUSED */
12965 static mblk_t *
12966 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12967     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12968     ill_rx_ring_t *ill_ring)
12969 {
12970 	conn_t		*connp;
12971 	uint32_t	sum;
12972 	uint32_t	u1;
12973 	uint16_t	*up;
12974 	int		offset;
12975 	ssize_t		len;
12976 	mblk_t		*mp1;
12977 	boolean_t	syn_present = B_FALSE;
12978 	tcph_t		*tcph;
12979 	uint_t		tcph_flags;
12980 	uint_t		ip_hdr_len;
12981 	ill_t		*ill = (ill_t *)q->q_ptr;
12982 	zoneid_t	zoneid = ire->ire_zoneid;
12983 	boolean_t	cksum_err;
12984 	uint16_t	hck_flags = 0;
12985 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12986 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12987 
12988 #define	rptr	((uchar_t *)ipha)
12989 
12990 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12991 	ASSERT(ill != NULL);
12992 
12993 	/*
12994 	 * FAST PATH for tcp packets
12995 	 */
12996 
12997 	/* u1 is # words of IP options */
12998 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12999 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13000 
13001 	/* IP options present */
13002 	if (u1) {
13003 		goto ipoptions;
13004 	} else if (!mctl_present) {
13005 		/* Check the IP header checksum.  */
13006 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
13007 			/* Clear the IP header h/w cksum flag */
13008 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13009 		} else if (!mctl_present) {
13010 			/*
13011 			 * Don't verify header checksum if this packet
13012 			 * is coming back from AH/ESP as we already did it.
13013 			 */
13014 #define	uph	((uint16_t *)ipha)
13015 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13016 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13017 #undef	uph
13018 			/* finish doing IP checksum */
13019 			sum = (sum & 0xFFFF) + (sum >> 16);
13020 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13021 			if (sum != 0 && sum != 0xFFFF) {
13022 				BUMP_MIB(ill->ill_ip_mib,
13023 				    ipIfStatsInCksumErrs);
13024 				goto error;
13025 			}
13026 		}
13027 	}
13028 
13029 	if (!mctl_present) {
13030 		UPDATE_IB_PKT_COUNT(ire);
13031 		ire->ire_last_used_time = lbolt;
13032 	}
13033 
13034 	/* packet part of fragmented IP packet? */
13035 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13036 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13037 		goto fragmented;
13038 	}
13039 
13040 	/* u1 = IP header length (20 bytes) */
13041 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13042 
13043 	/* does packet contain IP+TCP headers? */
13044 	len = mp->b_wptr - rptr;
13045 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13046 		IP_STAT(ipst, ip_tcppullup);
13047 		goto tcppullup;
13048 	}
13049 
13050 	/* TCP options present? */
13051 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13052 
13053 	/*
13054 	 * If options need to be pulled up, then goto tcpoptions.
13055 	 * otherwise we are still in the fast path
13056 	 */
13057 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13058 		IP_STAT(ipst, ip_tcpoptions);
13059 		goto tcpoptions;
13060 	}
13061 
13062 	/* multiple mblks of tcp data? */
13063 	if ((mp1 = mp->b_cont) != NULL) {
13064 		IP_STAT(ipst, ip_multipkttcp);
13065 		len += msgdsize(mp1);
13066 	}
13067 
13068 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13069 
13070 	/* part of pseudo checksum */
13071 
13072 	/* TCP datagram length */
13073 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13074 
13075 #define	iphs    ((uint16_t *)ipha)
13076 
13077 #ifdef	_BIG_ENDIAN
13078 	u1 += IPPROTO_TCP;
13079 #else
13080 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13081 #endif
13082 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13083 
13084 	/*
13085 	 * Revert to software checksum calculation if the interface
13086 	 * isn't capable of checksum offload or if IPsec is present.
13087 	 */
13088 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13089 		hck_flags = DB_CKSUMFLAGS(mp);
13090 
13091 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13092 		IP_STAT(ipst, ip_in_sw_cksum);
13093 
13094 	IP_CKSUM_RECV(hck_flags, u1,
13095 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13096 	    (int32_t)((uchar_t *)up - rptr),
13097 	    mp, mp1, cksum_err);
13098 
13099 	if (cksum_err) {
13100 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13101 
13102 		if (hck_flags & HCK_FULLCKSUM)
13103 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13104 		else if (hck_flags & HCK_PARTIALCKSUM)
13105 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13106 		else
13107 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13108 
13109 		goto error;
13110 	}
13111 
13112 try_again:
13113 
13114 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13115 	    zoneid, ipst)) == NULL) {
13116 		/* Send the TH_RST */
13117 		goto no_conn;
13118 	}
13119 
13120 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13121 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13122 
13123 	/*
13124 	 * TCP FAST PATH for AF_INET socket.
13125 	 *
13126 	 * TCP fast path to avoid extra work. An AF_INET socket type
13127 	 * does not have facility to receive extra information via
13128 	 * ip_process or ip_add_info. Also, when the connection was
13129 	 * established, we made a check if this connection is impacted
13130 	 * by any global IPsec policy or per connection policy (a
13131 	 * policy that comes in effect later will not apply to this
13132 	 * connection). Since all this can be determined at the
13133 	 * connection establishment time, a quick check of flags
13134 	 * can avoid extra work.
13135 	 */
13136 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13137 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13138 		ASSERT(first_mp == mp);
13139 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13140 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13141 			SET_SQUEUE(mp, tcp_rput_data, connp);
13142 			return (mp);
13143 		}
13144 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13145 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13146 		SET_SQUEUE(mp, tcp_input, connp);
13147 		return (mp);
13148 	}
13149 
13150 	if (tcph_flags == TH_SYN) {
13151 		if (IPCL_IS_TCP(connp)) {
13152 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13153 			DB_CKSUMSTART(mp) =
13154 			    (intptr_t)ip_squeue_get(ill_ring);
13155 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13156 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13157 				BUMP_MIB(ill->ill_ip_mib,
13158 				    ipIfStatsHCInDelivers);
13159 				SET_SQUEUE(mp, connp->conn_recv, connp);
13160 				return (mp);
13161 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13162 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13163 				BUMP_MIB(ill->ill_ip_mib,
13164 				    ipIfStatsHCInDelivers);
13165 				ip_squeue_enter_unbound++;
13166 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13167 				    connp);
13168 				return (mp);
13169 			}
13170 			syn_present = B_TRUE;
13171 		}
13172 	}
13173 
13174 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13175 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13176 
13177 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13178 		/* No need to send this packet to TCP */
13179 		if ((flags & TH_RST) || (flags & TH_URG)) {
13180 			CONN_DEC_REF(connp);
13181 			freemsg(first_mp);
13182 			return (NULL);
13183 		}
13184 		if (flags & TH_ACK) {
13185 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13186 			    ipst->ips_netstack->netstack_tcp, connp);
13187 			CONN_DEC_REF(connp);
13188 			return (NULL);
13189 		}
13190 
13191 		CONN_DEC_REF(connp);
13192 		freemsg(first_mp);
13193 		return (NULL);
13194 	}
13195 
13196 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13197 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13198 		    ipha, NULL, mctl_present);
13199 		if (first_mp == NULL) {
13200 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13201 			CONN_DEC_REF(connp);
13202 			return (NULL);
13203 		}
13204 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13205 			ASSERT(syn_present);
13206 			if (mctl_present) {
13207 				ASSERT(first_mp != mp);
13208 				first_mp->b_datap->db_struioflag |=
13209 				    STRUIO_POLICY;
13210 			} else {
13211 				ASSERT(first_mp == mp);
13212 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13213 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13214 			}
13215 		} else {
13216 			/*
13217 			 * Discard first_mp early since we're dealing with a
13218 			 * fully-connected conn_t and tcp doesn't do policy in
13219 			 * this case.
13220 			 */
13221 			if (mctl_present) {
13222 				freeb(first_mp);
13223 				mctl_present = B_FALSE;
13224 			}
13225 			first_mp = mp;
13226 		}
13227 	}
13228 
13229 	/* Initiate IPPF processing for fastpath */
13230 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13231 		uint32_t	ill_index;
13232 
13233 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13234 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13235 		if (mp == NULL) {
13236 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13237 			    "deferred/dropped during IPPF processing\n"));
13238 			CONN_DEC_REF(connp);
13239 			if (mctl_present)
13240 				freeb(first_mp);
13241 			return (NULL);
13242 		} else if (mctl_present) {
13243 			/*
13244 			 * ip_process might return a new mp.
13245 			 */
13246 			ASSERT(first_mp != mp);
13247 			first_mp->b_cont = mp;
13248 		} else {
13249 			first_mp = mp;
13250 		}
13251 
13252 	}
13253 
13254 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13255 		/*
13256 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13257 		 * make sure IPF_RECVIF is passed to ip_add_info.
13258 		 */
13259 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13260 		    IPCL_ZONEID(connp), ipst);
13261 		if (mp == NULL) {
13262 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13263 			CONN_DEC_REF(connp);
13264 			if (mctl_present)
13265 				freeb(first_mp);
13266 			return (NULL);
13267 		} else if (mctl_present) {
13268 			/*
13269 			 * ip_add_info might return a new mp.
13270 			 */
13271 			ASSERT(first_mp != mp);
13272 			first_mp->b_cont = mp;
13273 		} else {
13274 			first_mp = mp;
13275 		}
13276 	}
13277 
13278 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13279 	if (IPCL_IS_TCP(connp)) {
13280 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13281 		return (first_mp);
13282 	} else {
13283 		/* SOCK_RAW, IPPROTO_TCP case */
13284 		(connp->conn_recv)(connp, first_mp, NULL);
13285 		CONN_DEC_REF(connp);
13286 		return (NULL);
13287 	}
13288 
13289 no_conn:
13290 	/* Initiate IPPf processing, if needed. */
13291 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13292 		uint32_t ill_index;
13293 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13294 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13295 		if (first_mp == NULL) {
13296 			return (NULL);
13297 		}
13298 	}
13299 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13300 
13301 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13302 	    ipst->ips_netstack->netstack_tcp, NULL);
13303 	return (NULL);
13304 ipoptions:
13305 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13306 		goto slow_done;
13307 	}
13308 
13309 	UPDATE_IB_PKT_COUNT(ire);
13310 	ire->ire_last_used_time = lbolt;
13311 
13312 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13313 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13314 fragmented:
13315 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13316 			if (mctl_present)
13317 				freeb(first_mp);
13318 			goto slow_done;
13319 		}
13320 		/*
13321 		 * Make sure that first_mp points back to mp as
13322 		 * the mp we came in with could have changed in
13323 		 * ip_rput_fragment().
13324 		 */
13325 		ASSERT(!mctl_present);
13326 		ipha = (ipha_t *)mp->b_rptr;
13327 		first_mp = mp;
13328 	}
13329 
13330 	/* Now we have a complete datagram, destined for this machine. */
13331 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13332 
13333 	len = mp->b_wptr - mp->b_rptr;
13334 	/* Pull up a minimal TCP header, if necessary. */
13335 	if (len < (u1 + 20)) {
13336 tcppullup:
13337 		if (!pullupmsg(mp, u1 + 20)) {
13338 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13339 			goto error;
13340 		}
13341 		ipha = (ipha_t *)mp->b_rptr;
13342 		len = mp->b_wptr - mp->b_rptr;
13343 	}
13344 
13345 	/*
13346 	 * Extract the offset field from the TCP header.  As usual, we
13347 	 * try to help the compiler more than the reader.
13348 	 */
13349 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13350 	if (offset != 5) {
13351 tcpoptions:
13352 		if (offset < 5) {
13353 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13354 			goto error;
13355 		}
13356 		/*
13357 		 * There must be TCP options.
13358 		 * Make sure we can grab them.
13359 		 */
13360 		offset <<= 2;
13361 		offset += u1;
13362 		if (len < offset) {
13363 			if (!pullupmsg(mp, offset)) {
13364 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13365 				goto error;
13366 			}
13367 			ipha = (ipha_t *)mp->b_rptr;
13368 			len = mp->b_wptr - rptr;
13369 		}
13370 	}
13371 
13372 	/* Get the total packet length in len, including headers. */
13373 	if (mp->b_cont)
13374 		len = msgdsize(mp);
13375 
13376 	/*
13377 	 * Check the TCP checksum by pulling together the pseudo-
13378 	 * header checksum, and passing it to ip_csum to be added in
13379 	 * with the TCP datagram.
13380 	 *
13381 	 * Since we are not using the hwcksum if available we must
13382 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13383 	 * If either of these fails along the way the mblk is freed.
13384 	 * If this logic ever changes and mblk is reused to say send
13385 	 * ICMP's back, then this flag may need to be cleared in
13386 	 * other places as well.
13387 	 */
13388 	DB_CKSUMFLAGS(mp) = 0;
13389 
13390 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13391 
13392 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13393 #ifdef	_BIG_ENDIAN
13394 	u1 += IPPROTO_TCP;
13395 #else
13396 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13397 #endif
13398 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13399 	/*
13400 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13401 	 */
13402 	IP_STAT(ipst, ip_in_sw_cksum);
13403 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13404 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13405 		goto error;
13406 	}
13407 
13408 	IP_STAT(ipst, ip_tcp_slow_path);
13409 	goto try_again;
13410 #undef  iphs
13411 #undef  rptr
13412 
13413 error:
13414 	freemsg(first_mp);
13415 slow_done:
13416 	return (NULL);
13417 }
13418 
13419 /* ARGSUSED */
13420 static void
13421 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13422     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13423 {
13424 	conn_t		*connp;
13425 	uint32_t	sum;
13426 	uint32_t	u1;
13427 	ssize_t		len;
13428 	sctp_hdr_t	*sctph;
13429 	zoneid_t	zoneid = ire->ire_zoneid;
13430 	uint32_t	pktsum;
13431 	uint32_t	calcsum;
13432 	uint32_t	ports;
13433 	in6_addr_t	map_src, map_dst;
13434 	ill_t		*ill = (ill_t *)q->q_ptr;
13435 	ip_stack_t	*ipst;
13436 	sctp_stack_t	*sctps;
13437 	boolean_t	sctp_csum_err = B_FALSE;
13438 
13439 	ASSERT(recv_ill != NULL);
13440 	ipst = recv_ill->ill_ipst;
13441 	sctps = ipst->ips_netstack->netstack_sctp;
13442 
13443 #define	rptr	((uchar_t *)ipha)
13444 
13445 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13446 	ASSERT(ill != NULL);
13447 
13448 	/* u1 is # words of IP options */
13449 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13450 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13451 
13452 	/* IP options present */
13453 	if (u1 > 0) {
13454 		goto ipoptions;
13455 	} else {
13456 		/* Check the IP header checksum.  */
13457 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13458 		    !mctl_present) {
13459 #define	uph	((uint16_t *)ipha)
13460 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13461 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13462 #undef	uph
13463 			/* finish doing IP checksum */
13464 			sum = (sum & 0xFFFF) + (sum >> 16);
13465 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13466 			/*
13467 			 * Don't verify header checksum if this packet
13468 			 * is coming back from AH/ESP as we already did it.
13469 			 */
13470 			if (sum != 0 && sum != 0xFFFF) {
13471 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13472 				goto error;
13473 			}
13474 		}
13475 		/*
13476 		 * Since there is no SCTP h/w cksum support yet, just
13477 		 * clear the flag.
13478 		 */
13479 		DB_CKSUMFLAGS(mp) = 0;
13480 	}
13481 
13482 	/*
13483 	 * Don't verify header checksum if this packet is coming
13484 	 * back from AH/ESP as we already did it.
13485 	 */
13486 	if (!mctl_present) {
13487 		UPDATE_IB_PKT_COUNT(ire);
13488 		ire->ire_last_used_time = lbolt;
13489 	}
13490 
13491 	/* packet part of fragmented IP packet? */
13492 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13493 	if (u1 & (IPH_MF | IPH_OFFSET))
13494 		goto fragmented;
13495 
13496 	/* u1 = IP header length (20 bytes) */
13497 	u1 = IP_SIMPLE_HDR_LENGTH;
13498 
13499 find_sctp_client:
13500 	/* Pullup if we don't have the sctp common header. */
13501 	len = MBLKL(mp);
13502 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13503 		if (mp->b_cont == NULL ||
13504 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13505 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13506 			goto error;
13507 		}
13508 		ipha = (ipha_t *)mp->b_rptr;
13509 		len = MBLKL(mp);
13510 	}
13511 
13512 	sctph = (sctp_hdr_t *)(rptr + u1);
13513 #ifdef	DEBUG
13514 	if (!skip_sctp_cksum) {
13515 #endif
13516 		pktsum = sctph->sh_chksum;
13517 		sctph->sh_chksum = 0;
13518 		calcsum = sctp_cksum(mp, u1);
13519 		sctph->sh_chksum = pktsum;
13520 		if (calcsum != pktsum)
13521 			sctp_csum_err = B_TRUE;
13522 #ifdef	DEBUG	/* skip_sctp_cksum */
13523 	}
13524 #endif
13525 	/* get the ports */
13526 	ports = *(uint32_t *)&sctph->sh_sport;
13527 
13528 	IRE_REFRELE(ire);
13529 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13530 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13531 	if (sctp_csum_err) {
13532 		/*
13533 		 * No potential sctp checksum errors go to the Sun
13534 		 * sctp stack however they might be Adler-32 summed
13535 		 * packets a userland stack bound to a raw IP socket
13536 		 * could reasonably use. Note though that Adler-32 is
13537 		 * a long deprecated algorithm and customer sctp
13538 		 * networks should eventually migrate to CRC-32 at
13539 		 * which time this facility should be removed.
13540 		 */
13541 		flags |= IP_FF_SCTP_CSUM_ERR;
13542 		goto no_conn;
13543 	}
13544 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13545 	    sctps)) == NULL) {
13546 		/* Check for raw socket or OOTB handling */
13547 		goto no_conn;
13548 	}
13549 
13550 	/* Found a client; up it goes */
13551 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13552 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13553 	return;
13554 
13555 no_conn:
13556 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13557 	    ports, mctl_present, flags, B_TRUE, zoneid);
13558 	return;
13559 
13560 ipoptions:
13561 	DB_CKSUMFLAGS(mp) = 0;
13562 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13563 		goto slow_done;
13564 
13565 	UPDATE_IB_PKT_COUNT(ire);
13566 	ire->ire_last_used_time = lbolt;
13567 
13568 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13569 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13570 fragmented:
13571 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13572 			goto slow_done;
13573 		/*
13574 		 * Make sure that first_mp points back to mp as
13575 		 * the mp we came in with could have changed in
13576 		 * ip_rput_fragment().
13577 		 */
13578 		ASSERT(!mctl_present);
13579 		ipha = (ipha_t *)mp->b_rptr;
13580 		first_mp = mp;
13581 	}
13582 
13583 	/* Now we have a complete datagram, destined for this machine. */
13584 	u1 = IPH_HDR_LENGTH(ipha);
13585 	goto find_sctp_client;
13586 #undef  iphs
13587 #undef  rptr
13588 
13589 error:
13590 	freemsg(first_mp);
13591 slow_done:
13592 	IRE_REFRELE(ire);
13593 }
13594 
13595 #define	VER_BITS	0xF0
13596 #define	VERSION_6	0x60
13597 
13598 static boolean_t
13599 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13600     ipaddr_t *dstp, ip_stack_t *ipst)
13601 {
13602 	uint_t	opt_len;
13603 	ipha_t *ipha;
13604 	ssize_t len;
13605 	uint_t	pkt_len;
13606 
13607 	ASSERT(ill != NULL);
13608 	IP_STAT(ipst, ip_ipoptions);
13609 	ipha = *iphapp;
13610 
13611 #define	rptr    ((uchar_t *)ipha)
13612 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13613 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13614 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13615 		freemsg(mp);
13616 		return (B_FALSE);
13617 	}
13618 
13619 	/* multiple mblk or too short */
13620 	pkt_len = ntohs(ipha->ipha_length);
13621 
13622 	/* Get the number of words of IP options in the IP header. */
13623 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13624 	if (opt_len) {
13625 		/* IP Options present!  Validate and process. */
13626 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13627 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13628 			goto done;
13629 		}
13630 		/*
13631 		 * Recompute complete header length and make sure we
13632 		 * have access to all of it.
13633 		 */
13634 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13635 		if (len > (mp->b_wptr - rptr)) {
13636 			if (len > pkt_len) {
13637 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13638 				goto done;
13639 			}
13640 			if (!pullupmsg(mp, len)) {
13641 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13642 				goto done;
13643 			}
13644 			ipha = (ipha_t *)mp->b_rptr;
13645 		}
13646 		/*
13647 		 * Go off to ip_rput_options which returns the next hop
13648 		 * destination address, which may have been affected
13649 		 * by source routing.
13650 		 */
13651 		IP_STAT(ipst, ip_opt);
13652 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13653 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13654 			return (B_FALSE);
13655 		}
13656 	}
13657 	*iphapp = ipha;
13658 	return (B_TRUE);
13659 done:
13660 	/* clear b_prev - used by ip_mroute_decap */
13661 	mp->b_prev = NULL;
13662 	freemsg(mp);
13663 	return (B_FALSE);
13664 #undef  rptr
13665 }
13666 
13667 /*
13668  * Deal with the fact that there is no ire for the destination.
13669  */
13670 static ire_t *
13671 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13672 {
13673 	ipha_t	*ipha;
13674 	ill_t	*ill;
13675 	ire_t	*ire;
13676 	ip_stack_t *ipst;
13677 	enum	ire_forward_action ret_action;
13678 
13679 	ipha = (ipha_t *)mp->b_rptr;
13680 	ill = (ill_t *)q->q_ptr;
13681 
13682 	ASSERT(ill != NULL);
13683 	ipst = ill->ill_ipst;
13684 
13685 	/*
13686 	 * No IRE for this destination, so it can't be for us.
13687 	 * Unless we are forwarding, drop the packet.
13688 	 * We have to let source routed packets through
13689 	 * since we don't yet know if they are 'ping -l'
13690 	 * packets i.e. if they will go out over the
13691 	 * same interface as they came in on.
13692 	 */
13693 	if (ll_multicast) {
13694 		freemsg(mp);
13695 		return (NULL);
13696 	}
13697 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13698 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13699 		freemsg(mp);
13700 		return (NULL);
13701 	}
13702 
13703 	/*
13704 	 * Mark this packet as having originated externally.
13705 	 *
13706 	 * For non-forwarding code path, ire_send later double
13707 	 * checks this interface to see if it is still exists
13708 	 * post-ARP resolution.
13709 	 *
13710 	 * Also, IPQOS uses this to differentiate between
13711 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13712 	 * QOS packet processing in ip_wput_attach_llhdr().
13713 	 * The QoS module can mark the b_band for a fastpath message
13714 	 * or the dl_priority field in a unitdata_req header for
13715 	 * CoS marking. This info can only be found in
13716 	 * ip_wput_attach_llhdr().
13717 	 */
13718 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13719 	/*
13720 	 * Clear the indication that this may have a hardware checksum
13721 	 * as we are not using it
13722 	 */
13723 	DB_CKSUMFLAGS(mp) = 0;
13724 
13725 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13726 	    msg_getlabel(mp), ipst);
13727 
13728 	if (ire == NULL && ret_action == Forward_check_multirt) {
13729 		/* Let ip_newroute handle CGTP  */
13730 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13731 		return (NULL);
13732 	}
13733 
13734 	if (ire != NULL)
13735 		return (ire);
13736 
13737 	mp->b_prev = mp->b_next = 0;
13738 
13739 	if (ret_action == Forward_blackhole) {
13740 		freemsg(mp);
13741 		return (NULL);
13742 	}
13743 	/* send icmp unreachable */
13744 	q = WR(q);
13745 	/* Sent by forwarding path, and router is global zone */
13746 	if (ip_source_routed(ipha, ipst)) {
13747 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13748 		    GLOBAL_ZONEID, ipst);
13749 	} else {
13750 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13751 		    ipst);
13752 	}
13753 
13754 	return (NULL);
13755 
13756 }
13757 
13758 /*
13759  * check ip header length and align it.
13760  */
13761 static boolean_t
13762 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13763 {
13764 	ssize_t len;
13765 	ill_t *ill;
13766 	ipha_t	*ipha;
13767 
13768 	len = MBLKL(mp);
13769 
13770 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13771 		ill = (ill_t *)q->q_ptr;
13772 
13773 		if (!OK_32PTR(mp->b_rptr))
13774 			IP_STAT(ipst, ip_notaligned1);
13775 		else
13776 			IP_STAT(ipst, ip_notaligned2);
13777 		/* Guard against bogus device drivers */
13778 		if (len < 0) {
13779 			/* clear b_prev - used by ip_mroute_decap */
13780 			mp->b_prev = NULL;
13781 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13782 			freemsg(mp);
13783 			return (B_FALSE);
13784 		}
13785 
13786 		if (ip_rput_pullups++ == 0) {
13787 			ipha = (ipha_t *)mp->b_rptr;
13788 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13789 			    "ip_check_and_align_header: %s forced us to "
13790 			    " pullup pkt, hdr len %ld, hdr addr %p",
13791 			    ill->ill_name, len, (void *)ipha);
13792 		}
13793 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13794 			/* clear b_prev - used by ip_mroute_decap */
13795 			mp->b_prev = NULL;
13796 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13797 			freemsg(mp);
13798 			return (B_FALSE);
13799 		}
13800 	}
13801 	return (B_TRUE);
13802 }
13803 
13804 /*
13805  * Handle the situation where a packet came in on `ill' but matched an IRE
13806  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13807  * for interface statistics.
13808  */
13809 ire_t *
13810 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13811 {
13812 	ire_t		*new_ire;
13813 	ill_t		*ire_ill;
13814 	uint_t		ifindex;
13815 	ip_stack_t	*ipst = ill->ill_ipst;
13816 	boolean_t	strict_check = B_FALSE;
13817 
13818 	/*
13819 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13820 	 * issue (e.g. packet received on an underlying interface matched an
13821 	 * IRE_LOCAL on its associated group interface).
13822 	 */
13823 	if (ire->ire_rfq != NULL &&
13824 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13825 		return (ire);
13826 	}
13827 
13828 	/*
13829 	 * Do another ire lookup here, using the ingress ill, to see if the
13830 	 * interface is in a usesrc group.
13831 	 * As long as the ills belong to the same group, we don't consider
13832 	 * them to be arriving on the wrong interface. Thus, if the switch
13833 	 * is doing inbound load spreading, we won't drop packets when the
13834 	 * ip*_strict_dst_multihoming switch is on.
13835 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13836 	 * where the local address may not be unique. In this case we were
13837 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13838 	 * actually returned. The new lookup, which is more specific, should
13839 	 * only find the IRE_LOCAL associated with the ingress ill if one
13840 	 * exists.
13841 	 */
13842 
13843 	if (ire->ire_ipversion == IPV4_VERSION) {
13844 		if (ipst->ips_ip_strict_dst_multihoming)
13845 			strict_check = B_TRUE;
13846 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13847 		    ill->ill_ipif, ALL_ZONES, NULL,
13848 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13849 	} else {
13850 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13851 		if (ipst->ips_ipv6_strict_dst_multihoming)
13852 			strict_check = B_TRUE;
13853 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13854 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13855 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13856 	}
13857 	/*
13858 	 * If the same ire that was returned in ip_input() is found then this
13859 	 * is an indication that usesrc groups are in use. The packet
13860 	 * arrived on a different ill in the group than the one associated with
13861 	 * the destination address.  If a different ire was found then the same
13862 	 * IP address must be hosted on multiple ills. This is possible with
13863 	 * unnumbered point2point interfaces. We switch to use this new ire in
13864 	 * order to have accurate interface statistics.
13865 	 */
13866 	if (new_ire != NULL) {
13867 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13868 			ire_refrele(ire);
13869 			ire = new_ire;
13870 		} else {
13871 			ire_refrele(new_ire);
13872 		}
13873 		return (ire);
13874 	} else if ((ire->ire_rfq == NULL) &&
13875 	    (ire->ire_ipversion == IPV4_VERSION)) {
13876 		/*
13877 		 * The best match could have been the original ire which
13878 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13879 		 * the strict multihoming checks are irrelevant as we consider
13880 		 * local addresses hosted on lo0 to be interface agnostic. We
13881 		 * only expect a null ire_rfq on IREs which are associated with
13882 		 * lo0 hence we can return now.
13883 		 */
13884 		return (ire);
13885 	}
13886 
13887 	/*
13888 	 * Chase pointers once and store locally.
13889 	 */
13890 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13891 	    (ill_t *)(ire->ire_rfq->q_ptr);
13892 	ifindex = ill->ill_usesrc_ifindex;
13893 
13894 	/*
13895 	 * Check if it's a legal address on the 'usesrc' interface.
13896 	 */
13897 	if ((ifindex != 0) && (ire_ill != NULL) &&
13898 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13899 		return (ire);
13900 	}
13901 
13902 	/*
13903 	 * If the ip*_strict_dst_multihoming switch is on then we can
13904 	 * only accept this packet if the interface is marked as routing.
13905 	 */
13906 	if (!(strict_check))
13907 		return (ire);
13908 
13909 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13910 	    ILLF_ROUTER) != 0) {
13911 		return (ire);
13912 	}
13913 
13914 	ire_refrele(ire);
13915 	return (NULL);
13916 }
13917 
13918 /*
13919  *
13920  * This is the fast forward path. If we are here, we dont need to
13921  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13922  * needed to find the nexthop in this case is much simpler
13923  */
13924 ire_t *
13925 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13926 {
13927 	ipha_t	*ipha;
13928 	ire_t	*src_ire;
13929 	ill_t	*stq_ill;
13930 	uint_t	hlen;
13931 	uint_t	pkt_len;
13932 	uint32_t sum;
13933 	queue_t	*dev_q;
13934 	ip_stack_t *ipst = ill->ill_ipst;
13935 	mblk_t *fpmp;
13936 	enum	ire_forward_action ret_action;
13937 
13938 	ipha = (ipha_t *)mp->b_rptr;
13939 
13940 	if (ire != NULL &&
13941 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13942 	    ire->ire_zoneid != ALL_ZONES) {
13943 		/*
13944 		 * Should only use IREs that are visible to the global
13945 		 * zone for forwarding.
13946 		 */
13947 		ire_refrele(ire);
13948 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13949 		/*
13950 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13951 		 * transient cases. In such case, just drop the packet
13952 		 */
13953 		if (ire->ire_type != IRE_CACHE)
13954 			goto drop;
13955 	}
13956 
13957 	/*
13958 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13959 	 * The loopback address check for both src and dst has already
13960 	 * been checked in ip_input
13961 	 */
13962 
13963 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13964 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13965 		goto drop;
13966 	}
13967 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13968 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13969 
13970 	if (src_ire != NULL) {
13971 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13972 		ire_refrele(src_ire);
13973 		goto drop;
13974 	}
13975 
13976 	/* No ire cache of nexthop. So first create one  */
13977 	if (ire == NULL) {
13978 
13979 		ire = ire_forward_simple(dst, &ret_action, ipst);
13980 
13981 		/*
13982 		 * We only come to ip_fast_forward if ip_cgtp_filter
13983 		 * is not set. So ire_forward() should not return with
13984 		 * Forward_check_multirt as the next action.
13985 		 */
13986 		ASSERT(ret_action != Forward_check_multirt);
13987 		if (ire == NULL) {
13988 			/* An attempt was made to forward the packet */
13989 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13990 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13991 			mp->b_prev = mp->b_next = 0;
13992 			/* send icmp unreachable */
13993 			/* Sent by forwarding path, and router is global zone */
13994 			if (ret_action == Forward_ret_icmp_err) {
13995 				if (ip_source_routed(ipha, ipst)) {
13996 					icmp_unreachable(ill->ill_wq, mp,
13997 					    ICMP_SOURCE_ROUTE_FAILED,
13998 					    GLOBAL_ZONEID, ipst);
13999 				} else {
14000 					icmp_unreachable(ill->ill_wq, mp,
14001 					    ICMP_HOST_UNREACHABLE,
14002 					    GLOBAL_ZONEID, ipst);
14003 				}
14004 			} else {
14005 				freemsg(mp);
14006 			}
14007 			return (NULL);
14008 		}
14009 	}
14010 
14011 	/*
14012 	 * Forwarding fastpath exception case:
14013 	 * If any of the following are true, we take the slowpath:
14014 	 *	o forwarding is not enabled
14015 	 *	o incoming and outgoing interface are the same, or in the same
14016 	 *	  IPMP group.
14017 	 *	o corresponding ire is in incomplete state
14018 	 *	o packet needs fragmentation
14019 	 *	o ARP cache is not resolved
14020 	 *
14021 	 * The codeflow from here on is thus:
14022 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14023 	 */
14024 	pkt_len = ntohs(ipha->ipha_length);
14025 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14026 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14027 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
14028 	    (ire->ire_nce == NULL) ||
14029 	    (pkt_len > ire->ire_max_frag) ||
14030 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14031 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14032 	    ipha->ipha_ttl <= 1) {
14033 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14034 		    ipha, ill, B_FALSE, B_TRUE);
14035 		return (ire);
14036 	}
14037 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14038 
14039 	DTRACE_PROBE4(ip4__forwarding__start,
14040 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14041 
14042 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14043 	    ipst->ips_ipv4firewall_forwarding,
14044 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14045 
14046 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14047 
14048 	if (mp == NULL)
14049 		goto drop;
14050 
14051 	mp->b_datap->db_struioun.cksum.flags = 0;
14052 	/* Adjust the checksum to reflect the ttl decrement. */
14053 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14054 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14055 	ipha->ipha_ttl--;
14056 
14057 	/*
14058 	 * Write the link layer header.  We can do this safely here,
14059 	 * because we have already tested to make sure that the IP
14060 	 * policy is not set, and that we have a fast path destination
14061 	 * header.
14062 	 */
14063 	mp->b_rptr -= hlen;
14064 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14065 
14066 	UPDATE_IB_PKT_COUNT(ire);
14067 	ire->ire_last_used_time = lbolt;
14068 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14069 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14070 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14071 
14072 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14073 		dev_q = ire->ire_stq->q_next;
14074 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14075 			goto indiscard;
14076 	}
14077 
14078 	DTRACE_PROBE4(ip4__physical__out__start,
14079 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14080 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14081 	    ipst->ips_ipv4firewall_physical_out,
14082 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14083 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14084 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14085 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14086 	    ip6_t *, NULL, int, 0);
14087 
14088 	if (mp != NULL) {
14089 		if (ipst->ips_ipobs_enabled) {
14090 			zoneid_t szone;
14091 
14092 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14093 			    ipst, ALL_ZONES);
14094 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14095 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14096 		}
14097 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14098 	}
14099 	return (ire);
14100 
14101 indiscard:
14102 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14103 drop:
14104 	if (mp != NULL)
14105 		freemsg(mp);
14106 	return (ire);
14107 
14108 }
14109 
14110 /*
14111  * This function is called in the forwarding slowpath, when
14112  * either the ire lacks the link-layer address, or the packet needs
14113  * further processing(eg. fragmentation), before transmission.
14114  */
14115 
14116 static void
14117 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14118     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14119 {
14120 	queue_t		*dev_q;
14121 	ire_t		*src_ire;
14122 	ip_stack_t	*ipst = ill->ill_ipst;
14123 	boolean_t	same_illgrp = B_FALSE;
14124 
14125 	ASSERT(ire->ire_stq != NULL);
14126 
14127 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14128 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14129 
14130 	/*
14131 	 * If the caller of this function is ip_fast_forward() skip the
14132 	 * next three checks as it does not apply.
14133 	 */
14134 	if (from_ip_fast_forward)
14135 		goto skip;
14136 
14137 	if (ll_multicast != 0) {
14138 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14139 		goto drop_pkt;
14140 	}
14141 
14142 	/*
14143 	 * check if ipha_src is a broadcast address. Note that this
14144 	 * check is redundant when we get here from ip_fast_forward()
14145 	 * which has already done this check. However, since we can
14146 	 * also get here from ip_rput_process_broadcast() or, for
14147 	 * for the slow path through ip_fast_forward(), we perform
14148 	 * the check again for code-reusability
14149 	 */
14150 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14151 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14152 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14153 		if (src_ire != NULL)
14154 			ire_refrele(src_ire);
14155 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14156 		ip2dbg(("ip_rput_process_forward: Received packet with"
14157 		    " bad src/dst address on %s\n", ill->ill_name));
14158 		goto drop_pkt;
14159 	}
14160 
14161 	/*
14162 	 * Check if we want to forward this one at this time.
14163 	 * We allow source routed packets on a host provided that
14164 	 * they go out the same ill or illgrp as they came in on.
14165 	 *
14166 	 * XXX To be quicker, we may wish to not chase pointers to
14167 	 * get the ILLF_ROUTER flag and instead store the
14168 	 * forwarding policy in the ire.  An unfortunate
14169 	 * side-effect of that would be requiring an ire flush
14170 	 * whenever the ILLF_ROUTER flag changes.
14171 	 */
14172 skip:
14173 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14174 
14175 	if (((ill->ill_flags &
14176 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14177 	    !(ip_source_routed(ipha, ipst) &&
14178 	    (ire->ire_rfq == q || same_illgrp))) {
14179 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14180 		if (ip_source_routed(ipha, ipst)) {
14181 			q = WR(q);
14182 			/*
14183 			 * Clear the indication that this may have
14184 			 * hardware checksum as we are not using it.
14185 			 */
14186 			DB_CKSUMFLAGS(mp) = 0;
14187 			/* Sent by forwarding path, and router is global zone */
14188 			icmp_unreachable(q, mp,
14189 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14190 			return;
14191 		}
14192 		goto drop_pkt;
14193 	}
14194 
14195 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14196 
14197 	/* Packet is being forwarded. Turning off hwcksum flag. */
14198 	DB_CKSUMFLAGS(mp) = 0;
14199 	if (ipst->ips_ip_g_send_redirects) {
14200 		/*
14201 		 * Check whether the incoming interface and outgoing
14202 		 * interface is part of the same group. If so,
14203 		 * send redirects.
14204 		 *
14205 		 * Check the source address to see if it originated
14206 		 * on the same logical subnet it is going back out on.
14207 		 * If so, we should be able to send it a redirect.
14208 		 * Avoid sending a redirect if the destination
14209 		 * is directly connected (i.e., ipha_dst is the same
14210 		 * as ire_gateway_addr or the ire_addr of the
14211 		 * nexthop IRE_CACHE ), or if the packet was source
14212 		 * routed out this interface.
14213 		 */
14214 		ipaddr_t src, nhop;
14215 		mblk_t	*mp1;
14216 		ire_t	*nhop_ire = NULL;
14217 
14218 		/*
14219 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14220 		 * If so, send redirects.
14221 		 */
14222 		if ((ire->ire_rfq == q || same_illgrp) &&
14223 		    !ip_source_routed(ipha, ipst)) {
14224 
14225 			nhop = (ire->ire_gateway_addr != 0 ?
14226 			    ire->ire_gateway_addr : ire->ire_addr);
14227 
14228 			if (ipha->ipha_dst == nhop) {
14229 				/*
14230 				 * We avoid sending a redirect if the
14231 				 * destination is directly connected
14232 				 * because it is possible that multiple
14233 				 * IP subnets may have been configured on
14234 				 * the link, and the source may not
14235 				 * be on the same subnet as ip destination,
14236 				 * even though they are on the same
14237 				 * physical link.
14238 				 */
14239 				goto sendit;
14240 			}
14241 
14242 			src = ipha->ipha_src;
14243 
14244 			/*
14245 			 * We look up the interface ire for the nexthop,
14246 			 * to see if ipha_src is in the same subnet
14247 			 * as the nexthop.
14248 			 *
14249 			 * Note that, if, in the future, IRE_CACHE entries
14250 			 * are obsoleted,  this lookup will not be needed,
14251 			 * as the ire passed to this function will be the
14252 			 * same as the nhop_ire computed below.
14253 			 */
14254 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14255 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14256 			    0, NULL, MATCH_IRE_TYPE, ipst);
14257 
14258 			if (nhop_ire != NULL) {
14259 				if ((src & nhop_ire->ire_mask) ==
14260 				    (nhop & nhop_ire->ire_mask)) {
14261 					/*
14262 					 * The source is directly connected.
14263 					 * Just copy the ip header (which is
14264 					 * in the first mblk)
14265 					 */
14266 					mp1 = copyb(mp);
14267 					if (mp1 != NULL) {
14268 						icmp_send_redirect(WR(q), mp1,
14269 						    nhop, ipst);
14270 					}
14271 				}
14272 				ire_refrele(nhop_ire);
14273 			}
14274 		}
14275 	}
14276 sendit:
14277 	dev_q = ire->ire_stq->q_next;
14278 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14279 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14280 		freemsg(mp);
14281 		return;
14282 	}
14283 
14284 	ip_rput_forward(ire, ipha, mp, ill);
14285 	return;
14286 
14287 drop_pkt:
14288 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14289 	freemsg(mp);
14290 }
14291 
14292 ire_t *
14293 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14294     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14295 {
14296 	queue_t		*q;
14297 	uint16_t	hcksumflags;
14298 	ip_stack_t	*ipst = ill->ill_ipst;
14299 
14300 	q = *qp;
14301 
14302 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14303 
14304 	/*
14305 	 * Clear the indication that this may have hardware
14306 	 * checksum as we are not using it for forwarding.
14307 	 */
14308 	hcksumflags = DB_CKSUMFLAGS(mp);
14309 	DB_CKSUMFLAGS(mp) = 0;
14310 
14311 	/*
14312 	 * Directed broadcast forwarding: if the packet came in over a
14313 	 * different interface then it is routed out over we can forward it.
14314 	 */
14315 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14316 		ire_refrele(ire);
14317 		freemsg(mp);
14318 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14319 		return (NULL);
14320 	}
14321 	/*
14322 	 * For multicast we have set dst to be INADDR_BROADCAST
14323 	 * for delivering to all STREAMS.
14324 	 */
14325 	if (!CLASSD(ipha->ipha_dst)) {
14326 		ire_t *new_ire;
14327 		ipif_t *ipif;
14328 
14329 		ipif = ipif_get_next_ipif(NULL, ill);
14330 		if (ipif == NULL) {
14331 discard:		ire_refrele(ire);
14332 			freemsg(mp);
14333 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14334 			return (NULL);
14335 		}
14336 		new_ire = ire_ctable_lookup(dst, 0, 0,
14337 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14338 		ipif_refrele(ipif);
14339 
14340 		if (new_ire != NULL) {
14341 			/*
14342 			 * If the matching IRE_BROADCAST is part of an IPMP
14343 			 * group, then drop the packet unless our ill has been
14344 			 * nominated to receive for the group.
14345 			 */
14346 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14347 			    new_ire->ire_rfq != q) {
14348 				ire_refrele(new_ire);
14349 				goto discard;
14350 			}
14351 
14352 			/*
14353 			 * In the special case of multirouted broadcast
14354 			 * packets, we unconditionally need to "gateway"
14355 			 * them to the appropriate interface here.
14356 			 * In the normal case, this cannot happen, because
14357 			 * there is no broadcast IRE tagged with the
14358 			 * RTF_MULTIRT flag.
14359 			 */
14360 			if (new_ire->ire_flags & RTF_MULTIRT) {
14361 				ire_refrele(new_ire);
14362 				if (ire->ire_rfq != NULL) {
14363 					q = ire->ire_rfq;
14364 					*qp = q;
14365 				}
14366 			} else {
14367 				ire_refrele(ire);
14368 				ire = new_ire;
14369 			}
14370 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14371 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14372 				/*
14373 				 * Free the message if
14374 				 * ip_g_forward_directed_bcast is turned
14375 				 * off for non-local broadcast.
14376 				 */
14377 				ire_refrele(ire);
14378 				freemsg(mp);
14379 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14380 				return (NULL);
14381 			}
14382 		} else {
14383 			/*
14384 			 * This CGTP packet successfully passed the
14385 			 * CGTP filter, but the related CGTP
14386 			 * broadcast IRE has not been found,
14387 			 * meaning that the redundant ipif is
14388 			 * probably down. However, if we discarded
14389 			 * this packet, its duplicate would be
14390 			 * filtered out by the CGTP filter so none
14391 			 * of them would get through. So we keep
14392 			 * going with this one.
14393 			 */
14394 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14395 			if (ire->ire_rfq != NULL) {
14396 				q = ire->ire_rfq;
14397 				*qp = q;
14398 			}
14399 		}
14400 	}
14401 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14402 		/*
14403 		 * Verify that there are not more then one
14404 		 * IRE_BROADCAST with this broadcast address which
14405 		 * has ire_stq set.
14406 		 * TODO: simplify, loop over all IRE's
14407 		 */
14408 		ire_t	*ire1;
14409 		int	num_stq = 0;
14410 		mblk_t	*mp1;
14411 
14412 		/* Find the first one with ire_stq set */
14413 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14414 		for (ire1 = ire; ire1 &&
14415 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14416 		    ire1 = ire1->ire_next)
14417 			;
14418 		if (ire1) {
14419 			ire_refrele(ire);
14420 			ire = ire1;
14421 			IRE_REFHOLD(ire);
14422 		}
14423 
14424 		/* Check if there are additional ones with stq set */
14425 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14426 			if (ire->ire_addr != ire1->ire_addr)
14427 				break;
14428 			if (ire1->ire_stq) {
14429 				num_stq++;
14430 				break;
14431 			}
14432 		}
14433 		rw_exit(&ire->ire_bucket->irb_lock);
14434 		if (num_stq == 1 && ire->ire_stq != NULL) {
14435 			ip1dbg(("ip_rput_process_broadcast: directed "
14436 			    "broadcast to 0x%x\n",
14437 			    ntohl(ire->ire_addr)));
14438 			mp1 = copymsg(mp);
14439 			if (mp1) {
14440 				switch (ipha->ipha_protocol) {
14441 				case IPPROTO_UDP:
14442 					ip_udp_input(q, mp1, ipha, ire, ill);
14443 					break;
14444 				default:
14445 					ip_proto_input(q, mp1, ipha, ire, ill,
14446 					    0);
14447 					break;
14448 				}
14449 			}
14450 			/*
14451 			 * Adjust ttl to 2 (1+1 - the forward engine
14452 			 * will decrement it by one.
14453 			 */
14454 			if (ip_csum_hdr(ipha)) {
14455 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14456 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14457 				freemsg(mp);
14458 				ire_refrele(ire);
14459 				return (NULL);
14460 			}
14461 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14462 			ipha->ipha_hdr_checksum = 0;
14463 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14464 			ip_rput_process_forward(q, mp, ire, ipha,
14465 			    ill, ll_multicast, B_FALSE);
14466 			ire_refrele(ire);
14467 			return (NULL);
14468 		}
14469 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14470 		    ntohl(ire->ire_addr)));
14471 	}
14472 
14473 	/* Restore any hardware checksum flags */
14474 	DB_CKSUMFLAGS(mp) = hcksumflags;
14475 	return (ire);
14476 }
14477 
14478 /* ARGSUSED */
14479 static boolean_t
14480 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14481     int *ll_multicast, ipaddr_t *dstp)
14482 {
14483 	ip_stack_t	*ipst = ill->ill_ipst;
14484 
14485 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14486 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14487 	    ntohs(ipha->ipha_length));
14488 
14489 	/*
14490 	 * So that we don't end up with dups, only one ill in an IPMP group is
14491 	 * nominated to receive multicast traffic.
14492 	 */
14493 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14494 		goto drop_pkt;
14495 
14496 	/*
14497 	 * Forward packets only if we have joined the allmulti
14498 	 * group on this interface.
14499 	 */
14500 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14501 		int retval;
14502 
14503 		/*
14504 		 * Clear the indication that this may have hardware
14505 		 * checksum as we are not using it.
14506 		 */
14507 		DB_CKSUMFLAGS(mp) = 0;
14508 		retval = ip_mforward(ill, ipha, mp);
14509 		/* ip_mforward updates mib variables if needed */
14510 		/* clear b_prev - used by ip_mroute_decap */
14511 		mp->b_prev = NULL;
14512 
14513 		switch (retval) {
14514 		case 0:
14515 			/*
14516 			 * pkt is okay and arrived on phyint.
14517 			 *
14518 			 * If we are running as a multicast router
14519 			 * we need to see all IGMP and/or PIM packets.
14520 			 */
14521 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14522 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14523 				goto done;
14524 			}
14525 			break;
14526 		case -1:
14527 			/* pkt is mal-formed, toss it */
14528 			goto drop_pkt;
14529 		case 1:
14530 			/* pkt is okay and arrived on a tunnel */
14531 			/*
14532 			 * If we are running a multicast router
14533 			 *  we need to see all igmp packets.
14534 			 */
14535 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14536 				*dstp = INADDR_BROADCAST;
14537 				*ll_multicast = 1;
14538 				return (B_FALSE);
14539 			}
14540 
14541 			goto drop_pkt;
14542 		}
14543 	}
14544 
14545 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14546 		/*
14547 		 * This might just be caused by the fact that
14548 		 * multiple IP Multicast addresses map to the same
14549 		 * link layer multicast - no need to increment counter!
14550 		 */
14551 		freemsg(mp);
14552 		return (B_TRUE);
14553 	}
14554 done:
14555 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14556 	/*
14557 	 * This assumes the we deliver to all streams for multicast
14558 	 * and broadcast packets.
14559 	 */
14560 	*dstp = INADDR_BROADCAST;
14561 	*ll_multicast = 1;
14562 	return (B_FALSE);
14563 drop_pkt:
14564 	ip2dbg(("ip_rput: drop pkt\n"));
14565 	freemsg(mp);
14566 	return (B_TRUE);
14567 }
14568 
14569 /*
14570  * This function is used to both return an indication of whether or not
14571  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14572  * and in doing so, determine whether or not it is broadcast vs multicast.
14573  * For it to be a broadcast packet, we must have the appropriate mblk_t
14574  * hanging off the ill_t.  If this is either not present or doesn't match
14575  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14576  * to be multicast.  Thus NICs that have no broadcast address (or no
14577  * capability for one, such as point to point links) cannot return as
14578  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14579  * the return values simplifies the current use of the return value of this
14580  * function, which is to pass through the multicast/broadcast characteristic
14581  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14582  * changing the return value to some other symbol demands the appropriate
14583  * "translation" when hpe_flags is set prior to calling hook_run() for
14584  * packet events.
14585  */
14586 int
14587 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14588 {
14589 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14590 	mblk_t *bmp;
14591 
14592 	if (ind->dl_group_address) {
14593 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14594 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14595 		    MBLKL(mb) &&
14596 		    (bmp = ill->ill_bcast_mp) != NULL) {
14597 			dl_unitdata_req_t *dlur;
14598 			uint8_t *bphys_addr;
14599 
14600 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14601 			if (ill->ill_sap_length < 0)
14602 				bphys_addr = (uchar_t *)dlur +
14603 				    dlur->dl_dest_addr_offset;
14604 			else
14605 				bphys_addr = (uchar_t *)dlur +
14606 				    dlur->dl_dest_addr_offset +
14607 				    ill->ill_sap_length;
14608 
14609 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14610 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14611 				return (HPE_BROADCAST);
14612 			}
14613 			return (HPE_MULTICAST);
14614 		}
14615 		return (HPE_MULTICAST);
14616 	}
14617 	return (0);
14618 }
14619 
14620 static boolean_t
14621 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14622     int *ll_multicast, mblk_t **mpp)
14623 {
14624 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14625 	boolean_t must_copy = B_FALSE;
14626 	struct iocblk   *iocp;
14627 	ipha_t		*ipha;
14628 	ip_stack_t	*ipst = ill->ill_ipst;
14629 
14630 #define	rptr    ((uchar_t *)ipha)
14631 
14632 	first_mp = *first_mpp;
14633 	mp = *mpp;
14634 
14635 	ASSERT(first_mp == mp);
14636 
14637 	/*
14638 	 * if db_ref > 1 then copymsg and free original. Packet may be
14639 	 * changed and do not want other entity who has a reference to this
14640 	 * message to trip over the changes. This is a blind change because
14641 	 * trying to catch all places that might change packet is too
14642 	 * difficult (since it may be a module above this one)
14643 	 *
14644 	 * This corresponds to the non-fast path case. We walk down the full
14645 	 * chain in this case, and check the db_ref count of all the dblks,
14646 	 * and do a copymsg if required. It is possible that the db_ref counts
14647 	 * of the data blocks in the mblk chain can be different.
14648 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14649 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14650 	 * 'snoop' is running.
14651 	 */
14652 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14653 		if (mp1->b_datap->db_ref > 1) {
14654 			must_copy = B_TRUE;
14655 			break;
14656 		}
14657 	}
14658 
14659 	if (must_copy) {
14660 		mp1 = copymsg(mp);
14661 		if (mp1 == NULL) {
14662 			for (mp1 = mp; mp1 != NULL;
14663 			    mp1 = mp1->b_cont) {
14664 				mp1->b_next = NULL;
14665 				mp1->b_prev = NULL;
14666 			}
14667 			freemsg(mp);
14668 			if (ill != NULL) {
14669 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14670 			} else {
14671 				BUMP_MIB(&ipst->ips_ip_mib,
14672 				    ipIfStatsInDiscards);
14673 			}
14674 			return (B_TRUE);
14675 		}
14676 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14677 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14678 			/* Copy b_prev - used by ip_mroute_decap */
14679 			to_mp->b_prev = from_mp->b_prev;
14680 			from_mp->b_prev = NULL;
14681 		}
14682 		*first_mpp = first_mp = mp1;
14683 		freemsg(mp);
14684 		mp = mp1;
14685 		*mpp = mp1;
14686 	}
14687 
14688 	ipha = (ipha_t *)mp->b_rptr;
14689 
14690 	/*
14691 	 * previous code has a case for M_DATA.
14692 	 * We want to check how that happens.
14693 	 */
14694 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14695 	switch (first_mp->b_datap->db_type) {
14696 	case M_PROTO:
14697 	case M_PCPROTO:
14698 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14699 		    DL_UNITDATA_IND) {
14700 			/* Go handle anything other than data elsewhere. */
14701 			ip_rput_dlpi(q, mp);
14702 			return (B_TRUE);
14703 		}
14704 
14705 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14706 		/* Ditch the DLPI header. */
14707 		mp1 = mp->b_cont;
14708 		ASSERT(first_mp == mp);
14709 		*first_mpp = mp1;
14710 		freeb(mp);
14711 		*mpp = mp1;
14712 		return (B_FALSE);
14713 	case M_IOCACK:
14714 		ip1dbg(("got iocack "));
14715 		iocp = (struct iocblk *)mp->b_rptr;
14716 		switch (iocp->ioc_cmd) {
14717 		case DL_IOC_HDR_INFO:
14718 			ill = (ill_t *)q->q_ptr;
14719 			ill_fastpath_ack(ill, mp);
14720 			return (B_TRUE);
14721 		case SIOCSTUNPARAM:
14722 		case OSIOCSTUNPARAM:
14723 			/* Go through qwriter_ip */
14724 			break;
14725 		case SIOCGTUNPARAM:
14726 		case OSIOCGTUNPARAM:
14727 			ip_rput_other(NULL, q, mp, NULL);
14728 			return (B_TRUE);
14729 		default:
14730 			putnext(q, mp);
14731 			return (B_TRUE);
14732 		}
14733 		/* FALLTHRU */
14734 	case M_ERROR:
14735 	case M_HANGUP:
14736 		/*
14737 		 * Since this is on the ill stream we unconditionally
14738 		 * bump up the refcount
14739 		 */
14740 		ill_refhold(ill);
14741 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14742 		return (B_TRUE);
14743 	case M_CTL:
14744 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14745 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14746 		    IPHADA_M_CTL)) {
14747 			/*
14748 			 * It's an IPsec accelerated packet.
14749 			 * Make sure that the ill from which we received the
14750 			 * packet has enabled IPsec hardware acceleration.
14751 			 */
14752 			if (!(ill->ill_capabilities &
14753 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14754 				/* IPsec kstats: bean counter */
14755 				freemsg(mp);
14756 				return (B_TRUE);
14757 			}
14758 
14759 			/*
14760 			 * Make mp point to the mblk following the M_CTL,
14761 			 * then process according to type of mp.
14762 			 * After this processing, first_mp will point to
14763 			 * the data-attributes and mp to the pkt following
14764 			 * the M_CTL.
14765 			 */
14766 			mp = first_mp->b_cont;
14767 			if (mp == NULL) {
14768 				freemsg(first_mp);
14769 				return (B_TRUE);
14770 			}
14771 			/*
14772 			 * A Hardware Accelerated packet can only be M_DATA
14773 			 * ESP or AH packet.
14774 			 */
14775 			if (mp->b_datap->db_type != M_DATA) {
14776 				/* non-M_DATA IPsec accelerated packet */
14777 				IPSECHW_DEBUG(IPSECHW_PKT,
14778 				    ("non-M_DATA IPsec accelerated pkt\n"));
14779 				freemsg(first_mp);
14780 				return (B_TRUE);
14781 			}
14782 			ipha = (ipha_t *)mp->b_rptr;
14783 			if (ipha->ipha_protocol != IPPROTO_AH &&
14784 			    ipha->ipha_protocol != IPPROTO_ESP) {
14785 				IPSECHW_DEBUG(IPSECHW_PKT,
14786 				    ("non-M_DATA IPsec accelerated pkt\n"));
14787 				freemsg(first_mp);
14788 				return (B_TRUE);
14789 			}
14790 			*mpp = mp;
14791 			return (B_FALSE);
14792 		}
14793 		putnext(q, mp);
14794 		return (B_TRUE);
14795 	case M_IOCNAK:
14796 		ip1dbg(("got iocnak "));
14797 		iocp = (struct iocblk *)mp->b_rptr;
14798 		switch (iocp->ioc_cmd) {
14799 		case SIOCSTUNPARAM:
14800 		case OSIOCSTUNPARAM:
14801 			/*
14802 			 * Since this is on the ill stream we unconditionally
14803 			 * bump up the refcount
14804 			 */
14805 			ill_refhold(ill);
14806 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14807 			return (B_TRUE);
14808 		case DL_IOC_HDR_INFO:
14809 		case SIOCGTUNPARAM:
14810 		case OSIOCGTUNPARAM:
14811 			ip_rput_other(NULL, q, mp, NULL);
14812 			return (B_TRUE);
14813 		default:
14814 			break;
14815 		}
14816 		/* FALLTHRU */
14817 	default:
14818 		putnext(q, mp);
14819 		return (B_TRUE);
14820 	}
14821 }
14822 
14823 /* Read side put procedure.  Packets coming from the wire arrive here. */
14824 void
14825 ip_rput(queue_t *q, mblk_t *mp)
14826 {
14827 	ill_t	*ill;
14828 	union DL_primitives *dl;
14829 
14830 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14831 
14832 	ill = (ill_t *)q->q_ptr;
14833 
14834 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14835 		/*
14836 		 * If things are opening or closing, only accept high-priority
14837 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14838 		 * created; on close, things hanging off the ill may have been
14839 		 * freed already.)
14840 		 */
14841 		dl = (union DL_primitives *)mp->b_rptr;
14842 		if (DB_TYPE(mp) != M_PCPROTO ||
14843 		    dl->dl_primitive == DL_UNITDATA_IND) {
14844 			/*
14845 			 * SIOC[GS]TUNPARAM ioctls can come here.
14846 			 */
14847 			inet_freemsg(mp);
14848 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14849 			    "ip_rput_end: q %p (%S)", q, "uninit");
14850 			return;
14851 		}
14852 	}
14853 
14854 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14855 	    "ip_rput_end: q %p (%S)", q, "end");
14856 
14857 	ip_input(ill, NULL, mp, NULL);
14858 }
14859 
14860 static mblk_t *
14861 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14862 {
14863 	mblk_t *mp1;
14864 	boolean_t adjusted = B_FALSE;
14865 	ip_stack_t *ipst = ill->ill_ipst;
14866 
14867 	IP_STAT(ipst, ip_db_ref);
14868 	/*
14869 	 * The IP_RECVSLLA option depends on having the
14870 	 * link layer header. First check that:
14871 	 * a> the underlying device is of type ether,
14872 	 * since this option is currently supported only
14873 	 * over ethernet.
14874 	 * b> there is enough room to copy over the link
14875 	 * layer header.
14876 	 *
14877 	 * Once the checks are done, adjust rptr so that
14878 	 * the link layer header will be copied via
14879 	 * copymsg. Note that, IFT_ETHER may be returned
14880 	 * by some non-ethernet drivers but in this case
14881 	 * the second check will fail.
14882 	 */
14883 	if (ill->ill_type == IFT_ETHER &&
14884 	    (mp->b_rptr - mp->b_datap->db_base) >=
14885 	    sizeof (struct ether_header)) {
14886 		mp->b_rptr -= sizeof (struct ether_header);
14887 		adjusted = B_TRUE;
14888 	}
14889 	mp1 = copymsg(mp);
14890 
14891 	if (mp1 == NULL) {
14892 		mp->b_next = NULL;
14893 		/* clear b_prev - used by ip_mroute_decap */
14894 		mp->b_prev = NULL;
14895 		freemsg(mp);
14896 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14897 		return (NULL);
14898 	}
14899 
14900 	if (adjusted) {
14901 		/*
14902 		 * Copy is done. Restore the pointer in
14903 		 * the _new_ mblk
14904 		 */
14905 		mp1->b_rptr += sizeof (struct ether_header);
14906 	}
14907 
14908 	/* Copy b_prev - used by ip_mroute_decap */
14909 	mp1->b_prev = mp->b_prev;
14910 	mp->b_prev = NULL;
14911 
14912 	/* preserve the hardware checksum flags and data, if present */
14913 	if (DB_CKSUMFLAGS(mp) != 0) {
14914 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14915 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14916 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14917 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14918 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14919 	}
14920 
14921 	freemsg(mp);
14922 	return (mp1);
14923 }
14924 
14925 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14926 	if (tail != NULL)					\
14927 		tail->b_next = mp;				\
14928 	else							\
14929 		head = mp;					\
14930 	tail = mp;						\
14931 	cnt++;							\
14932 }
14933 
14934 /*
14935  * Direct read side procedure capable of dealing with chains. GLDv3 based
14936  * drivers call this function directly with mblk chains while STREAMS
14937  * read side procedure ip_rput() calls this for single packet with ip_ring
14938  * set to NULL to process one packet at a time.
14939  *
14940  * The ill will always be valid if this function is called directly from
14941  * the driver.
14942  *
14943  * If ip_input() is called from GLDv3:
14944  *
14945  *   - This must be a non-VLAN IP stream.
14946  *   - 'mp' is either an untagged or a special priority-tagged packet.
14947  *   - Any VLAN tag that was in the MAC header has been stripped.
14948  *
14949  * If the IP header in packet is not 32-bit aligned, every message in the
14950  * chain will be aligned before further operations. This is required on SPARC
14951  * platform.
14952  */
14953 /* ARGSUSED */
14954 void
14955 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14956     struct mac_header_info_s *mhip)
14957 {
14958 	ipaddr_t		dst = NULL;
14959 	ipaddr_t		prev_dst;
14960 	ire_t			*ire = NULL;
14961 	ipha_t			*ipha;
14962 	uint_t			pkt_len;
14963 	ssize_t			len;
14964 	uint_t			opt_len;
14965 	int			ll_multicast;
14966 	int			cgtp_flt_pkt;
14967 	queue_t			*q = ill->ill_rq;
14968 	squeue_t		*curr_sqp = NULL;
14969 	mblk_t 			*head = NULL;
14970 	mblk_t			*tail = NULL;
14971 	mblk_t			*first_mp;
14972 	int			cnt = 0;
14973 	ip_stack_t		*ipst = ill->ill_ipst;
14974 	mblk_t			*mp;
14975 	mblk_t			*dmp;
14976 	uint8_t			tag;
14977 
14978 	ASSERT(mp_chain != NULL);
14979 	ASSERT(ill != NULL);
14980 
14981 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14982 
14983 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14984 
14985 #define	rptr	((uchar_t *)ipha)
14986 
14987 	while (mp_chain != NULL) {
14988 		mp = mp_chain;
14989 		mp_chain = mp_chain->b_next;
14990 		mp->b_next = NULL;
14991 		ll_multicast = 0;
14992 
14993 		/*
14994 		 * We do ire caching from one iteration to
14995 		 * another. In the event the packet chain contains
14996 		 * all packets from the same dst, this caching saves
14997 		 * an ire_cache_lookup for each of the succeeding
14998 		 * packets in a packet chain.
14999 		 */
15000 		prev_dst = dst;
15001 
15002 		/*
15003 		 * if db_ref > 1 then copymsg and free original. Packet
15004 		 * may be changed and we do not want the other entity
15005 		 * who has a reference to this message to trip over the
15006 		 * changes. This is a blind change because trying to
15007 		 * catch all places that might change the packet is too
15008 		 * difficult.
15009 		 *
15010 		 * This corresponds to the fast path case, where we have
15011 		 * a chain of M_DATA mblks.  We check the db_ref count
15012 		 * of only the 1st data block in the mblk chain. There
15013 		 * doesn't seem to be a reason why a device driver would
15014 		 * send up data with varying db_ref counts in the mblk
15015 		 * chain. In any case the Fast path is a private
15016 		 * interface, and our drivers don't do such a thing.
15017 		 * Given the above assumption, there is no need to walk
15018 		 * down the entire mblk chain (which could have a
15019 		 * potential performance problem)
15020 		 *
15021 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
15022 		 * to here because of exclusive ip stacks and vnics.
15023 		 * Packets transmitted from exclusive stack over vnic
15024 		 * can have db_ref > 1 and when it gets looped back to
15025 		 * another vnic in a different zone, you have ip_input()
15026 		 * getting dblks with db_ref > 1. So if someone
15027 		 * complains of TCP performance under this scenario,
15028 		 * take a serious look here on the impact of copymsg().
15029 		 */
15030 
15031 		if (DB_REF(mp) > 1) {
15032 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
15033 				continue;
15034 		}
15035 
15036 		/*
15037 		 * Check and align the IP header.
15038 		 */
15039 		first_mp = mp;
15040 		if (DB_TYPE(mp) == M_DATA) {
15041 			dmp = mp;
15042 		} else if (DB_TYPE(mp) == M_PROTO &&
15043 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15044 			dmp = mp->b_cont;
15045 		} else {
15046 			dmp = NULL;
15047 		}
15048 		if (dmp != NULL) {
15049 			/*
15050 			 * IP header ptr not aligned?
15051 			 * OR IP header not complete in first mblk
15052 			 */
15053 			if (!OK_32PTR(dmp->b_rptr) ||
15054 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15055 				if (!ip_check_and_align_header(q, dmp, ipst))
15056 					continue;
15057 			}
15058 		}
15059 
15060 		/*
15061 		 * ip_input fast path
15062 		 */
15063 
15064 		/* mblk type is not M_DATA */
15065 		if (DB_TYPE(mp) != M_DATA) {
15066 			if (ip_rput_process_notdata(q, &first_mp, ill,
15067 			    &ll_multicast, &mp))
15068 				continue;
15069 
15070 			/*
15071 			 * The only way we can get here is if we had a
15072 			 * packet that was either a DL_UNITDATA_IND or
15073 			 * an M_CTL for an IPsec accelerated packet.
15074 			 *
15075 			 * In either case, the first_mp will point to
15076 			 * the leading M_PROTO or M_CTL.
15077 			 */
15078 			ASSERT(first_mp != NULL);
15079 		} else if (mhip != NULL) {
15080 			/*
15081 			 * ll_multicast is set here so that it is ready
15082 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15083 			 * manipulates ll_multicast in the same fashion when
15084 			 * called from ip_rput_process_notdata.
15085 			 */
15086 			switch (mhip->mhi_dsttype) {
15087 			case MAC_ADDRTYPE_MULTICAST :
15088 				ll_multicast = HPE_MULTICAST;
15089 				break;
15090 			case MAC_ADDRTYPE_BROADCAST :
15091 				ll_multicast = HPE_BROADCAST;
15092 				break;
15093 			default :
15094 				break;
15095 			}
15096 		}
15097 
15098 		/* Only M_DATA can come here and it is always aligned */
15099 		ASSERT(DB_TYPE(mp) == M_DATA);
15100 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15101 
15102 		ipha = (ipha_t *)mp->b_rptr;
15103 		len = mp->b_wptr - rptr;
15104 		pkt_len = ntohs(ipha->ipha_length);
15105 
15106 		/*
15107 		 * We must count all incoming packets, even if they end
15108 		 * up being dropped later on.
15109 		 */
15110 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15111 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15112 
15113 		/* multiple mblk or too short */
15114 		len -= pkt_len;
15115 		if (len != 0) {
15116 			/*
15117 			 * Make sure we have data length consistent
15118 			 * with the IP header.
15119 			 */
15120 			if (mp->b_cont == NULL) {
15121 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15122 					BUMP_MIB(ill->ill_ip_mib,
15123 					    ipIfStatsInHdrErrors);
15124 					ip2dbg(("ip_input: drop pkt\n"));
15125 					freemsg(mp);
15126 					continue;
15127 				}
15128 				mp->b_wptr = rptr + pkt_len;
15129 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15130 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15131 					BUMP_MIB(ill->ill_ip_mib,
15132 					    ipIfStatsInHdrErrors);
15133 					ip2dbg(("ip_input: drop pkt\n"));
15134 					freemsg(mp);
15135 					continue;
15136 				}
15137 				(void) adjmsg(mp, -len);
15138 				IP_STAT(ipst, ip_multimblk3);
15139 			}
15140 		}
15141 
15142 		/* Obtain the dst of the current packet */
15143 		dst = ipha->ipha_dst;
15144 
15145 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15146 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15147 		    ipha, ip6_t *, NULL, int, 0);
15148 
15149 		/*
15150 		 * The following test for loopback is faster than
15151 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15152 		 * operations.
15153 		 * Note that these addresses are always in network byte order
15154 		 */
15155 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15156 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15157 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15158 			freemsg(mp);
15159 			continue;
15160 		}
15161 
15162 		/*
15163 		 * The event for packets being received from a 'physical'
15164 		 * interface is placed after validation of the source and/or
15165 		 * destination address as being local so that packets can be
15166 		 * redirected to loopback addresses using ipnat.
15167 		 */
15168 		DTRACE_PROBE4(ip4__physical__in__start,
15169 		    ill_t *, ill, ill_t *, NULL,
15170 		    ipha_t *, ipha, mblk_t *, first_mp);
15171 
15172 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15173 		    ipst->ips_ipv4firewall_physical_in,
15174 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15175 
15176 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15177 
15178 		if (first_mp == NULL) {
15179 			continue;
15180 		}
15181 		dst = ipha->ipha_dst;
15182 		/*
15183 		 * Attach any necessary label information to
15184 		 * this packet
15185 		 */
15186 		if (is_system_labeled() &&
15187 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15188 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15189 			freemsg(mp);
15190 			continue;
15191 		}
15192 
15193 		if (ipst->ips_ipobs_enabled) {
15194 			zoneid_t dzone;
15195 
15196 			/*
15197 			 * On the inbound path the src zone will be unknown as
15198 			 * this packet has come from the wire.
15199 			 */
15200 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15201 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15202 			    ill, IPV4_VERSION, 0, ipst);
15203 		}
15204 
15205 		/*
15206 		 * Reuse the cached ire only if the ipha_dst of the previous
15207 		 * packet is the same as the current packet AND it is not
15208 		 * INADDR_ANY.
15209 		 */
15210 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15211 		    (ire != NULL)) {
15212 			ire_refrele(ire);
15213 			ire = NULL;
15214 		}
15215 
15216 		opt_len = ipha->ipha_version_and_hdr_length -
15217 		    IP_SIMPLE_HDR_VERSION;
15218 
15219 		/*
15220 		 * Check to see if we can take the fastpath.
15221 		 * That is possible if the following conditions are met
15222 		 *	o Tsol disabled
15223 		 *	o CGTP disabled
15224 		 *	o ipp_action_count is 0
15225 		 *	o no options in the packet
15226 		 *	o not a RSVP packet
15227 		 * 	o not a multicast packet
15228 		 *	o ill not in IP_DHCPINIT_IF mode
15229 		 */
15230 		if (!is_system_labeled() &&
15231 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15232 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15233 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15234 			if (ire == NULL)
15235 				ire = ire_cache_lookup_simple(dst, ipst);
15236 			/*
15237 			 * Unless forwarding is enabled, dont call
15238 			 * ip_fast_forward(). Incoming packet is for forwarding
15239 			 */
15240 			if ((ill->ill_flags & ILLF_ROUTER) &&
15241 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15242 				ire = ip_fast_forward(ire, dst, ill, mp);
15243 				continue;
15244 			}
15245 			/* incoming packet is for local consumption */
15246 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15247 				goto local;
15248 		}
15249 
15250 		/*
15251 		 * Disable ire caching for anything more complex
15252 		 * than the simple fast path case we checked for above.
15253 		 */
15254 		if (ire != NULL) {
15255 			ire_refrele(ire);
15256 			ire = NULL;
15257 		}
15258 
15259 		/*
15260 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15261 		 * server to unicast DHCP packets to a DHCP client using the
15262 		 * IP address it is offering to the client.  This can be
15263 		 * disabled through the "broadcast bit", but not all DHCP
15264 		 * servers honor that bit.  Therefore, to interoperate with as
15265 		 * many DHCP servers as possible, the DHCP client allows the
15266 		 * server to unicast, but we treat those packets as broadcast
15267 		 * here.  Note that we don't rewrite the packet itself since
15268 		 * (a) that would mess up the checksums and (b) the DHCP
15269 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15270 		 * hand it the packet regardless.
15271 		 */
15272 		if (ill->ill_dhcpinit != 0 &&
15273 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15274 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15275 			udpha_t *udpha;
15276 
15277 			/*
15278 			 * Reload ipha since pullupmsg() can change b_rptr.
15279 			 */
15280 			ipha = (ipha_t *)mp->b_rptr;
15281 			udpha = (udpha_t *)&ipha[1];
15282 
15283 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15284 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15285 				    mblk_t *, mp);
15286 				dst = INADDR_BROADCAST;
15287 			}
15288 		}
15289 
15290 		/* Full-blown slow path */
15291 		if (opt_len != 0) {
15292 			if (len != 0)
15293 				IP_STAT(ipst, ip_multimblk4);
15294 			else
15295 				IP_STAT(ipst, ip_ipoptions);
15296 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15297 			    &dst, ipst))
15298 				continue;
15299 		}
15300 
15301 		/*
15302 		 * Invoke the CGTP (multirouting) filtering module to process
15303 		 * the incoming packet. Packets identified as duplicates
15304 		 * must be discarded. Filtering is active only if the
15305 		 * the ip_cgtp_filter ndd variable is non-zero.
15306 		 */
15307 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15308 		if (ipst->ips_ip_cgtp_filter &&
15309 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15310 			netstackid_t stackid;
15311 
15312 			stackid = ipst->ips_netstack->netstack_stackid;
15313 			cgtp_flt_pkt =
15314 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15315 			    ill->ill_phyint->phyint_ifindex, mp);
15316 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15317 				freemsg(first_mp);
15318 				continue;
15319 			}
15320 		}
15321 
15322 		/*
15323 		 * If rsvpd is running, let RSVP daemon handle its processing
15324 		 * and forwarding of RSVP multicast/unicast packets.
15325 		 * If rsvpd is not running but mrouted is running, RSVP
15326 		 * multicast packets are forwarded as multicast traffic
15327 		 * and RSVP unicast packets are forwarded by unicast router.
15328 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15329 		 * packets are not forwarded, but the unicast packets are
15330 		 * forwarded like unicast traffic.
15331 		 */
15332 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15333 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15334 		    NULL) {
15335 			/* RSVP packet and rsvpd running. Treat as ours */
15336 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15337 			/*
15338 			 * This assumes that we deliver to all streams for
15339 			 * multicast and broadcast packets.
15340 			 * We have to force ll_multicast to 1 to handle the
15341 			 * M_DATA messages passed in from ip_mroute_decap.
15342 			 */
15343 			dst = INADDR_BROADCAST;
15344 			ll_multicast = 1;
15345 		} else if (CLASSD(dst)) {
15346 			/* packet is multicast */
15347 			mp->b_next = NULL;
15348 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15349 			    &ll_multicast, &dst))
15350 				continue;
15351 		}
15352 
15353 		if (ire == NULL) {
15354 			ire = ire_cache_lookup(dst, ALL_ZONES,
15355 			    msg_getlabel(mp), ipst);
15356 		}
15357 
15358 		if (ire != NULL && ire->ire_stq != NULL &&
15359 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15360 		    ire->ire_zoneid != ALL_ZONES) {
15361 			/*
15362 			 * Should only use IREs that are visible from the
15363 			 * global zone for forwarding.
15364 			 */
15365 			ire_refrele(ire);
15366 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15367 			    msg_getlabel(mp), ipst);
15368 		}
15369 
15370 		if (ire == NULL) {
15371 			/*
15372 			 * No IRE for this destination, so it can't be for us.
15373 			 * Unless we are forwarding, drop the packet.
15374 			 * We have to let source routed packets through
15375 			 * since we don't yet know if they are 'ping -l'
15376 			 * packets i.e. if they will go out over the
15377 			 * same interface as they came in on.
15378 			 */
15379 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15380 			if (ire == NULL)
15381 				continue;
15382 		}
15383 
15384 		/*
15385 		 * Broadcast IRE may indicate either broadcast or
15386 		 * multicast packet
15387 		 */
15388 		if (ire->ire_type == IRE_BROADCAST) {
15389 			/*
15390 			 * Skip broadcast checks if packet is UDP multicast;
15391 			 * we'd rather not enter ip_rput_process_broadcast()
15392 			 * unless the packet is broadcast for real, since
15393 			 * that routine is a no-op for multicast.
15394 			 */
15395 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15396 			    !CLASSD(ipha->ipha_dst)) {
15397 				ire = ip_rput_process_broadcast(&q, mp,
15398 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15399 				    ll_multicast);
15400 				if (ire == NULL)
15401 					continue;
15402 			}
15403 		} else if (ire->ire_stq != NULL) {
15404 			/* fowarding? */
15405 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15406 			    ll_multicast, B_FALSE);
15407 			/* ip_rput_process_forward consumed the packet */
15408 			continue;
15409 		}
15410 
15411 local:
15412 		/*
15413 		 * If the queue in the ire is different to the ingress queue
15414 		 * then we need to check to see if we can accept the packet.
15415 		 * Note that for multicast packets and broadcast packets sent
15416 		 * to a broadcast address which is shared between multiple
15417 		 * interfaces we should not do this since we just got a random
15418 		 * broadcast ire.
15419 		 */
15420 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15421 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15422 			if (ire == NULL) {
15423 				/* Drop packet */
15424 				BUMP_MIB(ill->ill_ip_mib,
15425 				    ipIfStatsForwProhibits);
15426 				freemsg(mp);
15427 				continue;
15428 			}
15429 			if (ire->ire_rfq != NULL)
15430 				q = ire->ire_rfq;
15431 		}
15432 
15433 		switch (ipha->ipha_protocol) {
15434 		case IPPROTO_TCP:
15435 			ASSERT(first_mp == mp);
15436 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15437 			    mp, 0, q, ip_ring)) != NULL) {
15438 				if (curr_sqp == NULL) {
15439 					curr_sqp = GET_SQUEUE(mp);
15440 					ASSERT(cnt == 0);
15441 					cnt++;
15442 					head = tail = mp;
15443 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15444 					ASSERT(tail != NULL);
15445 					cnt++;
15446 					tail->b_next = mp;
15447 					tail = mp;
15448 				} else {
15449 					/*
15450 					 * A different squeue. Send the
15451 					 * chain for the previous squeue on
15452 					 * its way. This shouldn't happen
15453 					 * often unless interrupt binding
15454 					 * changes.
15455 					 */
15456 					IP_STAT(ipst, ip_input_multi_squeue);
15457 					SQUEUE_ENTER(curr_sqp, head,
15458 					    tail, cnt, SQ_PROCESS, tag);
15459 					curr_sqp = GET_SQUEUE(mp);
15460 					head = mp;
15461 					tail = mp;
15462 					cnt = 1;
15463 				}
15464 			}
15465 			continue;
15466 		case IPPROTO_UDP:
15467 			ASSERT(first_mp == mp);
15468 			ip_udp_input(q, mp, ipha, ire, ill);
15469 			continue;
15470 		case IPPROTO_SCTP:
15471 			ASSERT(first_mp == mp);
15472 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15473 			    q, dst);
15474 			/* ire has been released by ip_sctp_input */
15475 			ire = NULL;
15476 			continue;
15477 		default:
15478 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15479 			continue;
15480 		}
15481 	}
15482 
15483 	if (ire != NULL)
15484 		ire_refrele(ire);
15485 
15486 	if (head != NULL)
15487 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15488 
15489 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15490 	    "ip_input_end: q %p (%S)", q, "end");
15491 #undef  rptr
15492 }
15493 
15494 /*
15495  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15496  * a chain of packets in the poll mode. The packets have gone through the
15497  * data link processing but not IP processing. For performance and latency
15498  * reasons, the squeue wants to process the chain in line instead of feeding
15499  * it back via ip_input path.
15500  *
15501  * So this is a light weight function which checks to see if the packets
15502  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15503  * but we still do the paranoid check) meant for local machine and we don't
15504  * have labels etc enabled. Packets that meet the criterion are returned to
15505  * the squeue and processed inline while the rest go via ip_input path.
15506  */
15507 /*ARGSUSED*/
15508 mblk_t *
15509 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15510     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15511 {
15512 	mblk_t 		*mp;
15513 	ipaddr_t	dst = NULL;
15514 	ipaddr_t	prev_dst;
15515 	ire_t		*ire = NULL;
15516 	ipha_t		*ipha;
15517 	uint_t		pkt_len;
15518 	ssize_t		len;
15519 	uint_t		opt_len;
15520 	queue_t		*q = ill->ill_rq;
15521 	squeue_t	*curr_sqp;
15522 	mblk_t 		*ahead = NULL;	/* Accepted head */
15523 	mblk_t		*atail = NULL;	/* Accepted tail */
15524 	uint_t		acnt = 0;	/* Accepted count */
15525 	mblk_t		*utail = NULL;	/* Unaccepted head */
15526 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15527 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15528 	ip_stack_t	*ipst = ill->ill_ipst;
15529 
15530 	*cnt = 0;
15531 
15532 	ASSERT(ill != NULL);
15533 	ASSERT(ip_ring != NULL);
15534 
15535 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15536 
15537 #define	rptr	((uchar_t *)ipha)
15538 
15539 	while (mp_chain != NULL) {
15540 		mp = mp_chain;
15541 		mp_chain = mp_chain->b_next;
15542 		mp->b_next = NULL;
15543 
15544 		/*
15545 		 * We do ire caching from one iteration to
15546 		 * another. In the event the packet chain contains
15547 		 * all packets from the same dst, this caching saves
15548 		 * an ire_cache_lookup for each of the succeeding
15549 		 * packets in a packet chain.
15550 		 */
15551 		prev_dst = dst;
15552 
15553 		ipha = (ipha_t *)mp->b_rptr;
15554 		len = mp->b_wptr - rptr;
15555 
15556 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15557 
15558 		/*
15559 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15560 		 * or doesn't have min len, reject.
15561 		 */
15562 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15563 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15564 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15565 			continue;
15566 		}
15567 
15568 		pkt_len = ntohs(ipha->ipha_length);
15569 		if (len != pkt_len) {
15570 			if (len > pkt_len) {
15571 				mp->b_wptr = rptr + pkt_len;
15572 			} else {
15573 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15574 				continue;
15575 			}
15576 		}
15577 
15578 		opt_len = ipha->ipha_version_and_hdr_length -
15579 		    IP_SIMPLE_HDR_VERSION;
15580 		dst = ipha->ipha_dst;
15581 
15582 		/* IP version bad or there are IP options */
15583 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15584 		    mp, &ipha, &dst, ipst)))
15585 			continue;
15586 
15587 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15588 		    (ipst->ips_ip_cgtp_filter &&
15589 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15590 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15591 			continue;
15592 		}
15593 
15594 		/*
15595 		 * Reuse the cached ire only if the ipha_dst of the previous
15596 		 * packet is the same as the current packet AND it is not
15597 		 * INADDR_ANY.
15598 		 */
15599 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15600 		    (ire != NULL)) {
15601 			ire_refrele(ire);
15602 			ire = NULL;
15603 		}
15604 
15605 		if (ire == NULL)
15606 			ire = ire_cache_lookup_simple(dst, ipst);
15607 
15608 		/*
15609 		 * Unless forwarding is enabled, dont call
15610 		 * ip_fast_forward(). Incoming packet is for forwarding
15611 		 */
15612 		if ((ill->ill_flags & ILLF_ROUTER) &&
15613 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15614 
15615 			DTRACE_PROBE4(ip4__physical__in__start,
15616 			    ill_t *, ill, ill_t *, NULL,
15617 			    ipha_t *, ipha, mblk_t *, mp);
15618 
15619 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15620 			    ipst->ips_ipv4firewall_physical_in,
15621 			    ill, NULL, ipha, mp, mp, 0, ipst);
15622 
15623 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15624 
15625 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15626 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15627 			    pkt_len);
15628 
15629 			if (mp != NULL)
15630 				ire = ip_fast_forward(ire, dst, ill, mp);
15631 			continue;
15632 		}
15633 
15634 		/* incoming packet is for local consumption */
15635 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15636 			goto local_accept;
15637 
15638 		/*
15639 		 * Disable ire caching for anything more complex
15640 		 * than the simple fast path case we checked for above.
15641 		 */
15642 		if (ire != NULL) {
15643 			ire_refrele(ire);
15644 			ire = NULL;
15645 		}
15646 
15647 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15648 		    ipst);
15649 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15650 		    ire->ire_stq != NULL) {
15651 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15652 			if (ire != NULL) {
15653 				ire_refrele(ire);
15654 				ire = NULL;
15655 			}
15656 			continue;
15657 		}
15658 
15659 local_accept:
15660 
15661 		if (ire->ire_rfq != q) {
15662 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15663 			if (ire != NULL) {
15664 				ire_refrele(ire);
15665 				ire = NULL;
15666 			}
15667 			continue;
15668 		}
15669 
15670 		/*
15671 		 * The event for packets being received from a 'physical'
15672 		 * interface is placed after validation of the source and/or
15673 		 * destination address as being local so that packets can be
15674 		 * redirected to loopback addresses using ipnat.
15675 		 */
15676 		DTRACE_PROBE4(ip4__physical__in__start,
15677 		    ill_t *, ill, ill_t *, NULL,
15678 		    ipha_t *, ipha, mblk_t *, mp);
15679 
15680 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15681 		    ipst->ips_ipv4firewall_physical_in,
15682 		    ill, NULL, ipha, mp, mp, 0, ipst);
15683 
15684 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15685 
15686 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15687 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15688 
15689 		if (mp != NULL &&
15690 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15691 		    0, q, ip_ring)) != NULL) {
15692 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15693 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15694 			} else {
15695 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15696 				    SQ_FILL, SQTAG_IP_INPUT);
15697 			}
15698 		}
15699 	}
15700 
15701 	if (ire != NULL)
15702 		ire_refrele(ire);
15703 
15704 	if (uhead != NULL)
15705 		ip_input(ill, ip_ring, uhead, NULL);
15706 
15707 	if (ahead != NULL) {
15708 		*last = atail;
15709 		*cnt = acnt;
15710 		return (ahead);
15711 	}
15712 
15713 	return (NULL);
15714 #undef  rptr
15715 }
15716 
15717 static void
15718 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15719     t_uscalar_t err)
15720 {
15721 	if (dl_err == DL_SYSERR) {
15722 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15723 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15724 		    ill->ill_name, dl_primstr(prim), err);
15725 		return;
15726 	}
15727 
15728 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15729 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15730 	    dl_errstr(dl_err));
15731 }
15732 
15733 /*
15734  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15735  * than DL_UNITDATA_IND messages. If we need to process this message
15736  * exclusively, we call qwriter_ip, in which case we also need to call
15737  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15738  */
15739 void
15740 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15741 {
15742 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15743 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15744 	ill_t		*ill = q->q_ptr;
15745 	t_uscalar_t	prim = dloa->dl_primitive;
15746 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15747 
15748 	ip1dbg(("ip_rput_dlpi"));
15749 
15750 	/*
15751 	 * If we received an ACK but didn't send a request for it, then it
15752 	 * can't be part of any pending operation; discard up-front.
15753 	 */
15754 	switch (prim) {
15755 	case DL_ERROR_ACK:
15756 		reqprim = dlea->dl_error_primitive;
15757 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15758 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15759 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15760 		    dlea->dl_unix_errno));
15761 		break;
15762 	case DL_OK_ACK:
15763 		reqprim = dloa->dl_correct_primitive;
15764 		break;
15765 	case DL_INFO_ACK:
15766 		reqprim = DL_INFO_REQ;
15767 		break;
15768 	case DL_BIND_ACK:
15769 		reqprim = DL_BIND_REQ;
15770 		break;
15771 	case DL_PHYS_ADDR_ACK:
15772 		reqprim = DL_PHYS_ADDR_REQ;
15773 		break;
15774 	case DL_NOTIFY_ACK:
15775 		reqprim = DL_NOTIFY_REQ;
15776 		break;
15777 	case DL_CONTROL_ACK:
15778 		reqprim = DL_CONTROL_REQ;
15779 		break;
15780 	case DL_CAPABILITY_ACK:
15781 		reqprim = DL_CAPABILITY_REQ;
15782 		break;
15783 	}
15784 
15785 	if (prim != DL_NOTIFY_IND) {
15786 		if (reqprim == DL_PRIM_INVAL ||
15787 		    !ill_dlpi_pending(ill, reqprim)) {
15788 			/* Not a DLPI message we support or expected */
15789 			freemsg(mp);
15790 			return;
15791 		}
15792 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15793 		    dl_primstr(reqprim)));
15794 	}
15795 
15796 	switch (reqprim) {
15797 	case DL_UNBIND_REQ:
15798 		/*
15799 		 * NOTE: we mark the unbind as complete even if we got a
15800 		 * DL_ERROR_ACK, since there's not much else we can do.
15801 		 */
15802 		mutex_enter(&ill->ill_lock);
15803 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15804 		cv_signal(&ill->ill_cv);
15805 		mutex_exit(&ill->ill_lock);
15806 		break;
15807 
15808 	case DL_ENABMULTI_REQ:
15809 		if (prim == DL_OK_ACK) {
15810 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15811 				ill->ill_dlpi_multicast_state = IDS_OK;
15812 		}
15813 		break;
15814 	}
15815 
15816 	/*
15817 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15818 	 * need to become writer to continue to process it.  Because an
15819 	 * exclusive operation doesn't complete until replies to all queued
15820 	 * DLPI messages have been received, we know we're in the middle of an
15821 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15822 	 *
15823 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15824 	 * Since this is on the ill stream we unconditionally bump up the
15825 	 * refcount without doing ILL_CAN_LOOKUP().
15826 	 */
15827 	ill_refhold(ill);
15828 	if (prim == DL_NOTIFY_IND)
15829 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15830 	else
15831 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15832 }
15833 
15834 /*
15835  * Handling of DLPI messages that require exclusive access to the ipsq.
15836  *
15837  * Need to do ill_pending_mp_release on ioctl completion, which could
15838  * happen here. (along with mi_copy_done)
15839  */
15840 /* ARGSUSED */
15841 static void
15842 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15843 {
15844 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15845 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15846 	int		err = 0;
15847 	ill_t		*ill;
15848 	ipif_t		*ipif = NULL;
15849 	mblk_t		*mp1 = NULL;
15850 	conn_t		*connp = NULL;
15851 	t_uscalar_t	paddrreq;
15852 	mblk_t		*mp_hw;
15853 	boolean_t	success;
15854 	boolean_t	ioctl_aborted = B_FALSE;
15855 	boolean_t	log = B_TRUE;
15856 	ip_stack_t		*ipst;
15857 
15858 	ip1dbg(("ip_rput_dlpi_writer .."));
15859 	ill = (ill_t *)q->q_ptr;
15860 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15861 	ASSERT(IAM_WRITER_ILL(ill));
15862 
15863 	ipst = ill->ill_ipst;
15864 
15865 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15866 	/*
15867 	 * The current ioctl could have been aborted by the user and a new
15868 	 * ioctl to bring up another ill could have started. We could still
15869 	 * get a response from the driver later.
15870 	 */
15871 	if (ipif != NULL && ipif->ipif_ill != ill)
15872 		ioctl_aborted = B_TRUE;
15873 
15874 	switch (dloa->dl_primitive) {
15875 	case DL_ERROR_ACK:
15876 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15877 		    dl_primstr(dlea->dl_error_primitive)));
15878 
15879 		switch (dlea->dl_error_primitive) {
15880 		case DL_DISABMULTI_REQ:
15881 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15882 			break;
15883 		case DL_PROMISCON_REQ:
15884 		case DL_PROMISCOFF_REQ:
15885 		case DL_UNBIND_REQ:
15886 		case DL_ATTACH_REQ:
15887 		case DL_INFO_REQ:
15888 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15889 			break;
15890 		case DL_NOTIFY_REQ:
15891 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15892 			log = B_FALSE;
15893 			break;
15894 		case DL_PHYS_ADDR_REQ:
15895 			/*
15896 			 * For IPv6 only, there are two additional
15897 			 * phys_addr_req's sent to the driver to get the
15898 			 * IPv6 token and lla. This allows IP to acquire
15899 			 * the hardware address format for a given interface
15900 			 * without having built in knowledge of the hardware
15901 			 * address. ill_phys_addr_pend keeps track of the last
15902 			 * DL_PAR sent so we know which response we are
15903 			 * dealing with. ill_dlpi_done will update
15904 			 * ill_phys_addr_pend when it sends the next req.
15905 			 * We don't complete the IOCTL until all three DL_PARs
15906 			 * have been attempted, so set *_len to 0 and break.
15907 			 */
15908 			paddrreq = ill->ill_phys_addr_pend;
15909 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15910 			if (paddrreq == DL_IPV6_TOKEN) {
15911 				ill->ill_token_length = 0;
15912 				log = B_FALSE;
15913 				break;
15914 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15915 				ill->ill_nd_lla_len = 0;
15916 				log = B_FALSE;
15917 				break;
15918 			}
15919 			/*
15920 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15921 			 * We presumably have an IOCTL hanging out waiting
15922 			 * for completion. Find it and complete the IOCTL
15923 			 * with the error noted.
15924 			 * However, ill_dl_phys was called on an ill queue
15925 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15926 			 * set. But the ioctl is known to be pending on ill_wq.
15927 			 */
15928 			if (!ill->ill_ifname_pending)
15929 				break;
15930 			ill->ill_ifname_pending = 0;
15931 			if (!ioctl_aborted)
15932 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15933 			if (mp1 != NULL) {
15934 				/*
15935 				 * This operation (SIOCSLIFNAME) must have
15936 				 * happened on the ill. Assert there is no conn
15937 				 */
15938 				ASSERT(connp == NULL);
15939 				q = ill->ill_wq;
15940 			}
15941 			break;
15942 		case DL_BIND_REQ:
15943 			ill_dlpi_done(ill, DL_BIND_REQ);
15944 			if (ill->ill_ifname_pending)
15945 				break;
15946 			/*
15947 			 * Something went wrong with the bind.  We presumably
15948 			 * have an IOCTL hanging out waiting for completion.
15949 			 * Find it, take down the interface that was coming
15950 			 * up, and complete the IOCTL with the error noted.
15951 			 */
15952 			if (!ioctl_aborted)
15953 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15954 			if (mp1 != NULL) {
15955 				/*
15956 				 * This might be a result of a DL_NOTE_REPLUMB
15957 				 * notification. In that case, connp is NULL.
15958 				 */
15959 				if (connp != NULL)
15960 					q = CONNP_TO_WQ(connp);
15961 
15962 				(void) ipif_down(ipif, NULL, NULL);
15963 				/* error is set below the switch */
15964 			}
15965 			break;
15966 		case DL_ENABMULTI_REQ:
15967 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15968 
15969 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15970 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15971 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15972 				ipif_t *ipif;
15973 
15974 				printf("ip: joining multicasts failed (%d)"
15975 				    " on %s - will use link layer "
15976 				    "broadcasts for multicast\n",
15977 				    dlea->dl_errno, ill->ill_name);
15978 
15979 				/*
15980 				 * Set up the multicast mapping alone.
15981 				 * writer, so ok to access ill->ill_ipif
15982 				 * without any lock.
15983 				 */
15984 				ipif = ill->ill_ipif;
15985 				mutex_enter(&ill->ill_phyint->phyint_lock);
15986 				ill->ill_phyint->phyint_flags |=
15987 				    PHYI_MULTI_BCAST;
15988 				mutex_exit(&ill->ill_phyint->phyint_lock);
15989 
15990 				if (!ill->ill_isv6) {
15991 					(void) ipif_arp_setup_multicast(ipif,
15992 					    NULL);
15993 				} else {
15994 					(void) ipif_ndp_setup_multicast(ipif,
15995 					    NULL);
15996 				}
15997 			}
15998 			freemsg(mp);	/* Don't want to pass this up */
15999 			return;
16000 		case DL_CONTROL_REQ:
16001 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16002 			    "DL_CONTROL_REQ\n"));
16003 			ill_dlpi_done(ill, dlea->dl_error_primitive);
16004 			freemsg(mp);
16005 			return;
16006 		case DL_CAPABILITY_REQ:
16007 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16008 			    "DL_CAPABILITY REQ\n"));
16009 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
16010 				ill->ill_dlpi_capab_state = IDCS_FAILED;
16011 			ill_capability_done(ill);
16012 			freemsg(mp);
16013 			return;
16014 		}
16015 		/*
16016 		 * Note the error for IOCTL completion (mp1 is set when
16017 		 * ready to complete ioctl). If ill_ifname_pending_err is
16018 		 * set, an error occured during plumbing (ill_ifname_pending),
16019 		 * so we want to report that error.
16020 		 *
16021 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
16022 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
16023 		 * expected to get errack'd if the driver doesn't support
16024 		 * these flags (e.g. ethernet). log will be set to B_FALSE
16025 		 * if these error conditions are encountered.
16026 		 */
16027 		if (mp1 != NULL) {
16028 			if (ill->ill_ifname_pending_err != 0)  {
16029 				err = ill->ill_ifname_pending_err;
16030 				ill->ill_ifname_pending_err = 0;
16031 			} else {
16032 				err = dlea->dl_unix_errno ?
16033 				    dlea->dl_unix_errno : ENXIO;
16034 			}
16035 		/*
16036 		 * If we're plumbing an interface and an error hasn't already
16037 		 * been saved, set ill_ifname_pending_err to the error passed
16038 		 * up. Ignore the error if log is B_FALSE (see comment above).
16039 		 */
16040 		} else if (log && ill->ill_ifname_pending &&
16041 		    ill->ill_ifname_pending_err == 0) {
16042 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
16043 			    dlea->dl_unix_errno : ENXIO;
16044 		}
16045 
16046 		if (log)
16047 			ip_dlpi_error(ill, dlea->dl_error_primitive,
16048 			    dlea->dl_errno, dlea->dl_unix_errno);
16049 		break;
16050 	case DL_CAPABILITY_ACK:
16051 		ill_capability_ack(ill, mp);
16052 		/*
16053 		 * The message has been handed off to ill_capability_ack
16054 		 * and must not be freed below
16055 		 */
16056 		mp = NULL;
16057 		break;
16058 
16059 	case DL_CONTROL_ACK:
16060 		/* We treat all of these as "fire and forget" */
16061 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16062 		break;
16063 	case DL_INFO_ACK:
16064 		/* Call a routine to handle this one. */
16065 		ill_dlpi_done(ill, DL_INFO_REQ);
16066 		ip_ll_subnet_defaults(ill, mp);
16067 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16068 		return;
16069 	case DL_BIND_ACK:
16070 		/*
16071 		 * We should have an IOCTL waiting on this unless
16072 		 * sent by ill_dl_phys, in which case just return
16073 		 */
16074 		ill_dlpi_done(ill, DL_BIND_REQ);
16075 		if (ill->ill_ifname_pending)
16076 			break;
16077 
16078 		if (!ioctl_aborted)
16079 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16080 		if (mp1 == NULL)
16081 			break;
16082 		/*
16083 		 * mp1 was added by ill_dl_up(). if that is a result of
16084 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16085 		 */
16086 		if (connp != NULL)
16087 			q = CONNP_TO_WQ(connp);
16088 
16089 		/*
16090 		 * We are exclusive. So nothing can change even after
16091 		 * we get the pending mp. If need be we can put it back
16092 		 * and restart, as in calling ipif_arp_up()  below.
16093 		 */
16094 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16095 
16096 		mutex_enter(&ill->ill_lock);
16097 		ill->ill_dl_up = 1;
16098 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16099 		mutex_exit(&ill->ill_lock);
16100 
16101 		/*
16102 		 * Now bring up the resolver; when that is complete, we'll
16103 		 * create IREs.  Note that we intentionally mirror what
16104 		 * ipif_up() would have done, because we got here by way of
16105 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16106 		 */
16107 		if (ill->ill_isv6) {
16108 			if (ill->ill_flags & ILLF_XRESOLV) {
16109 				if (connp != NULL)
16110 					mutex_enter(&connp->conn_lock);
16111 				mutex_enter(&ill->ill_lock);
16112 				success = ipsq_pending_mp_add(connp, ipif, q,
16113 				    mp1, 0);
16114 				mutex_exit(&ill->ill_lock);
16115 				if (connp != NULL)
16116 					mutex_exit(&connp->conn_lock);
16117 				if (success) {
16118 					err = ipif_resolver_up(ipif,
16119 					    Res_act_initial);
16120 					if (err == EINPROGRESS) {
16121 						freemsg(mp);
16122 						return;
16123 					}
16124 					ASSERT(err != 0);
16125 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16126 					ASSERT(mp1 != NULL);
16127 				} else {
16128 					/* conn has started closing */
16129 					err = EINTR;
16130 				}
16131 			} else { /* Non XRESOLV interface */
16132 				(void) ipif_resolver_up(ipif, Res_act_initial);
16133 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16134 					err = ipif_up_done_v6(ipif);
16135 			}
16136 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16137 			/*
16138 			 * ARP and other v4 external resolvers.
16139 			 * Leave the pending mblk intact so that
16140 			 * the ioctl completes in ip_rput().
16141 			 */
16142 			if (connp != NULL)
16143 				mutex_enter(&connp->conn_lock);
16144 			mutex_enter(&ill->ill_lock);
16145 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16146 			mutex_exit(&ill->ill_lock);
16147 			if (connp != NULL)
16148 				mutex_exit(&connp->conn_lock);
16149 			if (success) {
16150 				err = ipif_resolver_up(ipif, Res_act_initial);
16151 				if (err == EINPROGRESS) {
16152 					freemsg(mp);
16153 					return;
16154 				}
16155 				ASSERT(err != 0);
16156 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16157 			} else {
16158 				/* The conn has started closing */
16159 				err = EINTR;
16160 			}
16161 		} else {
16162 			/*
16163 			 * This one is complete. Reply to pending ioctl.
16164 			 */
16165 			(void) ipif_resolver_up(ipif, Res_act_initial);
16166 			err = ipif_up_done(ipif);
16167 		}
16168 
16169 		if ((err == 0) && (ill->ill_up_ipifs)) {
16170 			err = ill_up_ipifs(ill, q, mp1);
16171 			if (err == EINPROGRESS) {
16172 				freemsg(mp);
16173 				return;
16174 			}
16175 		}
16176 
16177 		/*
16178 		 * If we have a moved ipif to bring up, and everything has
16179 		 * succeeded to this point, bring it up on the IPMP ill.
16180 		 * Otherwise, leave it down -- the admin can try to bring it
16181 		 * up by hand if need be.
16182 		 */
16183 		if (ill->ill_move_ipif != NULL) {
16184 			if (err != 0) {
16185 				ill->ill_move_ipif = NULL;
16186 			} else {
16187 				ipif = ill->ill_move_ipif;
16188 				ill->ill_move_ipif = NULL;
16189 				err = ipif_up(ipif, q, mp1);
16190 				if (err == EINPROGRESS) {
16191 					freemsg(mp);
16192 					return;
16193 				}
16194 			}
16195 		}
16196 		break;
16197 
16198 	case DL_NOTIFY_IND: {
16199 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16200 		ire_t *ire;
16201 		uint_t orig_mtu;
16202 		boolean_t need_ire_walk_v4 = B_FALSE;
16203 		boolean_t need_ire_walk_v6 = B_FALSE;
16204 
16205 		switch (notify->dl_notification) {
16206 		case DL_NOTE_PHYS_ADDR:
16207 			err = ill_set_phys_addr(ill, mp);
16208 			break;
16209 
16210 		case DL_NOTE_REPLUMB:
16211 			/*
16212 			 * Directly return after calling ill_replumb().
16213 			 * Note that we should not free mp as it is reused
16214 			 * in the ill_replumb() function.
16215 			 */
16216 			err = ill_replumb(ill, mp);
16217 			return;
16218 
16219 		case DL_NOTE_FASTPATH_FLUSH:
16220 			ill_fastpath_flush(ill);
16221 			break;
16222 
16223 		case DL_NOTE_SDU_SIZE:
16224 			/*
16225 			 * Change the MTU size of the interface, of all
16226 			 * attached ipif's, and of all relevant ire's.  The
16227 			 * new value's a uint32_t at notify->dl_data.
16228 			 * Mtu change Vs. new ire creation - protocol below.
16229 			 *
16230 			 * a Mark the ipif as IPIF_CHANGING.
16231 			 * b Set the new mtu in the ipif.
16232 			 * c Change the ire_max_frag on all affected ires
16233 			 * d Unmark the IPIF_CHANGING
16234 			 *
16235 			 * To see how the protocol works, assume an interface
16236 			 * route is also being added simultaneously by
16237 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16238 			 * the ire. If the ire is created before step a,
16239 			 * it will be cleaned up by step c. If the ire is
16240 			 * created after step d, it will see the new value of
16241 			 * ipif_mtu. Any attempt to create the ire between
16242 			 * steps a to d will fail because of the IPIF_CHANGING
16243 			 * flag. Note that ire_create() is passed a pointer to
16244 			 * the ipif_mtu, and not the value. During ire_add
16245 			 * under the bucket lock, the ire_max_frag of the
16246 			 * new ire being created is set from the ipif/ire from
16247 			 * which it is being derived.
16248 			 */
16249 			mutex_enter(&ill->ill_lock);
16250 
16251 			orig_mtu = ill->ill_max_mtu;
16252 			ill->ill_max_frag = (uint_t)notify->dl_data;
16253 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16254 
16255 			/*
16256 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16257 			 * clamp ill_max_mtu at it.
16258 			 */
16259 			if (ill->ill_user_mtu != 0 &&
16260 			    ill->ill_user_mtu < ill->ill_max_mtu)
16261 				ill->ill_max_mtu = ill->ill_user_mtu;
16262 
16263 			/*
16264 			 * If the MTU is unchanged, we're done.
16265 			 */
16266 			if (orig_mtu == ill->ill_max_mtu) {
16267 				mutex_exit(&ill->ill_lock);
16268 				break;
16269 			}
16270 
16271 			if (ill->ill_isv6) {
16272 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16273 					ill->ill_max_mtu = IPV6_MIN_MTU;
16274 			} else {
16275 				if (ill->ill_max_mtu < IP_MIN_MTU)
16276 					ill->ill_max_mtu = IP_MIN_MTU;
16277 			}
16278 			for (ipif = ill->ill_ipif; ipif != NULL;
16279 			    ipif = ipif->ipif_next) {
16280 				/*
16281 				 * Don't override the mtu if the user
16282 				 * has explicitly set it.
16283 				 */
16284 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16285 					continue;
16286 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16287 				if (ipif->ipif_isv6)
16288 					ire = ipif_to_ire_v6(ipif);
16289 				else
16290 					ire = ipif_to_ire(ipif);
16291 				if (ire != NULL) {
16292 					ire->ire_max_frag = ipif->ipif_mtu;
16293 					ire_refrele(ire);
16294 				}
16295 				if (ipif->ipif_flags & IPIF_UP) {
16296 					if (ill->ill_isv6)
16297 						need_ire_walk_v6 = B_TRUE;
16298 					else
16299 						need_ire_walk_v4 = B_TRUE;
16300 				}
16301 			}
16302 			mutex_exit(&ill->ill_lock);
16303 			if (need_ire_walk_v4)
16304 				ire_walk_v4(ill_mtu_change, (char *)ill,
16305 				    ALL_ZONES, ipst);
16306 			if (need_ire_walk_v6)
16307 				ire_walk_v6(ill_mtu_change, (char *)ill,
16308 				    ALL_ZONES, ipst);
16309 
16310 			/*
16311 			 * Refresh IPMP meta-interface MTU if necessary.
16312 			 */
16313 			if (IS_UNDER_IPMP(ill))
16314 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16315 			break;
16316 
16317 		case DL_NOTE_LINK_UP:
16318 		case DL_NOTE_LINK_DOWN: {
16319 			/*
16320 			 * We are writer. ill / phyint / ipsq assocs stable.
16321 			 * The RUNNING flag reflects the state of the link.
16322 			 */
16323 			phyint_t *phyint = ill->ill_phyint;
16324 			uint64_t new_phyint_flags;
16325 			boolean_t changed = B_FALSE;
16326 			boolean_t went_up;
16327 
16328 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16329 			mutex_enter(&phyint->phyint_lock);
16330 
16331 			new_phyint_flags = went_up ?
16332 			    phyint->phyint_flags | PHYI_RUNNING :
16333 			    phyint->phyint_flags & ~PHYI_RUNNING;
16334 
16335 			if (IS_IPMP(ill)) {
16336 				new_phyint_flags = went_up ?
16337 				    new_phyint_flags & ~PHYI_FAILED :
16338 				    new_phyint_flags | PHYI_FAILED;
16339 			}
16340 
16341 			if (new_phyint_flags != phyint->phyint_flags) {
16342 				phyint->phyint_flags = new_phyint_flags;
16343 				changed = B_TRUE;
16344 			}
16345 			mutex_exit(&phyint->phyint_lock);
16346 			/*
16347 			 * ill_restart_dad handles the DAD restart and routing
16348 			 * socket notification logic.
16349 			 */
16350 			if (changed) {
16351 				ill_restart_dad(phyint->phyint_illv4, went_up);
16352 				ill_restart_dad(phyint->phyint_illv6, went_up);
16353 			}
16354 			break;
16355 		}
16356 		case DL_NOTE_PROMISC_ON_PHYS: {
16357 			phyint_t *phyint = ill->ill_phyint;
16358 
16359 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16360 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16361 			mutex_enter(&phyint->phyint_lock);
16362 			phyint->phyint_flags |= PHYI_PROMISC;
16363 			mutex_exit(&phyint->phyint_lock);
16364 			break;
16365 		}
16366 		case DL_NOTE_PROMISC_OFF_PHYS: {
16367 			phyint_t *phyint = ill->ill_phyint;
16368 
16369 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16370 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16371 			mutex_enter(&phyint->phyint_lock);
16372 			phyint->phyint_flags &= ~PHYI_PROMISC;
16373 			mutex_exit(&phyint->phyint_lock);
16374 			break;
16375 		}
16376 		case DL_NOTE_CAPAB_RENEG:
16377 			/*
16378 			 * Something changed on the driver side.
16379 			 * It wants us to renegotiate the capabilities
16380 			 * on this ill. One possible cause is the aggregation
16381 			 * interface under us where a port got added or
16382 			 * went away.
16383 			 *
16384 			 * If the capability negotiation is already done
16385 			 * or is in progress, reset the capabilities and
16386 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16387 			 * so that when the ack comes back, we can start
16388 			 * the renegotiation process.
16389 			 *
16390 			 * Note that if ill_capab_reneg is already B_TRUE
16391 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16392 			 * the capability resetting request has been sent
16393 			 * and the renegotiation has not been started yet;
16394 			 * nothing needs to be done in this case.
16395 			 */
16396 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16397 			ill_capability_reset(ill, B_TRUE);
16398 			ipsq_current_finish(ipsq);
16399 			break;
16400 		default:
16401 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16402 			    "type 0x%x for DL_NOTIFY_IND\n",
16403 			    notify->dl_notification));
16404 			break;
16405 		}
16406 
16407 		/*
16408 		 * As this is an asynchronous operation, we
16409 		 * should not call ill_dlpi_done
16410 		 */
16411 		break;
16412 	}
16413 	case DL_NOTIFY_ACK: {
16414 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16415 
16416 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16417 			ill->ill_note_link = 1;
16418 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16419 		break;
16420 	}
16421 	case DL_PHYS_ADDR_ACK: {
16422 		/*
16423 		 * As part of plumbing the interface via SIOCSLIFNAME,
16424 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16425 		 * whose answers we receive here.  As each answer is received,
16426 		 * we call ill_dlpi_done() to dispatch the next request as
16427 		 * we're processing the current one.  Once all answers have
16428 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16429 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16430 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16431 		 * available, but we know the ioctl is pending on ill_wq.)
16432 		 */
16433 		uint_t	paddrlen, paddroff;
16434 
16435 		paddrreq = ill->ill_phys_addr_pend;
16436 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16437 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16438 
16439 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16440 		if (paddrreq == DL_IPV6_TOKEN) {
16441 			/*
16442 			 * bcopy to low-order bits of ill_token
16443 			 *
16444 			 * XXX Temporary hack - currently, all known tokens
16445 			 * are 64 bits, so I'll cheat for the moment.
16446 			 */
16447 			bcopy(mp->b_rptr + paddroff,
16448 			    &ill->ill_token.s6_addr32[2], paddrlen);
16449 			ill->ill_token_length = paddrlen;
16450 			break;
16451 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16452 			ASSERT(ill->ill_nd_lla_mp == NULL);
16453 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16454 			mp = NULL;
16455 			break;
16456 		}
16457 
16458 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16459 		ASSERT(ill->ill_phys_addr_mp == NULL);
16460 		if (!ill->ill_ifname_pending)
16461 			break;
16462 		ill->ill_ifname_pending = 0;
16463 		if (!ioctl_aborted)
16464 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16465 		if (mp1 != NULL) {
16466 			ASSERT(connp == NULL);
16467 			q = ill->ill_wq;
16468 		}
16469 		/*
16470 		 * If any error acks received during the plumbing sequence,
16471 		 * ill_ifname_pending_err will be set. Break out and send up
16472 		 * the error to the pending ioctl.
16473 		 */
16474 		if (ill->ill_ifname_pending_err != 0) {
16475 			err = ill->ill_ifname_pending_err;
16476 			ill->ill_ifname_pending_err = 0;
16477 			break;
16478 		}
16479 
16480 		ill->ill_phys_addr_mp = mp;
16481 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16482 		mp = NULL;
16483 
16484 		/*
16485 		 * If paddrlen is zero, the DLPI provider doesn't support
16486 		 * physical addresses.  The other two tests were historical
16487 		 * workarounds for bugs in our former PPP implementation, but
16488 		 * now other things have grown dependencies on them -- e.g.,
16489 		 * the tun module specifies a dl_addr_length of zero in its
16490 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16491 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16492 		 * but only after careful testing ensures that all dependent
16493 		 * broken DLPI providers have been fixed.
16494 		 */
16495 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16496 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16497 			ill->ill_phys_addr = NULL;
16498 		} else if (paddrlen != ill->ill_phys_addr_length) {
16499 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16500 			    paddrlen, ill->ill_phys_addr_length));
16501 			err = EINVAL;
16502 			break;
16503 		}
16504 
16505 		if (ill->ill_nd_lla_mp == NULL) {
16506 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16507 				err = ENOMEM;
16508 				break;
16509 			}
16510 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16511 		}
16512 
16513 		/*
16514 		 * Set the interface token.  If the zeroth interface address
16515 		 * is unspecified, then set it to the link local address.
16516 		 */
16517 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16518 			(void) ill_setdefaulttoken(ill);
16519 
16520 		ASSERT(ill->ill_ipif->ipif_id == 0);
16521 		if (ipif != NULL &&
16522 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16523 			(void) ipif_setlinklocal(ipif);
16524 		}
16525 		break;
16526 	}
16527 	case DL_OK_ACK:
16528 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16529 		    dl_primstr((int)dloa->dl_correct_primitive),
16530 		    dloa->dl_correct_primitive));
16531 		switch (dloa->dl_correct_primitive) {
16532 		case DL_ENABMULTI_REQ:
16533 		case DL_DISABMULTI_REQ:
16534 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16535 			break;
16536 		case DL_PROMISCON_REQ:
16537 		case DL_PROMISCOFF_REQ:
16538 		case DL_UNBIND_REQ:
16539 		case DL_ATTACH_REQ:
16540 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16541 			break;
16542 		}
16543 		break;
16544 	default:
16545 		break;
16546 	}
16547 
16548 	freemsg(mp);
16549 	if (mp1 == NULL)
16550 		return;
16551 
16552 	/*
16553 	 * The operation must complete without EINPROGRESS since
16554 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16555 	 * the operation will be stuck forever inside the IPSQ.
16556 	 */
16557 	ASSERT(err != EINPROGRESS);
16558 
16559 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16560 	case 0:
16561 		ipsq_current_finish(ipsq);
16562 		break;
16563 
16564 	case SIOCSLIFNAME:
16565 	case IF_UNITSEL: {
16566 		ill_t *ill_other = ILL_OTHER(ill);
16567 
16568 		/*
16569 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16570 		 * ill has a peer which is in an IPMP group, then place ill
16571 		 * into the same group.  One catch: although ifconfig plumbs
16572 		 * the appropriate IPMP meta-interface prior to plumbing this
16573 		 * ill, it is possible for multiple ifconfig applications to
16574 		 * race (or for another application to adjust plumbing), in
16575 		 * which case the IPMP meta-interface we need will be missing.
16576 		 * If so, kick the phyint out of the group.
16577 		 */
16578 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16579 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16580 			ipmp_illgrp_t	*illg;
16581 
16582 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16583 			if (illg == NULL)
16584 				ipmp_phyint_leave_grp(ill->ill_phyint);
16585 			else
16586 				ipmp_ill_join_illgrp(ill, illg);
16587 		}
16588 
16589 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16590 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16591 		else
16592 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16593 		break;
16594 	}
16595 	case SIOCLIFADDIF:
16596 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16597 		break;
16598 
16599 	default:
16600 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16601 		break;
16602 	}
16603 }
16604 
16605 /*
16606  * ip_rput_other is called by ip_rput to handle messages modifying the global
16607  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16608  */
16609 /* ARGSUSED */
16610 void
16611 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16612 {
16613 	ill_t		*ill = q->q_ptr;
16614 	struct iocblk	*iocp;
16615 	mblk_t		*mp1;
16616 	conn_t		*connp = NULL;
16617 
16618 	ip1dbg(("ip_rput_other "));
16619 	if (ipsq != NULL) {
16620 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16621 		ASSERT(ipsq->ipsq_xop ==
16622 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16623 	}
16624 
16625 	switch (mp->b_datap->db_type) {
16626 	case M_ERROR:
16627 	case M_HANGUP:
16628 		/*
16629 		 * The device has a problem.  We force the ILL down.  It can
16630 		 * be brought up again manually using SIOCSIFFLAGS (via
16631 		 * ifconfig or equivalent).
16632 		 */
16633 		ASSERT(ipsq != NULL);
16634 		if (mp->b_rptr < mp->b_wptr)
16635 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16636 		if (ill->ill_error == 0)
16637 			ill->ill_error = ENXIO;
16638 		if (!ill_down_start(q, mp))
16639 			return;
16640 		ipif_all_down_tail(ipsq, q, mp, NULL);
16641 		break;
16642 	case M_IOCACK:
16643 		iocp = (struct iocblk *)mp->b_rptr;
16644 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16645 		switch (iocp->ioc_cmd) {
16646 		case SIOCSTUNPARAM:
16647 		case OSIOCSTUNPARAM:
16648 			ASSERT(ipsq != NULL);
16649 			/*
16650 			 * Finish socket ioctl passed through to tun.
16651 			 * We should have an IOCTL waiting on this.
16652 			 */
16653 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16654 			if (ill->ill_isv6) {
16655 				struct iftun_req *ta;
16656 
16657 				/*
16658 				 * if a source or destination is
16659 				 * being set, try and set the link
16660 				 * local address for the tunnel
16661 				 */
16662 				ta = (struct iftun_req *)mp->b_cont->
16663 				    b_cont->b_rptr;
16664 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16665 					ipif_set_tun_llink(ill, ta);
16666 				}
16667 
16668 			}
16669 			if (mp1 != NULL) {
16670 				/*
16671 				 * Now copy back the b_next/b_prev used by
16672 				 * mi code for the mi_copy* functions.
16673 				 * See ip_sioctl_tunparam() for the reason.
16674 				 * Also protect against missing b_cont.
16675 				 */
16676 				if (mp->b_cont != NULL) {
16677 					mp->b_cont->b_next =
16678 					    mp1->b_cont->b_next;
16679 					mp->b_cont->b_prev =
16680 					    mp1->b_cont->b_prev;
16681 				}
16682 				inet_freemsg(mp1);
16683 				ASSERT(connp != NULL);
16684 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16685 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16686 			} else {
16687 				ASSERT(connp == NULL);
16688 				putnext(q, mp);
16689 			}
16690 			break;
16691 		case SIOCGTUNPARAM:
16692 		case OSIOCGTUNPARAM:
16693 			/*
16694 			 * This is really M_IOCDATA from the tunnel driver.
16695 			 * convert back and complete the ioctl.
16696 			 * We should have an IOCTL waiting on this.
16697 			 */
16698 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16699 			if (mp1) {
16700 				/*
16701 				 * Now copy back the b_next/b_prev used by
16702 				 * mi code for the mi_copy* functions.
16703 				 * See ip_sioctl_tunparam() for the reason.
16704 				 * Also protect against missing b_cont.
16705 				 */
16706 				if (mp->b_cont != NULL) {
16707 					mp->b_cont->b_next =
16708 					    mp1->b_cont->b_next;
16709 					mp->b_cont->b_prev =
16710 					    mp1->b_cont->b_prev;
16711 				}
16712 				inet_freemsg(mp1);
16713 				if (iocp->ioc_error == 0)
16714 					mp->b_datap->db_type = M_IOCDATA;
16715 				ASSERT(connp != NULL);
16716 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16717 				    iocp->ioc_error, COPYOUT, NULL);
16718 			} else {
16719 				ASSERT(connp == NULL);
16720 				putnext(q, mp);
16721 			}
16722 			break;
16723 		default:
16724 			break;
16725 		}
16726 		break;
16727 	case M_IOCNAK:
16728 		iocp = (struct iocblk *)mp->b_rptr;
16729 
16730 		switch (iocp->ioc_cmd) {
16731 			int mode;
16732 
16733 		case DL_IOC_HDR_INFO:
16734 			/*
16735 			 * If this was the first attempt, turn off the
16736 			 * fastpath probing.
16737 			 */
16738 			mutex_enter(&ill->ill_lock);
16739 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16740 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16741 				mutex_exit(&ill->ill_lock);
16742 				ill_fastpath_nack(ill);
16743 				ip1dbg(("ip_rput: DLPI fastpath off on "
16744 				    "interface %s\n",
16745 				    ill->ill_name));
16746 			} else {
16747 				mutex_exit(&ill->ill_lock);
16748 			}
16749 			freemsg(mp);
16750 			break;
16751 			case SIOCSTUNPARAM:
16752 		case OSIOCSTUNPARAM:
16753 			ASSERT(ipsq != NULL);
16754 			/*
16755 			 * Finish socket ioctl passed through to tun
16756 			 * We should have an IOCTL waiting on this.
16757 			 */
16758 			/* FALLTHRU */
16759 		case SIOCGTUNPARAM:
16760 		case OSIOCGTUNPARAM:
16761 			/*
16762 			 * This is really M_IOCDATA from the tunnel driver.
16763 			 * convert back and complete the ioctl.
16764 			 * We should have an IOCTL waiting on this.
16765 			 */
16766 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16767 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16768 				mp1 = ill_pending_mp_get(ill, &connp,
16769 				    iocp->ioc_id);
16770 				mode = COPYOUT;
16771 				ipsq = NULL;
16772 			} else {
16773 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16774 				mode = NO_COPYOUT;
16775 			}
16776 			if (mp1 != NULL) {
16777 				/*
16778 				 * Now copy back the b_next/b_prev used by
16779 				 * mi code for the mi_copy* functions.
16780 				 * See ip_sioctl_tunparam() for the reason.
16781 				 * Also protect against missing b_cont.
16782 				 */
16783 				if (mp->b_cont != NULL) {
16784 					mp->b_cont->b_next =
16785 					    mp1->b_cont->b_next;
16786 					mp->b_cont->b_prev =
16787 					    mp1->b_cont->b_prev;
16788 				}
16789 				inet_freemsg(mp1);
16790 				if (iocp->ioc_error == 0)
16791 					iocp->ioc_error = EINVAL;
16792 				ASSERT(connp != NULL);
16793 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16794 				    iocp->ioc_error, mode, ipsq);
16795 			} else {
16796 				ASSERT(connp == NULL);
16797 				putnext(q, mp);
16798 			}
16799 			break;
16800 		default:
16801 			break;
16802 		}
16803 	default:
16804 		break;
16805 	}
16806 }
16807 
16808 /*
16809  * NOTE : This function does not ire_refrele the ire argument passed in.
16810  *
16811  * IPQoS notes
16812  * IP policy is invoked twice for a forwarded packet, once on the read side
16813  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16814  * enabled. An additional parameter, in_ill, has been added for this purpose.
16815  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16816  * because ip_mroute drops this information.
16817  *
16818  */
16819 void
16820 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16821 {
16822 	uint32_t	old_pkt_len;
16823 	uint32_t	pkt_len;
16824 	queue_t	*q;
16825 	uint32_t	sum;
16826 #define	rptr	((uchar_t *)ipha)
16827 	uint32_t	max_frag;
16828 	uint32_t	ill_index;
16829 	ill_t		*out_ill;
16830 	mib2_ipIfStatsEntry_t *mibptr;
16831 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16832 
16833 	/* Get the ill_index of the incoming ILL */
16834 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16835 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16836 
16837 	/* Initiate Read side IPPF processing */
16838 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16839 		ip_process(IPP_FWD_IN, &mp, ill_index);
16840 		if (mp == NULL) {
16841 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16842 			    "during IPPF processing\n"));
16843 			return;
16844 		}
16845 	}
16846 
16847 	/* Adjust the checksum to reflect the ttl decrement. */
16848 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16849 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16850 
16851 	if (ipha->ipha_ttl-- <= 1) {
16852 		if (ip_csum_hdr(ipha)) {
16853 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16854 			goto drop_pkt;
16855 		}
16856 		/*
16857 		 * Note: ire_stq this will be NULL for multicast
16858 		 * datagrams using the long path through arp (the IRE
16859 		 * is not an IRE_CACHE). This should not cause
16860 		 * problems since we don't generate ICMP errors for
16861 		 * multicast packets.
16862 		 */
16863 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16864 		q = ire->ire_stq;
16865 		if (q != NULL) {
16866 			/* Sent by forwarding path, and router is global zone */
16867 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16868 			    GLOBAL_ZONEID, ipst);
16869 		} else
16870 			freemsg(mp);
16871 		return;
16872 	}
16873 
16874 	/*
16875 	 * Don't forward if the interface is down
16876 	 */
16877 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16878 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16879 		ip2dbg(("ip_rput_forward:interface is down\n"));
16880 		goto drop_pkt;
16881 	}
16882 
16883 	/* Get the ill_index of the outgoing ILL */
16884 	out_ill = ire_to_ill(ire);
16885 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16886 
16887 	DTRACE_PROBE4(ip4__forwarding__start,
16888 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16889 
16890 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16891 	    ipst->ips_ipv4firewall_forwarding,
16892 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16893 
16894 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16895 
16896 	if (mp == NULL)
16897 		return;
16898 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16899 
16900 	if (is_system_labeled()) {
16901 		mblk_t *mp1;
16902 
16903 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16904 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16905 			goto drop_pkt;
16906 		}
16907 		/* Size may have changed */
16908 		mp = mp1;
16909 		ipha = (ipha_t *)mp->b_rptr;
16910 		pkt_len = ntohs(ipha->ipha_length);
16911 	}
16912 
16913 	/* Check if there are options to update */
16914 	if (!IS_SIMPLE_IPH(ipha)) {
16915 		if (ip_csum_hdr(ipha)) {
16916 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16917 			goto drop_pkt;
16918 		}
16919 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16920 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16921 			return;
16922 		}
16923 
16924 		ipha->ipha_hdr_checksum = 0;
16925 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16926 	}
16927 	max_frag = ire->ire_max_frag;
16928 	if (pkt_len > max_frag) {
16929 		/*
16930 		 * It needs fragging on its way out.  We haven't
16931 		 * verified the header checksum yet.  Since we
16932 		 * are going to put a surely good checksum in the
16933 		 * outgoing header, we have to make sure that it
16934 		 * was good coming in.
16935 		 */
16936 		if (ip_csum_hdr(ipha)) {
16937 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16938 			goto drop_pkt;
16939 		}
16940 		/* Initiate Write side IPPF processing */
16941 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16942 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16943 			if (mp == NULL) {
16944 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16945 				    " during IPPF processing\n"));
16946 				return;
16947 			}
16948 		}
16949 		/*
16950 		 * Handle labeled packet resizing.
16951 		 *
16952 		 * If we have added a label, inform ip_wput_frag() of its
16953 		 * effect on the MTU for ICMP messages.
16954 		 */
16955 		if (pkt_len > old_pkt_len) {
16956 			uint32_t secopt_size;
16957 
16958 			secopt_size = pkt_len - old_pkt_len;
16959 			if (secopt_size < max_frag)
16960 				max_frag -= secopt_size;
16961 		}
16962 
16963 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16964 		    GLOBAL_ZONEID, ipst, NULL);
16965 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16966 		return;
16967 	}
16968 
16969 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16970 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16971 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16972 	    ipst->ips_ipv4firewall_physical_out,
16973 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16974 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16975 	if (mp == NULL)
16976 		return;
16977 
16978 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16979 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16980 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16981 	/* ip_xmit_v4 always consumes the packet */
16982 	return;
16983 
16984 drop_pkt:;
16985 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16986 	freemsg(mp);
16987 #undef	rptr
16988 }
16989 
16990 void
16991 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16992 {
16993 	ire_t	*ire;
16994 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16995 
16996 	ASSERT(!ipif->ipif_isv6);
16997 	/*
16998 	 * Find an IRE which matches the destination and the outgoing
16999 	 * queue in the cache table. All we need is an IRE_CACHE which
17000 	 * is pointing at ipif->ipif_ill.
17001 	 */
17002 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
17003 		dst = ipif->ipif_pp_dst_addr;
17004 
17005 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
17006 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
17007 	if (ire == NULL) {
17008 		/*
17009 		 * Mark this packet to make it be delivered to
17010 		 * ip_rput_forward after the new ire has been
17011 		 * created.
17012 		 */
17013 		mp->b_prev = NULL;
17014 		mp->b_next = mp;
17015 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
17016 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
17017 	} else {
17018 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
17019 		IRE_REFRELE(ire);
17020 	}
17021 }
17022 
17023 /* Update any source route, record route or timestamp options */
17024 static int
17025 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
17026 {
17027 	ipoptp_t	opts;
17028 	uchar_t		*opt;
17029 	uint8_t		optval;
17030 	uint8_t		optlen;
17031 	ipaddr_t	dst;
17032 	uint32_t	ts;
17033 	ire_t		*dst_ire = NULL;
17034 	ire_t		*tmp_ire = NULL;
17035 	timestruc_t	now;
17036 
17037 	ip2dbg(("ip_rput_forward_options\n"));
17038 	dst = ipha->ipha_dst;
17039 	for (optval = ipoptp_first(&opts, ipha);
17040 	    optval != IPOPT_EOL;
17041 	    optval = ipoptp_next(&opts)) {
17042 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17043 		opt = opts.ipoptp_cur;
17044 		optlen = opts.ipoptp_len;
17045 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
17046 		    optval, opts.ipoptp_len));
17047 		switch (optval) {
17048 			uint32_t off;
17049 		case IPOPT_SSRR:
17050 		case IPOPT_LSRR:
17051 			/* Check if adminstratively disabled */
17052 			if (!ipst->ips_ip_forward_src_routed) {
17053 				if (ire->ire_stq != NULL) {
17054 					/*
17055 					 * Sent by forwarding path, and router
17056 					 * is global zone
17057 					 */
17058 					icmp_unreachable(ire->ire_stq, mp,
17059 					    ICMP_SOURCE_ROUTE_FAILED,
17060 					    GLOBAL_ZONEID, ipst);
17061 				} else {
17062 					ip0dbg(("ip_rput_forward_options: "
17063 					    "unable to send unreach\n"));
17064 					freemsg(mp);
17065 				}
17066 				return (-1);
17067 			}
17068 
17069 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17070 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17071 			if (dst_ire == NULL) {
17072 				/*
17073 				 * Must be partial since ip_rput_options
17074 				 * checked for strict.
17075 				 */
17076 				break;
17077 			}
17078 			off = opt[IPOPT_OFFSET];
17079 			off--;
17080 		redo_srr:
17081 			if (optlen < IP_ADDR_LEN ||
17082 			    off > optlen - IP_ADDR_LEN) {
17083 				/* End of source route */
17084 				ip1dbg((
17085 				    "ip_rput_forward_options: end of SR\n"));
17086 				ire_refrele(dst_ire);
17087 				break;
17088 			}
17089 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17090 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17091 			    IP_ADDR_LEN);
17092 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17093 			    ntohl(dst)));
17094 
17095 			/*
17096 			 * Check if our address is present more than
17097 			 * once as consecutive hops in source route.
17098 			 */
17099 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17100 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17101 			if (tmp_ire != NULL) {
17102 				ire_refrele(tmp_ire);
17103 				off += IP_ADDR_LEN;
17104 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17105 				goto redo_srr;
17106 			}
17107 			ipha->ipha_dst = dst;
17108 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17109 			ire_refrele(dst_ire);
17110 			break;
17111 		case IPOPT_RR:
17112 			off = opt[IPOPT_OFFSET];
17113 			off--;
17114 			if (optlen < IP_ADDR_LEN ||
17115 			    off > optlen - IP_ADDR_LEN) {
17116 				/* No more room - ignore */
17117 				ip1dbg((
17118 				    "ip_rput_forward_options: end of RR\n"));
17119 				break;
17120 			}
17121 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17122 			    IP_ADDR_LEN);
17123 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17124 			break;
17125 		case IPOPT_TS:
17126 			/* Insert timestamp if there is room */
17127 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17128 			case IPOPT_TS_TSONLY:
17129 				off = IPOPT_TS_TIMELEN;
17130 				break;
17131 			case IPOPT_TS_PRESPEC:
17132 			case IPOPT_TS_PRESPEC_RFC791:
17133 				/* Verify that the address matched */
17134 				off = opt[IPOPT_OFFSET] - 1;
17135 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17136 				dst_ire = ire_ctable_lookup(dst, 0,
17137 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17138 				    MATCH_IRE_TYPE, ipst);
17139 				if (dst_ire == NULL) {
17140 					/* Not for us */
17141 					break;
17142 				}
17143 				ire_refrele(dst_ire);
17144 				/* FALLTHRU */
17145 			case IPOPT_TS_TSANDADDR:
17146 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17147 				break;
17148 			default:
17149 				/*
17150 				 * ip_*put_options should have already
17151 				 * dropped this packet.
17152 				 */
17153 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17154 				    "unknown IT - bug in ip_rput_options?\n");
17155 				return (0);	/* Keep "lint" happy */
17156 			}
17157 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17158 				/* Increase overflow counter */
17159 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17160 				opt[IPOPT_POS_OV_FLG] =
17161 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17162 				    (off << 4));
17163 				break;
17164 			}
17165 			off = opt[IPOPT_OFFSET] - 1;
17166 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17167 			case IPOPT_TS_PRESPEC:
17168 			case IPOPT_TS_PRESPEC_RFC791:
17169 			case IPOPT_TS_TSANDADDR:
17170 				bcopy(&ire->ire_src_addr,
17171 				    (char *)opt + off, IP_ADDR_LEN);
17172 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17173 				/* FALLTHRU */
17174 			case IPOPT_TS_TSONLY:
17175 				off = opt[IPOPT_OFFSET] - 1;
17176 				/* Compute # of milliseconds since midnight */
17177 				gethrestime(&now);
17178 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17179 				    now.tv_nsec / (NANOSEC / MILLISEC);
17180 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17181 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17182 				break;
17183 			}
17184 			break;
17185 		}
17186 	}
17187 	return (0);
17188 }
17189 
17190 /*
17191  * This is called after processing at least one of AH/ESP headers.
17192  *
17193  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17194  * the actual, physical interface on which the packet was received,
17195  * but, when ip_strict_dst_multihoming is set to 1, could be the
17196  * interface which had the ipha_dst configured when the packet went
17197  * through ip_rput. The ill_index corresponding to the recv_ill
17198  * is saved in ipsec_in_rill_index
17199  *
17200  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17201  * cannot assume "ire" points to valid data for any IPv6 cases.
17202  */
17203 void
17204 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17205 {
17206 	mblk_t *mp;
17207 	ipaddr_t dst;
17208 	in6_addr_t *v6dstp;
17209 	ipha_t *ipha;
17210 	ip6_t *ip6h;
17211 	ipsec_in_t *ii;
17212 	boolean_t ill_need_rele = B_FALSE;
17213 	boolean_t rill_need_rele = B_FALSE;
17214 	boolean_t ire_need_rele = B_FALSE;
17215 	netstack_t	*ns;
17216 	ip_stack_t	*ipst;
17217 
17218 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17219 	ASSERT(ii->ipsec_in_ill_index != 0);
17220 	ns = ii->ipsec_in_ns;
17221 	ASSERT(ii->ipsec_in_ns != NULL);
17222 	ipst = ns->netstack_ip;
17223 
17224 	mp = ipsec_mp->b_cont;
17225 	ASSERT(mp != NULL);
17226 
17227 	if (ill == NULL) {
17228 		ASSERT(recv_ill == NULL);
17229 		/*
17230 		 * We need to get the original queue on which ip_rput_local
17231 		 * or ip_rput_data_v6 was called.
17232 		 */
17233 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17234 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17235 		ill_need_rele = B_TRUE;
17236 
17237 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17238 			recv_ill = ill_lookup_on_ifindex(
17239 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17240 			    NULL, NULL, NULL, NULL, ipst);
17241 			rill_need_rele = B_TRUE;
17242 		} else {
17243 			recv_ill = ill;
17244 		}
17245 
17246 		if ((ill == NULL) || (recv_ill == NULL)) {
17247 			ip0dbg(("ip_fanout_proto_again: interface "
17248 			    "disappeared\n"));
17249 			if (ill != NULL)
17250 				ill_refrele(ill);
17251 			if (recv_ill != NULL)
17252 				ill_refrele(recv_ill);
17253 			freemsg(ipsec_mp);
17254 			return;
17255 		}
17256 	}
17257 
17258 	ASSERT(ill != NULL && recv_ill != NULL);
17259 
17260 	if (mp->b_datap->db_type == M_CTL) {
17261 		/*
17262 		 * AH/ESP is returning the ICMP message after
17263 		 * removing their headers. Fanout again till
17264 		 * it gets to the right protocol.
17265 		 */
17266 		if (ii->ipsec_in_v4) {
17267 			icmph_t *icmph;
17268 			int iph_hdr_length;
17269 			int hdr_length;
17270 
17271 			ipha = (ipha_t *)mp->b_rptr;
17272 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17273 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17274 			ipha = (ipha_t *)&icmph[1];
17275 			hdr_length = IPH_HDR_LENGTH(ipha);
17276 			/*
17277 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17278 			 * Reset the type to M_DATA.
17279 			 */
17280 			mp->b_datap->db_type = M_DATA;
17281 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17282 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17283 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17284 		} else {
17285 			icmp6_t *icmp6;
17286 			int hdr_length;
17287 
17288 			ip6h = (ip6_t *)mp->b_rptr;
17289 			/* Don't call hdr_length_v6() unless you have to. */
17290 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17291 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17292 			else
17293 				hdr_length = IPV6_HDR_LEN;
17294 
17295 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17296 			/*
17297 			 * icmp_inbound_error_fanout_v6 may need to do
17298 			 * pullupmsg.  Reset the type to M_DATA.
17299 			 */
17300 			mp->b_datap->db_type = M_DATA;
17301 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17302 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17303 			    ii->ipsec_in_zoneid);
17304 		}
17305 		if (ill_need_rele)
17306 			ill_refrele(ill);
17307 		if (rill_need_rele)
17308 			ill_refrele(recv_ill);
17309 		return;
17310 	}
17311 
17312 	if (ii->ipsec_in_v4) {
17313 		ipha = (ipha_t *)mp->b_rptr;
17314 		dst = ipha->ipha_dst;
17315 		if (CLASSD(dst)) {
17316 			/*
17317 			 * Multicast has to be delivered to all streams.
17318 			 */
17319 			dst = INADDR_BROADCAST;
17320 		}
17321 
17322 		if (ire == NULL) {
17323 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17324 			    msg_getlabel(mp), ipst);
17325 			if (ire == NULL) {
17326 				if (ill_need_rele)
17327 					ill_refrele(ill);
17328 				if (rill_need_rele)
17329 					ill_refrele(recv_ill);
17330 				ip1dbg(("ip_fanout_proto_again: "
17331 				    "IRE not found"));
17332 				freemsg(ipsec_mp);
17333 				return;
17334 			}
17335 			ire_need_rele = B_TRUE;
17336 		}
17337 
17338 		switch (ipha->ipha_protocol) {
17339 		case IPPROTO_UDP:
17340 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17341 			    recv_ill);
17342 			if (ire_need_rele)
17343 				ire_refrele(ire);
17344 			break;
17345 		case IPPROTO_TCP:
17346 			if (!ire_need_rele)
17347 				IRE_REFHOLD(ire);
17348 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17349 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17350 			IRE_REFRELE(ire);
17351 			if (mp != NULL) {
17352 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17353 				    mp, 1, SQ_PROCESS,
17354 				    SQTAG_IP_PROTO_AGAIN);
17355 			}
17356 			break;
17357 		case IPPROTO_SCTP:
17358 			if (!ire_need_rele)
17359 				IRE_REFHOLD(ire);
17360 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17361 			    ipsec_mp, 0, ill->ill_rq, dst);
17362 			break;
17363 		default:
17364 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17365 			    recv_ill, 0);
17366 			if (ire_need_rele)
17367 				ire_refrele(ire);
17368 			break;
17369 		}
17370 	} else {
17371 		uint32_t rput_flags = 0;
17372 
17373 		ip6h = (ip6_t *)mp->b_rptr;
17374 		v6dstp = &ip6h->ip6_dst;
17375 		/*
17376 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17377 		 * address.
17378 		 *
17379 		 * Currently, we don't store that state in the IPSEC_IN
17380 		 * message, and we may need to.
17381 		 */
17382 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17383 		    IP6_IN_LLMCAST : 0);
17384 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17385 		    NULL, NULL);
17386 	}
17387 	if (ill_need_rele)
17388 		ill_refrele(ill);
17389 	if (rill_need_rele)
17390 		ill_refrele(recv_ill);
17391 }
17392 
17393 /*
17394  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17395  * returns 'true' if there are still fragments left on the queue, in
17396  * which case we restart the timer.
17397  */
17398 void
17399 ill_frag_timer(void *arg)
17400 {
17401 	ill_t	*ill = (ill_t *)arg;
17402 	boolean_t frag_pending;
17403 	ip_stack_t	*ipst = ill->ill_ipst;
17404 	time_t	timeout;
17405 
17406 	mutex_enter(&ill->ill_lock);
17407 	ASSERT(!ill->ill_fragtimer_executing);
17408 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17409 		ill->ill_frag_timer_id = 0;
17410 		mutex_exit(&ill->ill_lock);
17411 		return;
17412 	}
17413 	ill->ill_fragtimer_executing = 1;
17414 	mutex_exit(&ill->ill_lock);
17415 
17416 	if (ill->ill_isv6)
17417 		timeout = ipst->ips_ipv6_frag_timeout;
17418 	else
17419 		timeout = ipst->ips_ip_g_frag_timeout;
17420 
17421 	frag_pending = ill_frag_timeout(ill, timeout);
17422 
17423 	/*
17424 	 * Restart the timer, if we have fragments pending or if someone
17425 	 * wanted us to be scheduled again.
17426 	 */
17427 	mutex_enter(&ill->ill_lock);
17428 	ill->ill_fragtimer_executing = 0;
17429 	ill->ill_frag_timer_id = 0;
17430 	if (frag_pending || ill->ill_fragtimer_needrestart)
17431 		ill_frag_timer_start(ill);
17432 	mutex_exit(&ill->ill_lock);
17433 }
17434 
17435 void
17436 ill_frag_timer_start(ill_t *ill)
17437 {
17438 	ip_stack_t	*ipst = ill->ill_ipst;
17439 	clock_t	timeo_ms;
17440 
17441 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17442 
17443 	/* If the ill is closing or opening don't proceed */
17444 	if (ill->ill_state_flags & ILL_CONDEMNED)
17445 		return;
17446 
17447 	if (ill->ill_fragtimer_executing) {
17448 		/*
17449 		 * ill_frag_timer is currently executing. Just record the
17450 		 * the fact that we want the timer to be restarted.
17451 		 * ill_frag_timer will post a timeout before it returns,
17452 		 * ensuring it will be called again.
17453 		 */
17454 		ill->ill_fragtimer_needrestart = 1;
17455 		return;
17456 	}
17457 
17458 	if (ill->ill_frag_timer_id == 0) {
17459 		if (ill->ill_isv6)
17460 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17461 		else
17462 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17463 		/*
17464 		 * The timer is neither running nor is the timeout handler
17465 		 * executing. Post a timeout so that ill_frag_timer will be
17466 		 * called
17467 		 */
17468 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17469 		    MSEC_TO_TICK(timeo_ms >> 1));
17470 		ill->ill_fragtimer_needrestart = 0;
17471 	}
17472 }
17473 
17474 /*
17475  * This routine is needed for loopback when forwarding multicasts.
17476  *
17477  * IPQoS Notes:
17478  * IPPF processing is done in fanout routines.
17479  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17480  * processing for IPsec packets is done when it comes back in clear.
17481  * NOTE : The callers of this function need to do the ire_refrele for the
17482  *	  ire that is being passed in.
17483  */
17484 void
17485 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17486     ill_t *recv_ill, uint32_t esp_udp_ports)
17487 {
17488 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17489 	ill_t	*ill = (ill_t *)q->q_ptr;
17490 	uint32_t	sum;
17491 	uint32_t	u1;
17492 	uint32_t	u2;
17493 	int		hdr_length;
17494 	boolean_t	mctl_present;
17495 	mblk_t		*first_mp = mp;
17496 	mblk_t		*hada_mp = NULL;
17497 	ipha_t		*inner_ipha;
17498 	ip_stack_t	*ipst;
17499 
17500 	ASSERT(recv_ill != NULL);
17501 	ipst = recv_ill->ill_ipst;
17502 
17503 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17504 	    "ip_rput_locl_start: q %p", q);
17505 
17506 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17507 	ASSERT(ill != NULL);
17508 
17509 #define	rptr	((uchar_t *)ipha)
17510 #define	iphs	((uint16_t *)ipha)
17511 
17512 	/*
17513 	 * no UDP or TCP packet should come here anymore.
17514 	 */
17515 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17516 	    ipha->ipha_protocol != IPPROTO_UDP);
17517 
17518 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17519 	if (mctl_present &&
17520 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17521 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17522 
17523 		/*
17524 		 * It's an IPsec accelerated packet.
17525 		 * Keep a pointer to the data attributes around until
17526 		 * we allocate the ipsec_info_t.
17527 		 */
17528 		IPSECHW_DEBUG(IPSECHW_PKT,
17529 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17530 		hada_mp = first_mp;
17531 		hada_mp->b_cont = NULL;
17532 		/*
17533 		 * Since it is accelerated, it comes directly from
17534 		 * the ill and the data attributes is followed by
17535 		 * the packet data.
17536 		 */
17537 		ASSERT(mp->b_datap->db_type != M_CTL);
17538 		first_mp = mp;
17539 		mctl_present = B_FALSE;
17540 	}
17541 
17542 	/*
17543 	 * IF M_CTL is not present, then ipsec_in_is_secure
17544 	 * should return B_TRUE. There is a case where loopback
17545 	 * packets has an M_CTL in the front with all the
17546 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17547 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17548 	 * packets never comes here, it is safe to ASSERT the
17549 	 * following.
17550 	 */
17551 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17552 
17553 	/*
17554 	 * Also, we should never have an mctl_present if this is an
17555 	 * ESP-in-UDP packet.
17556 	 */
17557 	ASSERT(!mctl_present || !esp_in_udp_packet);
17558 
17559 	/* u1 is # words of IP options */
17560 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17561 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17562 
17563 	/*
17564 	 * Don't verify header checksum if we just removed UDP header or
17565 	 * packet is coming back from AH/ESP.
17566 	 */
17567 	if (!esp_in_udp_packet && !mctl_present) {
17568 		if (u1) {
17569 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17570 				if (hada_mp != NULL)
17571 					freemsg(hada_mp);
17572 				return;
17573 			}
17574 		} else {
17575 			/* Check the IP header checksum.  */
17576 #define	uph	((uint16_t *)ipha)
17577 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17578 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17579 #undef  uph
17580 			/* finish doing IP checksum */
17581 			sum = (sum & 0xFFFF) + (sum >> 16);
17582 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17583 			if (sum && sum != 0xFFFF) {
17584 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17585 				goto drop_pkt;
17586 			}
17587 		}
17588 	}
17589 
17590 	/*
17591 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17592 	 * might be called more than once for secure packets, count only
17593 	 * the first time.
17594 	 */
17595 	if (!mctl_present) {
17596 		UPDATE_IB_PKT_COUNT(ire);
17597 		ire->ire_last_used_time = lbolt;
17598 	}
17599 
17600 	/* Check for fragmentation offset. */
17601 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17602 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17603 	if (u1) {
17604 		/*
17605 		 * We re-assemble fragments before we do the AH/ESP
17606 		 * processing. Thus, M_CTL should not be present
17607 		 * while we are re-assembling.
17608 		 */
17609 		ASSERT(!mctl_present);
17610 		ASSERT(first_mp == mp);
17611 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17612 			return;
17613 
17614 		/*
17615 		 * Make sure that first_mp points back to mp as
17616 		 * the mp we came in with could have changed in
17617 		 * ip_rput_fragment().
17618 		 */
17619 		ipha = (ipha_t *)mp->b_rptr;
17620 		first_mp = mp;
17621 	}
17622 
17623 	/*
17624 	 * Clear hardware checksumming flag as it is currently only
17625 	 * used by TCP and UDP.
17626 	 */
17627 	DB_CKSUMFLAGS(mp) = 0;
17628 
17629 	/* Now we have a complete datagram, destined for this machine. */
17630 	u1 = IPH_HDR_LENGTH(ipha);
17631 	switch (ipha->ipha_protocol) {
17632 	case IPPROTO_ICMP: {
17633 		ire_t		*ire_zone;
17634 		ilm_t		*ilm;
17635 		mblk_t		*mp1;
17636 		zoneid_t	last_zoneid;
17637 		ilm_walker_t	ilw;
17638 
17639 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17640 			ASSERT(ire->ire_type == IRE_BROADCAST);
17641 
17642 			/*
17643 			 * In the multicast case, applications may have joined
17644 			 * the group from different zones, so we need to deliver
17645 			 * the packet to each of them. Loop through the
17646 			 * multicast memberships structures (ilm) on the receive
17647 			 * ill and send a copy of the packet up each matching
17648 			 * one. However, we don't do this for multicasts sent on
17649 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17650 			 * they must stay in the sender's zone.
17651 			 *
17652 			 * ilm_add_v6() ensures that ilms in the same zone are
17653 			 * contiguous in the ill_ilm list. We use this property
17654 			 * to avoid sending duplicates needed when two
17655 			 * applications in the same zone join the same group on
17656 			 * different logical interfaces: we ignore the ilm if
17657 			 * its zoneid is the same as the last matching one.
17658 			 * In addition, the sending of the packet for
17659 			 * ire_zoneid is delayed until all of the other ilms
17660 			 * have been exhausted.
17661 			 */
17662 			last_zoneid = -1;
17663 			ilm = ilm_walker_start(&ilw, recv_ill);
17664 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17665 				if (ipha->ipha_dst != ilm->ilm_addr ||
17666 				    ilm->ilm_zoneid == last_zoneid ||
17667 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17668 				    ilm->ilm_zoneid == ALL_ZONES ||
17669 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17670 					continue;
17671 				mp1 = ip_copymsg(first_mp);
17672 				if (mp1 == NULL)
17673 					continue;
17674 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17675 				    0, sum, mctl_present, B_TRUE,
17676 				    recv_ill, ilm->ilm_zoneid);
17677 				last_zoneid = ilm->ilm_zoneid;
17678 			}
17679 			ilm_walker_finish(&ilw);
17680 		} else if (ire->ire_type == IRE_BROADCAST) {
17681 			/*
17682 			 * In the broadcast case, there may be many zones
17683 			 * which need a copy of the packet delivered to them.
17684 			 * There is one IRE_BROADCAST per broadcast address
17685 			 * and per zone; we walk those using a helper function.
17686 			 * In addition, the sending of the packet for ire is
17687 			 * delayed until all of the other ires have been
17688 			 * processed.
17689 			 */
17690 			IRB_REFHOLD(ire->ire_bucket);
17691 			ire_zone = NULL;
17692 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17693 			    ire)) != NULL) {
17694 				mp1 = ip_copymsg(first_mp);
17695 				if (mp1 == NULL)
17696 					continue;
17697 
17698 				UPDATE_IB_PKT_COUNT(ire_zone);
17699 				ire_zone->ire_last_used_time = lbolt;
17700 				icmp_inbound(q, mp1, B_TRUE, ill,
17701 				    0, sum, mctl_present, B_TRUE,
17702 				    recv_ill, ire_zone->ire_zoneid);
17703 			}
17704 			IRB_REFRELE(ire->ire_bucket);
17705 		}
17706 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17707 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17708 		    ire->ire_zoneid);
17709 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17710 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17711 		return;
17712 	}
17713 	case IPPROTO_IGMP:
17714 		/*
17715 		 * If we are not willing to accept IGMP packets in clear,
17716 		 * then check with global policy.
17717 		 */
17718 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17719 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17720 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17721 			if (first_mp == NULL)
17722 				return;
17723 		}
17724 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17725 			freemsg(first_mp);
17726 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17727 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17728 			return;
17729 		}
17730 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17731 			/* Bad packet - discarded by igmp_input */
17732 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17733 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17734 			if (mctl_present)
17735 				freeb(first_mp);
17736 			return;
17737 		}
17738 		/*
17739 		 * igmp_input() may have returned the pulled up message.
17740 		 * So first_mp and ipha need to be reinitialized.
17741 		 */
17742 		ipha = (ipha_t *)mp->b_rptr;
17743 		if (mctl_present)
17744 			first_mp->b_cont = mp;
17745 		else
17746 			first_mp = mp;
17747 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17748 		    connf_head != NULL) {
17749 			/* No user-level listener for IGMP packets */
17750 			goto drop_pkt;
17751 		}
17752 		/* deliver to local raw users */
17753 		break;
17754 	case IPPROTO_PIM:
17755 		/*
17756 		 * If we are not willing to accept PIM packets in clear,
17757 		 * then check with global policy.
17758 		 */
17759 		if (ipst->ips_pim_accept_clear_messages == 0) {
17760 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17761 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17762 			if (first_mp == NULL)
17763 				return;
17764 		}
17765 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17766 			freemsg(first_mp);
17767 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17768 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17769 			return;
17770 		}
17771 		if (pim_input(q, mp, ill) != 0) {
17772 			/* Bad packet - discarded by pim_input */
17773 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17774 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17775 			if (mctl_present)
17776 				freeb(first_mp);
17777 			return;
17778 		}
17779 
17780 		/*
17781 		 * pim_input() may have pulled up the message so ipha needs to
17782 		 * be reinitialized.
17783 		 */
17784 		ipha = (ipha_t *)mp->b_rptr;
17785 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17786 		    connf_head != NULL) {
17787 			/* No user-level listener for PIM packets */
17788 			goto drop_pkt;
17789 		}
17790 		/* deliver to local raw users */
17791 		break;
17792 	case IPPROTO_ENCAP:
17793 		/*
17794 		 * Handle self-encapsulated packets (IP-in-IP where
17795 		 * the inner addresses == the outer addresses).
17796 		 */
17797 		hdr_length = IPH_HDR_LENGTH(ipha);
17798 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17799 		    mp->b_wptr) {
17800 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17801 			    sizeof (ipha_t) - mp->b_rptr)) {
17802 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17803 				freemsg(first_mp);
17804 				return;
17805 			}
17806 			ipha = (ipha_t *)mp->b_rptr;
17807 		}
17808 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17809 		/*
17810 		 * Check the sanity of the inner IP header.
17811 		 */
17812 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17813 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17814 			freemsg(first_mp);
17815 			return;
17816 		}
17817 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17818 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17819 			freemsg(first_mp);
17820 			return;
17821 		}
17822 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17823 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17824 			ipsec_in_t *ii;
17825 
17826 			/*
17827 			 * Self-encapsulated tunnel packet. Remove
17828 			 * the outer IP header and fanout again.
17829 			 * We also need to make sure that the inner
17830 			 * header is pulled up until options.
17831 			 */
17832 			mp->b_rptr = (uchar_t *)inner_ipha;
17833 			ipha = inner_ipha;
17834 			hdr_length = IPH_HDR_LENGTH(ipha);
17835 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17836 				if (!pullupmsg(mp, (uchar_t *)ipha +
17837 				    + hdr_length - mp->b_rptr)) {
17838 					freemsg(first_mp);
17839 					return;
17840 				}
17841 				ipha = (ipha_t *)mp->b_rptr;
17842 			}
17843 			if (hdr_length > sizeof (ipha_t)) {
17844 				/* We got options on the inner packet. */
17845 				ipaddr_t dst = ipha->ipha_dst;
17846 
17847 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17848 				    -1) {
17849 					/* Bad options! */
17850 					return;
17851 				}
17852 				if (dst != ipha->ipha_dst) {
17853 					/*
17854 					 * Someone put a source-route in
17855 					 * the inside header of a self-
17856 					 * encapsulated packet.  Drop it
17857 					 * with extreme prejudice and let
17858 					 * the sender know.
17859 					 */
17860 					icmp_unreachable(q, first_mp,
17861 					    ICMP_SOURCE_ROUTE_FAILED,
17862 					    recv_ill->ill_zoneid, ipst);
17863 					return;
17864 				}
17865 			}
17866 			if (!mctl_present) {
17867 				ASSERT(first_mp == mp);
17868 				/*
17869 				 * This means that somebody is sending
17870 				 * Self-encapsualted packets without AH/ESP.
17871 				 * If AH/ESP was present, we would have already
17872 				 * allocated the first_mp.
17873 				 *
17874 				 * Send this packet to find a tunnel endpoint.
17875 				 * if I can't find one, an ICMP
17876 				 * PROTOCOL_UNREACHABLE will get sent.
17877 				 */
17878 				goto fanout;
17879 			}
17880 			/*
17881 			 * We generally store the ill_index if we need to
17882 			 * do IPsec processing as we lose the ill queue when
17883 			 * we come back. But in this case, we never should
17884 			 * have to store the ill_index here as it should have
17885 			 * been stored previously when we processed the
17886 			 * AH/ESP header in this routine or for non-ipsec
17887 			 * cases, we still have the queue. But for some bad
17888 			 * packets from the wire, we can get to IPsec after
17889 			 * this and we better store the index for that case.
17890 			 */
17891 			ill = (ill_t *)q->q_ptr;
17892 			ii = (ipsec_in_t *)first_mp->b_rptr;
17893 			ii->ipsec_in_ill_index =
17894 			    ill->ill_phyint->phyint_ifindex;
17895 			ii->ipsec_in_rill_index =
17896 			    recv_ill->ill_phyint->phyint_ifindex;
17897 			if (ii->ipsec_in_decaps) {
17898 				/*
17899 				 * This packet is self-encapsulated multiple
17900 				 * times. We don't want to recurse infinitely.
17901 				 * To keep it simple, drop the packet.
17902 				 */
17903 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17904 				freemsg(first_mp);
17905 				return;
17906 			}
17907 			ii->ipsec_in_decaps = B_TRUE;
17908 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17909 			    ire);
17910 			return;
17911 		}
17912 		break;
17913 	case IPPROTO_AH:
17914 	case IPPROTO_ESP: {
17915 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17916 
17917 		/*
17918 		 * Fast path for AH/ESP. If this is the first time
17919 		 * we are sending a datagram to AH/ESP, allocate
17920 		 * a IPSEC_IN message and prepend it. Otherwise,
17921 		 * just fanout.
17922 		 */
17923 
17924 		int ipsec_rc;
17925 		ipsec_in_t *ii;
17926 		netstack_t *ns = ipst->ips_netstack;
17927 
17928 		IP_STAT(ipst, ipsec_proto_ahesp);
17929 		if (!mctl_present) {
17930 			ASSERT(first_mp == mp);
17931 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17932 			if (first_mp == NULL) {
17933 				ip1dbg(("ip_proto_input: IPSEC_IN "
17934 				    "allocation failure.\n"));
17935 				freemsg(hada_mp); /* okay ifnull */
17936 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17937 				freemsg(mp);
17938 				return;
17939 			}
17940 			/*
17941 			 * Store the ill_index so that when we come back
17942 			 * from IPsec we ride on the same queue.
17943 			 */
17944 			ill = (ill_t *)q->q_ptr;
17945 			ii = (ipsec_in_t *)first_mp->b_rptr;
17946 			ii->ipsec_in_ill_index =
17947 			    ill->ill_phyint->phyint_ifindex;
17948 			ii->ipsec_in_rill_index =
17949 			    recv_ill->ill_phyint->phyint_ifindex;
17950 			first_mp->b_cont = mp;
17951 			/*
17952 			 * Cache hardware acceleration info.
17953 			 */
17954 			if (hada_mp != NULL) {
17955 				IPSECHW_DEBUG(IPSECHW_PKT,
17956 				    ("ip_rput_local: caching data attr.\n"));
17957 				ii->ipsec_in_accelerated = B_TRUE;
17958 				ii->ipsec_in_da = hada_mp;
17959 				hada_mp = NULL;
17960 			}
17961 		} else {
17962 			ii = (ipsec_in_t *)first_mp->b_rptr;
17963 		}
17964 
17965 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17966 
17967 		if (!ipsec_loaded(ipss)) {
17968 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17969 			    ire->ire_zoneid, ipst);
17970 			return;
17971 		}
17972 
17973 		ns = ipst->ips_netstack;
17974 		/* select inbound SA and have IPsec process the pkt */
17975 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17976 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17977 			boolean_t esp_in_udp_sa;
17978 			if (esph == NULL)
17979 				return;
17980 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17981 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17982 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17983 			    IPSA_F_NATT) != 0);
17984 			/*
17985 			 * The following is a fancy, but quick, way of saying:
17986 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17987 			 *    OR
17988 			 * ESP SA and ESP-in-UDP packet --> drop
17989 			 */
17990 			if (esp_in_udp_sa != esp_in_udp_packet) {
17991 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17992 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17993 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17994 				    &ns->netstack_ipsec->ipsec_dropper);
17995 				return;
17996 			}
17997 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17998 			    first_mp, esph);
17999 		} else {
18000 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
18001 			if (ah == NULL)
18002 				return;
18003 			ASSERT(ii->ipsec_in_ah_sa != NULL);
18004 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
18005 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
18006 			    first_mp, ah);
18007 		}
18008 
18009 		switch (ipsec_rc) {
18010 		case IPSEC_STATUS_SUCCESS:
18011 			break;
18012 		case IPSEC_STATUS_FAILED:
18013 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
18014 			/* FALLTHRU */
18015 		case IPSEC_STATUS_PENDING:
18016 			return;
18017 		}
18018 		/* we're done with IPsec processing, send it up */
18019 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
18020 		return;
18021 	}
18022 	default:
18023 		break;
18024 	}
18025 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
18026 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
18027 		    ire->ire_zoneid));
18028 		goto drop_pkt;
18029 	}
18030 	/*
18031 	 * Handle protocols with which IP is less intimate.  There
18032 	 * can be more than one stream bound to a particular
18033 	 * protocol.  When this is the case, each one gets a copy
18034 	 * of any incoming packets.
18035 	 */
18036 fanout:
18037 	ip_fanout_proto(q, first_mp, ill, ipha,
18038 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
18039 	    B_TRUE, recv_ill, ire->ire_zoneid);
18040 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18041 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
18042 	return;
18043 
18044 drop_pkt:
18045 	freemsg(first_mp);
18046 	if (hada_mp != NULL)
18047 		freeb(hada_mp);
18048 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18049 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
18050 #undef	rptr
18051 #undef  iphs
18052 
18053 }
18054 
18055 /*
18056  * Update any source route, record route or timestamp options.
18057  * Check that we are at end of strict source route.
18058  * The options have already been checked for sanity in ip_rput_options().
18059  */
18060 static boolean_t
18061 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
18062     ip_stack_t *ipst)
18063 {
18064 	ipoptp_t	opts;
18065 	uchar_t		*opt;
18066 	uint8_t		optval;
18067 	uint8_t		optlen;
18068 	ipaddr_t	dst;
18069 	uint32_t	ts;
18070 	ire_t		*dst_ire;
18071 	timestruc_t	now;
18072 	zoneid_t	zoneid;
18073 	ill_t		*ill;
18074 
18075 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18076 
18077 	ip2dbg(("ip_rput_local_options\n"));
18078 
18079 	for (optval = ipoptp_first(&opts, ipha);
18080 	    optval != IPOPT_EOL;
18081 	    optval = ipoptp_next(&opts)) {
18082 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18083 		opt = opts.ipoptp_cur;
18084 		optlen = opts.ipoptp_len;
18085 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18086 		    optval, optlen));
18087 		switch (optval) {
18088 			uint32_t off;
18089 		case IPOPT_SSRR:
18090 		case IPOPT_LSRR:
18091 			off = opt[IPOPT_OFFSET];
18092 			off--;
18093 			if (optlen < IP_ADDR_LEN ||
18094 			    off > optlen - IP_ADDR_LEN) {
18095 				/* End of source route */
18096 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18097 				break;
18098 			}
18099 			/*
18100 			 * This will only happen if two consecutive entries
18101 			 * in the source route contains our address or if
18102 			 * it is a packet with a loose source route which
18103 			 * reaches us before consuming the whole source route
18104 			 */
18105 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18106 			if (optval == IPOPT_SSRR) {
18107 				goto bad_src_route;
18108 			}
18109 			/*
18110 			 * Hack: instead of dropping the packet truncate the
18111 			 * source route to what has been used by filling the
18112 			 * rest with IPOPT_NOP.
18113 			 */
18114 			opt[IPOPT_OLEN] = (uint8_t)off;
18115 			while (off < optlen) {
18116 				opt[off++] = IPOPT_NOP;
18117 			}
18118 			break;
18119 		case IPOPT_RR:
18120 			off = opt[IPOPT_OFFSET];
18121 			off--;
18122 			if (optlen < IP_ADDR_LEN ||
18123 			    off > optlen - IP_ADDR_LEN) {
18124 				/* No more room - ignore */
18125 				ip1dbg((
18126 				    "ip_rput_local_options: end of RR\n"));
18127 				break;
18128 			}
18129 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18130 			    IP_ADDR_LEN);
18131 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18132 			break;
18133 		case IPOPT_TS:
18134 			/* Insert timestamp if there is romm */
18135 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18136 			case IPOPT_TS_TSONLY:
18137 				off = IPOPT_TS_TIMELEN;
18138 				break;
18139 			case IPOPT_TS_PRESPEC:
18140 			case IPOPT_TS_PRESPEC_RFC791:
18141 				/* Verify that the address matched */
18142 				off = opt[IPOPT_OFFSET] - 1;
18143 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18144 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18145 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18146 				    ipst);
18147 				if (dst_ire == NULL) {
18148 					/* Not for us */
18149 					break;
18150 				}
18151 				ire_refrele(dst_ire);
18152 				/* FALLTHRU */
18153 			case IPOPT_TS_TSANDADDR:
18154 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18155 				break;
18156 			default:
18157 				/*
18158 				 * ip_*put_options should have already
18159 				 * dropped this packet.
18160 				 */
18161 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18162 				    "unknown IT - bug in ip_rput_options?\n");
18163 				return (B_TRUE);	/* Keep "lint" happy */
18164 			}
18165 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18166 				/* Increase overflow counter */
18167 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18168 				opt[IPOPT_POS_OV_FLG] =
18169 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18170 				    (off << 4));
18171 				break;
18172 			}
18173 			off = opt[IPOPT_OFFSET] - 1;
18174 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18175 			case IPOPT_TS_PRESPEC:
18176 			case IPOPT_TS_PRESPEC_RFC791:
18177 			case IPOPT_TS_TSANDADDR:
18178 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18179 				    IP_ADDR_LEN);
18180 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18181 				/* FALLTHRU */
18182 			case IPOPT_TS_TSONLY:
18183 				off = opt[IPOPT_OFFSET] - 1;
18184 				/* Compute # of milliseconds since midnight */
18185 				gethrestime(&now);
18186 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18187 				    now.tv_nsec / (NANOSEC / MILLISEC);
18188 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18189 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18190 				break;
18191 			}
18192 			break;
18193 		}
18194 	}
18195 	return (B_TRUE);
18196 
18197 bad_src_route:
18198 	q = WR(q);
18199 	if (q->q_next != NULL)
18200 		ill = q->q_ptr;
18201 	else
18202 		ill = NULL;
18203 
18204 	/* make sure we clear any indication of a hardware checksum */
18205 	DB_CKSUMFLAGS(mp) = 0;
18206 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18207 	if (zoneid == ALL_ZONES)
18208 		freemsg(mp);
18209 	else
18210 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18211 	return (B_FALSE);
18212 
18213 }
18214 
18215 /*
18216  * Process IP options in an inbound packet.  If an option affects the
18217  * effective destination address, return the next hop address via dstp.
18218  * Returns -1 if something fails in which case an ICMP error has been sent
18219  * and mp freed.
18220  */
18221 static int
18222 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18223     ip_stack_t *ipst)
18224 {
18225 	ipoptp_t	opts;
18226 	uchar_t		*opt;
18227 	uint8_t		optval;
18228 	uint8_t		optlen;
18229 	ipaddr_t	dst;
18230 	intptr_t	code = 0;
18231 	ire_t		*ire = NULL;
18232 	zoneid_t	zoneid;
18233 	ill_t		*ill;
18234 
18235 	ip2dbg(("ip_rput_options\n"));
18236 	dst = ipha->ipha_dst;
18237 	for (optval = ipoptp_first(&opts, ipha);
18238 	    optval != IPOPT_EOL;
18239 	    optval = ipoptp_next(&opts)) {
18240 		opt = opts.ipoptp_cur;
18241 		optlen = opts.ipoptp_len;
18242 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18243 		    optval, optlen));
18244 		/*
18245 		 * Note: we need to verify the checksum before we
18246 		 * modify anything thus this routine only extracts the next
18247 		 * hop dst from any source route.
18248 		 */
18249 		switch (optval) {
18250 			uint32_t off;
18251 		case IPOPT_SSRR:
18252 		case IPOPT_LSRR:
18253 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18254 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18255 			if (ire == NULL) {
18256 				if (optval == IPOPT_SSRR) {
18257 					ip1dbg(("ip_rput_options: not next"
18258 					    " strict source route 0x%x\n",
18259 					    ntohl(dst)));
18260 					code = (char *)&ipha->ipha_dst -
18261 					    (char *)ipha;
18262 					goto param_prob; /* RouterReq's */
18263 				}
18264 				ip2dbg(("ip_rput_options: "
18265 				    "not next source route 0x%x\n",
18266 				    ntohl(dst)));
18267 				break;
18268 			}
18269 			ire_refrele(ire);
18270 
18271 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18272 				ip1dbg((
18273 				    "ip_rput_options: bad option offset\n"));
18274 				code = (char *)&opt[IPOPT_OLEN] -
18275 				    (char *)ipha;
18276 				goto param_prob;
18277 			}
18278 			off = opt[IPOPT_OFFSET];
18279 			off--;
18280 		redo_srr:
18281 			if (optlen < IP_ADDR_LEN ||
18282 			    off > optlen - IP_ADDR_LEN) {
18283 				/* End of source route */
18284 				ip1dbg(("ip_rput_options: end of SR\n"));
18285 				break;
18286 			}
18287 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18288 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18289 			    ntohl(dst)));
18290 
18291 			/*
18292 			 * Check if our address is present more than
18293 			 * once as consecutive hops in source route.
18294 			 * XXX verify per-interface ip_forwarding
18295 			 * for source route?
18296 			 */
18297 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18298 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18299 
18300 			if (ire != NULL) {
18301 				ire_refrele(ire);
18302 				off += IP_ADDR_LEN;
18303 				goto redo_srr;
18304 			}
18305 
18306 			if (dst == htonl(INADDR_LOOPBACK)) {
18307 				ip1dbg(("ip_rput_options: loopback addr in "
18308 				    "source route!\n"));
18309 				goto bad_src_route;
18310 			}
18311 			/*
18312 			 * For strict: verify that dst is directly
18313 			 * reachable.
18314 			 */
18315 			if (optval == IPOPT_SSRR) {
18316 				ire = ire_ftable_lookup(dst, 0, 0,
18317 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18318 				    msg_getlabel(mp),
18319 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18320 				if (ire == NULL) {
18321 					ip1dbg(("ip_rput_options: SSRR not "
18322 					    "directly reachable: 0x%x\n",
18323 					    ntohl(dst)));
18324 					goto bad_src_route;
18325 				}
18326 				ire_refrele(ire);
18327 			}
18328 			/*
18329 			 * Defer update of the offset and the record route
18330 			 * until the packet is forwarded.
18331 			 */
18332 			break;
18333 		case IPOPT_RR:
18334 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18335 				ip1dbg((
18336 				    "ip_rput_options: bad option offset\n"));
18337 				code = (char *)&opt[IPOPT_OLEN] -
18338 				    (char *)ipha;
18339 				goto param_prob;
18340 			}
18341 			break;
18342 		case IPOPT_TS:
18343 			/*
18344 			 * Verify that length >= 5 and that there is either
18345 			 * room for another timestamp or that the overflow
18346 			 * counter is not maxed out.
18347 			 */
18348 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18349 			if (optlen < IPOPT_MINLEN_IT) {
18350 				goto param_prob;
18351 			}
18352 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18353 				ip1dbg((
18354 				    "ip_rput_options: bad option offset\n"));
18355 				code = (char *)&opt[IPOPT_OFFSET] -
18356 				    (char *)ipha;
18357 				goto param_prob;
18358 			}
18359 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18360 			case IPOPT_TS_TSONLY:
18361 				off = IPOPT_TS_TIMELEN;
18362 				break;
18363 			case IPOPT_TS_TSANDADDR:
18364 			case IPOPT_TS_PRESPEC:
18365 			case IPOPT_TS_PRESPEC_RFC791:
18366 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18367 				break;
18368 			default:
18369 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18370 				    (char *)ipha;
18371 				goto param_prob;
18372 			}
18373 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18374 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18375 				/*
18376 				 * No room and the overflow counter is 15
18377 				 * already.
18378 				 */
18379 				goto param_prob;
18380 			}
18381 			break;
18382 		}
18383 	}
18384 
18385 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18386 		*dstp = dst;
18387 		return (0);
18388 	}
18389 
18390 	ip1dbg(("ip_rput_options: error processing IP options."));
18391 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18392 
18393 param_prob:
18394 	q = WR(q);
18395 	if (q->q_next != NULL)
18396 		ill = q->q_ptr;
18397 	else
18398 		ill = NULL;
18399 
18400 	/* make sure we clear any indication of a hardware checksum */
18401 	DB_CKSUMFLAGS(mp) = 0;
18402 	/* Don't know whether this is for non-global or global/forwarding */
18403 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18404 	if (zoneid == ALL_ZONES)
18405 		freemsg(mp);
18406 	else
18407 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18408 	return (-1);
18409 
18410 bad_src_route:
18411 	q = WR(q);
18412 	if (q->q_next != NULL)
18413 		ill = q->q_ptr;
18414 	else
18415 		ill = NULL;
18416 
18417 	/* make sure we clear any indication of a hardware checksum */
18418 	DB_CKSUMFLAGS(mp) = 0;
18419 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18420 	if (zoneid == ALL_ZONES)
18421 		freemsg(mp);
18422 	else
18423 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18424 	return (-1);
18425 }
18426 
18427 /*
18428  * IP & ICMP info in >=14 msg's ...
18429  *  - ip fixed part (mib2_ip_t)
18430  *  - icmp fixed part (mib2_icmp_t)
18431  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18432  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18433  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18434  *  - ipRouteAttributeTable (ip 102)	labeled routes
18435  *  - ip multicast membership (ip_member_t)
18436  *  - ip multicast source filtering (ip_grpsrc_t)
18437  *  - igmp fixed part (struct igmpstat)
18438  *  - multicast routing stats (struct mrtstat)
18439  *  - multicast routing vifs (array of struct vifctl)
18440  *  - multicast routing routes (array of struct mfcctl)
18441  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18442  *					One per ill plus one generic
18443  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18444  *					One per ill plus one generic
18445  *  - ipv6RouteEntry			all IPv6 IREs
18446  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18447  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18448  *  - ipv6AddrEntry			all IPv6 ipifs
18449  *  - ipv6 multicast membership (ipv6_member_t)
18450  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18451  *
18452  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18453  *
18454  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18455  * already filled in by the caller.
18456  * Return value of 0 indicates that no messages were sent and caller
18457  * should free mpctl.
18458  */
18459 int
18460 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18461 {
18462 	ip_stack_t *ipst;
18463 	sctp_stack_t *sctps;
18464 
18465 	if (q->q_next != NULL) {
18466 		ipst = ILLQ_TO_IPST(q);
18467 	} else {
18468 		ipst = CONNQ_TO_IPST(q);
18469 	}
18470 	ASSERT(ipst != NULL);
18471 	sctps = ipst->ips_netstack->netstack_sctp;
18472 
18473 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18474 		return (0);
18475 	}
18476 
18477 	/*
18478 	 * For the purposes of the (broken) packet shell use
18479 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18480 	 * to make TCP and UDP appear first in the list of mib items.
18481 	 * TBD: We could expand this and use it in netstat so that
18482 	 * the kernel doesn't have to produce large tables (connections,
18483 	 * routes, etc) when netstat only wants the statistics or a particular
18484 	 * table.
18485 	 */
18486 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18487 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18488 			return (1);
18489 		}
18490 	}
18491 
18492 	if (level != MIB2_TCP) {
18493 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18494 			return (1);
18495 		}
18496 	}
18497 
18498 	if (level != MIB2_UDP) {
18499 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18500 			return (1);
18501 		}
18502 	}
18503 
18504 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18505 	    ipst)) == NULL) {
18506 		return (1);
18507 	}
18508 
18509 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18510 		return (1);
18511 	}
18512 
18513 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18514 		return (1);
18515 	}
18516 
18517 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18518 		return (1);
18519 	}
18520 
18521 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18522 		return (1);
18523 	}
18524 
18525 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18526 		return (1);
18527 	}
18528 
18529 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18530 		return (1);
18531 	}
18532 
18533 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18534 		return (1);
18535 	}
18536 
18537 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18538 		return (1);
18539 	}
18540 
18541 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18542 		return (1);
18543 	}
18544 
18545 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18546 		return (1);
18547 	}
18548 
18549 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18550 		return (1);
18551 	}
18552 
18553 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18554 		return (1);
18555 	}
18556 
18557 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18558 		return (1);
18559 	}
18560 
18561 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18562 	if (mpctl == NULL)
18563 		return (1);
18564 
18565 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18566 	if (mpctl == NULL)
18567 		return (1);
18568 
18569 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18570 		return (1);
18571 	}
18572 	freemsg(mpctl);
18573 	return (1);
18574 }
18575 
18576 /* Get global (legacy) IPv4 statistics */
18577 static mblk_t *
18578 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18579     ip_stack_t *ipst)
18580 {
18581 	mib2_ip_t		old_ip_mib;
18582 	struct opthdr		*optp;
18583 	mblk_t			*mp2ctl;
18584 
18585 	/*
18586 	 * make a copy of the original message
18587 	 */
18588 	mp2ctl = copymsg(mpctl);
18589 
18590 	/* fixed length IP structure... */
18591 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18592 	optp->level = MIB2_IP;
18593 	optp->name = 0;
18594 	SET_MIB(old_ip_mib.ipForwarding,
18595 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18596 	SET_MIB(old_ip_mib.ipDefaultTTL,
18597 	    (uint32_t)ipst->ips_ip_def_ttl);
18598 	SET_MIB(old_ip_mib.ipReasmTimeout,
18599 	    ipst->ips_ip_g_frag_timeout);
18600 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18601 	    sizeof (mib2_ipAddrEntry_t));
18602 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18603 	    sizeof (mib2_ipRouteEntry_t));
18604 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18605 	    sizeof (mib2_ipNetToMediaEntry_t));
18606 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18607 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18608 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18609 	    sizeof (mib2_ipAttributeEntry_t));
18610 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18611 
18612 	/*
18613 	 * Grab the statistics from the new IP MIB
18614 	 */
18615 	SET_MIB(old_ip_mib.ipInReceives,
18616 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18617 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18618 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18619 	SET_MIB(old_ip_mib.ipForwDatagrams,
18620 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18621 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18622 	    ipmib->ipIfStatsInUnknownProtos);
18623 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18624 	SET_MIB(old_ip_mib.ipInDelivers,
18625 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18626 	SET_MIB(old_ip_mib.ipOutRequests,
18627 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18628 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18629 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18630 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18631 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18632 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18633 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18634 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18635 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18636 
18637 	/* ipRoutingDiscards is not being used */
18638 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18639 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18640 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18641 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18642 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18643 	    ipmib->ipIfStatsReasmDuplicates);
18644 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18645 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18646 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18647 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18648 	SET_MIB(old_ip_mib.rawipInOverflows,
18649 	    ipmib->rawipIfStatsInOverflows);
18650 
18651 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18652 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18653 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18654 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18655 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18656 	    ipmib->ipIfStatsOutSwitchIPVersion);
18657 
18658 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18659 	    (int)sizeof (old_ip_mib))) {
18660 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18661 		    (uint_t)sizeof (old_ip_mib)));
18662 	}
18663 
18664 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18665 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18666 	    (int)optp->level, (int)optp->name, (int)optp->len));
18667 	qreply(q, mpctl);
18668 	return (mp2ctl);
18669 }
18670 
18671 /* Per interface IPv4 statistics */
18672 static mblk_t *
18673 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18674 {
18675 	struct opthdr		*optp;
18676 	mblk_t			*mp2ctl;
18677 	ill_t			*ill;
18678 	ill_walk_context_t	ctx;
18679 	mblk_t			*mp_tail = NULL;
18680 	mib2_ipIfStatsEntry_t	global_ip_mib;
18681 
18682 	/*
18683 	 * Make a copy of the original message
18684 	 */
18685 	mp2ctl = copymsg(mpctl);
18686 
18687 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18688 	optp->level = MIB2_IP;
18689 	optp->name = MIB2_IP_TRAFFIC_STATS;
18690 	/* Include "unknown interface" ip_mib */
18691 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18692 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18693 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18694 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18695 	    (ipst->ips_ip_g_forward ? 1 : 2));
18696 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18697 	    (uint32_t)ipst->ips_ip_def_ttl);
18698 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18699 	    sizeof (mib2_ipIfStatsEntry_t));
18700 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18701 	    sizeof (mib2_ipAddrEntry_t));
18702 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18703 	    sizeof (mib2_ipRouteEntry_t));
18704 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18705 	    sizeof (mib2_ipNetToMediaEntry_t));
18706 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18707 	    sizeof (ip_member_t));
18708 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18709 	    sizeof (ip_grpsrc_t));
18710 
18711 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18712 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18713 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18714 		    "failed to allocate %u bytes\n",
18715 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18716 	}
18717 
18718 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18719 
18720 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18721 	ill = ILL_START_WALK_V4(&ctx, ipst);
18722 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18723 		ill->ill_ip_mib->ipIfStatsIfIndex =
18724 		    ill->ill_phyint->phyint_ifindex;
18725 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18726 		    (ipst->ips_ip_g_forward ? 1 : 2));
18727 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18728 		    (uint32_t)ipst->ips_ip_def_ttl);
18729 
18730 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18731 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18732 		    (char *)ill->ill_ip_mib,
18733 		    (int)sizeof (*ill->ill_ip_mib))) {
18734 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18735 			    "failed to allocate %u bytes\n",
18736 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18737 		}
18738 	}
18739 	rw_exit(&ipst->ips_ill_g_lock);
18740 
18741 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18742 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18743 	    "level %d, name %d, len %d\n",
18744 	    (int)optp->level, (int)optp->name, (int)optp->len));
18745 	qreply(q, mpctl);
18746 
18747 	if (mp2ctl == NULL)
18748 		return (NULL);
18749 
18750 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18751 }
18752 
18753 /* Global IPv4 ICMP statistics */
18754 static mblk_t *
18755 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18756 {
18757 	struct opthdr		*optp;
18758 	mblk_t			*mp2ctl;
18759 
18760 	/*
18761 	 * Make a copy of the original message
18762 	 */
18763 	mp2ctl = copymsg(mpctl);
18764 
18765 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18766 	optp->level = MIB2_ICMP;
18767 	optp->name = 0;
18768 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18769 	    (int)sizeof (ipst->ips_icmp_mib))) {
18770 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18771 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18772 	}
18773 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18774 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18775 	    (int)optp->level, (int)optp->name, (int)optp->len));
18776 	qreply(q, mpctl);
18777 	return (mp2ctl);
18778 }
18779 
18780 /* Global IPv4 IGMP statistics */
18781 static mblk_t *
18782 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18783 {
18784 	struct opthdr		*optp;
18785 	mblk_t			*mp2ctl;
18786 
18787 	/*
18788 	 * make a copy of the original message
18789 	 */
18790 	mp2ctl = copymsg(mpctl);
18791 
18792 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18793 	optp->level = EXPER_IGMP;
18794 	optp->name = 0;
18795 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18796 	    (int)sizeof (ipst->ips_igmpstat))) {
18797 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18798 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18799 	}
18800 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18801 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18802 	    (int)optp->level, (int)optp->name, (int)optp->len));
18803 	qreply(q, mpctl);
18804 	return (mp2ctl);
18805 }
18806 
18807 /* Global IPv4 Multicast Routing statistics */
18808 static mblk_t *
18809 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18810 {
18811 	struct opthdr		*optp;
18812 	mblk_t			*mp2ctl;
18813 
18814 	/*
18815 	 * make a copy of the original message
18816 	 */
18817 	mp2ctl = copymsg(mpctl);
18818 
18819 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18820 	optp->level = EXPER_DVMRP;
18821 	optp->name = 0;
18822 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18823 		ip0dbg(("ip_mroute_stats: failed\n"));
18824 	}
18825 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18826 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18827 	    (int)optp->level, (int)optp->name, (int)optp->len));
18828 	qreply(q, mpctl);
18829 	return (mp2ctl);
18830 }
18831 
18832 /* IPv4 address information */
18833 static mblk_t *
18834 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18835 {
18836 	struct opthdr		*optp;
18837 	mblk_t			*mp2ctl;
18838 	mblk_t			*mp_tail = NULL;
18839 	ill_t			*ill;
18840 	ipif_t			*ipif;
18841 	uint_t			bitval;
18842 	mib2_ipAddrEntry_t	mae;
18843 	zoneid_t		zoneid;
18844 	ill_walk_context_t ctx;
18845 
18846 	/*
18847 	 * make a copy of the original message
18848 	 */
18849 	mp2ctl = copymsg(mpctl);
18850 
18851 	/* ipAddrEntryTable */
18852 
18853 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18854 	optp->level = MIB2_IP;
18855 	optp->name = MIB2_IP_ADDR;
18856 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18857 
18858 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18859 	ill = ILL_START_WALK_V4(&ctx, ipst);
18860 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18861 		for (ipif = ill->ill_ipif; ipif != NULL;
18862 		    ipif = ipif->ipif_next) {
18863 			if (ipif->ipif_zoneid != zoneid &&
18864 			    ipif->ipif_zoneid != ALL_ZONES)
18865 				continue;
18866 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18867 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18868 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18869 
18870 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18871 			    OCTET_LENGTH);
18872 			mae.ipAdEntIfIndex.o_length =
18873 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18874 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18875 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18876 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18877 			mae.ipAdEntInfo.ae_subnet_len =
18878 			    ip_mask_to_plen(ipif->ipif_net_mask);
18879 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18880 			for (bitval = 1;
18881 			    bitval &&
18882 			    !(bitval & ipif->ipif_brd_addr);
18883 			    bitval <<= 1)
18884 				noop;
18885 			mae.ipAdEntBcastAddr = bitval;
18886 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18887 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18888 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18889 			mae.ipAdEntInfo.ae_broadcast_addr =
18890 			    ipif->ipif_brd_addr;
18891 			mae.ipAdEntInfo.ae_pp_dst_addr =
18892 			    ipif->ipif_pp_dst_addr;
18893 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18894 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18895 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18896 
18897 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18898 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18899 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18900 				    "allocate %u bytes\n",
18901 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18902 			}
18903 		}
18904 	}
18905 	rw_exit(&ipst->ips_ill_g_lock);
18906 
18907 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18908 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18909 	    (int)optp->level, (int)optp->name, (int)optp->len));
18910 	qreply(q, mpctl);
18911 	return (mp2ctl);
18912 }
18913 
18914 /* IPv6 address information */
18915 static mblk_t *
18916 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18917 {
18918 	struct opthdr		*optp;
18919 	mblk_t			*mp2ctl;
18920 	mblk_t			*mp_tail = NULL;
18921 	ill_t			*ill;
18922 	ipif_t			*ipif;
18923 	mib2_ipv6AddrEntry_t	mae6;
18924 	zoneid_t		zoneid;
18925 	ill_walk_context_t	ctx;
18926 
18927 	/*
18928 	 * make a copy of the original message
18929 	 */
18930 	mp2ctl = copymsg(mpctl);
18931 
18932 	/* ipv6AddrEntryTable */
18933 
18934 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18935 	optp->level = MIB2_IP6;
18936 	optp->name = MIB2_IP6_ADDR;
18937 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18938 
18939 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18940 	ill = ILL_START_WALK_V6(&ctx, ipst);
18941 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18942 		for (ipif = ill->ill_ipif; ipif != NULL;
18943 		    ipif = ipif->ipif_next) {
18944 			if (ipif->ipif_zoneid != zoneid &&
18945 			    ipif->ipif_zoneid != ALL_ZONES)
18946 				continue;
18947 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18948 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18949 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18950 
18951 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18952 			    OCTET_LENGTH);
18953 			mae6.ipv6AddrIfIndex.o_length =
18954 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18955 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18956 			mae6.ipv6AddrPfxLength =
18957 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18958 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18959 			mae6.ipv6AddrInfo.ae_subnet_len =
18960 			    mae6.ipv6AddrPfxLength;
18961 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18962 
18963 			/* Type: stateless(1), stateful(2), unknown(3) */
18964 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18965 				mae6.ipv6AddrType = 1;
18966 			else
18967 				mae6.ipv6AddrType = 2;
18968 			/* Anycast: true(1), false(2) */
18969 			if (ipif->ipif_flags & IPIF_ANYCAST)
18970 				mae6.ipv6AddrAnycastFlag = 1;
18971 			else
18972 				mae6.ipv6AddrAnycastFlag = 2;
18973 
18974 			/*
18975 			 * Address status: preferred(1), deprecated(2),
18976 			 * invalid(3), inaccessible(4), unknown(5)
18977 			 */
18978 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18979 				mae6.ipv6AddrStatus = 3;
18980 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18981 				mae6.ipv6AddrStatus = 2;
18982 			else
18983 				mae6.ipv6AddrStatus = 1;
18984 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18985 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18986 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18987 			    ipif->ipif_v6pp_dst_addr;
18988 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18989 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18990 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18991 			mae6.ipv6AddrIdentifier = ill->ill_token;
18992 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18993 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18994 			mae6.ipv6AddrRetransmitTime =
18995 			    ill->ill_reachable_retrans_time;
18996 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18997 			    (char *)&mae6,
18998 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18999 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
19000 				    "allocate %u bytes\n",
19001 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
19002 			}
19003 		}
19004 	}
19005 	rw_exit(&ipst->ips_ill_g_lock);
19006 
19007 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19008 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
19009 	    (int)optp->level, (int)optp->name, (int)optp->len));
19010 	qreply(q, mpctl);
19011 	return (mp2ctl);
19012 }
19013 
19014 /* IPv4 multicast group membership. */
19015 static mblk_t *
19016 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19017 {
19018 	struct opthdr		*optp;
19019 	mblk_t			*mp2ctl;
19020 	ill_t			*ill;
19021 	ipif_t			*ipif;
19022 	ilm_t			*ilm;
19023 	ip_member_t		ipm;
19024 	mblk_t			*mp_tail = NULL;
19025 	ill_walk_context_t	ctx;
19026 	zoneid_t		zoneid;
19027 	ilm_walker_t		ilw;
19028 
19029 	/*
19030 	 * make a copy of the original message
19031 	 */
19032 	mp2ctl = copymsg(mpctl);
19033 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19034 
19035 	/* ipGroupMember table */
19036 	optp = (struct opthdr *)&mpctl->b_rptr[
19037 	    sizeof (struct T_optmgmt_ack)];
19038 	optp->level = MIB2_IP;
19039 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
19040 
19041 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19042 	ill = ILL_START_WALK_V4(&ctx, ipst);
19043 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19044 		if (IS_UNDER_IPMP(ill))
19045 			continue;
19046 
19047 		ilm = ilm_walker_start(&ilw, ill);
19048 		for (ipif = ill->ill_ipif; ipif != NULL;
19049 		    ipif = ipif->ipif_next) {
19050 			if (ipif->ipif_zoneid != zoneid &&
19051 			    ipif->ipif_zoneid != ALL_ZONES)
19052 				continue;	/* not this zone */
19053 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
19054 			    OCTET_LENGTH);
19055 			ipm.ipGroupMemberIfIndex.o_length =
19056 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
19057 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19058 				ASSERT(ilm->ilm_ipif != NULL);
19059 				ASSERT(ilm->ilm_ill == NULL);
19060 				if (ilm->ilm_ipif != ipif)
19061 					continue;
19062 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
19063 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
19064 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
19065 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19066 				    (char *)&ipm, (int)sizeof (ipm))) {
19067 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
19068 					    "failed to allocate %u bytes\n",
19069 					    (uint_t)sizeof (ipm)));
19070 				}
19071 			}
19072 		}
19073 		ilm_walker_finish(&ilw);
19074 	}
19075 	rw_exit(&ipst->ips_ill_g_lock);
19076 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19077 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19078 	    (int)optp->level, (int)optp->name, (int)optp->len));
19079 	qreply(q, mpctl);
19080 	return (mp2ctl);
19081 }
19082 
19083 /* IPv6 multicast group membership. */
19084 static mblk_t *
19085 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19086 {
19087 	struct opthdr		*optp;
19088 	mblk_t			*mp2ctl;
19089 	ill_t			*ill;
19090 	ilm_t			*ilm;
19091 	ipv6_member_t		ipm6;
19092 	mblk_t			*mp_tail = NULL;
19093 	ill_walk_context_t	ctx;
19094 	zoneid_t		zoneid;
19095 	ilm_walker_t		ilw;
19096 
19097 	/*
19098 	 * make a copy of the original message
19099 	 */
19100 	mp2ctl = copymsg(mpctl);
19101 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19102 
19103 	/* ip6GroupMember table */
19104 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19105 	optp->level = MIB2_IP6;
19106 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19107 
19108 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19109 	ill = ILL_START_WALK_V6(&ctx, ipst);
19110 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19111 		if (IS_UNDER_IPMP(ill))
19112 			continue;
19113 
19114 		ilm = ilm_walker_start(&ilw, ill);
19115 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19116 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19117 			ASSERT(ilm->ilm_ipif == NULL);
19118 			ASSERT(ilm->ilm_ill != NULL);
19119 			if (ilm->ilm_zoneid != zoneid)
19120 				continue;	/* not this zone */
19121 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19122 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19123 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19124 			if (!snmp_append_data2(mpctl->b_cont,
19125 			    &mp_tail,
19126 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19127 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19128 				    "failed to allocate %u bytes\n",
19129 				    (uint_t)sizeof (ipm6)));
19130 			}
19131 		}
19132 		ilm_walker_finish(&ilw);
19133 	}
19134 	rw_exit(&ipst->ips_ill_g_lock);
19135 
19136 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19137 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19138 	    (int)optp->level, (int)optp->name, (int)optp->len));
19139 	qreply(q, mpctl);
19140 	return (mp2ctl);
19141 }
19142 
19143 /* IP multicast filtered sources */
19144 static mblk_t *
19145 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19146 {
19147 	struct opthdr		*optp;
19148 	mblk_t			*mp2ctl;
19149 	ill_t			*ill;
19150 	ipif_t			*ipif;
19151 	ilm_t			*ilm;
19152 	ip_grpsrc_t		ips;
19153 	mblk_t			*mp_tail = NULL;
19154 	ill_walk_context_t	ctx;
19155 	zoneid_t		zoneid;
19156 	int			i;
19157 	slist_t			*sl;
19158 	ilm_walker_t		ilw;
19159 
19160 	/*
19161 	 * make a copy of the original message
19162 	 */
19163 	mp2ctl = copymsg(mpctl);
19164 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19165 
19166 	/* ipGroupSource table */
19167 	optp = (struct opthdr *)&mpctl->b_rptr[
19168 	    sizeof (struct T_optmgmt_ack)];
19169 	optp->level = MIB2_IP;
19170 	optp->name = EXPER_IP_GROUP_SOURCES;
19171 
19172 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19173 	ill = ILL_START_WALK_V4(&ctx, ipst);
19174 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19175 		if (IS_UNDER_IPMP(ill))
19176 			continue;
19177 
19178 		ilm = ilm_walker_start(&ilw, ill);
19179 		for (ipif = ill->ill_ipif; ipif != NULL;
19180 		    ipif = ipif->ipif_next) {
19181 			if (ipif->ipif_zoneid != zoneid)
19182 				continue;	/* not this zone */
19183 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19184 			    OCTET_LENGTH);
19185 			ips.ipGroupSourceIfIndex.o_length =
19186 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19187 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19188 				ASSERT(ilm->ilm_ipif != NULL);
19189 				ASSERT(ilm->ilm_ill == NULL);
19190 				sl = ilm->ilm_filter;
19191 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19192 					continue;
19193 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19194 				for (i = 0; i < sl->sl_numsrc; i++) {
19195 					if (!IN6_IS_ADDR_V4MAPPED(
19196 					    &sl->sl_addr[i]))
19197 						continue;
19198 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19199 					    ips.ipGroupSourceAddress);
19200 					if (snmp_append_data2(mpctl->b_cont,
19201 					    &mp_tail, (char *)&ips,
19202 					    (int)sizeof (ips)) == 0) {
19203 						ip1dbg(("ip_snmp_get_mib2_"
19204 						    "ip_group_src: failed to "
19205 						    "allocate %u bytes\n",
19206 						    (uint_t)sizeof (ips)));
19207 					}
19208 				}
19209 			}
19210 		}
19211 		ilm_walker_finish(&ilw);
19212 	}
19213 	rw_exit(&ipst->ips_ill_g_lock);
19214 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19215 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19216 	    (int)optp->level, (int)optp->name, (int)optp->len));
19217 	qreply(q, mpctl);
19218 	return (mp2ctl);
19219 }
19220 
19221 /* IPv6 multicast filtered sources. */
19222 static mblk_t *
19223 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19224 {
19225 	struct opthdr		*optp;
19226 	mblk_t			*mp2ctl;
19227 	ill_t			*ill;
19228 	ilm_t			*ilm;
19229 	ipv6_grpsrc_t		ips6;
19230 	mblk_t			*mp_tail = NULL;
19231 	ill_walk_context_t	ctx;
19232 	zoneid_t		zoneid;
19233 	int			i;
19234 	slist_t			*sl;
19235 	ilm_walker_t		ilw;
19236 
19237 	/*
19238 	 * make a copy of the original message
19239 	 */
19240 	mp2ctl = copymsg(mpctl);
19241 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19242 
19243 	/* ip6GroupMember table */
19244 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19245 	optp->level = MIB2_IP6;
19246 	optp->name = EXPER_IP6_GROUP_SOURCES;
19247 
19248 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19249 	ill = ILL_START_WALK_V6(&ctx, ipst);
19250 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19251 		if (IS_UNDER_IPMP(ill))
19252 			continue;
19253 
19254 		ilm = ilm_walker_start(&ilw, ill);
19255 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19256 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19257 			ASSERT(ilm->ilm_ipif == NULL);
19258 			ASSERT(ilm->ilm_ill != NULL);
19259 			sl = ilm->ilm_filter;
19260 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19261 				continue;
19262 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19263 			for (i = 0; i < sl->sl_numsrc; i++) {
19264 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19265 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19266 				    (char *)&ips6, (int)sizeof (ips6))) {
19267 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19268 					    "group_src: failed to allocate "
19269 					    "%u bytes\n",
19270 					    (uint_t)sizeof (ips6)));
19271 				}
19272 			}
19273 		}
19274 		ilm_walker_finish(&ilw);
19275 	}
19276 	rw_exit(&ipst->ips_ill_g_lock);
19277 
19278 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19279 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19280 	    (int)optp->level, (int)optp->name, (int)optp->len));
19281 	qreply(q, mpctl);
19282 	return (mp2ctl);
19283 }
19284 
19285 /* Multicast routing virtual interface table. */
19286 static mblk_t *
19287 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19288 {
19289 	struct opthdr		*optp;
19290 	mblk_t			*mp2ctl;
19291 
19292 	/*
19293 	 * make a copy of the original message
19294 	 */
19295 	mp2ctl = copymsg(mpctl);
19296 
19297 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19298 	optp->level = EXPER_DVMRP;
19299 	optp->name = EXPER_DVMRP_VIF;
19300 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19301 		ip0dbg(("ip_mroute_vif: failed\n"));
19302 	}
19303 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19304 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19305 	    (int)optp->level, (int)optp->name, (int)optp->len));
19306 	qreply(q, mpctl);
19307 	return (mp2ctl);
19308 }
19309 
19310 /* Multicast routing table. */
19311 static mblk_t *
19312 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19313 {
19314 	struct opthdr		*optp;
19315 	mblk_t			*mp2ctl;
19316 
19317 	/*
19318 	 * make a copy of the original message
19319 	 */
19320 	mp2ctl = copymsg(mpctl);
19321 
19322 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19323 	optp->level = EXPER_DVMRP;
19324 	optp->name = EXPER_DVMRP_MRT;
19325 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19326 		ip0dbg(("ip_mroute_mrt: failed\n"));
19327 	}
19328 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19329 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19330 	    (int)optp->level, (int)optp->name, (int)optp->len));
19331 	qreply(q, mpctl);
19332 	return (mp2ctl);
19333 }
19334 
19335 /*
19336  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19337  * in one IRE walk.
19338  */
19339 static mblk_t *
19340 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19341     ip_stack_t *ipst)
19342 {
19343 	struct opthdr	*optp;
19344 	mblk_t		*mp2ctl;	/* Returned */
19345 	mblk_t		*mp3ctl;	/* nettomedia */
19346 	mblk_t		*mp4ctl;	/* routeattrs */
19347 	iproutedata_t	ird;
19348 	zoneid_t	zoneid;
19349 
19350 	/*
19351 	 * make copies of the original message
19352 	 *	- mp2ctl is returned unchanged to the caller for his use
19353 	 *	- mpctl is sent upstream as ipRouteEntryTable
19354 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19355 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19356 	 */
19357 	mp2ctl = copymsg(mpctl);
19358 	mp3ctl = copymsg(mpctl);
19359 	mp4ctl = copymsg(mpctl);
19360 	if (mp3ctl == NULL || mp4ctl == NULL) {
19361 		freemsg(mp4ctl);
19362 		freemsg(mp3ctl);
19363 		freemsg(mp2ctl);
19364 		freemsg(mpctl);
19365 		return (NULL);
19366 	}
19367 
19368 	bzero(&ird, sizeof (ird));
19369 
19370 	ird.ird_route.lp_head = mpctl->b_cont;
19371 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19372 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19373 	/*
19374 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19375 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19376 	 * intended a temporary solution until a proper MIB API is provided
19377 	 * that provides complete filtering/caller-opt-in.
19378 	 */
19379 	if (level == EXPER_IP_AND_TESTHIDDEN)
19380 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19381 
19382 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19383 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19384 
19385 	/* ipRouteEntryTable in mpctl */
19386 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19387 	optp->level = MIB2_IP;
19388 	optp->name = MIB2_IP_ROUTE;
19389 	optp->len = msgdsize(ird.ird_route.lp_head);
19390 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19391 	    (int)optp->level, (int)optp->name, (int)optp->len));
19392 	qreply(q, mpctl);
19393 
19394 	/* ipNetToMediaEntryTable in mp3ctl */
19395 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19396 	optp->level = MIB2_IP;
19397 	optp->name = MIB2_IP_MEDIA;
19398 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19399 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19400 	    (int)optp->level, (int)optp->name, (int)optp->len));
19401 	qreply(q, mp3ctl);
19402 
19403 	/* ipRouteAttributeTable in mp4ctl */
19404 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19405 	optp->level = MIB2_IP;
19406 	optp->name = EXPER_IP_RTATTR;
19407 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19408 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19409 	    (int)optp->level, (int)optp->name, (int)optp->len));
19410 	if (optp->len == 0)
19411 		freemsg(mp4ctl);
19412 	else
19413 		qreply(q, mp4ctl);
19414 
19415 	return (mp2ctl);
19416 }
19417 
19418 /*
19419  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19420  * ipv6NetToMediaEntryTable in an NDP walk.
19421  */
19422 static mblk_t *
19423 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19424     ip_stack_t *ipst)
19425 {
19426 	struct opthdr	*optp;
19427 	mblk_t		*mp2ctl;	/* Returned */
19428 	mblk_t		*mp3ctl;	/* nettomedia */
19429 	mblk_t		*mp4ctl;	/* routeattrs */
19430 	iproutedata_t	ird;
19431 	zoneid_t	zoneid;
19432 
19433 	/*
19434 	 * make copies of the original message
19435 	 *	- mp2ctl is returned unchanged to the caller for his use
19436 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19437 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19438 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19439 	 */
19440 	mp2ctl = copymsg(mpctl);
19441 	mp3ctl = copymsg(mpctl);
19442 	mp4ctl = copymsg(mpctl);
19443 	if (mp3ctl == NULL || mp4ctl == NULL) {
19444 		freemsg(mp4ctl);
19445 		freemsg(mp3ctl);
19446 		freemsg(mp2ctl);
19447 		freemsg(mpctl);
19448 		return (NULL);
19449 	}
19450 
19451 	bzero(&ird, sizeof (ird));
19452 
19453 	ird.ird_route.lp_head = mpctl->b_cont;
19454 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19455 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19456 	/*
19457 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19458 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19459 	 * intended a temporary solution until a proper MIB API is provided
19460 	 * that provides complete filtering/caller-opt-in.
19461 	 */
19462 	if (level == EXPER_IP_AND_TESTHIDDEN)
19463 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19464 
19465 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19466 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19467 
19468 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19469 	optp->level = MIB2_IP6;
19470 	optp->name = MIB2_IP6_ROUTE;
19471 	optp->len = msgdsize(ird.ird_route.lp_head);
19472 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19473 	    (int)optp->level, (int)optp->name, (int)optp->len));
19474 	qreply(q, mpctl);
19475 
19476 	/* ipv6NetToMediaEntryTable in mp3ctl */
19477 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19478 
19479 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19480 	optp->level = MIB2_IP6;
19481 	optp->name = MIB2_IP6_MEDIA;
19482 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19483 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19484 	    (int)optp->level, (int)optp->name, (int)optp->len));
19485 	qreply(q, mp3ctl);
19486 
19487 	/* ipv6RouteAttributeTable in mp4ctl */
19488 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19489 	optp->level = MIB2_IP6;
19490 	optp->name = EXPER_IP_RTATTR;
19491 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19492 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19493 	    (int)optp->level, (int)optp->name, (int)optp->len));
19494 	if (optp->len == 0)
19495 		freemsg(mp4ctl);
19496 	else
19497 		qreply(q, mp4ctl);
19498 
19499 	return (mp2ctl);
19500 }
19501 
19502 /*
19503  * IPv6 mib: One per ill
19504  */
19505 static mblk_t *
19506 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19507 {
19508 	struct opthdr		*optp;
19509 	mblk_t			*mp2ctl;
19510 	ill_t			*ill;
19511 	ill_walk_context_t	ctx;
19512 	mblk_t			*mp_tail = NULL;
19513 
19514 	/*
19515 	 * Make a copy of the original message
19516 	 */
19517 	mp2ctl = copymsg(mpctl);
19518 
19519 	/* fixed length IPv6 structure ... */
19520 
19521 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19522 	optp->level = MIB2_IP6;
19523 	optp->name = 0;
19524 	/* Include "unknown interface" ip6_mib */
19525 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19526 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19527 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19528 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19529 	    ipst->ips_ipv6_forward ? 1 : 2);
19530 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19531 	    ipst->ips_ipv6_def_hops);
19532 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19533 	    sizeof (mib2_ipIfStatsEntry_t));
19534 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19535 	    sizeof (mib2_ipv6AddrEntry_t));
19536 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19537 	    sizeof (mib2_ipv6RouteEntry_t));
19538 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19539 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19540 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19541 	    sizeof (ipv6_member_t));
19542 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19543 	    sizeof (ipv6_grpsrc_t));
19544 
19545 	/*
19546 	 * Synchronize 64- and 32-bit counters
19547 	 */
19548 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19549 	    ipIfStatsHCInReceives);
19550 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19551 	    ipIfStatsHCInDelivers);
19552 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19553 	    ipIfStatsHCOutRequests);
19554 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19555 	    ipIfStatsHCOutForwDatagrams);
19556 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19557 	    ipIfStatsHCOutMcastPkts);
19558 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19559 	    ipIfStatsHCInMcastPkts);
19560 
19561 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19562 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19563 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19564 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19565 	}
19566 
19567 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19568 	ill = ILL_START_WALK_V6(&ctx, ipst);
19569 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19570 		ill->ill_ip_mib->ipIfStatsIfIndex =
19571 		    ill->ill_phyint->phyint_ifindex;
19572 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19573 		    ipst->ips_ipv6_forward ? 1 : 2);
19574 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19575 		    ill->ill_max_hops);
19576 
19577 		/*
19578 		 * Synchronize 64- and 32-bit counters
19579 		 */
19580 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19581 		    ipIfStatsHCInReceives);
19582 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19583 		    ipIfStatsHCInDelivers);
19584 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19585 		    ipIfStatsHCOutRequests);
19586 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19587 		    ipIfStatsHCOutForwDatagrams);
19588 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19589 		    ipIfStatsHCOutMcastPkts);
19590 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19591 		    ipIfStatsHCInMcastPkts);
19592 
19593 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19594 		    (char *)ill->ill_ip_mib,
19595 		    (int)sizeof (*ill->ill_ip_mib))) {
19596 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19597 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19598 		}
19599 	}
19600 	rw_exit(&ipst->ips_ill_g_lock);
19601 
19602 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19603 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19604 	    (int)optp->level, (int)optp->name, (int)optp->len));
19605 	qreply(q, mpctl);
19606 	return (mp2ctl);
19607 }
19608 
19609 /*
19610  * ICMPv6 mib: One per ill
19611  */
19612 static mblk_t *
19613 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19614 {
19615 	struct opthdr		*optp;
19616 	mblk_t			*mp2ctl;
19617 	ill_t			*ill;
19618 	ill_walk_context_t	ctx;
19619 	mblk_t			*mp_tail = NULL;
19620 	/*
19621 	 * Make a copy of the original message
19622 	 */
19623 	mp2ctl = copymsg(mpctl);
19624 
19625 	/* fixed length ICMPv6 structure ... */
19626 
19627 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19628 	optp->level = MIB2_ICMP6;
19629 	optp->name = 0;
19630 	/* Include "unknown interface" icmp6_mib */
19631 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19632 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19633 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19634 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19635 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19636 	    (char *)&ipst->ips_icmp6_mib,
19637 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19638 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19639 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19640 	}
19641 
19642 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19643 	ill = ILL_START_WALK_V6(&ctx, ipst);
19644 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19645 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19646 		    ill->ill_phyint->phyint_ifindex;
19647 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19648 		    (char *)ill->ill_icmp6_mib,
19649 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19650 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19651 			    "%u bytes\n",
19652 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19653 		}
19654 	}
19655 	rw_exit(&ipst->ips_ill_g_lock);
19656 
19657 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19658 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19659 	    (int)optp->level, (int)optp->name, (int)optp->len));
19660 	qreply(q, mpctl);
19661 	return (mp2ctl);
19662 }
19663 
19664 /*
19665  * ire_walk routine to create both ipRouteEntryTable and
19666  * ipRouteAttributeTable in one IRE walk
19667  */
19668 static void
19669 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19670 {
19671 	ill_t				*ill;
19672 	ipif_t				*ipif;
19673 	mib2_ipRouteEntry_t		*re;
19674 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19675 	ipaddr_t			gw_addr;
19676 	tsol_ire_gw_secattr_t		*attrp;
19677 	tsol_gc_t			*gc = NULL;
19678 	tsol_gcgrp_t			*gcgrp = NULL;
19679 	uint_t				sacnt = 0;
19680 	int				i;
19681 
19682 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19683 
19684 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19685 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19686 		return;
19687 	}
19688 
19689 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19690 		return;
19691 
19692 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19693 		mutex_enter(&attrp->igsa_lock);
19694 		if ((gc = attrp->igsa_gc) != NULL) {
19695 			gcgrp = gc->gc_grp;
19696 			ASSERT(gcgrp != NULL);
19697 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19698 			sacnt = 1;
19699 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19700 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19701 			gc = gcgrp->gcgrp_head;
19702 			sacnt = gcgrp->gcgrp_count;
19703 		}
19704 		mutex_exit(&attrp->igsa_lock);
19705 
19706 		/* do nothing if there's no gc to report */
19707 		if (gc == NULL) {
19708 			ASSERT(sacnt == 0);
19709 			if (gcgrp != NULL) {
19710 				/* we might as well drop the lock now */
19711 				rw_exit(&gcgrp->gcgrp_rwlock);
19712 				gcgrp = NULL;
19713 			}
19714 			attrp = NULL;
19715 		}
19716 
19717 		ASSERT(gc == NULL || (gcgrp != NULL &&
19718 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19719 	}
19720 	ASSERT(sacnt == 0 || gc != NULL);
19721 
19722 	if (sacnt != 0 &&
19723 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19724 		kmem_free(re, sizeof (*re));
19725 		rw_exit(&gcgrp->gcgrp_rwlock);
19726 		return;
19727 	}
19728 
19729 	/*
19730 	 * Return all IRE types for route table... let caller pick and choose
19731 	 */
19732 	re->ipRouteDest = ire->ire_addr;
19733 	ipif = ire->ire_ipif;
19734 	re->ipRouteIfIndex.o_length = 0;
19735 	if (ire->ire_type == IRE_CACHE) {
19736 		ill = (ill_t *)ire->ire_stq->q_ptr;
19737 		re->ipRouteIfIndex.o_length =
19738 		    ill->ill_name_length == 0 ? 0 :
19739 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19740 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19741 		    re->ipRouteIfIndex.o_length);
19742 	} else if (ipif != NULL) {
19743 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19744 		re->ipRouteIfIndex.o_length =
19745 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19746 	}
19747 	re->ipRouteMetric1 = -1;
19748 	re->ipRouteMetric2 = -1;
19749 	re->ipRouteMetric3 = -1;
19750 	re->ipRouteMetric4 = -1;
19751 
19752 	gw_addr = ire->ire_gateway_addr;
19753 
19754 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19755 		re->ipRouteNextHop = ire->ire_src_addr;
19756 	else
19757 		re->ipRouteNextHop = gw_addr;
19758 	/* indirect(4), direct(3), or invalid(2) */
19759 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19760 		re->ipRouteType = 2;
19761 	else
19762 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19763 	re->ipRouteProto = -1;
19764 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19765 	re->ipRouteMask = ire->ire_mask;
19766 	re->ipRouteMetric5 = -1;
19767 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19768 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19769 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19770 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19771 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19772 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19773 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19774 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19775 
19776 	if (ire->ire_flags & RTF_DYNAMIC) {
19777 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19778 	} else {
19779 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19780 	}
19781 
19782 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19783 	    (char *)re, (int)sizeof (*re))) {
19784 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19785 		    (uint_t)sizeof (*re)));
19786 	}
19787 
19788 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19789 		iaeptr->iae_routeidx = ird->ird_idx;
19790 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19791 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19792 	}
19793 
19794 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19795 	    (char *)iae, sacnt * sizeof (*iae))) {
19796 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19797 		    (unsigned)(sacnt * sizeof (*iae))));
19798 	}
19799 
19800 	/* bump route index for next pass */
19801 	ird->ird_idx++;
19802 
19803 	kmem_free(re, sizeof (*re));
19804 	if (sacnt != 0)
19805 		kmem_free(iae, sacnt * sizeof (*iae));
19806 
19807 	if (gcgrp != NULL)
19808 		rw_exit(&gcgrp->gcgrp_rwlock);
19809 }
19810 
19811 /*
19812  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19813  */
19814 static void
19815 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19816 {
19817 	ill_t				*ill;
19818 	ipif_t				*ipif;
19819 	mib2_ipv6RouteEntry_t		*re;
19820 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19821 	in6_addr_t			gw_addr_v6;
19822 	tsol_ire_gw_secattr_t		*attrp;
19823 	tsol_gc_t			*gc = NULL;
19824 	tsol_gcgrp_t			*gcgrp = NULL;
19825 	uint_t				sacnt = 0;
19826 	int				i;
19827 
19828 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19829 
19830 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19831 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19832 		return;
19833 	}
19834 
19835 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19836 		return;
19837 
19838 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19839 		mutex_enter(&attrp->igsa_lock);
19840 		if ((gc = attrp->igsa_gc) != NULL) {
19841 			gcgrp = gc->gc_grp;
19842 			ASSERT(gcgrp != NULL);
19843 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19844 			sacnt = 1;
19845 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19846 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19847 			gc = gcgrp->gcgrp_head;
19848 			sacnt = gcgrp->gcgrp_count;
19849 		}
19850 		mutex_exit(&attrp->igsa_lock);
19851 
19852 		/* do nothing if there's no gc to report */
19853 		if (gc == NULL) {
19854 			ASSERT(sacnt == 0);
19855 			if (gcgrp != NULL) {
19856 				/* we might as well drop the lock now */
19857 				rw_exit(&gcgrp->gcgrp_rwlock);
19858 				gcgrp = NULL;
19859 			}
19860 			attrp = NULL;
19861 		}
19862 
19863 		ASSERT(gc == NULL || (gcgrp != NULL &&
19864 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19865 	}
19866 	ASSERT(sacnt == 0 || gc != NULL);
19867 
19868 	if (sacnt != 0 &&
19869 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19870 		kmem_free(re, sizeof (*re));
19871 		rw_exit(&gcgrp->gcgrp_rwlock);
19872 		return;
19873 	}
19874 
19875 	/*
19876 	 * Return all IRE types for route table... let caller pick and choose
19877 	 */
19878 	re->ipv6RouteDest = ire->ire_addr_v6;
19879 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19880 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19881 	re->ipv6RouteIfIndex.o_length = 0;
19882 	ipif = ire->ire_ipif;
19883 	if (ire->ire_type == IRE_CACHE) {
19884 		ill = (ill_t *)ire->ire_stq->q_ptr;
19885 		re->ipv6RouteIfIndex.o_length =
19886 		    ill->ill_name_length == 0 ? 0 :
19887 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19888 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19889 		    re->ipv6RouteIfIndex.o_length);
19890 	} else if (ipif != NULL) {
19891 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19892 		re->ipv6RouteIfIndex.o_length =
19893 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19894 	}
19895 
19896 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19897 
19898 	mutex_enter(&ire->ire_lock);
19899 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19900 	mutex_exit(&ire->ire_lock);
19901 
19902 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19903 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19904 	else
19905 		re->ipv6RouteNextHop = gw_addr_v6;
19906 
19907 	/* remote(4), local(3), or discard(2) */
19908 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19909 		re->ipv6RouteType = 2;
19910 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19911 		re->ipv6RouteType = 3;
19912 	else
19913 		re->ipv6RouteType = 4;
19914 
19915 	re->ipv6RouteProtocol	= -1;
19916 	re->ipv6RoutePolicy	= 0;
19917 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19918 	re->ipv6RouteNextHopRDI	= 0;
19919 	re->ipv6RouteWeight	= 0;
19920 	re->ipv6RouteMetric	= 0;
19921 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19922 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19923 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19924 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19925 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19926 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19927 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19928 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19929 
19930 	if (ire->ire_flags & RTF_DYNAMIC) {
19931 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19932 	} else {
19933 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19934 	}
19935 
19936 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19937 	    (char *)re, (int)sizeof (*re))) {
19938 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19939 		    (uint_t)sizeof (*re)));
19940 	}
19941 
19942 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19943 		iaeptr->iae_routeidx = ird->ird_idx;
19944 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19945 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19946 	}
19947 
19948 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19949 	    (char *)iae, sacnt * sizeof (*iae))) {
19950 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19951 		    (unsigned)(sacnt * sizeof (*iae))));
19952 	}
19953 
19954 	/* bump route index for next pass */
19955 	ird->ird_idx++;
19956 
19957 	kmem_free(re, sizeof (*re));
19958 	if (sacnt != 0)
19959 		kmem_free(iae, sacnt * sizeof (*iae));
19960 
19961 	if (gcgrp != NULL)
19962 		rw_exit(&gcgrp->gcgrp_rwlock);
19963 }
19964 
19965 /*
19966  * ndp_walk routine to create ipv6NetToMediaEntryTable
19967  */
19968 static int
19969 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19970 {
19971 	ill_t				*ill;
19972 	mib2_ipv6NetToMediaEntry_t	ntme;
19973 	dl_unitdata_req_t		*dl;
19974 
19975 	ill = nce->nce_ill;
19976 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19977 		return (0);
19978 
19979 	/*
19980 	 * Neighbor cache entry attached to IRE with on-link
19981 	 * destination.
19982 	 */
19983 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19984 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19985 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19986 	    (nce->nce_res_mp != NULL)) {
19987 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19988 		ntme.ipv6NetToMediaPhysAddress.o_length =
19989 		    dl->dl_dest_addr_length;
19990 	} else {
19991 		ntme.ipv6NetToMediaPhysAddress.o_length =
19992 		    ill->ill_phys_addr_length;
19993 	}
19994 	if (nce->nce_res_mp != NULL) {
19995 		bcopy((char *)nce->nce_res_mp->b_rptr +
19996 		    NCE_LL_ADDR_OFFSET(ill),
19997 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19998 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19999 	} else {
20000 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
20001 		    ill->ill_phys_addr_length);
20002 	}
20003 	/*
20004 	 * Note: Returns ND_* states. Should be:
20005 	 * reachable(1), stale(2), delay(3), probe(4),
20006 	 * invalid(5), unknown(6)
20007 	 */
20008 	ntme.ipv6NetToMediaState = nce->nce_state;
20009 	ntme.ipv6NetToMediaLastUpdated = 0;
20010 
20011 	/* other(1), dynamic(2), static(3), local(4) */
20012 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
20013 		ntme.ipv6NetToMediaType = 4;
20014 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
20015 		ntme.ipv6NetToMediaType = 1;
20016 	} else {
20017 		ntme.ipv6NetToMediaType = 2;
20018 	}
20019 
20020 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
20021 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
20022 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
20023 		    (uint_t)sizeof (ntme)));
20024 	}
20025 	return (0);
20026 }
20027 
20028 /*
20029  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
20030  */
20031 /* ARGSUSED */
20032 int
20033 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
20034 {
20035 	switch (level) {
20036 	case MIB2_IP:
20037 	case MIB2_ICMP:
20038 		switch (name) {
20039 		default:
20040 			break;
20041 		}
20042 		return (1);
20043 	default:
20044 		return (1);
20045 	}
20046 }
20047 
20048 /*
20049  * When there exists both a 64- and 32-bit counter of a particular type
20050  * (i.e., InReceives), only the 64-bit counters are added.
20051  */
20052 void
20053 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
20054 {
20055 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
20056 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
20057 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
20058 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
20059 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
20060 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
20061 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
20062 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
20063 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
20064 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
20065 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
20066 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
20067 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
20068 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
20069 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20070 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20071 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20072 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20073 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20074 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20075 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20076 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20077 	    o2->ipIfStatsInWrongIPVersion);
20078 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20079 	    o2->ipIfStatsInWrongIPVersion);
20080 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20081 	    o2->ipIfStatsOutSwitchIPVersion);
20082 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20083 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20084 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20085 	    o2->ipIfStatsHCInForwDatagrams);
20086 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20087 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20088 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20089 	    o2->ipIfStatsHCOutForwDatagrams);
20090 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20091 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20092 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20093 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20094 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20095 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20096 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20097 	    o2->ipIfStatsHCOutMcastOctets);
20098 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20099 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20100 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20101 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20102 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20103 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20104 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20105 }
20106 
20107 void
20108 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20109 {
20110 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20111 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20112 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20113 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20114 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20115 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20116 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20117 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20118 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20119 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20120 	    o2->ipv6IfIcmpInRouterSolicits);
20121 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20122 	    o2->ipv6IfIcmpInRouterAdvertisements);
20123 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20124 	    o2->ipv6IfIcmpInNeighborSolicits);
20125 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20126 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20127 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20128 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20129 	    o2->ipv6IfIcmpInGroupMembQueries);
20130 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20131 	    o2->ipv6IfIcmpInGroupMembResponses);
20132 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20133 	    o2->ipv6IfIcmpInGroupMembReductions);
20134 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20135 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20136 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20137 	    o2->ipv6IfIcmpOutDestUnreachs);
20138 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20139 	    o2->ipv6IfIcmpOutAdminProhibs);
20140 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20141 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20142 	    o2->ipv6IfIcmpOutParmProblems);
20143 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20144 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20145 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20146 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20147 	    o2->ipv6IfIcmpOutRouterSolicits);
20148 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20149 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20150 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20151 	    o2->ipv6IfIcmpOutNeighborSolicits);
20152 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20153 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20154 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20155 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20156 	    o2->ipv6IfIcmpOutGroupMembQueries);
20157 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20158 	    o2->ipv6IfIcmpOutGroupMembResponses);
20159 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20160 	    o2->ipv6IfIcmpOutGroupMembReductions);
20161 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20162 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20163 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20164 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20165 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20166 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20167 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20168 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20169 	    o2->ipv6IfIcmpInGroupMembTotal);
20170 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20171 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20172 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20173 	    o2->ipv6IfIcmpInGroupMembBadReports);
20174 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20175 	    o2->ipv6IfIcmpInGroupMembOurReports);
20176 }
20177 
20178 /*
20179  * Called before the options are updated to check if this packet will
20180  * be source routed from here.
20181  * This routine assumes that the options are well formed i.e. that they
20182  * have already been checked.
20183  */
20184 static boolean_t
20185 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20186 {
20187 	ipoptp_t	opts;
20188 	uchar_t		*opt;
20189 	uint8_t		optval;
20190 	uint8_t		optlen;
20191 	ipaddr_t	dst;
20192 	ire_t		*ire;
20193 
20194 	if (IS_SIMPLE_IPH(ipha)) {
20195 		ip2dbg(("not source routed\n"));
20196 		return (B_FALSE);
20197 	}
20198 	dst = ipha->ipha_dst;
20199 	for (optval = ipoptp_first(&opts, ipha);
20200 	    optval != IPOPT_EOL;
20201 	    optval = ipoptp_next(&opts)) {
20202 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20203 		opt = opts.ipoptp_cur;
20204 		optlen = opts.ipoptp_len;
20205 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20206 		    optval, optlen));
20207 		switch (optval) {
20208 			uint32_t off;
20209 		case IPOPT_SSRR:
20210 		case IPOPT_LSRR:
20211 			/*
20212 			 * If dst is one of our addresses and there are some
20213 			 * entries left in the source route return (true).
20214 			 */
20215 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20216 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20217 			if (ire == NULL) {
20218 				ip2dbg(("ip_source_routed: not next"
20219 				    " source route 0x%x\n",
20220 				    ntohl(dst)));
20221 				return (B_FALSE);
20222 			}
20223 			ire_refrele(ire);
20224 			off = opt[IPOPT_OFFSET];
20225 			off--;
20226 			if (optlen < IP_ADDR_LEN ||
20227 			    off > optlen - IP_ADDR_LEN) {
20228 				/* End of source route */
20229 				ip1dbg(("ip_source_routed: end of SR\n"));
20230 				return (B_FALSE);
20231 			}
20232 			return (B_TRUE);
20233 		}
20234 	}
20235 	ip2dbg(("not source routed\n"));
20236 	return (B_FALSE);
20237 }
20238 
20239 /*
20240  * Check if the packet contains any source route.
20241  */
20242 static boolean_t
20243 ip_source_route_included(ipha_t *ipha)
20244 {
20245 	ipoptp_t	opts;
20246 	uint8_t		optval;
20247 
20248 	if (IS_SIMPLE_IPH(ipha))
20249 		return (B_FALSE);
20250 	for (optval = ipoptp_first(&opts, ipha);
20251 	    optval != IPOPT_EOL;
20252 	    optval = ipoptp_next(&opts)) {
20253 		switch (optval) {
20254 		case IPOPT_SSRR:
20255 		case IPOPT_LSRR:
20256 			return (B_TRUE);
20257 		}
20258 	}
20259 	return (B_FALSE);
20260 }
20261 
20262 /*
20263  * Called when the IRE expiration timer fires.
20264  */
20265 void
20266 ip_trash_timer_expire(void *args)
20267 {
20268 	int			flush_flag = 0;
20269 	ire_expire_arg_t	iea;
20270 	ip_stack_t		*ipst = (ip_stack_t *)args;
20271 
20272 	iea.iea_ipst = ipst;	/* No netstack_hold */
20273 
20274 	/*
20275 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20276 	 * This lock makes sure that a new invocation of this function
20277 	 * that occurs due to an almost immediate timer firing will not
20278 	 * progress beyond this point until the current invocation is done
20279 	 */
20280 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20281 	ipst->ips_ip_ire_expire_id = 0;
20282 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20283 
20284 	/* Periodic timer */
20285 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20286 	    ipst->ips_ip_ire_arp_interval) {
20287 		/*
20288 		 * Remove all IRE_CACHE entries since they might
20289 		 * contain arp information.
20290 		 */
20291 		flush_flag |= FLUSH_ARP_TIME;
20292 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20293 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20294 	}
20295 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20296 	    ipst->ips_ip_ire_redir_interval) {
20297 		/* Remove all redirects */
20298 		flush_flag |= FLUSH_REDIRECT_TIME;
20299 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20300 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20301 	}
20302 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20303 	    ipst->ips_ip_ire_pathmtu_interval) {
20304 		/* Increase path mtu */
20305 		flush_flag |= FLUSH_MTU_TIME;
20306 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20307 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20308 	}
20309 
20310 	/*
20311 	 * Optimize for the case when there are no redirects in the
20312 	 * ftable, that is, no need to walk the ftable in that case.
20313 	 */
20314 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20315 		iea.iea_flush_flag = flush_flag;
20316 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20317 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20318 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20319 		    NULL, ALL_ZONES, ipst);
20320 	}
20321 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20322 	    ipst->ips_ip_redirect_cnt > 0) {
20323 		iea.iea_flush_flag = flush_flag;
20324 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20325 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20326 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20327 	}
20328 	if (flush_flag & FLUSH_MTU_TIME) {
20329 		/*
20330 		 * Walk all IPv6 IRE's and update them
20331 		 * Note that ARP and redirect timers are not
20332 		 * needed since NUD handles stale entries.
20333 		 */
20334 		flush_flag = FLUSH_MTU_TIME;
20335 		iea.iea_flush_flag = flush_flag;
20336 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20337 		    ALL_ZONES, ipst);
20338 	}
20339 
20340 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20341 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20342 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20343 
20344 	/*
20345 	 * Hold the lock to serialize timeout calls and prevent
20346 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20347 	 * for the timer to fire and a new invocation of this function
20348 	 * to start before the return value of timeout has been stored
20349 	 * in ip_ire_expire_id by the current invocation.
20350 	 */
20351 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20352 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20353 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20354 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20355 }
20356 
20357 /*
20358  * Called by the memory allocator subsystem directly, when the system
20359  * is running low on memory.
20360  */
20361 /* ARGSUSED */
20362 void
20363 ip_trash_ire_reclaim(void *args)
20364 {
20365 	netstack_handle_t nh;
20366 	netstack_t *ns;
20367 
20368 	netstack_next_init(&nh);
20369 	while ((ns = netstack_next(&nh)) != NULL) {
20370 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20371 		netstack_rele(ns);
20372 	}
20373 	netstack_next_fini(&nh);
20374 }
20375 
20376 static void
20377 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20378 {
20379 	ire_cache_count_t icc;
20380 	ire_cache_reclaim_t icr;
20381 	ncc_cache_count_t ncc;
20382 	nce_cache_reclaim_t ncr;
20383 	uint_t delete_cnt;
20384 	/*
20385 	 * Memory reclaim call back.
20386 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20387 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20388 	 * entries, determine what fraction to free for
20389 	 * each category of IRE_CACHE entries giving absolute priority
20390 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20391 	 * entry will be freed unless all offlink entries are freed).
20392 	 */
20393 	icc.icc_total = 0;
20394 	icc.icc_unused = 0;
20395 	icc.icc_offlink = 0;
20396 	icc.icc_pmtu = 0;
20397 	icc.icc_onlink = 0;
20398 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20399 
20400 	/*
20401 	 * Free NCEs for IPv6 like the onlink ires.
20402 	 */
20403 	ncc.ncc_total = 0;
20404 	ncc.ncc_host = 0;
20405 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20406 
20407 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20408 	    icc.icc_pmtu + icc.icc_onlink);
20409 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20410 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20411 	if (delete_cnt == 0)
20412 		return;
20413 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20414 	/* Always delete all unused offlink entries */
20415 	icr.icr_ipst = ipst;
20416 	icr.icr_unused = 1;
20417 	if (delete_cnt <= icc.icc_unused) {
20418 		/*
20419 		 * Only need to free unused entries.  In other words,
20420 		 * there are enough unused entries to free to meet our
20421 		 * target number of freed ire cache entries.
20422 		 */
20423 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20424 		ncr.ncr_host = 0;
20425 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20426 		/*
20427 		 * Only need to free unused entries, plus a fraction of offlink
20428 		 * entries.  It follows from the first if statement that
20429 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20430 		 */
20431 		delete_cnt -= icc.icc_unused;
20432 		/* Round up # deleted by truncating fraction */
20433 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20434 		icr.icr_pmtu = icr.icr_onlink = 0;
20435 		ncr.ncr_host = 0;
20436 	} else if (delete_cnt <=
20437 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20438 		/*
20439 		 * Free all unused and offlink entries, plus a fraction of
20440 		 * pmtu entries.  It follows from the previous if statement
20441 		 * that icc_pmtu is non-zero, and that
20442 		 * delete_cnt != icc_unused + icc_offlink.
20443 		 */
20444 		icr.icr_offlink = 1;
20445 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20446 		/* Round up # deleted by truncating fraction */
20447 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20448 		icr.icr_onlink = 0;
20449 		ncr.ncr_host = 0;
20450 	} else {
20451 		/*
20452 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20453 		 * of onlink entries.  If we're here, then we know that
20454 		 * icc_onlink is non-zero, and that
20455 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20456 		 */
20457 		icr.icr_offlink = icr.icr_pmtu = 1;
20458 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20459 		    icc.icc_pmtu;
20460 		/* Round up # deleted by truncating fraction */
20461 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20462 		/* Using the same delete fraction as for onlink IREs */
20463 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20464 	}
20465 #ifdef DEBUG
20466 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20467 	    "fractions %d/%d/%d/%d\n",
20468 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20469 	    icc.icc_unused, icc.icc_offlink,
20470 	    icc.icc_pmtu, icc.icc_onlink,
20471 	    icr.icr_unused, icr.icr_offlink,
20472 	    icr.icr_pmtu, icr.icr_onlink));
20473 #endif
20474 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20475 	if (ncr.ncr_host != 0)
20476 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20477 		    (uchar_t *)&ncr, ipst);
20478 #ifdef DEBUG
20479 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20480 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20481 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20482 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20483 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20484 	    icc.icc_pmtu, icc.icc_onlink));
20485 #endif
20486 }
20487 
20488 /*
20489  * ip_unbind is called when a copy of an unbind request is received from the
20490  * upper level protocol.  We remove this conn from any fanout hash list it is
20491  * on, and zero out the bind information.  No reply is expected up above.
20492  */
20493 void
20494 ip_unbind(conn_t *connp)
20495 {
20496 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20497 
20498 	if (is_system_labeled() && connp->conn_anon_port) {
20499 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20500 		    connp->conn_mlp_type, connp->conn_ulp,
20501 		    ntohs(connp->conn_lport), B_FALSE);
20502 		connp->conn_anon_port = 0;
20503 	}
20504 	connp->conn_mlp_type = mlptSingle;
20505 
20506 	ipcl_hash_remove(connp);
20507 
20508 }
20509 
20510 /*
20511  * Write side put procedure.  Outbound data, IOCTLs, responses from
20512  * resolvers, etc, come down through here.
20513  *
20514  * arg2 is always a queue_t *.
20515  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20516  * the zoneid.
20517  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20518  */
20519 void
20520 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20521 {
20522 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20523 }
20524 
20525 void
20526 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20527     ip_opt_info_t *infop)
20528 {
20529 	conn_t		*connp = NULL;
20530 	queue_t		*q = (queue_t *)arg2;
20531 	ipha_t		*ipha;
20532 #define	rptr	((uchar_t *)ipha)
20533 	ire_t		*ire = NULL;
20534 	ire_t		*sctp_ire = NULL;
20535 	uint32_t	v_hlen_tos_len;
20536 	ipaddr_t	dst;
20537 	mblk_t		*first_mp = NULL;
20538 	boolean_t	mctl_present;
20539 	ipsec_out_t	*io;
20540 	int		match_flags;
20541 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20542 	ipif_t		*dst_ipif;
20543 	boolean_t	multirt_need_resolve = B_FALSE;
20544 	mblk_t		*copy_mp = NULL;
20545 	int		err = 0;
20546 	zoneid_t	zoneid;
20547 	boolean_t	need_decref = B_FALSE;
20548 	boolean_t	ignore_dontroute = B_FALSE;
20549 	boolean_t	ignore_nexthop = B_FALSE;
20550 	boolean_t	ip_nexthop = B_FALSE;
20551 	ipaddr_t	nexthop_addr;
20552 	ip_stack_t	*ipst;
20553 
20554 #ifdef	_BIG_ENDIAN
20555 #define	V_HLEN	(v_hlen_tos_len >> 24)
20556 #else
20557 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20558 #endif
20559 
20560 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20561 	    "ip_wput_start: q %p", q);
20562 
20563 	/*
20564 	 * ip_wput fast path
20565 	 */
20566 
20567 	/* is packet from ARP ? */
20568 	if (q->q_next != NULL) {
20569 		zoneid = (zoneid_t)(uintptr_t)arg;
20570 		goto qnext;
20571 	}
20572 
20573 	connp = (conn_t *)arg;
20574 	ASSERT(connp != NULL);
20575 	zoneid = connp->conn_zoneid;
20576 	ipst = connp->conn_netstack->netstack_ip;
20577 	ASSERT(ipst != NULL);
20578 
20579 	/* is queue flow controlled? */
20580 	if ((q->q_first != NULL || connp->conn_draining) &&
20581 	    (caller == IP_WPUT)) {
20582 		ASSERT(!need_decref);
20583 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20584 		(void) putq(q, mp);
20585 		return;
20586 	}
20587 
20588 	/* Multidata transmit? */
20589 	if (DB_TYPE(mp) == M_MULTIDATA) {
20590 		/*
20591 		 * We should never get here, since all Multidata messages
20592 		 * originating from tcp should have been directed over to
20593 		 * tcp_multisend() in the first place.
20594 		 */
20595 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20596 		freemsg(mp);
20597 		return;
20598 	} else if (DB_TYPE(mp) != M_DATA)
20599 		goto notdata;
20600 
20601 	if (mp->b_flag & MSGHASREF) {
20602 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20603 		mp->b_flag &= ~MSGHASREF;
20604 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20605 		need_decref = B_TRUE;
20606 	}
20607 	ipha = (ipha_t *)mp->b_rptr;
20608 
20609 	/* is IP header non-aligned or mblk smaller than basic IP header */
20610 #ifndef SAFETY_BEFORE_SPEED
20611 	if (!OK_32PTR(rptr) ||
20612 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20613 		goto hdrtoosmall;
20614 #endif
20615 
20616 	ASSERT(OK_32PTR(ipha));
20617 
20618 	/*
20619 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20620 	 * wrong version, we'll catch it again in ip_output_v6.
20621 	 *
20622 	 * Note that this is *only* locally-generated output here, and never
20623 	 * forwarded data, and that we need to deal only with transports that
20624 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20625 	 * label.)
20626 	 */
20627 	if (is_system_labeled() &&
20628 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20629 	    !connp->conn_ulp_labeled) {
20630 		cred_t	*credp;
20631 		pid_t	pid;
20632 
20633 		credp = BEST_CRED(mp, connp, &pid);
20634 		err = tsol_check_label(credp, &mp,
20635 		    connp->conn_mac_exempt, ipst, pid);
20636 		ipha = (ipha_t *)mp->b_rptr;
20637 		if (err != 0) {
20638 			first_mp = mp;
20639 			if (err == EINVAL)
20640 				goto icmp_parameter_problem;
20641 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20642 			goto discard_pkt;
20643 		}
20644 	}
20645 
20646 	ASSERT(infop != NULL);
20647 
20648 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20649 		/*
20650 		 * IP_PKTINFO ancillary option is present.
20651 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20652 		 * allows using address of any zone as the source address.
20653 		 */
20654 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20655 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20656 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20657 		if (ire == NULL)
20658 			goto drop_pkt;
20659 		ire_refrele(ire);
20660 		ire = NULL;
20661 	}
20662 
20663 	/*
20664 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20665 	 */
20666 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20667 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20668 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20669 
20670 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20671 			goto drop_pkt;
20672 		/*
20673 		 * check that there is an ipif belonging
20674 		 * to our zone. IPCL_ZONEID is not used because
20675 		 * IP_ALLZONES option is valid only when the ill is
20676 		 * accessible from all zones i.e has a valid ipif in
20677 		 * all zones.
20678 		 */
20679 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20680 			goto drop_pkt;
20681 		}
20682 	}
20683 
20684 	/*
20685 	 * If there is a policy, try to attach an ipsec_out in
20686 	 * the front. At the end, first_mp either points to a
20687 	 * M_DATA message or IPSEC_OUT message linked to a
20688 	 * M_DATA message. We have to do it now as we might
20689 	 * lose the "conn" if we go through ip_newroute.
20690 	 */
20691 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20692 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20693 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20694 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20695 			if (need_decref)
20696 				CONN_DEC_REF(connp);
20697 			return;
20698 		} else {
20699 			ASSERT(mp->b_datap->db_type == M_CTL);
20700 			first_mp = mp;
20701 			mp = mp->b_cont;
20702 			mctl_present = B_TRUE;
20703 		}
20704 	} else {
20705 		first_mp = mp;
20706 		mctl_present = B_FALSE;
20707 	}
20708 
20709 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20710 
20711 	/* is wrong version or IP options present */
20712 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20713 		goto version_hdrlen_check;
20714 	dst = ipha->ipha_dst;
20715 
20716 	/* If IP_BOUND_IF has been set, use that ill. */
20717 	if (connp->conn_outgoing_ill != NULL) {
20718 		xmit_ill = conn_get_held_ill(connp,
20719 		    &connp->conn_outgoing_ill, &err);
20720 		if (err == ILL_LOOKUP_FAILED)
20721 			goto drop_pkt;
20722 
20723 		goto send_from_ill;
20724 	}
20725 
20726 	/* is packet multicast? */
20727 	if (CLASSD(dst))
20728 		goto multicast;
20729 
20730 	/*
20731 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20732 	 * takes precedence over conn_dontroute and conn_nexthop_set
20733 	 */
20734 	if (xmit_ill != NULL)
20735 		goto send_from_ill;
20736 
20737 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20738 		/*
20739 		 * If the destination is a broadcast, local, or loopback
20740 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20741 		 * standard path.
20742 		 */
20743 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20744 		if ((ire == NULL) || (ire->ire_type &
20745 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20746 			if (ire != NULL) {
20747 				ire_refrele(ire);
20748 				/* No more access to ire */
20749 				ire = NULL;
20750 			}
20751 			/*
20752 			 * bypass routing checks and go directly to interface.
20753 			 */
20754 			if (connp->conn_dontroute)
20755 				goto dontroute;
20756 
20757 			ASSERT(connp->conn_nexthop_set);
20758 			ip_nexthop = B_TRUE;
20759 			nexthop_addr = connp->conn_nexthop_v4;
20760 			goto send_from_ill;
20761 		}
20762 
20763 		/* Must be a broadcast, a loopback or a local ire */
20764 		ire_refrele(ire);
20765 		/* No more access to ire */
20766 		ire = NULL;
20767 	}
20768 
20769 	/*
20770 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20771 	 * this for the tcp global queue and listen end point
20772 	 * as it does not really have a real destination to
20773 	 * talk to.  This is also true for SCTP.
20774 	 */
20775 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20776 	    !connp->conn_fully_bound) {
20777 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20778 		if (ire == NULL)
20779 			goto noirefound;
20780 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20781 		    "ip_wput_end: q %p (%S)", q, "end");
20782 
20783 		/*
20784 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20785 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20786 		 */
20787 		if (ire->ire_flags & RTF_MULTIRT) {
20788 
20789 			/*
20790 			 * Force the TTL of multirouted packets if required.
20791 			 * The TTL of such packets is bounded by the
20792 			 * ip_multirt_ttl ndd variable.
20793 			 */
20794 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20795 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20796 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20797 				    "(was %d), dst 0x%08x\n",
20798 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20799 				    ntohl(ire->ire_addr)));
20800 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20801 			}
20802 			/*
20803 			 * We look at this point if there are pending
20804 			 * unresolved routes. ire_multirt_resolvable()
20805 			 * checks in O(n) that all IRE_OFFSUBNET ire
20806 			 * entries for the packet's destination and
20807 			 * flagged RTF_MULTIRT are currently resolved.
20808 			 * If some remain unresolved, we make a copy
20809 			 * of the current message. It will be used
20810 			 * to initiate additional route resolutions.
20811 			 */
20812 			multirt_need_resolve =
20813 			    ire_multirt_need_resolve(ire->ire_addr,
20814 			    msg_getlabel(first_mp), ipst);
20815 			ip2dbg(("ip_wput[TCP]: ire %p, "
20816 			    "multirt_need_resolve %d, first_mp %p\n",
20817 			    (void *)ire, multirt_need_resolve,
20818 			    (void *)first_mp));
20819 			if (multirt_need_resolve) {
20820 				copy_mp = copymsg(first_mp);
20821 				if (copy_mp != NULL) {
20822 					MULTIRT_DEBUG_TAG(copy_mp);
20823 				}
20824 			}
20825 		}
20826 
20827 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20828 
20829 		/*
20830 		 * Try to resolve another multiroute if
20831 		 * ire_multirt_need_resolve() deemed it necessary.
20832 		 */
20833 		if (copy_mp != NULL)
20834 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20835 		if (need_decref)
20836 			CONN_DEC_REF(connp);
20837 		return;
20838 	}
20839 
20840 	/*
20841 	 * Access to conn_ire_cache. (protected by conn_lock)
20842 	 *
20843 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20844 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20845 	 * send a packet or two with the IRE_CACHE that is going away.
20846 	 * Access to the ire requires an ire refhold on the ire prior to
20847 	 * its use since an interface unplumb thread may delete the cached
20848 	 * ire and release the refhold at any time.
20849 	 *
20850 	 * Caching an ire in the conn_ire_cache
20851 	 *
20852 	 * o Caching an ire pointer in the conn requires a strict check for
20853 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20854 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20855 	 * in the conn is done after making sure under the bucket lock that the
20856 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20857 	 * caching an ire after the unplumb thread has cleaned up the conn.
20858 	 * If the conn does not send a packet subsequently the unplumb thread
20859 	 * will be hanging waiting for the ire count to drop to zero.
20860 	 *
20861 	 * o We also need to atomically test for a null conn_ire_cache and
20862 	 * set the conn_ire_cache under the the protection of the conn_lock
20863 	 * to avoid races among concurrent threads trying to simultaneously
20864 	 * cache an ire in the conn_ire_cache.
20865 	 */
20866 	mutex_enter(&connp->conn_lock);
20867 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20868 
20869 	if (ire != NULL && ire->ire_addr == dst &&
20870 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20871 
20872 		IRE_REFHOLD(ire);
20873 		mutex_exit(&connp->conn_lock);
20874 
20875 	} else {
20876 		boolean_t cached = B_FALSE;
20877 		connp->conn_ire_cache = NULL;
20878 		mutex_exit(&connp->conn_lock);
20879 		/* Release the old ire */
20880 		if (ire != NULL && sctp_ire == NULL)
20881 			IRE_REFRELE_NOTR(ire);
20882 
20883 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20884 		if (ire == NULL)
20885 			goto noirefound;
20886 		IRE_REFHOLD_NOTR(ire);
20887 
20888 		mutex_enter(&connp->conn_lock);
20889 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20890 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20891 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20892 				if (connp->conn_ulp == IPPROTO_TCP)
20893 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20894 				connp->conn_ire_cache = ire;
20895 				cached = B_TRUE;
20896 			}
20897 			rw_exit(&ire->ire_bucket->irb_lock);
20898 		}
20899 		mutex_exit(&connp->conn_lock);
20900 
20901 		/*
20902 		 * We can continue to use the ire but since it was
20903 		 * not cached, we should drop the extra reference.
20904 		 */
20905 		if (!cached)
20906 			IRE_REFRELE_NOTR(ire);
20907 	}
20908 
20909 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20910 	    "ip_wput_end: q %p (%S)", q, "end");
20911 
20912 	/*
20913 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20914 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20915 	 */
20916 	if (ire->ire_flags & RTF_MULTIRT) {
20917 		/*
20918 		 * Force the TTL of multirouted packets if required.
20919 		 * The TTL of such packets is bounded by the
20920 		 * ip_multirt_ttl ndd variable.
20921 		 */
20922 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20923 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20924 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20925 			    "(was %d), dst 0x%08x\n",
20926 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20927 			    ntohl(ire->ire_addr)));
20928 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20929 		}
20930 
20931 		/*
20932 		 * At this point, we check to see if there are any pending
20933 		 * unresolved routes. ire_multirt_resolvable()
20934 		 * checks in O(n) that all IRE_OFFSUBNET ire
20935 		 * entries for the packet's destination and
20936 		 * flagged RTF_MULTIRT are currently resolved.
20937 		 * If some remain unresolved, we make a copy
20938 		 * of the current message. It will be used
20939 		 * to initiate additional route resolutions.
20940 		 */
20941 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20942 		    msg_getlabel(first_mp), ipst);
20943 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20944 		    "multirt_need_resolve %d, first_mp %p\n",
20945 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20946 		if (multirt_need_resolve) {
20947 			copy_mp = copymsg(first_mp);
20948 			if (copy_mp != NULL) {
20949 				MULTIRT_DEBUG_TAG(copy_mp);
20950 			}
20951 		}
20952 	}
20953 
20954 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20955 
20956 	/*
20957 	 * Try to resolve another multiroute if
20958 	 * ire_multirt_resolvable() deemed it necessary
20959 	 */
20960 	if (copy_mp != NULL)
20961 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20962 	if (need_decref)
20963 		CONN_DEC_REF(connp);
20964 	return;
20965 
20966 qnext:
20967 	/*
20968 	 * Upper Level Protocols pass down complete IP datagrams
20969 	 * as M_DATA messages.	Everything else is a sideshow.
20970 	 *
20971 	 * 1) We could be re-entering ip_wput because of ip_neworute
20972 	 *    in which case we could have a IPSEC_OUT message. We
20973 	 *    need to pass through ip_wput like other datagrams and
20974 	 *    hence cannot branch to ip_wput_nondata.
20975 	 *
20976 	 * 2) ARP, AH, ESP, and other clients who are on the module
20977 	 *    instance of IP stream, give us something to deal with.
20978 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20979 	 *
20980 	 * 3) ICMP replies also could come here.
20981 	 */
20982 	ipst = ILLQ_TO_IPST(q);
20983 
20984 	if (DB_TYPE(mp) != M_DATA) {
20985 notdata:
20986 		if (DB_TYPE(mp) == M_CTL) {
20987 			/*
20988 			 * M_CTL messages are used by ARP, AH and ESP to
20989 			 * communicate with IP. We deal with IPSEC_IN and
20990 			 * IPSEC_OUT here. ip_wput_nondata handles other
20991 			 * cases.
20992 			 */
20993 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20994 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20995 				first_mp = mp->b_cont;
20996 				first_mp->b_flag &= ~MSGHASREF;
20997 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20998 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20999 				CONN_DEC_REF(connp);
21000 				connp = NULL;
21001 			}
21002 			if (ii->ipsec_info_type == IPSEC_IN) {
21003 				/*
21004 				 * Either this message goes back to
21005 				 * IPsec for further processing or to
21006 				 * ULP after policy checks.
21007 				 */
21008 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
21009 				return;
21010 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
21011 				io = (ipsec_out_t *)ii;
21012 				if (io->ipsec_out_proc_begin) {
21013 					/*
21014 					 * IPsec processing has already started.
21015 					 * Complete it.
21016 					 * IPQoS notes: We don't care what is
21017 					 * in ipsec_out_ill_index since this
21018 					 * won't be processed for IPQoS policies
21019 					 * in ipsec_out_process.
21020 					 */
21021 					ipsec_out_process(q, mp, NULL,
21022 					    io->ipsec_out_ill_index);
21023 					return;
21024 				} else {
21025 					connp = (q->q_next != NULL) ?
21026 					    NULL : Q_TO_CONN(q);
21027 					first_mp = mp;
21028 					mp = mp->b_cont;
21029 					mctl_present = B_TRUE;
21030 				}
21031 				zoneid = io->ipsec_out_zoneid;
21032 				ASSERT(zoneid != ALL_ZONES);
21033 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
21034 				/*
21035 				 * It's an IPsec control message requesting
21036 				 * an SADB update to be sent to the IPsec
21037 				 * hardware acceleration capable ills.
21038 				 */
21039 				ipsec_ctl_t *ipsec_ctl =
21040 				    (ipsec_ctl_t *)mp->b_rptr;
21041 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
21042 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
21043 				mblk_t *cmp = mp->b_cont;
21044 
21045 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
21046 				ASSERT(cmp != NULL);
21047 
21048 				freeb(mp);
21049 				ill_ipsec_capab_send_all(satype, cmp, sa,
21050 				    ipst->ips_netstack);
21051 				return;
21052 			} else {
21053 				/*
21054 				 * This must be ARP or special TSOL signaling.
21055 				 */
21056 				ip_wput_nondata(NULL, q, mp, NULL);
21057 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21058 				    "ip_wput_end: q %p (%S)", q, "nondata");
21059 				return;
21060 			}
21061 		} else {
21062 			/*
21063 			 * This must be non-(ARP/AH/ESP) messages.
21064 			 */
21065 			ASSERT(!need_decref);
21066 			ip_wput_nondata(NULL, q, mp, NULL);
21067 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21068 			    "ip_wput_end: q %p (%S)", q, "nondata");
21069 			return;
21070 		}
21071 	} else {
21072 		first_mp = mp;
21073 		mctl_present = B_FALSE;
21074 	}
21075 
21076 	ASSERT(first_mp != NULL);
21077 
21078 	if (mctl_present) {
21079 		io = (ipsec_out_t *)first_mp->b_rptr;
21080 		if (io->ipsec_out_ip_nexthop) {
21081 			/*
21082 			 * We may have lost the conn context if we are
21083 			 * coming here from ip_newroute(). Copy the
21084 			 * nexthop information.
21085 			 */
21086 			ip_nexthop = B_TRUE;
21087 			nexthop_addr = io->ipsec_out_nexthop_addr;
21088 
21089 			ipha = (ipha_t *)mp->b_rptr;
21090 			dst = ipha->ipha_dst;
21091 			goto send_from_ill;
21092 		}
21093 	}
21094 
21095 	ASSERT(xmit_ill == NULL);
21096 
21097 	/* We have a complete IP datagram heading outbound. */
21098 	ipha = (ipha_t *)mp->b_rptr;
21099 
21100 #ifndef SPEED_BEFORE_SAFETY
21101 	/*
21102 	 * Make sure we have a full-word aligned message and that at least
21103 	 * a simple IP header is accessible in the first message.  If not,
21104 	 * try a pullup.  For labeled systems we need to always take this
21105 	 * path as M_CTLs are "notdata" but have trailing data to process.
21106 	 */
21107 	if (!OK_32PTR(rptr) ||
21108 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21109 hdrtoosmall:
21110 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21111 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21112 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21113 			if (first_mp == NULL)
21114 				first_mp = mp;
21115 			goto discard_pkt;
21116 		}
21117 
21118 		/* This function assumes that mp points to an IPv4 packet. */
21119 		if (is_system_labeled() &&
21120 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21121 		    (connp == NULL || !connp->conn_ulp_labeled)) {
21122 			cred_t	*credp;
21123 			pid_t	pid;
21124 
21125 			if (connp != NULL) {
21126 				credp = BEST_CRED(mp, connp, &pid);
21127 				err = tsol_check_label(credp, &mp,
21128 				    connp->conn_mac_exempt, ipst, pid);
21129 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
21130 				err = tsol_check_label(credp, &mp,
21131 				    B_FALSE, ipst, pid);
21132 			}
21133 			ipha = (ipha_t *)mp->b_rptr;
21134 			if (mctl_present)
21135 				first_mp->b_cont = mp;
21136 			else
21137 				first_mp = mp;
21138 			if (err != 0) {
21139 				if (err == EINVAL)
21140 					goto icmp_parameter_problem;
21141 				ip2dbg(("ip_wput: label check failed (%d)\n",
21142 				    err));
21143 				goto discard_pkt;
21144 			}
21145 		}
21146 
21147 		ipha = (ipha_t *)mp->b_rptr;
21148 		if (first_mp == NULL) {
21149 			ASSERT(xmit_ill == NULL);
21150 			/*
21151 			 * If we got here because of "goto hdrtoosmall"
21152 			 * We need to attach a IPSEC_OUT.
21153 			 */
21154 			if (connp->conn_out_enforce_policy) {
21155 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21156 				    NULL, ipha->ipha_protocol,
21157 				    ipst->ips_netstack)) == NULL)) {
21158 					BUMP_MIB(&ipst->ips_ip_mib,
21159 					    ipIfStatsOutDiscards);
21160 					if (need_decref)
21161 						CONN_DEC_REF(connp);
21162 					return;
21163 				} else {
21164 					ASSERT(mp->b_datap->db_type == M_CTL);
21165 					first_mp = mp;
21166 					mp = mp->b_cont;
21167 					mctl_present = B_TRUE;
21168 				}
21169 			} else {
21170 				first_mp = mp;
21171 				mctl_present = B_FALSE;
21172 			}
21173 		}
21174 	}
21175 #endif
21176 
21177 	/* Most of the code below is written for speed, not readability */
21178 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21179 
21180 	/*
21181 	 * If ip_newroute() fails, we're going to need a full
21182 	 * header for the icmp wraparound.
21183 	 */
21184 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21185 		uint_t	v_hlen;
21186 version_hdrlen_check:
21187 		ASSERT(first_mp != NULL);
21188 		v_hlen = V_HLEN;
21189 		/*
21190 		 * siphon off IPv6 packets coming down from transport
21191 		 * layer modules here.
21192 		 * Note: high-order bit carries NUD reachability confirmation
21193 		 */
21194 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21195 			/*
21196 			 * FIXME: assume that callers of ip_output* call
21197 			 * the right version?
21198 			 */
21199 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21200 			ASSERT(xmit_ill == NULL);
21201 			if (need_decref)
21202 				mp->b_flag |= MSGHASREF;
21203 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21204 			return;
21205 		}
21206 
21207 		if ((v_hlen >> 4) != IP_VERSION) {
21208 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21209 			    "ip_wput_end: q %p (%S)", q, "badvers");
21210 			goto discard_pkt;
21211 		}
21212 		/*
21213 		 * Is the header length at least 20 bytes?
21214 		 *
21215 		 * Are there enough bytes accessible in the header?  If
21216 		 * not, try a pullup.
21217 		 */
21218 		v_hlen &= 0xF;
21219 		v_hlen <<= 2;
21220 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21221 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21222 			    "ip_wput_end: q %p (%S)", q, "badlen");
21223 			goto discard_pkt;
21224 		}
21225 		if (v_hlen > (mp->b_wptr - rptr)) {
21226 			if (!pullupmsg(mp, v_hlen)) {
21227 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21228 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21229 				goto discard_pkt;
21230 			}
21231 			ipha = (ipha_t *)mp->b_rptr;
21232 		}
21233 		/*
21234 		 * Move first entry from any source route into ipha_dst and
21235 		 * verify the options
21236 		 */
21237 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21238 		    zoneid, ipst)) {
21239 			ASSERT(xmit_ill == NULL);
21240 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21241 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21242 			    "ip_wput_end: q %p (%S)", q, "badopts");
21243 			if (need_decref)
21244 				CONN_DEC_REF(connp);
21245 			return;
21246 		}
21247 	}
21248 	dst = ipha->ipha_dst;
21249 
21250 	/*
21251 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21252 	 * we have to run the packet through ip_newroute which will take
21253 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21254 	 * a resolver, or assigning a default gateway, etc.
21255 	 */
21256 	if (CLASSD(dst)) {
21257 		ipif_t	*ipif;
21258 		uint32_t setsrc = 0;
21259 
21260 multicast:
21261 		ASSERT(first_mp != NULL);
21262 		ip2dbg(("ip_wput: CLASSD\n"));
21263 		if (connp == NULL) {
21264 			/*
21265 			 * Use the first good ipif on the ill.
21266 			 * XXX Should this ever happen? (Appears
21267 			 * to show up with just ppp and no ethernet due
21268 			 * to in.rdisc.)
21269 			 * However, ire_send should be able to
21270 			 * call ip_wput_ire directly.
21271 			 *
21272 			 * XXX Also, this can happen for ICMP and other packets
21273 			 * with multicast source addresses.  Perhaps we should
21274 			 * fix things so that we drop the packet in question,
21275 			 * but for now, just run with it.
21276 			 */
21277 			ill_t *ill = (ill_t *)q->q_ptr;
21278 
21279 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21280 			if (ipif == NULL) {
21281 				if (need_decref)
21282 					CONN_DEC_REF(connp);
21283 				freemsg(first_mp);
21284 				return;
21285 			}
21286 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21287 			    ntohl(dst), ill->ill_name));
21288 		} else {
21289 			/*
21290 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21291 			 * and IP_MULTICAST_IF.  The block comment above this
21292 			 * function explains the locking mechanism used here.
21293 			 */
21294 			if (xmit_ill == NULL) {
21295 				xmit_ill = conn_get_held_ill(connp,
21296 				    &connp->conn_outgoing_ill, &err);
21297 				if (err == ILL_LOOKUP_FAILED) {
21298 					ip1dbg(("ip_wput: No ill for "
21299 					    "IP_BOUND_IF\n"));
21300 					BUMP_MIB(&ipst->ips_ip_mib,
21301 					    ipIfStatsOutNoRoutes);
21302 					goto drop_pkt;
21303 				}
21304 			}
21305 
21306 			if (xmit_ill == NULL) {
21307 				ipif = conn_get_held_ipif(connp,
21308 				    &connp->conn_multicast_ipif, &err);
21309 				if (err == IPIF_LOOKUP_FAILED) {
21310 					ip1dbg(("ip_wput: No ipif for "
21311 					    "multicast\n"));
21312 					BUMP_MIB(&ipst->ips_ip_mib,
21313 					    ipIfStatsOutNoRoutes);
21314 					goto drop_pkt;
21315 				}
21316 			}
21317 			if (xmit_ill != NULL) {
21318 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21319 				if (ipif == NULL) {
21320 					ip1dbg(("ip_wput: No ipif for "
21321 					    "xmit_ill\n"));
21322 					BUMP_MIB(&ipst->ips_ip_mib,
21323 					    ipIfStatsOutNoRoutes);
21324 					goto drop_pkt;
21325 				}
21326 			} else if (ipif == NULL || ipif->ipif_isv6) {
21327 				/*
21328 				 * We must do this ipif determination here
21329 				 * else we could pass through ip_newroute
21330 				 * and come back here without the conn context.
21331 				 *
21332 				 * Note: we do late binding i.e. we bind to
21333 				 * the interface when the first packet is sent.
21334 				 * For performance reasons we do not rebind on
21335 				 * each packet but keep the binding until the
21336 				 * next IP_MULTICAST_IF option.
21337 				 *
21338 				 * conn_multicast_{ipif,ill} are shared between
21339 				 * IPv4 and IPv6 and AF_INET6 sockets can
21340 				 * send both IPv4 and IPv6 packets. Hence
21341 				 * we have to check that "isv6" matches above.
21342 				 */
21343 				if (ipif != NULL)
21344 					ipif_refrele(ipif);
21345 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21346 				if (ipif == NULL) {
21347 					ip1dbg(("ip_wput: No ipif for "
21348 					    "multicast\n"));
21349 					BUMP_MIB(&ipst->ips_ip_mib,
21350 					    ipIfStatsOutNoRoutes);
21351 					goto drop_pkt;
21352 				}
21353 				err = conn_set_held_ipif(connp,
21354 				    &connp->conn_multicast_ipif, ipif);
21355 				if (err == IPIF_LOOKUP_FAILED) {
21356 					ipif_refrele(ipif);
21357 					ip1dbg(("ip_wput: No ipif for "
21358 					    "multicast\n"));
21359 					BUMP_MIB(&ipst->ips_ip_mib,
21360 					    ipIfStatsOutNoRoutes);
21361 					goto drop_pkt;
21362 				}
21363 			}
21364 		}
21365 		ASSERT(!ipif->ipif_isv6);
21366 		/*
21367 		 * As we may lose the conn by the time we reach ip_wput_ire,
21368 		 * we copy conn_multicast_loop and conn_dontroute on to an
21369 		 * ipsec_out. In case if this datagram goes out secure,
21370 		 * we need the ill_index also. Copy that also into the
21371 		 * ipsec_out.
21372 		 */
21373 		if (mctl_present) {
21374 			io = (ipsec_out_t *)first_mp->b_rptr;
21375 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21376 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21377 		} else {
21378 			ASSERT(mp == first_mp);
21379 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21380 			    BPRI_HI)) == NULL) {
21381 				ipif_refrele(ipif);
21382 				first_mp = mp;
21383 				goto discard_pkt;
21384 			}
21385 			first_mp->b_datap->db_type = M_CTL;
21386 			first_mp->b_wptr += sizeof (ipsec_info_t);
21387 			/* ipsec_out_secure is B_FALSE now */
21388 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21389 			io = (ipsec_out_t *)first_mp->b_rptr;
21390 			io->ipsec_out_type = IPSEC_OUT;
21391 			io->ipsec_out_len = sizeof (ipsec_out_t);
21392 			io->ipsec_out_use_global_policy = B_TRUE;
21393 			io->ipsec_out_ns = ipst->ips_netstack;
21394 			first_mp->b_cont = mp;
21395 			mctl_present = B_TRUE;
21396 		}
21397 
21398 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21399 		io->ipsec_out_ill_index =
21400 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21401 
21402 		if (connp != NULL) {
21403 			io->ipsec_out_multicast_loop =
21404 			    connp->conn_multicast_loop;
21405 			io->ipsec_out_dontroute = connp->conn_dontroute;
21406 			io->ipsec_out_zoneid = connp->conn_zoneid;
21407 		}
21408 		/*
21409 		 * If the application uses IP_MULTICAST_IF with
21410 		 * different logical addresses of the same ILL, we
21411 		 * need to make sure that the soruce address of
21412 		 * the packet matches the logical IP address used
21413 		 * in the option. We do it by initializing ipha_src
21414 		 * here. This should keep IPsec also happy as
21415 		 * when we return from IPsec processing, we don't
21416 		 * have to worry about getting the right address on
21417 		 * the packet. Thus it is sufficient to look for
21418 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21419 		 * MATCH_IRE_IPIF.
21420 		 *
21421 		 * NOTE : We need to do it for non-secure case also as
21422 		 * this might go out secure if there is a global policy
21423 		 * match in ip_wput_ire.
21424 		 *
21425 		 * As we do not have the ire yet, it is possible that
21426 		 * we set the source address here and then later discover
21427 		 * that the ire implies the source address to be assigned
21428 		 * through the RTF_SETSRC flag.
21429 		 * In that case, the setsrc variable will remind us
21430 		 * that overwritting the source address by the one
21431 		 * of the RTF_SETSRC-flagged ire is allowed.
21432 		 */
21433 		if (ipha->ipha_src == INADDR_ANY &&
21434 		    (connp == NULL || !connp->conn_unspec_src)) {
21435 			ipha->ipha_src = ipif->ipif_src_addr;
21436 			setsrc = RTF_SETSRC;
21437 		}
21438 		/*
21439 		 * Find an IRE which matches the destination and the outgoing
21440 		 * queue (i.e. the outgoing interface.)
21441 		 * For loopback use a unicast IP address for
21442 		 * the ire lookup.
21443 		 */
21444 		if (IS_LOOPBACK(ipif->ipif_ill))
21445 			dst = ipif->ipif_lcl_addr;
21446 
21447 		/*
21448 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21449 		 * We don't need to lookup ire in ctable as the packet
21450 		 * needs to be sent to the destination through the specified
21451 		 * ill irrespective of ires in the cache table.
21452 		 */
21453 		ire = NULL;
21454 		if (xmit_ill == NULL) {
21455 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21456 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21457 		}
21458 
21459 		if (ire == NULL) {
21460 			/*
21461 			 * Multicast loopback and multicast forwarding is
21462 			 * done in ip_wput_ire.
21463 			 *
21464 			 * Mark this packet to make it be delivered to
21465 			 * ip_wput_ire after the new ire has been
21466 			 * created.
21467 			 *
21468 			 * The call to ip_newroute_ipif takes into account
21469 			 * the setsrc reminder. In any case, we take care
21470 			 * of the RTF_MULTIRT flag.
21471 			 */
21472 			mp->b_prev = mp->b_next = NULL;
21473 			if (xmit_ill == NULL ||
21474 			    xmit_ill->ill_ipif_up_count > 0) {
21475 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21476 				    setsrc | RTF_MULTIRT, zoneid, infop);
21477 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21478 				    "ip_wput_end: q %p (%S)", q, "noire");
21479 			} else {
21480 				freemsg(first_mp);
21481 			}
21482 			ipif_refrele(ipif);
21483 			if (xmit_ill != NULL)
21484 				ill_refrele(xmit_ill);
21485 			if (need_decref)
21486 				CONN_DEC_REF(connp);
21487 			return;
21488 		}
21489 
21490 		ipif_refrele(ipif);
21491 		ipif = NULL;
21492 		ASSERT(xmit_ill == NULL);
21493 
21494 		/*
21495 		 * Honor the RTF_SETSRC flag for multicast packets,
21496 		 * if allowed by the setsrc reminder.
21497 		 */
21498 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21499 			ipha->ipha_src = ire->ire_src_addr;
21500 		}
21501 
21502 		/*
21503 		 * Unconditionally force the TTL to 1 for
21504 		 * multirouted multicast packets:
21505 		 * multirouted multicast should not cross
21506 		 * multicast routers.
21507 		 */
21508 		if (ire->ire_flags & RTF_MULTIRT) {
21509 			if (ipha->ipha_ttl > 1) {
21510 				ip2dbg(("ip_wput: forcing multicast "
21511 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21512 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21513 				ipha->ipha_ttl = 1;
21514 			}
21515 		}
21516 	} else {
21517 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21518 		if ((ire != NULL) && (ire->ire_type &
21519 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21520 			ignore_dontroute = B_TRUE;
21521 			ignore_nexthop = B_TRUE;
21522 		}
21523 		if (ire != NULL) {
21524 			ire_refrele(ire);
21525 			ire = NULL;
21526 		}
21527 		/*
21528 		 * Guard against coming in from arp in which case conn is NULL.
21529 		 * Also guard against non M_DATA with dontroute set but
21530 		 * destined to local, loopback or broadcast addresses.
21531 		 */
21532 		if (connp != NULL && connp->conn_dontroute &&
21533 		    !ignore_dontroute) {
21534 dontroute:
21535 			/*
21536 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21537 			 * routing protocols from seeing false direct
21538 			 * connectivity.
21539 			 */
21540 			ipha->ipha_ttl = 1;
21541 			/* If suitable ipif not found, drop packet */
21542 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21543 			if (dst_ipif == NULL) {
21544 noroute:
21545 				ip1dbg(("ip_wput: no route for dst using"
21546 				    " SO_DONTROUTE\n"));
21547 				BUMP_MIB(&ipst->ips_ip_mib,
21548 				    ipIfStatsOutNoRoutes);
21549 				mp->b_prev = mp->b_next = NULL;
21550 				if (first_mp == NULL)
21551 					first_mp = mp;
21552 				goto drop_pkt;
21553 			} else {
21554 				/*
21555 				 * If suitable ipif has been found, set
21556 				 * xmit_ill to the corresponding
21557 				 * ipif_ill because we'll be using the
21558 				 * send_from_ill logic below.
21559 				 */
21560 				ASSERT(xmit_ill == NULL);
21561 				xmit_ill = dst_ipif->ipif_ill;
21562 				mutex_enter(&xmit_ill->ill_lock);
21563 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21564 					mutex_exit(&xmit_ill->ill_lock);
21565 					xmit_ill = NULL;
21566 					ipif_refrele(dst_ipif);
21567 					goto noroute;
21568 				}
21569 				ill_refhold_locked(xmit_ill);
21570 				mutex_exit(&xmit_ill->ill_lock);
21571 				ipif_refrele(dst_ipif);
21572 			}
21573 		}
21574 
21575 send_from_ill:
21576 		if (xmit_ill != NULL) {
21577 			ipif_t *ipif;
21578 
21579 			/*
21580 			 * Mark this packet as originated locally
21581 			 */
21582 			mp->b_prev = mp->b_next = NULL;
21583 
21584 			/*
21585 			 * Could be SO_DONTROUTE case also.
21586 			 * Verify that at least one ipif is up on the ill.
21587 			 */
21588 			if (xmit_ill->ill_ipif_up_count == 0) {
21589 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21590 				    xmit_ill->ill_name));
21591 				goto drop_pkt;
21592 			}
21593 
21594 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21595 			if (ipif == NULL) {
21596 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21597 				    xmit_ill->ill_name));
21598 				goto drop_pkt;
21599 			}
21600 
21601 			match_flags = 0;
21602 			if (IS_UNDER_IPMP(xmit_ill))
21603 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21604 
21605 			/*
21606 			 * Look for a ire that is part of the group,
21607 			 * if found use it else call ip_newroute_ipif.
21608 			 * IPCL_ZONEID is not used for matching because
21609 			 * IP_ALLZONES option is valid only when the
21610 			 * ill is accessible from all zones i.e has a
21611 			 * valid ipif in all zones.
21612 			 */
21613 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21614 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21615 			    msg_getlabel(mp), match_flags, ipst);
21616 			/*
21617 			 * If an ire exists use it or else create
21618 			 * an ire but don't add it to the cache.
21619 			 * Adding an ire may cause issues with
21620 			 * asymmetric routing.
21621 			 * In case of multiroute always act as if
21622 			 * ire does not exist.
21623 			 */
21624 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21625 				if (ire != NULL)
21626 					ire_refrele(ire);
21627 				ip_newroute_ipif(q, first_mp, ipif,
21628 				    dst, connp, 0, zoneid, infop);
21629 				ipif_refrele(ipif);
21630 				ip1dbg(("ip_output: xmit_ill via %s\n",
21631 				    xmit_ill->ill_name));
21632 				ill_refrele(xmit_ill);
21633 				if (need_decref)
21634 					CONN_DEC_REF(connp);
21635 				return;
21636 			}
21637 			ipif_refrele(ipif);
21638 		} else if (ip_nexthop || (connp != NULL &&
21639 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21640 			if (!ip_nexthop) {
21641 				ip_nexthop = B_TRUE;
21642 				nexthop_addr = connp->conn_nexthop_v4;
21643 			}
21644 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21645 			    MATCH_IRE_GW;
21646 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21647 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21648 		} else {
21649 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21650 			    ipst);
21651 		}
21652 		if (!ire) {
21653 			if (ip_nexthop && !ignore_nexthop) {
21654 				if (mctl_present) {
21655 					io = (ipsec_out_t *)first_mp->b_rptr;
21656 					ASSERT(first_mp->b_datap->db_type ==
21657 					    M_CTL);
21658 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21659 				} else {
21660 					ASSERT(mp == first_mp);
21661 					first_mp = allocb(
21662 					    sizeof (ipsec_info_t), BPRI_HI);
21663 					if (first_mp == NULL) {
21664 						first_mp = mp;
21665 						goto discard_pkt;
21666 					}
21667 					first_mp->b_datap->db_type = M_CTL;
21668 					first_mp->b_wptr +=
21669 					    sizeof (ipsec_info_t);
21670 					/* ipsec_out_secure is B_FALSE now */
21671 					bzero(first_mp->b_rptr,
21672 					    sizeof (ipsec_info_t));
21673 					io = (ipsec_out_t *)first_mp->b_rptr;
21674 					io->ipsec_out_type = IPSEC_OUT;
21675 					io->ipsec_out_len =
21676 					    sizeof (ipsec_out_t);
21677 					io->ipsec_out_use_global_policy =
21678 					    B_TRUE;
21679 					io->ipsec_out_ns = ipst->ips_netstack;
21680 					first_mp->b_cont = mp;
21681 					mctl_present = B_TRUE;
21682 				}
21683 				io->ipsec_out_ip_nexthop = ip_nexthop;
21684 				io->ipsec_out_nexthop_addr = nexthop_addr;
21685 			}
21686 noirefound:
21687 			/*
21688 			 * Mark this packet as having originated on
21689 			 * this machine.  This will be noted in
21690 			 * ire_add_then_send, which needs to know
21691 			 * whether to run it back through ip_wput or
21692 			 * ip_rput following successful resolution.
21693 			 */
21694 			mp->b_prev = NULL;
21695 			mp->b_next = NULL;
21696 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21697 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21698 			    "ip_wput_end: q %p (%S)", q, "newroute");
21699 			if (xmit_ill != NULL)
21700 				ill_refrele(xmit_ill);
21701 			if (need_decref)
21702 				CONN_DEC_REF(connp);
21703 			return;
21704 		}
21705 	}
21706 
21707 	/* We now know where we are going with it. */
21708 
21709 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21710 	    "ip_wput_end: q %p (%S)", q, "end");
21711 
21712 	/*
21713 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21714 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21715 	 */
21716 	if (ire->ire_flags & RTF_MULTIRT) {
21717 		/*
21718 		 * Force the TTL of multirouted packets if required.
21719 		 * The TTL of such packets is bounded by the
21720 		 * ip_multirt_ttl ndd variable.
21721 		 */
21722 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21723 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21724 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21725 			    "(was %d), dst 0x%08x\n",
21726 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21727 			    ntohl(ire->ire_addr)));
21728 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21729 		}
21730 		/*
21731 		 * At this point, we check to see if there are any pending
21732 		 * unresolved routes. ire_multirt_resolvable()
21733 		 * checks in O(n) that all IRE_OFFSUBNET ire
21734 		 * entries for the packet's destination and
21735 		 * flagged RTF_MULTIRT are currently resolved.
21736 		 * If some remain unresolved, we make a copy
21737 		 * of the current message. It will be used
21738 		 * to initiate additional route resolutions.
21739 		 */
21740 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21741 		    msg_getlabel(first_mp), ipst);
21742 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21743 		    "multirt_need_resolve %d, first_mp %p\n",
21744 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21745 		if (multirt_need_resolve) {
21746 			copy_mp = copymsg(first_mp);
21747 			if (copy_mp != NULL) {
21748 				MULTIRT_DEBUG_TAG(copy_mp);
21749 			}
21750 		}
21751 	}
21752 
21753 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21754 	/*
21755 	 * Try to resolve another multiroute if
21756 	 * ire_multirt_resolvable() deemed it necessary.
21757 	 * At this point, we need to distinguish
21758 	 * multicasts from other packets. For multicasts,
21759 	 * we call ip_newroute_ipif() and request that both
21760 	 * multirouting and setsrc flags are checked.
21761 	 */
21762 	if (copy_mp != NULL) {
21763 		if (CLASSD(dst)) {
21764 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21765 			if (ipif) {
21766 				ASSERT(infop->ip_opt_ill_index == 0);
21767 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21768 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21769 				ipif_refrele(ipif);
21770 			} else {
21771 				MULTIRT_DEBUG_UNTAG(copy_mp);
21772 				freemsg(copy_mp);
21773 				copy_mp = NULL;
21774 			}
21775 		} else {
21776 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21777 		}
21778 	}
21779 	if (xmit_ill != NULL)
21780 		ill_refrele(xmit_ill);
21781 	if (need_decref)
21782 		CONN_DEC_REF(connp);
21783 	return;
21784 
21785 icmp_parameter_problem:
21786 	/* could not have originated externally */
21787 	ASSERT(mp->b_prev == NULL);
21788 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21789 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21790 		/* it's the IP header length that's in trouble */
21791 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21792 		first_mp = NULL;
21793 	}
21794 
21795 discard_pkt:
21796 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21797 drop_pkt:
21798 	ip1dbg(("ip_wput: dropped packet\n"));
21799 	if (ire != NULL)
21800 		ire_refrele(ire);
21801 	if (need_decref)
21802 		CONN_DEC_REF(connp);
21803 	freemsg(first_mp);
21804 	if (xmit_ill != NULL)
21805 		ill_refrele(xmit_ill);
21806 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21807 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21808 }
21809 
21810 /*
21811  * If this is a conn_t queue, then we pass in the conn. This includes the
21812  * zoneid.
21813  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21814  * in which case we use the global zoneid since those are all part of
21815  * the global zone.
21816  */
21817 void
21818 ip_wput(queue_t *q, mblk_t *mp)
21819 {
21820 	if (CONN_Q(q))
21821 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21822 	else
21823 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21824 }
21825 
21826 /*
21827  *
21828  * The following rules must be observed when accessing any ipif or ill
21829  * that has been cached in the conn. Typically conn_outgoing_ill,
21830  * conn_multicast_ipif and conn_multicast_ill.
21831  *
21832  * Access: The ipif or ill pointed to from the conn can be accessed under
21833  * the protection of the conn_lock or after it has been refheld under the
21834  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21835  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21836  * The reason for this is that a concurrent unplumb could actually be
21837  * cleaning up these cached pointers by walking the conns and might have
21838  * finished cleaning up the conn in question. The macros check that an
21839  * unplumb has not yet started on the ipif or ill.
21840  *
21841  * Caching: An ipif or ill pointer may be cached in the conn only after
21842  * making sure that an unplumb has not started. So the caching is done
21843  * while holding both the conn_lock and the ill_lock and after using the
21844  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21845  * flag before starting the cleanup of conns.
21846  *
21847  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21848  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21849  * or a reference to the ipif or a reference to an ire that references the
21850  * ipif. An ipif only changes its ill when migrating from an underlying ill
21851  * to an IPMP ill in ipif_up().
21852  */
21853 ipif_t *
21854 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21855 {
21856 	ipif_t	*ipif;
21857 	ill_t	*ill;
21858 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21859 
21860 	*err = 0;
21861 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21862 	mutex_enter(&connp->conn_lock);
21863 	ipif = *ipifp;
21864 	if (ipif != NULL) {
21865 		ill = ipif->ipif_ill;
21866 		mutex_enter(&ill->ill_lock);
21867 		if (IPIF_CAN_LOOKUP(ipif)) {
21868 			ipif_refhold_locked(ipif);
21869 			mutex_exit(&ill->ill_lock);
21870 			mutex_exit(&connp->conn_lock);
21871 			rw_exit(&ipst->ips_ill_g_lock);
21872 			return (ipif);
21873 		} else {
21874 			*err = IPIF_LOOKUP_FAILED;
21875 		}
21876 		mutex_exit(&ill->ill_lock);
21877 	}
21878 	mutex_exit(&connp->conn_lock);
21879 	rw_exit(&ipst->ips_ill_g_lock);
21880 	return (NULL);
21881 }
21882 
21883 ill_t *
21884 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21885 {
21886 	ill_t	*ill;
21887 
21888 	*err = 0;
21889 	mutex_enter(&connp->conn_lock);
21890 	ill = *illp;
21891 	if (ill != NULL) {
21892 		mutex_enter(&ill->ill_lock);
21893 		if (ILL_CAN_LOOKUP(ill)) {
21894 			ill_refhold_locked(ill);
21895 			mutex_exit(&ill->ill_lock);
21896 			mutex_exit(&connp->conn_lock);
21897 			return (ill);
21898 		} else {
21899 			*err = ILL_LOOKUP_FAILED;
21900 		}
21901 		mutex_exit(&ill->ill_lock);
21902 	}
21903 	mutex_exit(&connp->conn_lock);
21904 	return (NULL);
21905 }
21906 
21907 static int
21908 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21909 {
21910 	ill_t	*ill;
21911 
21912 	ill = ipif->ipif_ill;
21913 	mutex_enter(&connp->conn_lock);
21914 	mutex_enter(&ill->ill_lock);
21915 	if (IPIF_CAN_LOOKUP(ipif)) {
21916 		*ipifp = ipif;
21917 		mutex_exit(&ill->ill_lock);
21918 		mutex_exit(&connp->conn_lock);
21919 		return (0);
21920 	}
21921 	mutex_exit(&ill->ill_lock);
21922 	mutex_exit(&connp->conn_lock);
21923 	return (IPIF_LOOKUP_FAILED);
21924 }
21925 
21926 /*
21927  * This is called if the outbound datagram needs fragmentation.
21928  *
21929  * NOTE : This function does not ire_refrele the ire argument passed in.
21930  */
21931 static void
21932 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21933     ip_stack_t *ipst, conn_t *connp)
21934 {
21935 	ipha_t		*ipha;
21936 	mblk_t		*mp;
21937 	uint32_t	v_hlen_tos_len;
21938 	uint32_t	max_frag;
21939 	uint32_t	frag_flag;
21940 	boolean_t	dont_use;
21941 
21942 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21943 		mp = ipsec_mp->b_cont;
21944 	} else {
21945 		mp = ipsec_mp;
21946 	}
21947 
21948 	ipha = (ipha_t *)mp->b_rptr;
21949 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21950 
21951 #ifdef	_BIG_ENDIAN
21952 #define	V_HLEN	(v_hlen_tos_len >> 24)
21953 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21954 #else
21955 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21956 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21957 #endif
21958 
21959 #ifndef SPEED_BEFORE_SAFETY
21960 	/*
21961 	 * Check that ipha_length is consistent with
21962 	 * the mblk length
21963 	 */
21964 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21965 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21966 		    LENGTH, msgdsize(mp)));
21967 		freemsg(ipsec_mp);
21968 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21969 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21970 		    "packet length mismatch");
21971 		return;
21972 	}
21973 #endif
21974 	/*
21975 	 * Don't use frag_flag if pre-built packet or source
21976 	 * routed or if multicast (since multicast packets do not solicit
21977 	 * ICMP "packet too big" messages). Get the values of
21978 	 * max_frag and frag_flag atomically by acquiring the
21979 	 * ire_lock.
21980 	 */
21981 	mutex_enter(&ire->ire_lock);
21982 	max_frag = ire->ire_max_frag;
21983 	frag_flag = ire->ire_frag_flag;
21984 	mutex_exit(&ire->ire_lock);
21985 
21986 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21987 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21988 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21989 
21990 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21991 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21992 }
21993 
21994 /*
21995  * Used for deciding the MSS size for the upper layer. Thus
21996  * we need to check the outbound policy values in the conn.
21997  */
21998 int
21999 conn_ipsec_length(conn_t *connp)
22000 {
22001 	ipsec_latch_t *ipl;
22002 
22003 	ipl = connp->conn_latch;
22004 	if (ipl == NULL)
22005 		return (0);
22006 
22007 	if (ipl->ipl_out_policy == NULL)
22008 		return (0);
22009 
22010 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
22011 }
22012 
22013 /*
22014  * Returns an estimate of the IPsec headers size. This is used if
22015  * we don't want to call into IPsec to get the exact size.
22016  */
22017 int
22018 ipsec_out_extra_length(mblk_t *ipsec_mp)
22019 {
22020 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
22021 	ipsec_action_t *a;
22022 
22023 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
22024 	if (!io->ipsec_out_secure)
22025 		return (0);
22026 
22027 	a = io->ipsec_out_act;
22028 
22029 	if (a == NULL) {
22030 		ASSERT(io->ipsec_out_policy != NULL);
22031 		a = io->ipsec_out_policy->ipsp_act;
22032 	}
22033 	ASSERT(a != NULL);
22034 
22035 	return (a->ipa_ovhd);
22036 }
22037 
22038 /*
22039  * Returns an estimate of the IPsec headers size. This is used if
22040  * we don't want to call into IPsec to get the exact size.
22041  */
22042 int
22043 ipsec_in_extra_length(mblk_t *ipsec_mp)
22044 {
22045 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22046 	ipsec_action_t *a;
22047 
22048 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22049 
22050 	a = ii->ipsec_in_action;
22051 	return (a == NULL ? 0 : a->ipa_ovhd);
22052 }
22053 
22054 /*
22055  * If there are any source route options, return the true final
22056  * destination. Otherwise, return the destination.
22057  */
22058 ipaddr_t
22059 ip_get_dst(ipha_t *ipha)
22060 {
22061 	ipoptp_t	opts;
22062 	uchar_t		*opt;
22063 	uint8_t		optval;
22064 	uint8_t		optlen;
22065 	ipaddr_t	dst;
22066 	uint32_t off;
22067 
22068 	dst = ipha->ipha_dst;
22069 
22070 	if (IS_SIMPLE_IPH(ipha))
22071 		return (dst);
22072 
22073 	for (optval = ipoptp_first(&opts, ipha);
22074 	    optval != IPOPT_EOL;
22075 	    optval = ipoptp_next(&opts)) {
22076 		opt = opts.ipoptp_cur;
22077 		optlen = opts.ipoptp_len;
22078 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22079 		switch (optval) {
22080 		case IPOPT_SSRR:
22081 		case IPOPT_LSRR:
22082 			off = opt[IPOPT_OFFSET];
22083 			/*
22084 			 * If one of the conditions is true, it means
22085 			 * end of options and dst already has the right
22086 			 * value.
22087 			 */
22088 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22089 				off = optlen - IP_ADDR_LEN;
22090 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22091 			}
22092 			return (dst);
22093 		default:
22094 			break;
22095 		}
22096 	}
22097 
22098 	return (dst);
22099 }
22100 
22101 mblk_t *
22102 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22103     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22104 {
22105 	ipsec_out_t	*io;
22106 	mblk_t		*first_mp;
22107 	boolean_t policy_present;
22108 	ip_stack_t	*ipst;
22109 	ipsec_stack_t	*ipss;
22110 
22111 	ASSERT(ire != NULL);
22112 	ipst = ire->ire_ipst;
22113 	ipss = ipst->ips_netstack->netstack_ipsec;
22114 
22115 	first_mp = mp;
22116 	if (mp->b_datap->db_type == M_CTL) {
22117 		io = (ipsec_out_t *)first_mp->b_rptr;
22118 		/*
22119 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22120 		 *
22121 		 * 1) There is per-socket policy (including cached global
22122 		 *    policy) or a policy on the IP-in-IP tunnel.
22123 		 * 2) There is no per-socket policy, but it is
22124 		 *    a multicast packet that needs to go out
22125 		 *    on a specific interface. This is the case
22126 		 *    where (ip_wput and ip_wput_multicast) attaches
22127 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22128 		 *
22129 		 * In case (2) we check with global policy to
22130 		 * see if there is a match and set the ill_index
22131 		 * appropriately so that we can lookup the ire
22132 		 * properly in ip_wput_ipsec_out.
22133 		 */
22134 
22135 		/*
22136 		 * ipsec_out_use_global_policy is set to B_FALSE
22137 		 * in ipsec_in_to_out(). Refer to that function for
22138 		 * details.
22139 		 */
22140 		if ((io->ipsec_out_latch == NULL) &&
22141 		    (io->ipsec_out_use_global_policy)) {
22142 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22143 			    ire, connp, unspec_src, zoneid));
22144 		}
22145 		if (!io->ipsec_out_secure) {
22146 			/*
22147 			 * If this is not a secure packet, drop
22148 			 * the IPSEC_OUT mp and treat it as a clear
22149 			 * packet. This happens when we are sending
22150 			 * a ICMP reply back to a clear packet. See
22151 			 * ipsec_in_to_out() for details.
22152 			 */
22153 			mp = first_mp->b_cont;
22154 			freeb(first_mp);
22155 		}
22156 		return (mp);
22157 	}
22158 	/*
22159 	 * See whether we need to attach a global policy here. We
22160 	 * don't depend on the conn (as it could be null) for deciding
22161 	 * what policy this datagram should go through because it
22162 	 * should have happened in ip_wput if there was some
22163 	 * policy. This normally happens for connections which are not
22164 	 * fully bound preventing us from caching policies in
22165 	 * ip_bind. Packets coming from the TCP listener/global queue
22166 	 * - which are non-hard_bound - could also be affected by
22167 	 * applying policy here.
22168 	 *
22169 	 * If this packet is coming from tcp global queue or listener,
22170 	 * we will be applying policy here.  This may not be *right*
22171 	 * if these packets are coming from the detached connection as
22172 	 * it could have gone in clear before. This happens only if a
22173 	 * TCP connection started when there is no policy and somebody
22174 	 * added policy before it became detached. Thus packets of the
22175 	 * detached connection could go out secure and the other end
22176 	 * would drop it because it will be expecting in clear. The
22177 	 * converse is not true i.e if somebody starts a TCP
22178 	 * connection and deletes the policy, all the packets will
22179 	 * still go out with the policy that existed before deleting
22180 	 * because ip_unbind sends up policy information which is used
22181 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22182 	 * TCP to attach a dummy IPSEC_OUT and set
22183 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22184 	 * affect performance for normal cases, we are not doing it.
22185 	 * Thus, set policy before starting any TCP connections.
22186 	 *
22187 	 * NOTE - We might apply policy even for a hard bound connection
22188 	 * - for which we cached policy in ip_bind - if somebody added
22189 	 * global policy after we inherited the policy in ip_bind.
22190 	 * This means that the packets that were going out in clear
22191 	 * previously would start going secure and hence get dropped
22192 	 * on the other side. To fix this, TCP attaches a dummy
22193 	 * ipsec_out and make sure that we don't apply global policy.
22194 	 */
22195 	if (ipha != NULL)
22196 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22197 	else
22198 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22199 	if (!policy_present)
22200 		return (mp);
22201 
22202 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22203 	    zoneid));
22204 }
22205 
22206 /*
22207  * This function does the ire_refrele of the ire passed in as the
22208  * argument. As this function looks up more ires i.e broadcast ires,
22209  * it needs to REFRELE them. Currently, for simplicity we don't
22210  * differentiate the one passed in and looked up here. We always
22211  * REFRELE.
22212  * IPQoS Notes:
22213  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22214  * IPsec packets are done in ipsec_out_process.
22215  */
22216 void
22217 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22218     zoneid_t zoneid)
22219 {
22220 	ipha_t		*ipha;
22221 #define	rptr	((uchar_t *)ipha)
22222 	queue_t		*stq;
22223 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22224 	uint32_t	v_hlen_tos_len;
22225 	uint32_t	ttl_protocol;
22226 	ipaddr_t	src;
22227 	ipaddr_t	dst;
22228 	uint32_t	cksum;
22229 	ipaddr_t	orig_src;
22230 	ire_t		*ire1;
22231 	mblk_t		*next_mp;
22232 	uint_t		hlen;
22233 	uint16_t	*up;
22234 	uint32_t	max_frag = ire->ire_max_frag;
22235 	ill_t		*ill = ire_to_ill(ire);
22236 	int		clusterwide;
22237 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22238 	int		ipsec_len;
22239 	mblk_t		*first_mp;
22240 	ipsec_out_t	*io;
22241 	boolean_t	conn_dontroute;		/* conn value for multicast */
22242 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22243 	boolean_t	multicast_forward;	/* Should we forward ? */
22244 	boolean_t	unspec_src;
22245 	ill_t		*conn_outgoing_ill = NULL;
22246 	ill_t		*ire_ill;
22247 	ill_t		*ire1_ill;
22248 	ill_t		*out_ill;
22249 	uint32_t 	ill_index = 0;
22250 	boolean_t	multirt_send = B_FALSE;
22251 	int		err;
22252 	ipxmit_state_t	pktxmit_state;
22253 	ip_stack_t	*ipst = ire->ire_ipst;
22254 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22255 
22256 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22257 	    "ip_wput_ire_start: q %p", q);
22258 
22259 	multicast_forward = B_FALSE;
22260 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22261 
22262 	if (ire->ire_flags & RTF_MULTIRT) {
22263 		/*
22264 		 * Multirouting case. The bucket where ire is stored
22265 		 * probably holds other RTF_MULTIRT flagged ire
22266 		 * to the destination. In this call to ip_wput_ire,
22267 		 * we attempt to send the packet through all
22268 		 * those ires. Thus, we first ensure that ire is the
22269 		 * first RTF_MULTIRT ire in the bucket,
22270 		 * before walking the ire list.
22271 		 */
22272 		ire_t *first_ire;
22273 		irb_t *irb = ire->ire_bucket;
22274 		ASSERT(irb != NULL);
22275 
22276 		/* Make sure we do not omit any multiroute ire. */
22277 		IRB_REFHOLD(irb);
22278 		for (first_ire = irb->irb_ire;
22279 		    first_ire != NULL;
22280 		    first_ire = first_ire->ire_next) {
22281 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22282 			    (first_ire->ire_addr == ire->ire_addr) &&
22283 			    !(first_ire->ire_marks &
22284 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22285 				break;
22286 		}
22287 
22288 		if ((first_ire != NULL) && (first_ire != ire)) {
22289 			IRE_REFHOLD(first_ire);
22290 			ire_refrele(ire);
22291 			ire = first_ire;
22292 			ill = ire_to_ill(ire);
22293 		}
22294 		IRB_REFRELE(irb);
22295 	}
22296 
22297 	/*
22298 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22299 	 * for performance we don't grab the mutexs in the fastpath
22300 	 */
22301 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22302 	    connp->conn_outgoing_ill != NULL) {
22303 		conn_outgoing_ill = conn_get_held_ill(connp,
22304 		    &connp->conn_outgoing_ill, &err);
22305 		if (err == ILL_LOOKUP_FAILED) {
22306 			ire_refrele(ire);
22307 			freemsg(mp);
22308 			return;
22309 		}
22310 	}
22311 
22312 	if (mp->b_datap->db_type != M_CTL) {
22313 		ipha = (ipha_t *)mp->b_rptr;
22314 	} else {
22315 		io = (ipsec_out_t *)mp->b_rptr;
22316 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22317 		ASSERT(zoneid == io->ipsec_out_zoneid);
22318 		ASSERT(zoneid != ALL_ZONES);
22319 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22320 		dst = ipha->ipha_dst;
22321 		/*
22322 		 * For the multicast case, ipsec_out carries conn_dontroute and
22323 		 * conn_multicast_loop as conn may not be available here. We
22324 		 * need this for multicast loopback and forwarding which is done
22325 		 * later in the code.
22326 		 */
22327 		if (CLASSD(dst)) {
22328 			conn_dontroute = io->ipsec_out_dontroute;
22329 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22330 			/*
22331 			 * If conn_dontroute is not set or conn_multicast_loop
22332 			 * is set, we need to do forwarding/loopback. For
22333 			 * datagrams from ip_wput_multicast, conn_dontroute is
22334 			 * set to B_TRUE and conn_multicast_loop is set to
22335 			 * B_FALSE so that we neither do forwarding nor
22336 			 * loopback.
22337 			 */
22338 			if (!conn_dontroute || conn_multicast_loop)
22339 				multicast_forward = B_TRUE;
22340 		}
22341 	}
22342 
22343 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22344 	    ire->ire_zoneid != ALL_ZONES) {
22345 		/*
22346 		 * When a zone sends a packet to another zone, we try to deliver
22347 		 * the packet under the same conditions as if the destination
22348 		 * was a real node on the network. To do so, we look for a
22349 		 * matching route in the forwarding table.
22350 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22351 		 * ip_newroute() does.
22352 		 * Note that IRE_LOCAL are special, since they are used
22353 		 * when the zoneid doesn't match in some cases. This means that
22354 		 * we need to handle ipha_src differently since ire_src_addr
22355 		 * belongs to the receiving zone instead of the sending zone.
22356 		 * When ip_restrict_interzone_loopback is set, then
22357 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22358 		 * for loopback between zones when the logical "Ethernet" would
22359 		 * have looped them back.
22360 		 */
22361 		ire_t *src_ire;
22362 
22363 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22364 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22365 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22366 		if (src_ire != NULL &&
22367 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22368 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22369 		    ire_local_same_lan(ire, src_ire))) {
22370 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22371 				ipha->ipha_src = src_ire->ire_src_addr;
22372 			ire_refrele(src_ire);
22373 		} else {
22374 			ire_refrele(ire);
22375 			if (conn_outgoing_ill != NULL)
22376 				ill_refrele(conn_outgoing_ill);
22377 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22378 			if (src_ire != NULL) {
22379 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22380 					ire_refrele(src_ire);
22381 					freemsg(mp);
22382 					return;
22383 				}
22384 				ire_refrele(src_ire);
22385 			}
22386 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22387 				/* Failed */
22388 				freemsg(mp);
22389 				return;
22390 			}
22391 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22392 			    ipst);
22393 			return;
22394 		}
22395 	}
22396 
22397 	if (mp->b_datap->db_type == M_CTL ||
22398 	    ipss->ipsec_outbound_v4_policy_present) {
22399 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22400 		    unspec_src, zoneid);
22401 		if (mp == NULL) {
22402 			ire_refrele(ire);
22403 			if (conn_outgoing_ill != NULL)
22404 				ill_refrele(conn_outgoing_ill);
22405 			return;
22406 		}
22407 		/*
22408 		 * Trusted Extensions supports all-zones interfaces, so
22409 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22410 		 * the global zone.
22411 		 */
22412 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22413 			io = (ipsec_out_t *)mp->b_rptr;
22414 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22415 			zoneid = io->ipsec_out_zoneid;
22416 		}
22417 	}
22418 
22419 	first_mp = mp;
22420 	ipsec_len = 0;
22421 
22422 	if (first_mp->b_datap->db_type == M_CTL) {
22423 		io = (ipsec_out_t *)first_mp->b_rptr;
22424 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22425 		mp = first_mp->b_cont;
22426 		ipsec_len = ipsec_out_extra_length(first_mp);
22427 		ASSERT(ipsec_len >= 0);
22428 		/* We already picked up the zoneid from the M_CTL above */
22429 		ASSERT(zoneid == io->ipsec_out_zoneid);
22430 		ASSERT(zoneid != ALL_ZONES);
22431 
22432 		/*
22433 		 * Drop M_CTL here if IPsec processing is not needed.
22434 		 * (Non-IPsec use of M_CTL extracted any information it
22435 		 * needed above).
22436 		 */
22437 		if (ipsec_len == 0) {
22438 			freeb(first_mp);
22439 			first_mp = mp;
22440 		}
22441 	}
22442 
22443 	/*
22444 	 * Fast path for ip_wput_ire
22445 	 */
22446 
22447 	ipha = (ipha_t *)mp->b_rptr;
22448 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22449 	dst = ipha->ipha_dst;
22450 
22451 	/*
22452 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22453 	 * if the socket is a SOCK_RAW type. The transport checksum should
22454 	 * be provided in the pre-built packet, so we don't need to compute it.
22455 	 * Also, other application set flags, like DF, should not be altered.
22456 	 * Other transport MUST pass down zero.
22457 	 */
22458 	ip_hdr_included = ipha->ipha_ident;
22459 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22460 
22461 	if (CLASSD(dst)) {
22462 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22463 		    ntohl(dst),
22464 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22465 		    ntohl(ire->ire_addr)));
22466 	}
22467 
22468 /* Macros to extract header fields from data already in registers */
22469 #ifdef	_BIG_ENDIAN
22470 #define	V_HLEN	(v_hlen_tos_len >> 24)
22471 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22472 #define	PROTO	(ttl_protocol & 0xFF)
22473 #else
22474 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22475 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22476 #define	PROTO	(ttl_protocol >> 8)
22477 #endif
22478 
22479 	orig_src = src = ipha->ipha_src;
22480 	/* (The loop back to "another" is explained down below.) */
22481 another:;
22482 	/*
22483 	 * Assign an ident value for this packet.  We assign idents on
22484 	 * a per destination basis out of the IRE.  There could be
22485 	 * other threads targeting the same destination, so we have to
22486 	 * arrange for a atomic increment.  Note that we use a 32-bit
22487 	 * atomic add because it has better performance than its
22488 	 * 16-bit sibling.
22489 	 *
22490 	 * If running in cluster mode and if the source address
22491 	 * belongs to a replicated service then vector through
22492 	 * cl_inet_ipident vector to allocate ip identifier
22493 	 * NOTE: This is a contract private interface with the
22494 	 * clustering group.
22495 	 */
22496 	clusterwide = 0;
22497 	if (cl_inet_ipident) {
22498 		ASSERT(cl_inet_isclusterwide);
22499 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22500 
22501 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22502 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22503 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22504 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22505 			    (uint8_t *)(uintptr_t)dst, NULL);
22506 			clusterwide = 1;
22507 		}
22508 	}
22509 	if (!clusterwide) {
22510 		ipha->ipha_ident =
22511 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22512 	}
22513 
22514 #ifndef _BIG_ENDIAN
22515 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22516 #endif
22517 
22518 	/*
22519 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22520 	 * This is needed to obey conn_unspec_src when packets go through
22521 	 * ip_newroute + arp.
22522 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22523 	 */
22524 	if (src == INADDR_ANY && !unspec_src) {
22525 		/*
22526 		 * Assign the appropriate source address from the IRE if none
22527 		 * was specified.
22528 		 */
22529 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22530 
22531 		src = ire->ire_src_addr;
22532 		if (connp == NULL) {
22533 			ip1dbg(("ip_wput_ire: no connp and no src "
22534 			    "address for dst 0x%x, using src 0x%x\n",
22535 			    ntohl(dst),
22536 			    ntohl(src)));
22537 		}
22538 		ipha->ipha_src = src;
22539 	}
22540 	stq = ire->ire_stq;
22541 
22542 	/*
22543 	 * We only allow ire chains for broadcasts since there will
22544 	 * be multiple IRE_CACHE entries for the same multicast
22545 	 * address (one per ipif).
22546 	 */
22547 	next_mp = NULL;
22548 
22549 	/* broadcast packet */
22550 	if (ire->ire_type == IRE_BROADCAST)
22551 		goto broadcast;
22552 
22553 	/* loopback ? */
22554 	if (stq == NULL)
22555 		goto nullstq;
22556 
22557 	/* The ill_index for outbound ILL */
22558 	ill_index = Q_TO_INDEX(stq);
22559 
22560 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22561 	ttl_protocol = ((uint16_t *)ipha)[4];
22562 
22563 	/* pseudo checksum (do it in parts for IP header checksum) */
22564 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22565 
22566 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22567 		queue_t *dev_q = stq->q_next;
22568 
22569 		/*
22570 		 * For DIRECT_CAPABLE, we do flow control at
22571 		 * the time of sending the packet. See
22572 		 * ILL_SEND_TX().
22573 		 */
22574 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22575 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22576 			goto blocked;
22577 
22578 		if ((PROTO == IPPROTO_UDP) &&
22579 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22580 			hlen = (V_HLEN & 0xF) << 2;
22581 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22582 			if (*up != 0) {
22583 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22584 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22585 				/* Software checksum? */
22586 				if (DB_CKSUMFLAGS(mp) == 0) {
22587 					IP_STAT(ipst, ip_out_sw_cksum);
22588 					IP_STAT_UPDATE(ipst,
22589 					    ip_udp_out_sw_cksum_bytes,
22590 					    LENGTH - hlen);
22591 				}
22592 			}
22593 		}
22594 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22595 		hlen = (V_HLEN & 0xF) << 2;
22596 		if (PROTO == IPPROTO_TCP) {
22597 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22598 			/*
22599 			 * The packet header is processed once and for all, even
22600 			 * in the multirouting case. We disable hardware
22601 			 * checksum if the packet is multirouted, as it will be
22602 			 * replicated via several interfaces, and not all of
22603 			 * them may have this capability.
22604 			 */
22605 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22606 			    LENGTH, max_frag, ipsec_len, cksum);
22607 			/* Software checksum? */
22608 			if (DB_CKSUMFLAGS(mp) == 0) {
22609 				IP_STAT(ipst, ip_out_sw_cksum);
22610 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22611 				    LENGTH - hlen);
22612 			}
22613 		} else {
22614 			sctp_hdr_t	*sctph;
22615 
22616 			ASSERT(PROTO == IPPROTO_SCTP);
22617 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22618 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22619 			/*
22620 			 * Zero out the checksum field to ensure proper
22621 			 * checksum calculation.
22622 			 */
22623 			sctph->sh_chksum = 0;
22624 #ifdef	DEBUG
22625 			if (!skip_sctp_cksum)
22626 #endif
22627 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22628 		}
22629 	}
22630 
22631 	/*
22632 	 * If this is a multicast packet and originated from ip_wput
22633 	 * we need to do loopback and forwarding checks. If it comes
22634 	 * from ip_wput_multicast, we SHOULD not do this.
22635 	 */
22636 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22637 
22638 	/* checksum */
22639 	cksum += ttl_protocol;
22640 
22641 	/* fragment the packet */
22642 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22643 		goto fragmentit;
22644 	/*
22645 	 * Don't use frag_flag if packet is pre-built or source
22646 	 * routed or if multicast (since multicast packets do
22647 	 * not solicit ICMP "packet too big" messages).
22648 	 */
22649 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22650 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22651 	    !ip_source_route_included(ipha)) &&
22652 	    !CLASSD(ipha->ipha_dst))
22653 		ipha->ipha_fragment_offset_and_flags |=
22654 		    htons(ire->ire_frag_flag);
22655 
22656 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22657 		/* calculate IP header checksum */
22658 		cksum += ipha->ipha_ident;
22659 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22660 		cksum += ipha->ipha_fragment_offset_and_flags;
22661 
22662 		/* IP options present */
22663 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22664 		if (hlen)
22665 			goto checksumoptions;
22666 
22667 		/* calculate hdr checksum */
22668 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22669 		cksum = ~(cksum + (cksum >> 16));
22670 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22671 	}
22672 	if (ipsec_len != 0) {
22673 		/*
22674 		 * We will do the rest of the processing after
22675 		 * we come back from IPsec in ip_wput_ipsec_out().
22676 		 */
22677 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22678 
22679 		io = (ipsec_out_t *)first_mp->b_rptr;
22680 		io->ipsec_out_ill_index =
22681 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22682 		ipsec_out_process(q, first_mp, ire, 0);
22683 		ire_refrele(ire);
22684 		if (conn_outgoing_ill != NULL)
22685 			ill_refrele(conn_outgoing_ill);
22686 		return;
22687 	}
22688 
22689 	/*
22690 	 * In most cases, the emission loop below is entered only
22691 	 * once. Only in the case where the ire holds the
22692 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22693 	 * flagged ires in the bucket, and send the packet
22694 	 * through all crossed RTF_MULTIRT routes.
22695 	 */
22696 	if (ire->ire_flags & RTF_MULTIRT) {
22697 		multirt_send = B_TRUE;
22698 	}
22699 	do {
22700 		if (multirt_send) {
22701 			irb_t *irb;
22702 			/*
22703 			 * We are in a multiple send case, need to get
22704 			 * the next ire and make a duplicate of the packet.
22705 			 * ire1 holds here the next ire to process in the
22706 			 * bucket. If multirouting is expected,
22707 			 * any non-RTF_MULTIRT ire that has the
22708 			 * right destination address is ignored.
22709 			 */
22710 			irb = ire->ire_bucket;
22711 			ASSERT(irb != NULL);
22712 
22713 			IRB_REFHOLD(irb);
22714 			for (ire1 = ire->ire_next;
22715 			    ire1 != NULL;
22716 			    ire1 = ire1->ire_next) {
22717 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22718 					continue;
22719 				if (ire1->ire_addr != ire->ire_addr)
22720 					continue;
22721 				if (ire1->ire_marks &
22722 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22723 					continue;
22724 
22725 				/* Got one */
22726 				IRE_REFHOLD(ire1);
22727 				break;
22728 			}
22729 			IRB_REFRELE(irb);
22730 
22731 			if (ire1 != NULL) {
22732 				next_mp = copyb(mp);
22733 				if ((next_mp == NULL) ||
22734 				    ((mp->b_cont != NULL) &&
22735 				    ((next_mp->b_cont =
22736 				    dupmsg(mp->b_cont)) == NULL))) {
22737 					freemsg(next_mp);
22738 					next_mp = NULL;
22739 					ire_refrele(ire1);
22740 					ire1 = NULL;
22741 				}
22742 			}
22743 
22744 			/* Last multiroute ire; don't loop anymore. */
22745 			if (ire1 == NULL) {
22746 				multirt_send = B_FALSE;
22747 			}
22748 		}
22749 
22750 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22751 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22752 		    mblk_t *, mp);
22753 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22754 		    ipst->ips_ipv4firewall_physical_out,
22755 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22756 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22757 
22758 		if (mp == NULL)
22759 			goto release_ire_and_ill;
22760 
22761 		if (ipst->ips_ipobs_enabled) {
22762 			zoneid_t szone;
22763 
22764 			/*
22765 			 * On the outbound path the destination zone will be
22766 			 * unknown as we're sending this packet out on the
22767 			 * wire.
22768 			 */
22769 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22770 			    ALL_ZONES);
22771 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22772 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22773 		}
22774 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22775 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22776 
22777 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22778 
22779 		if ((pktxmit_state == SEND_FAILED) ||
22780 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22781 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22782 			    "- packet dropped\n"));
22783 release_ire_and_ill:
22784 			ire_refrele(ire);
22785 			if (next_mp != NULL) {
22786 				freemsg(next_mp);
22787 				ire_refrele(ire1);
22788 			}
22789 			if (conn_outgoing_ill != NULL)
22790 				ill_refrele(conn_outgoing_ill);
22791 			return;
22792 		}
22793 
22794 		if (CLASSD(dst)) {
22795 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22796 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22797 			    LENGTH);
22798 		}
22799 
22800 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22801 		    "ip_wput_ire_end: q %p (%S)",
22802 		    q, "last copy out");
22803 		IRE_REFRELE(ire);
22804 
22805 		if (multirt_send) {
22806 			ASSERT(ire1);
22807 			/*
22808 			 * Proceed with the next RTF_MULTIRT ire,
22809 			 * Also set up the send-to queue accordingly.
22810 			 */
22811 			ire = ire1;
22812 			ire1 = NULL;
22813 			stq = ire->ire_stq;
22814 			mp = next_mp;
22815 			next_mp = NULL;
22816 			ipha = (ipha_t *)mp->b_rptr;
22817 			ill_index = Q_TO_INDEX(stq);
22818 			ill = (ill_t *)stq->q_ptr;
22819 		}
22820 	} while (multirt_send);
22821 	if (conn_outgoing_ill != NULL)
22822 		ill_refrele(conn_outgoing_ill);
22823 	return;
22824 
22825 	/*
22826 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22827 	 */
22828 broadcast:
22829 	{
22830 		/*
22831 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22832 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22833 		 * can be overridden stack-wide through the ip_broadcast_ttl
22834 		 * ndd tunable, or on a per-connection basis through the
22835 		 * IP_BROADCAST_TTL socket option.
22836 		 *
22837 		 * In the event that we are replying to incoming ICMP packets,
22838 		 * connp could be NULL.
22839 		 */
22840 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22841 		if (connp != NULL) {
22842 			if (connp->conn_dontroute)
22843 				ipha->ipha_ttl = 1;
22844 			else if (connp->conn_broadcast_ttl != 0)
22845 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22846 		}
22847 
22848 		/*
22849 		 * Note that we are not doing a IRB_REFHOLD here.
22850 		 * Actually we don't care if the list changes i.e
22851 		 * if somebody deletes an IRE from the list while
22852 		 * we drop the lock, the next time we come around
22853 		 * ire_next will be NULL and hence we won't send
22854 		 * out multiple copies which is fine.
22855 		 */
22856 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22857 		ire1 = ire->ire_next;
22858 		if (conn_outgoing_ill != NULL) {
22859 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22860 				ASSERT(ire1 == ire->ire_next);
22861 				if (ire1 != NULL && ire1->ire_addr == dst) {
22862 					ire_refrele(ire);
22863 					ire = ire1;
22864 					IRE_REFHOLD(ire);
22865 					ire1 = ire->ire_next;
22866 					continue;
22867 				}
22868 				rw_exit(&ire->ire_bucket->irb_lock);
22869 				/* Did not find a matching ill */
22870 				ip1dbg(("ip_wput_ire: broadcast with no "
22871 				    "matching IP_BOUND_IF ill %s dst %x\n",
22872 				    conn_outgoing_ill->ill_name, dst));
22873 				freemsg(first_mp);
22874 				if (ire != NULL)
22875 					ire_refrele(ire);
22876 				ill_refrele(conn_outgoing_ill);
22877 				return;
22878 			}
22879 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22880 			/*
22881 			 * If the next IRE has the same address and is not one
22882 			 * of the two copies that we need to send, try to see
22883 			 * whether this copy should be sent at all. This
22884 			 * assumes that we insert loopbacks first and then
22885 			 * non-loopbacks. This is acheived by inserting the
22886 			 * loopback always before non-loopback.
22887 			 * This is used to send a single copy of a broadcast
22888 			 * packet out all physical interfaces that have an
22889 			 * matching IRE_BROADCAST while also looping
22890 			 * back one copy (to ip_wput_local) for each
22891 			 * matching physical interface. However, we avoid
22892 			 * sending packets out different logical that match by
22893 			 * having ipif_up/ipif_down supress duplicate
22894 			 * IRE_BROADCASTS.
22895 			 *
22896 			 * This feature is currently used to get broadcasts
22897 			 * sent to multiple interfaces, when the broadcast
22898 			 * address being used applies to multiple interfaces.
22899 			 * For example, a whole net broadcast will be
22900 			 * replicated on every connected subnet of
22901 			 * the target net.
22902 			 *
22903 			 * Each zone has its own set of IRE_BROADCASTs, so that
22904 			 * we're able to distribute inbound packets to multiple
22905 			 * zones who share a broadcast address. We avoid looping
22906 			 * back outbound packets in different zones but on the
22907 			 * same ill, as the application would see duplicates.
22908 			 *
22909 			 * This logic assumes that ire_add_v4() groups the
22910 			 * IRE_BROADCAST entries so that those with the same
22911 			 * ire_addr are kept together.
22912 			 */
22913 			ire_ill = ire->ire_ipif->ipif_ill;
22914 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22915 				while (ire1 != NULL && ire1->ire_addr == dst) {
22916 					ire1_ill = ire1->ire_ipif->ipif_ill;
22917 					if (ire1_ill != ire_ill)
22918 						break;
22919 					ire1 = ire1->ire_next;
22920 				}
22921 			}
22922 		}
22923 		ASSERT(multirt_send == B_FALSE);
22924 		if (ire1 != NULL && ire1->ire_addr == dst) {
22925 			if ((ire->ire_flags & RTF_MULTIRT) &&
22926 			    (ire1->ire_flags & RTF_MULTIRT)) {
22927 				/*
22928 				 * We are in the multirouting case.
22929 				 * The message must be sent at least
22930 				 * on both ires. These ires have been
22931 				 * inserted AFTER the standard ones
22932 				 * in ip_rt_add(). There are thus no
22933 				 * other ire entries for the destination
22934 				 * address in the rest of the bucket
22935 				 * that do not have the RTF_MULTIRT
22936 				 * flag. We don't process a copy
22937 				 * of the message here. This will be
22938 				 * done in the final sending loop.
22939 				 */
22940 				multirt_send = B_TRUE;
22941 			} else {
22942 				next_mp = ip_copymsg(first_mp);
22943 				if (next_mp != NULL)
22944 					IRE_REFHOLD(ire1);
22945 			}
22946 		}
22947 		rw_exit(&ire->ire_bucket->irb_lock);
22948 	}
22949 
22950 	if (stq) {
22951 		/*
22952 		 * A non-NULL send-to queue means this packet is going
22953 		 * out of this machine.
22954 		 */
22955 		out_ill = (ill_t *)stq->q_ptr;
22956 
22957 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22958 		ttl_protocol = ((uint16_t *)ipha)[4];
22959 		/*
22960 		 * We accumulate the pseudo header checksum in cksum.
22961 		 * This is pretty hairy code, so watch close.  One
22962 		 * thing to keep in mind is that UDP and TCP have
22963 		 * stored their respective datagram lengths in their
22964 		 * checksum fields.  This lines things up real nice.
22965 		 */
22966 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22967 		    (src >> 16) + (src & 0xFFFF);
22968 		/*
22969 		 * We assume the udp checksum field contains the
22970 		 * length, so to compute the pseudo header checksum,
22971 		 * all we need is the protocol number and src/dst.
22972 		 */
22973 		/* Provide the checksums for UDP and TCP. */
22974 		if ((PROTO == IPPROTO_TCP) &&
22975 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22976 			/* hlen gets the number of uchar_ts in the IP header */
22977 			hlen = (V_HLEN & 0xF) << 2;
22978 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22979 			IP_STAT(ipst, ip_out_sw_cksum);
22980 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22981 			    LENGTH - hlen);
22982 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22983 		} else if (PROTO == IPPROTO_SCTP &&
22984 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22985 			sctp_hdr_t	*sctph;
22986 
22987 			hlen = (V_HLEN & 0xF) << 2;
22988 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22989 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22990 			sctph->sh_chksum = 0;
22991 #ifdef	DEBUG
22992 			if (!skip_sctp_cksum)
22993 #endif
22994 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22995 		} else {
22996 			queue_t	*dev_q = stq->q_next;
22997 
22998 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22999 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
23000 blocked:
23001 				ipha->ipha_ident = ip_hdr_included;
23002 				/*
23003 				 * If we don't have a conn to apply
23004 				 * backpressure, free the message.
23005 				 * In the ire_send path, we don't know
23006 				 * the position to requeue the packet. Rather
23007 				 * than reorder packets, we just drop this
23008 				 * packet.
23009 				 */
23010 				if (ipst->ips_ip_output_queue &&
23011 				    connp != NULL &&
23012 				    caller != IRE_SEND) {
23013 					if (caller == IP_WSRV) {
23014 						idl_tx_list_t *idl_txl;
23015 
23016 						idl_txl =
23017 						    &ipst->ips_idl_tx_list[0];
23018 						connp->conn_did_putbq = 1;
23019 						(void) putbq(connp->conn_wq,
23020 						    first_mp);
23021 						conn_drain_insert(connp,
23022 						    idl_txl);
23023 						/*
23024 						 * This is the service thread,
23025 						 * and the queue is already
23026 						 * noenabled. The check for
23027 						 * canput and the putbq is not
23028 						 * atomic. So we need to check
23029 						 * again.
23030 						 */
23031 						if (canput(stq->q_next))
23032 							connp->conn_did_putbq
23033 							    = 0;
23034 						IP_STAT(ipst, ip_conn_flputbq);
23035 					} else {
23036 						/*
23037 						 * We are not the service proc.
23038 						 * ip_wsrv will be scheduled or
23039 						 * is already running.
23040 						 */
23041 
23042 						(void) putq(connp->conn_wq,
23043 						    first_mp);
23044 					}
23045 				} else {
23046 					out_ill = (ill_t *)stq->q_ptr;
23047 					BUMP_MIB(out_ill->ill_ip_mib,
23048 					    ipIfStatsOutDiscards);
23049 					freemsg(first_mp);
23050 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23051 					    "ip_wput_ire_end: q %p (%S)",
23052 					    q, "discard");
23053 				}
23054 				ire_refrele(ire);
23055 				if (next_mp) {
23056 					ire_refrele(ire1);
23057 					freemsg(next_mp);
23058 				}
23059 				if (conn_outgoing_ill != NULL)
23060 					ill_refrele(conn_outgoing_ill);
23061 				return;
23062 			}
23063 			if ((PROTO == IPPROTO_UDP) &&
23064 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23065 				/*
23066 				 * hlen gets the number of uchar_ts in the
23067 				 * IP header
23068 				 */
23069 				hlen = (V_HLEN & 0xF) << 2;
23070 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23071 				max_frag = ire->ire_max_frag;
23072 				if (*up != 0) {
23073 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23074 					    up, PROTO, hlen, LENGTH, max_frag,
23075 					    ipsec_len, cksum);
23076 					/* Software checksum? */
23077 					if (DB_CKSUMFLAGS(mp) == 0) {
23078 						IP_STAT(ipst, ip_out_sw_cksum);
23079 						IP_STAT_UPDATE(ipst,
23080 						    ip_udp_out_sw_cksum_bytes,
23081 						    LENGTH - hlen);
23082 					}
23083 				}
23084 			}
23085 		}
23086 		/*
23087 		 * Need to do this even when fragmenting. The local
23088 		 * loopback can be done without computing checksums
23089 		 * but forwarding out other interface must be done
23090 		 * after the IP checksum (and ULP checksums) have been
23091 		 * computed.
23092 		 *
23093 		 * NOTE : multicast_forward is set only if this packet
23094 		 * originated from ip_wput. For packets originating from
23095 		 * ip_wput_multicast, it is not set.
23096 		 */
23097 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23098 multi_loopback:
23099 			ip2dbg(("ip_wput: multicast, loop %d\n",
23100 			    conn_multicast_loop));
23101 
23102 			/*  Forget header checksum offload */
23103 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23104 
23105 			/*
23106 			 * Local loopback of multicasts?  Check the
23107 			 * ill.
23108 			 *
23109 			 * Note that the loopback function will not come
23110 			 * in through ip_rput - it will only do the
23111 			 * client fanout thus we need to do an mforward
23112 			 * as well.  The is different from the BSD
23113 			 * logic.
23114 			 */
23115 			if (ill != NULL) {
23116 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23117 				    ALL_ZONES) != NULL) {
23118 					/*
23119 					 * Pass along the virtual output q.
23120 					 * ip_wput_local() will distribute the
23121 					 * packet to all the matching zones,
23122 					 * except the sending zone when
23123 					 * IP_MULTICAST_LOOP is false.
23124 					 */
23125 					ip_multicast_loopback(q, ill, first_mp,
23126 					    conn_multicast_loop ? 0 :
23127 					    IP_FF_NO_MCAST_LOOP, zoneid);
23128 				}
23129 			}
23130 			if (ipha->ipha_ttl == 0) {
23131 				/*
23132 				 * 0 => only to this host i.e. we are
23133 				 * done. We are also done if this was the
23134 				 * loopback interface since it is sufficient
23135 				 * to loopback one copy of a multicast packet.
23136 				 */
23137 				freemsg(first_mp);
23138 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23139 				    "ip_wput_ire_end: q %p (%S)",
23140 				    q, "loopback");
23141 				ire_refrele(ire);
23142 				if (conn_outgoing_ill != NULL)
23143 					ill_refrele(conn_outgoing_ill);
23144 				return;
23145 			}
23146 			/*
23147 			 * ILLF_MULTICAST is checked in ip_newroute
23148 			 * i.e. we don't need to check it here since
23149 			 * all IRE_CACHEs come from ip_newroute.
23150 			 * For multicast traffic, SO_DONTROUTE is interpreted
23151 			 * to mean only send the packet out the interface
23152 			 * (optionally specified with IP_MULTICAST_IF)
23153 			 * and do not forward it out additional interfaces.
23154 			 * RSVP and the rsvp daemon is an example of a
23155 			 * protocol and user level process that
23156 			 * handles it's own routing. Hence, it uses the
23157 			 * SO_DONTROUTE option to accomplish this.
23158 			 */
23159 
23160 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23161 			    ill != NULL) {
23162 				/* Unconditionally redo the checksum */
23163 				ipha->ipha_hdr_checksum = 0;
23164 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23165 
23166 				/*
23167 				 * If this needs to go out secure, we need
23168 				 * to wait till we finish the IPsec
23169 				 * processing.
23170 				 */
23171 				if (ipsec_len == 0 &&
23172 				    ip_mforward(ill, ipha, mp)) {
23173 					freemsg(first_mp);
23174 					ip1dbg(("ip_wput: mforward failed\n"));
23175 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23176 					    "ip_wput_ire_end: q %p (%S)",
23177 					    q, "mforward failed");
23178 					ire_refrele(ire);
23179 					if (conn_outgoing_ill != NULL)
23180 						ill_refrele(conn_outgoing_ill);
23181 					return;
23182 				}
23183 			}
23184 		}
23185 		max_frag = ire->ire_max_frag;
23186 		cksum += ttl_protocol;
23187 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23188 			/* No fragmentation required for this one. */
23189 			/*
23190 			 * Don't use frag_flag if packet is pre-built or source
23191 			 * routed or if multicast (since multicast packets do
23192 			 * not solicit ICMP "packet too big" messages).
23193 			 */
23194 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23195 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23196 			    !ip_source_route_included(ipha)) &&
23197 			    !CLASSD(ipha->ipha_dst))
23198 				ipha->ipha_fragment_offset_and_flags |=
23199 				    htons(ire->ire_frag_flag);
23200 
23201 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23202 				/* Complete the IP header checksum. */
23203 				cksum += ipha->ipha_ident;
23204 				cksum += (v_hlen_tos_len >> 16)+
23205 				    (v_hlen_tos_len & 0xFFFF);
23206 				cksum += ipha->ipha_fragment_offset_and_flags;
23207 				hlen = (V_HLEN & 0xF) -
23208 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23209 				if (hlen) {
23210 checksumoptions:
23211 					/*
23212 					 * Account for the IP Options in the IP
23213 					 * header checksum.
23214 					 */
23215 					up = (uint16_t *)(rptr+
23216 					    IP_SIMPLE_HDR_LENGTH);
23217 					do {
23218 						cksum += up[0];
23219 						cksum += up[1];
23220 						up += 2;
23221 					} while (--hlen);
23222 				}
23223 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23224 				cksum = ~(cksum + (cksum >> 16));
23225 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23226 			}
23227 			if (ipsec_len != 0) {
23228 				ipsec_out_process(q, first_mp, ire, ill_index);
23229 				if (!next_mp) {
23230 					ire_refrele(ire);
23231 					if (conn_outgoing_ill != NULL)
23232 						ill_refrele(conn_outgoing_ill);
23233 					return;
23234 				}
23235 				goto next;
23236 			}
23237 
23238 			/*
23239 			 * multirt_send has already been handled
23240 			 * for broadcast, but not yet for multicast
23241 			 * or IP options.
23242 			 */
23243 			if (next_mp == NULL) {
23244 				if (ire->ire_flags & RTF_MULTIRT) {
23245 					multirt_send = B_TRUE;
23246 				}
23247 			}
23248 
23249 			/*
23250 			 * In most cases, the emission loop below is
23251 			 * entered only once. Only in the case where
23252 			 * the ire holds the RTF_MULTIRT flag, do we loop
23253 			 * to process all RTF_MULTIRT ires in the bucket,
23254 			 * and send the packet through all crossed
23255 			 * RTF_MULTIRT routes.
23256 			 */
23257 			do {
23258 				if (multirt_send) {
23259 					irb_t *irb;
23260 
23261 					irb = ire->ire_bucket;
23262 					ASSERT(irb != NULL);
23263 					/*
23264 					 * We are in a multiple send case,
23265 					 * need to get the next IRE and make
23266 					 * a duplicate of the packet.
23267 					 */
23268 					IRB_REFHOLD(irb);
23269 					for (ire1 = ire->ire_next;
23270 					    ire1 != NULL;
23271 					    ire1 = ire1->ire_next) {
23272 						if (!(ire1->ire_flags &
23273 						    RTF_MULTIRT))
23274 							continue;
23275 
23276 						if (ire1->ire_addr !=
23277 						    ire->ire_addr)
23278 							continue;
23279 
23280 						if (ire1->ire_marks &
23281 						    (IRE_MARK_CONDEMNED |
23282 						    IRE_MARK_TESTHIDDEN))
23283 							continue;
23284 
23285 						/* Got one */
23286 						IRE_REFHOLD(ire1);
23287 						break;
23288 					}
23289 					IRB_REFRELE(irb);
23290 
23291 					if (ire1 != NULL) {
23292 						next_mp = copyb(mp);
23293 						if ((next_mp == NULL) ||
23294 						    ((mp->b_cont != NULL) &&
23295 						    ((next_mp->b_cont =
23296 						    dupmsg(mp->b_cont))
23297 						    == NULL))) {
23298 							freemsg(next_mp);
23299 							next_mp = NULL;
23300 							ire_refrele(ire1);
23301 							ire1 = NULL;
23302 						}
23303 					}
23304 
23305 					/*
23306 					 * Last multiroute ire; don't loop
23307 					 * anymore. The emission is over
23308 					 * and next_mp is NULL.
23309 					 */
23310 					if (ire1 == NULL) {
23311 						multirt_send = B_FALSE;
23312 					}
23313 				}
23314 
23315 				out_ill = ire_to_ill(ire);
23316 				DTRACE_PROBE4(ip4__physical__out__start,
23317 				    ill_t *, NULL,
23318 				    ill_t *, out_ill,
23319 				    ipha_t *, ipha, mblk_t *, mp);
23320 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23321 				    ipst->ips_ipv4firewall_physical_out,
23322 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23323 				DTRACE_PROBE1(ip4__physical__out__end,
23324 				    mblk_t *, mp);
23325 				if (mp == NULL)
23326 					goto release_ire_and_ill_2;
23327 
23328 				ASSERT(ipsec_len == 0);
23329 				mp->b_prev =
23330 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23331 				DTRACE_PROBE2(ip__xmit__2,
23332 				    mblk_t *, mp, ire_t *, ire);
23333 				pktxmit_state = ip_xmit_v4(mp, ire,
23334 				    NULL, B_TRUE, connp);
23335 				if ((pktxmit_state == SEND_FAILED) ||
23336 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23337 release_ire_and_ill_2:
23338 					if (next_mp) {
23339 						freemsg(next_mp);
23340 						ire_refrele(ire1);
23341 					}
23342 					ire_refrele(ire);
23343 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23344 					    "ip_wput_ire_end: q %p (%S)",
23345 					    q, "discard MDATA");
23346 					if (conn_outgoing_ill != NULL)
23347 						ill_refrele(conn_outgoing_ill);
23348 					return;
23349 				}
23350 
23351 				if (CLASSD(dst)) {
23352 					BUMP_MIB(out_ill->ill_ip_mib,
23353 					    ipIfStatsHCOutMcastPkts);
23354 					UPDATE_MIB(out_ill->ill_ip_mib,
23355 					    ipIfStatsHCOutMcastOctets,
23356 					    LENGTH);
23357 				} else if (ire->ire_type == IRE_BROADCAST) {
23358 					BUMP_MIB(out_ill->ill_ip_mib,
23359 					    ipIfStatsHCOutBcastPkts);
23360 				}
23361 
23362 				if (multirt_send) {
23363 					/*
23364 					 * We are in a multiple send case,
23365 					 * need to re-enter the sending loop
23366 					 * using the next ire.
23367 					 */
23368 					ire_refrele(ire);
23369 					ire = ire1;
23370 					stq = ire->ire_stq;
23371 					mp = next_mp;
23372 					next_mp = NULL;
23373 					ipha = (ipha_t *)mp->b_rptr;
23374 					ill_index = Q_TO_INDEX(stq);
23375 				}
23376 			} while (multirt_send);
23377 
23378 			if (!next_mp) {
23379 				/*
23380 				 * Last copy going out (the ultra-common
23381 				 * case).  Note that we intentionally replicate
23382 				 * the putnext rather than calling it before
23383 				 * the next_mp check in hopes of a little
23384 				 * tail-call action out of the compiler.
23385 				 */
23386 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23387 				    "ip_wput_ire_end: q %p (%S)",
23388 				    q, "last copy out(1)");
23389 				ire_refrele(ire);
23390 				if (conn_outgoing_ill != NULL)
23391 					ill_refrele(conn_outgoing_ill);
23392 				return;
23393 			}
23394 			/* More copies going out below. */
23395 		} else {
23396 			int offset;
23397 fragmentit:
23398 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23399 			/*
23400 			 * If this would generate a icmp_frag_needed message,
23401 			 * we need to handle it before we do the IPsec
23402 			 * processing. Otherwise, we need to strip the IPsec
23403 			 * headers before we send up the message to the ULPs
23404 			 * which becomes messy and difficult.
23405 			 */
23406 			if (ipsec_len != 0) {
23407 				if ((max_frag < (unsigned int)(LENGTH +
23408 				    ipsec_len)) && (offset & IPH_DF)) {
23409 					out_ill = (ill_t *)stq->q_ptr;
23410 					BUMP_MIB(out_ill->ill_ip_mib,
23411 					    ipIfStatsOutFragFails);
23412 					BUMP_MIB(out_ill->ill_ip_mib,
23413 					    ipIfStatsOutFragReqds);
23414 					ipha->ipha_hdr_checksum = 0;
23415 					ipha->ipha_hdr_checksum =
23416 					    (uint16_t)ip_csum_hdr(ipha);
23417 					icmp_frag_needed(ire->ire_stq, first_mp,
23418 					    max_frag, zoneid, ipst);
23419 					if (!next_mp) {
23420 						ire_refrele(ire);
23421 						if (conn_outgoing_ill != NULL) {
23422 							ill_refrele(
23423 							    conn_outgoing_ill);
23424 						}
23425 						return;
23426 					}
23427 				} else {
23428 					/*
23429 					 * This won't cause a icmp_frag_needed
23430 					 * message. to be generated. Send it on
23431 					 * the wire. Note that this could still
23432 					 * cause fragmentation and all we
23433 					 * do is the generation of the message
23434 					 * to the ULP if needed before IPsec.
23435 					 */
23436 					if (!next_mp) {
23437 						ipsec_out_process(q, first_mp,
23438 						    ire, ill_index);
23439 						TRACE_2(TR_FAC_IP,
23440 						    TR_IP_WPUT_IRE_END,
23441 						    "ip_wput_ire_end: q %p "
23442 						    "(%S)", q,
23443 						    "last ipsec_out_process");
23444 						ire_refrele(ire);
23445 						if (conn_outgoing_ill != NULL) {
23446 							ill_refrele(
23447 							    conn_outgoing_ill);
23448 						}
23449 						return;
23450 					}
23451 					ipsec_out_process(q, first_mp,
23452 					    ire, ill_index);
23453 				}
23454 			} else {
23455 				/*
23456 				 * Initiate IPPF processing. For
23457 				 * fragmentable packets we finish
23458 				 * all QOS packet processing before
23459 				 * calling:
23460 				 * ip_wput_ire_fragmentit->ip_wput_frag
23461 				 */
23462 
23463 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23464 					ip_process(IPP_LOCAL_OUT, &mp,
23465 					    ill_index);
23466 					if (mp == NULL) {
23467 						out_ill = (ill_t *)stq->q_ptr;
23468 						BUMP_MIB(out_ill->ill_ip_mib,
23469 						    ipIfStatsOutDiscards);
23470 						if (next_mp != NULL) {
23471 							freemsg(next_mp);
23472 							ire_refrele(ire1);
23473 						}
23474 						ire_refrele(ire);
23475 						TRACE_2(TR_FAC_IP,
23476 						    TR_IP_WPUT_IRE_END,
23477 						    "ip_wput_ire: q %p (%S)",
23478 						    q, "discard MDATA");
23479 						if (conn_outgoing_ill != NULL) {
23480 							ill_refrele(
23481 							    conn_outgoing_ill);
23482 						}
23483 						return;
23484 					}
23485 				}
23486 				if (!next_mp) {
23487 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23488 					    "ip_wput_ire_end: q %p (%S)",
23489 					    q, "last fragmentation");
23490 					ip_wput_ire_fragmentit(mp, ire,
23491 					    zoneid, ipst, connp);
23492 					ire_refrele(ire);
23493 					if (conn_outgoing_ill != NULL)
23494 						ill_refrele(conn_outgoing_ill);
23495 					return;
23496 				}
23497 				ip_wput_ire_fragmentit(mp, ire,
23498 				    zoneid, ipst, connp);
23499 			}
23500 		}
23501 	} else {
23502 nullstq:
23503 		/* A NULL stq means the destination address is local. */
23504 		UPDATE_OB_PKT_COUNT(ire);
23505 		ire->ire_last_used_time = lbolt;
23506 		ASSERT(ire->ire_ipif != NULL);
23507 		if (!next_mp) {
23508 			/*
23509 			 * Is there an "in" and "out" for traffic local
23510 			 * to a host (loopback)?  The code in Solaris doesn't
23511 			 * explicitly draw a line in its code for in vs out,
23512 			 * so we've had to draw a line in the sand: ip_wput_ire
23513 			 * is considered to be the "output" side and
23514 			 * ip_wput_local to be the "input" side.
23515 			 */
23516 			out_ill = ire_to_ill(ire);
23517 
23518 			/*
23519 			 * DTrace this as ip:::send.  A blocked packet will
23520 			 * fire the send probe, but not the receive probe.
23521 			 */
23522 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23523 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23524 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23525 
23526 			DTRACE_PROBE4(ip4__loopback__out__start,
23527 			    ill_t *, NULL, ill_t *, out_ill,
23528 			    ipha_t *, ipha, mblk_t *, first_mp);
23529 
23530 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23531 			    ipst->ips_ipv4firewall_loopback_out,
23532 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23533 
23534 			DTRACE_PROBE1(ip4__loopback__out_end,
23535 			    mblk_t *, first_mp);
23536 
23537 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23538 			    "ip_wput_ire_end: q %p (%S)",
23539 			    q, "local address");
23540 
23541 			if (first_mp != NULL)
23542 				ip_wput_local(q, out_ill, ipha,
23543 				    first_mp, ire, 0, ire->ire_zoneid);
23544 			ire_refrele(ire);
23545 			if (conn_outgoing_ill != NULL)
23546 				ill_refrele(conn_outgoing_ill);
23547 			return;
23548 		}
23549 
23550 		out_ill = ire_to_ill(ire);
23551 
23552 		/*
23553 		 * DTrace this as ip:::send.  A blocked packet will fire the
23554 		 * send probe, but not the receive probe.
23555 		 */
23556 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23557 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23558 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23559 
23560 		DTRACE_PROBE4(ip4__loopback__out__start,
23561 		    ill_t *, NULL, ill_t *, out_ill,
23562 		    ipha_t *, ipha, mblk_t *, first_mp);
23563 
23564 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23565 		    ipst->ips_ipv4firewall_loopback_out,
23566 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23567 
23568 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23569 
23570 		if (first_mp != NULL)
23571 			ip_wput_local(q, out_ill, ipha,
23572 			    first_mp, ire, 0, ire->ire_zoneid);
23573 	}
23574 next:
23575 	/*
23576 	 * More copies going out to additional interfaces.
23577 	 * ire1 has already been held. We don't need the
23578 	 * "ire" anymore.
23579 	 */
23580 	ire_refrele(ire);
23581 	ire = ire1;
23582 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23583 	mp = next_mp;
23584 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23585 	ill = ire_to_ill(ire);
23586 	first_mp = mp;
23587 	if (ipsec_len != 0) {
23588 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23589 		mp = mp->b_cont;
23590 	}
23591 	dst = ire->ire_addr;
23592 	ipha = (ipha_t *)mp->b_rptr;
23593 	/*
23594 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23595 	 * Restore ipha_ident "no checksum" flag.
23596 	 */
23597 	src = orig_src;
23598 	ipha->ipha_ident = ip_hdr_included;
23599 	goto another;
23600 
23601 #undef	rptr
23602 #undef	Q_TO_INDEX
23603 }
23604 
23605 /*
23606  * Routine to allocate a message that is used to notify the ULP about MDT.
23607  * The caller may provide a pointer to the link-layer MDT capabilities,
23608  * or NULL if MDT is to be disabled on the stream.
23609  */
23610 mblk_t *
23611 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23612 {
23613 	mblk_t *mp;
23614 	ip_mdt_info_t *mdti;
23615 	ill_mdt_capab_t *idst;
23616 
23617 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23618 		DB_TYPE(mp) = M_CTL;
23619 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23620 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23621 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23622 		idst = &(mdti->mdt_capab);
23623 
23624 		/*
23625 		 * If the caller provides us with the capability, copy
23626 		 * it over into our notification message; otherwise
23627 		 * we zero out the capability portion.
23628 		 */
23629 		if (isrc != NULL)
23630 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23631 		else
23632 			bzero((caddr_t)idst, sizeof (*idst));
23633 	}
23634 	return (mp);
23635 }
23636 
23637 /*
23638  * Routine which determines whether MDT can be enabled on the destination
23639  * IRE and IPC combination, and if so, allocates and returns the MDT
23640  * notification mblk that may be used by ULP.  We also check if we need to
23641  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23642  * MDT usage in the past have been lifted.  This gets called during IP
23643  * and ULP binding.
23644  */
23645 mblk_t *
23646 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23647     ill_mdt_capab_t *mdt_cap)
23648 {
23649 	mblk_t *mp;
23650 	boolean_t rc = B_FALSE;
23651 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23652 
23653 	ASSERT(dst_ire != NULL);
23654 	ASSERT(connp != NULL);
23655 	ASSERT(mdt_cap != NULL);
23656 
23657 	/*
23658 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23659 	 * Multidata, which is handled in tcp_multisend().  This
23660 	 * is the reason why we do all these checks here, to ensure
23661 	 * that we don't enable Multidata for the cases which we
23662 	 * can't handle at the moment.
23663 	 */
23664 	do {
23665 		/* Only do TCP at the moment */
23666 		if (connp->conn_ulp != IPPROTO_TCP)
23667 			break;
23668 
23669 		/*
23670 		 * IPsec outbound policy present?  Note that we get here
23671 		 * after calling ipsec_conn_cache_policy() where the global
23672 		 * policy checking is performed.  conn_latch will be
23673 		 * non-NULL as long as there's a policy defined,
23674 		 * i.e. conn_out_enforce_policy may be NULL in such case
23675 		 * when the connection is non-secure, and hence we check
23676 		 * further if the latch refers to an outbound policy.
23677 		 */
23678 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23679 			break;
23680 
23681 		/* CGTP (multiroute) is enabled? */
23682 		if (dst_ire->ire_flags & RTF_MULTIRT)
23683 			break;
23684 
23685 		/* Outbound IPQoS enabled? */
23686 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23687 			/*
23688 			 * In this case, we disable MDT for this and all
23689 			 * future connections going over the interface.
23690 			 */
23691 			mdt_cap->ill_mdt_on = 0;
23692 			break;
23693 		}
23694 
23695 		/* socket option(s) present? */
23696 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23697 			break;
23698 
23699 		rc = B_TRUE;
23700 	/* CONSTCOND */
23701 	} while (0);
23702 
23703 	/* Remember the result */
23704 	connp->conn_mdt_ok = rc;
23705 
23706 	if (!rc)
23707 		return (NULL);
23708 	else if (!mdt_cap->ill_mdt_on) {
23709 		/*
23710 		 * If MDT has been previously turned off in the past, and we
23711 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23712 		 * then enable it for this interface.
23713 		 */
23714 		mdt_cap->ill_mdt_on = 1;
23715 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23716 		    "interface %s\n", ill_name));
23717 	}
23718 
23719 	/* Allocate the MDT info mblk */
23720 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23721 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23722 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23723 		return (NULL);
23724 	}
23725 	return (mp);
23726 }
23727 
23728 /*
23729  * Routine to allocate a message that is used to notify the ULP about LSO.
23730  * The caller may provide a pointer to the link-layer LSO capabilities,
23731  * or NULL if LSO is to be disabled on the stream.
23732  */
23733 mblk_t *
23734 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23735 {
23736 	mblk_t *mp;
23737 	ip_lso_info_t *lsoi;
23738 	ill_lso_capab_t *idst;
23739 
23740 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23741 		DB_TYPE(mp) = M_CTL;
23742 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23743 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23744 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23745 		idst = &(lsoi->lso_capab);
23746 
23747 		/*
23748 		 * If the caller provides us with the capability, copy
23749 		 * it over into our notification message; otherwise
23750 		 * we zero out the capability portion.
23751 		 */
23752 		if (isrc != NULL)
23753 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23754 		else
23755 			bzero((caddr_t)idst, sizeof (*idst));
23756 	}
23757 	return (mp);
23758 }
23759 
23760 /*
23761  * Routine which determines whether LSO can be enabled on the destination
23762  * IRE and IPC combination, and if so, allocates and returns the LSO
23763  * notification mblk that may be used by ULP.  We also check if we need to
23764  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23765  * LSO usage in the past have been lifted.  This gets called during IP
23766  * and ULP binding.
23767  */
23768 mblk_t *
23769 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23770     ill_lso_capab_t *lso_cap)
23771 {
23772 	mblk_t *mp;
23773 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23774 
23775 	ASSERT(dst_ire != NULL);
23776 	ASSERT(connp != NULL);
23777 	ASSERT(lso_cap != NULL);
23778 
23779 	connp->conn_lso_ok = B_TRUE;
23780 
23781 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23782 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23783 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23784 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23785 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23786 		connp->conn_lso_ok = B_FALSE;
23787 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23788 			/*
23789 			 * Disable LSO for this and all future connections going
23790 			 * over the interface.
23791 			 */
23792 			lso_cap->ill_lso_on = 0;
23793 		}
23794 	}
23795 
23796 	if (!connp->conn_lso_ok)
23797 		return (NULL);
23798 	else if (!lso_cap->ill_lso_on) {
23799 		/*
23800 		 * If LSO has been previously turned off in the past, and we
23801 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23802 		 * then enable it for this interface.
23803 		 */
23804 		lso_cap->ill_lso_on = 1;
23805 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23806 		    ill_name));
23807 	}
23808 
23809 	/* Allocate the LSO info mblk */
23810 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23811 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23812 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23813 
23814 	return (mp);
23815 }
23816 
23817 /*
23818  * Create destination address attribute, and fill it with the physical
23819  * destination address and SAP taken from the template DL_UNITDATA_REQ
23820  * message block.
23821  */
23822 boolean_t
23823 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23824 {
23825 	dl_unitdata_req_t *dlurp;
23826 	pattr_t *pa;
23827 	pattrinfo_t pa_info;
23828 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23829 	uint_t das_len, das_off;
23830 
23831 	ASSERT(dlmp != NULL);
23832 
23833 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23834 	das_len = dlurp->dl_dest_addr_length;
23835 	das_off = dlurp->dl_dest_addr_offset;
23836 
23837 	pa_info.type = PATTR_DSTADDRSAP;
23838 	pa_info.len = sizeof (**das) + das_len - 1;
23839 
23840 	/* create and associate the attribute */
23841 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23842 	if (pa != NULL) {
23843 		ASSERT(*das != NULL);
23844 		(*das)->addr_is_group = 0;
23845 		(*das)->addr_len = (uint8_t)das_len;
23846 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23847 	}
23848 
23849 	return (pa != NULL);
23850 }
23851 
23852 /*
23853  * Create hardware checksum attribute and fill it with the values passed.
23854  */
23855 boolean_t
23856 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23857     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23858 {
23859 	pattr_t *pa;
23860 	pattrinfo_t pa_info;
23861 
23862 	ASSERT(mmd != NULL);
23863 
23864 	pa_info.type = PATTR_HCKSUM;
23865 	pa_info.len = sizeof (pattr_hcksum_t);
23866 
23867 	/* create and associate the attribute */
23868 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23869 	if (pa != NULL) {
23870 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23871 
23872 		hck->hcksum_start_offset = start_offset;
23873 		hck->hcksum_stuff_offset = stuff_offset;
23874 		hck->hcksum_end_offset = end_offset;
23875 		hck->hcksum_flags = flags;
23876 	}
23877 	return (pa != NULL);
23878 }
23879 
23880 /*
23881  * Create zerocopy attribute and fill it with the specified flags
23882  */
23883 boolean_t
23884 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23885 {
23886 	pattr_t *pa;
23887 	pattrinfo_t pa_info;
23888 
23889 	ASSERT(mmd != NULL);
23890 	pa_info.type = PATTR_ZCOPY;
23891 	pa_info.len = sizeof (pattr_zcopy_t);
23892 
23893 	/* create and associate the attribute */
23894 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23895 	if (pa != NULL) {
23896 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23897 
23898 		zcopy->zcopy_flags = flags;
23899 	}
23900 	return (pa != NULL);
23901 }
23902 
23903 /*
23904  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23905  * block chain. We could rewrite to handle arbitrary message block chains but
23906  * that would make the code complicated and slow. Right now there three
23907  * restrictions:
23908  *
23909  *   1. The first message block must contain the complete IP header and
23910  *	at least 1 byte of payload data.
23911  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23912  *	so that we can use a single Multidata message.
23913  *   3. No frag must be distributed over two or more message blocks so
23914  *	that we don't need more than two packet descriptors per frag.
23915  *
23916  * The above restrictions allow us to support userland applications (which
23917  * will send down a single message block) and NFS over UDP (which will
23918  * send down a chain of at most three message blocks).
23919  *
23920  * We also don't use MDT for payloads with less than or equal to
23921  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23922  */
23923 boolean_t
23924 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23925 {
23926 	int	blocks;
23927 	ssize_t	total, missing, size;
23928 
23929 	ASSERT(mp != NULL);
23930 	ASSERT(hdr_len > 0);
23931 
23932 	size = MBLKL(mp) - hdr_len;
23933 	if (size <= 0)
23934 		return (B_FALSE);
23935 
23936 	/* The first mblk contains the header and some payload. */
23937 	blocks = 1;
23938 	total = size;
23939 	size %= len;
23940 	missing = (size == 0) ? 0 : (len - size);
23941 	mp = mp->b_cont;
23942 
23943 	while (mp != NULL) {
23944 		/*
23945 		 * Give up if we encounter a zero length message block.
23946 		 * In practice, this should rarely happen and therefore
23947 		 * not worth the trouble of freeing and re-linking the
23948 		 * mblk from the chain to handle such case.
23949 		 */
23950 		if ((size = MBLKL(mp)) == 0)
23951 			return (B_FALSE);
23952 
23953 		/* Too many payload buffers for a single Multidata message? */
23954 		if (++blocks > MULTIDATA_MAX_PBUFS)
23955 			return (B_FALSE);
23956 
23957 		total += size;
23958 		/* Is a frag distributed over two or more message blocks? */
23959 		if (missing > size)
23960 			return (B_FALSE);
23961 		size -= missing;
23962 
23963 		size %= len;
23964 		missing = (size == 0) ? 0 : (len - size);
23965 
23966 		mp = mp->b_cont;
23967 	}
23968 
23969 	return (total > ip_wput_frag_mdt_min);
23970 }
23971 
23972 /*
23973  * Outbound IPv4 fragmentation routine using MDT.
23974  */
23975 static void
23976 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23977     uint32_t frag_flag, int offset)
23978 {
23979 	ipha_t		*ipha_orig;
23980 	int		i1, ip_data_end;
23981 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23982 	mblk_t		*hdr_mp, *md_mp = NULL;
23983 	unsigned char	*hdr_ptr, *pld_ptr;
23984 	multidata_t	*mmd;
23985 	ip_pdescinfo_t	pdi;
23986 	ill_t		*ill;
23987 	ip_stack_t	*ipst = ire->ire_ipst;
23988 
23989 	ASSERT(DB_TYPE(mp) == M_DATA);
23990 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23991 
23992 	ill = ire_to_ill(ire);
23993 	ASSERT(ill != NULL);
23994 
23995 	ipha_orig = (ipha_t *)mp->b_rptr;
23996 	mp->b_rptr += sizeof (ipha_t);
23997 
23998 	/* Calculate how many packets we will send out */
23999 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24000 	pkts = (i1 + len - 1) / len;
24001 	ASSERT(pkts > 1);
24002 
24003 	/* Allocate a message block which will hold all the IP Headers. */
24004 	wroff = ipst->ips_ip_wroff_extra;
24005 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24006 
24007 	i1 = pkts * hdr_chunk_len;
24008 	/*
24009 	 * Create the header buffer, Multidata and destination address
24010 	 * and SAP attribute that should be associated with it.
24011 	 */
24012 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24013 	    ((hdr_mp->b_wptr += i1),
24014 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24015 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24016 		freemsg(mp);
24017 		if (md_mp == NULL) {
24018 			freemsg(hdr_mp);
24019 		} else {
24020 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24021 			freemsg(md_mp);
24022 		}
24023 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24024 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24025 		return;
24026 	}
24027 	IP_STAT(ipst, ip_frag_mdt_allocd);
24028 
24029 	/*
24030 	 * Add a payload buffer to the Multidata; this operation must not
24031 	 * fail, or otherwise our logic in this routine is broken.  There
24032 	 * is no memory allocation done by the routine, so any returned
24033 	 * failure simply tells us that we've done something wrong.
24034 	 *
24035 	 * A failure tells us that either we're adding the same payload
24036 	 * buffer more than once, or we're trying to add more buffers than
24037 	 * allowed.  None of the above cases should happen, and we panic
24038 	 * because either there's horrible heap corruption, and/or
24039 	 * programming mistake.
24040 	 */
24041 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24042 		goto pbuf_panic;
24043 
24044 	hdr_ptr = hdr_mp->b_rptr;
24045 	pld_ptr = mp->b_rptr;
24046 
24047 	/* Establish the ending byte offset, based on the starting offset. */
24048 	offset <<= 3;
24049 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24050 	    IP_SIMPLE_HDR_LENGTH;
24051 
24052 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24053 
24054 	while (pld_ptr < mp->b_wptr) {
24055 		ipha_t		*ipha;
24056 		uint16_t	offset_and_flags;
24057 		uint16_t	ip_len;
24058 		int		error;
24059 
24060 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24061 		ipha = (ipha_t *)(hdr_ptr + wroff);
24062 		ASSERT(OK_32PTR(ipha));
24063 		*ipha = *ipha_orig;
24064 
24065 		if (ip_data_end - offset > len) {
24066 			offset_and_flags = IPH_MF;
24067 		} else {
24068 			/*
24069 			 * Last frag. Set len to the length of this last piece.
24070 			 */
24071 			len = ip_data_end - offset;
24072 			/* A frag of a frag might have IPH_MF non-zero */
24073 			offset_and_flags =
24074 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24075 			    IPH_MF;
24076 		}
24077 		offset_and_flags |= (uint16_t)(offset >> 3);
24078 		offset_and_flags |= (uint16_t)frag_flag;
24079 		/* Store the offset and flags in the IP header. */
24080 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24081 
24082 		/* Store the length in the IP header. */
24083 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24084 		ipha->ipha_length = htons(ip_len);
24085 
24086 		/*
24087 		 * Set the IP header checksum.  Note that mp is just
24088 		 * the header, so this is easy to pass to ip_csum.
24089 		 */
24090 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24091 
24092 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24093 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24094 		    NULL, int, 0);
24095 
24096 		/*
24097 		 * Record offset and size of header and data of the next packet
24098 		 * in the multidata message.
24099 		 */
24100 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24101 		PDESC_PLD_INIT(&pdi);
24102 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24103 		ASSERT(i1 > 0);
24104 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24105 		if (i1 == len) {
24106 			pld_ptr += len;
24107 		} else {
24108 			i1 = len - i1;
24109 			mp = mp->b_cont;
24110 			ASSERT(mp != NULL);
24111 			ASSERT(MBLKL(mp) >= i1);
24112 			/*
24113 			 * Attach the next payload message block to the
24114 			 * multidata message.
24115 			 */
24116 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24117 				goto pbuf_panic;
24118 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24119 			pld_ptr = mp->b_rptr + i1;
24120 		}
24121 
24122 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24123 		    KM_NOSLEEP)) == NULL) {
24124 			/*
24125 			 * Any failure other than ENOMEM indicates that we
24126 			 * have passed in invalid pdesc info or parameters
24127 			 * to mmd_addpdesc, which must not happen.
24128 			 *
24129 			 * EINVAL is a result of failure on boundary checks
24130 			 * against the pdesc info contents.  It should not
24131 			 * happen, and we panic because either there's
24132 			 * horrible heap corruption, and/or programming
24133 			 * mistake.
24134 			 */
24135 			if (error != ENOMEM) {
24136 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24137 				    "pdesc logic error detected for "
24138 				    "mmd %p pinfo %p (%d)\n",
24139 				    (void *)mmd, (void *)&pdi, error);
24140 				/* NOTREACHED */
24141 			}
24142 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24143 			/* Free unattached payload message blocks as well */
24144 			md_mp->b_cont = mp->b_cont;
24145 			goto free_mmd;
24146 		}
24147 
24148 		/* Advance fragment offset. */
24149 		offset += len;
24150 
24151 		/* Advance to location for next header in the buffer. */
24152 		hdr_ptr += hdr_chunk_len;
24153 
24154 		/* Did we reach the next payload message block? */
24155 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24156 			mp = mp->b_cont;
24157 			/*
24158 			 * Attach the next message block with payload
24159 			 * data to the multidata message.
24160 			 */
24161 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24162 				goto pbuf_panic;
24163 			pld_ptr = mp->b_rptr;
24164 		}
24165 	}
24166 
24167 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24168 	ASSERT(mp->b_wptr == pld_ptr);
24169 
24170 	/* Update IP statistics */
24171 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24172 
24173 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24174 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24175 
24176 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24177 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24178 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24179 
24180 	if (pkt_type == OB_PKT) {
24181 		ire->ire_ob_pkt_count += pkts;
24182 		if (ire->ire_ipif != NULL)
24183 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24184 	} else {
24185 		/* The type is IB_PKT in the forwarding path. */
24186 		ire->ire_ib_pkt_count += pkts;
24187 		ASSERT(!IRE_IS_LOCAL(ire));
24188 		if (ire->ire_type & IRE_BROADCAST) {
24189 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24190 		} else {
24191 			UPDATE_MIB(ill->ill_ip_mib,
24192 			    ipIfStatsHCOutForwDatagrams, pkts);
24193 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24194 		}
24195 	}
24196 	ire->ire_last_used_time = lbolt;
24197 	/* Send it down */
24198 	putnext(ire->ire_stq, md_mp);
24199 	return;
24200 
24201 pbuf_panic:
24202 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24203 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24204 	    pbuf_idx);
24205 	/* NOTREACHED */
24206 }
24207 
24208 /*
24209  * Outbound IP fragmentation routine.
24210  *
24211  * NOTE : This routine does not ire_refrele the ire that is passed in
24212  * as the argument.
24213  */
24214 static void
24215 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24216     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24217 {
24218 	int		i1;
24219 	mblk_t		*ll_hdr_mp;
24220 	int 		ll_hdr_len;
24221 	int		hdr_len;
24222 	mblk_t		*hdr_mp;
24223 	ipha_t		*ipha;
24224 	int		ip_data_end;
24225 	int		len;
24226 	mblk_t		*mp = mp_orig, *mp1;
24227 	int		offset;
24228 	queue_t		*q;
24229 	uint32_t	v_hlen_tos_len;
24230 	mblk_t		*first_mp;
24231 	boolean_t	mctl_present;
24232 	ill_t		*ill;
24233 	ill_t		*out_ill;
24234 	mblk_t		*xmit_mp;
24235 	mblk_t		*carve_mp;
24236 	ire_t		*ire1 = NULL;
24237 	ire_t		*save_ire = NULL;
24238 	mblk_t  	*next_mp = NULL;
24239 	boolean_t	last_frag = B_FALSE;
24240 	boolean_t	multirt_send = B_FALSE;
24241 	ire_t		*first_ire = NULL;
24242 	irb_t		*irb = NULL;
24243 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24244 
24245 	ill = ire_to_ill(ire);
24246 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24247 
24248 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24249 
24250 	if (max_frag == 0) {
24251 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24252 		    " -  dropping packet\n"));
24253 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24254 		freemsg(mp);
24255 		return;
24256 	}
24257 
24258 	/*
24259 	 * IPsec does not allow hw accelerated packets to be fragmented
24260 	 * This check is made in ip_wput_ipsec_out prior to coming here
24261 	 * via ip_wput_ire_fragmentit.
24262 	 *
24263 	 * If at this point we have an ire whose ARP request has not
24264 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24265 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24266 	 * This packet and all fragmentable packets for this ire will
24267 	 * continue to get dropped while ire_nce->nce_state remains in
24268 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24269 	 * ND_REACHABLE, all subsquent large packets for this ire will
24270 	 * get fragemented and sent out by this function.
24271 	 */
24272 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24273 		/* If nce_state is ND_INITIAL, trigger ARP query */
24274 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24275 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24276 		    " -  dropping packet\n"));
24277 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24278 		freemsg(mp);
24279 		return;
24280 	}
24281 
24282 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24283 	    "ip_wput_frag_start:");
24284 
24285 	if (mp->b_datap->db_type == M_CTL) {
24286 		first_mp = mp;
24287 		mp_orig = mp = mp->b_cont;
24288 		mctl_present = B_TRUE;
24289 	} else {
24290 		first_mp = mp;
24291 		mctl_present = B_FALSE;
24292 	}
24293 
24294 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24295 	ipha = (ipha_t *)mp->b_rptr;
24296 
24297 	/*
24298 	 * If the Don't Fragment flag is on, generate an ICMP destination
24299 	 * unreachable, fragmentation needed.
24300 	 */
24301 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24302 	if (offset & IPH_DF) {
24303 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24304 		if (is_system_labeled()) {
24305 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24306 			    ire->ire_max_frag - max_frag, AF_INET);
24307 		}
24308 		/*
24309 		 * Need to compute hdr checksum if called from ip_wput_ire.
24310 		 * Note that ip_rput_forward verifies the checksum before
24311 		 * calling this routine so in that case this is a noop.
24312 		 */
24313 		ipha->ipha_hdr_checksum = 0;
24314 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24315 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24316 		    ipst);
24317 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24318 		    "ip_wput_frag_end:(%S)",
24319 		    "don't fragment");
24320 		return;
24321 	}
24322 	/*
24323 	 * Labeled systems adjust max_frag if they add a label
24324 	 * to send the correct path mtu.  We need the real mtu since we
24325 	 * are fragmenting the packet after label adjustment.
24326 	 */
24327 	if (is_system_labeled())
24328 		max_frag = ire->ire_max_frag;
24329 	if (mctl_present)
24330 		freeb(first_mp);
24331 	/*
24332 	 * Establish the starting offset.  May not be zero if we are fragging
24333 	 * a fragment that is being forwarded.
24334 	 */
24335 	offset = offset & IPH_OFFSET;
24336 
24337 	/* TODO why is this test needed? */
24338 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24339 	if (((max_frag - LENGTH) & ~7) < 8) {
24340 		/* TODO: notify ulp somehow */
24341 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24342 		freemsg(mp);
24343 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24344 		    "ip_wput_frag_end:(%S)",
24345 		    "len < 8");
24346 		return;
24347 	}
24348 
24349 	hdr_len = (V_HLEN & 0xF) << 2;
24350 
24351 	ipha->ipha_hdr_checksum = 0;
24352 
24353 	/*
24354 	 * Establish the number of bytes maximum per frag, after putting
24355 	 * in the header.
24356 	 */
24357 	len = (max_frag - hdr_len) & ~7;
24358 
24359 	/* Check if we can use MDT to send out the frags. */
24360 	ASSERT(!IRE_IS_LOCAL(ire));
24361 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24362 	    ipst->ips_ip_multidata_outbound &&
24363 	    !(ire->ire_flags & RTF_MULTIRT) &&
24364 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24365 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24366 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24367 		ASSERT(ill->ill_mdt_capab != NULL);
24368 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24369 			/*
24370 			 * If MDT has been previously turned off in the past,
24371 			 * and we currently can do MDT (due to IPQoS policy
24372 			 * removal, etc.) then enable it for this interface.
24373 			 */
24374 			ill->ill_mdt_capab->ill_mdt_on = 1;
24375 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24376 			    ill->ill_name));
24377 		}
24378 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24379 		    offset);
24380 		return;
24381 	}
24382 
24383 	/* Get a copy of the header for the trailing frags */
24384 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24385 	    mp);
24386 	if (!hdr_mp) {
24387 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24388 		freemsg(mp);
24389 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24390 		    "ip_wput_frag_end:(%S)",
24391 		    "couldn't copy hdr");
24392 		return;
24393 	}
24394 
24395 	/* Store the starting offset, with the MoreFrags flag. */
24396 	i1 = offset | IPH_MF | frag_flag;
24397 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24398 
24399 	/* Establish the ending byte offset, based on the starting offset. */
24400 	offset <<= 3;
24401 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24402 
24403 	/* Store the length of the first fragment in the IP header. */
24404 	i1 = len + hdr_len;
24405 	ASSERT(i1 <= IP_MAXPACKET);
24406 	ipha->ipha_length = htons((uint16_t)i1);
24407 
24408 	/*
24409 	 * Compute the IP header checksum for the first frag.  We have to
24410 	 * watch out that we stop at the end of the header.
24411 	 */
24412 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24413 
24414 	/*
24415 	 * Now carve off the first frag.  Note that this will include the
24416 	 * original IP header.
24417 	 */
24418 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24419 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24420 		freeb(hdr_mp);
24421 		freemsg(mp_orig);
24422 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24423 		    "ip_wput_frag_end:(%S)",
24424 		    "couldn't carve first");
24425 		return;
24426 	}
24427 
24428 	/*
24429 	 * Multirouting case. Each fragment is replicated
24430 	 * via all non-condemned RTF_MULTIRT routes
24431 	 * currently resolved.
24432 	 * We ensure that first_ire is the first RTF_MULTIRT
24433 	 * ire in the bucket.
24434 	 */
24435 	if (ire->ire_flags & RTF_MULTIRT) {
24436 		irb = ire->ire_bucket;
24437 		ASSERT(irb != NULL);
24438 
24439 		multirt_send = B_TRUE;
24440 
24441 		/* Make sure we do not omit any multiroute ire. */
24442 		IRB_REFHOLD(irb);
24443 		for (first_ire = irb->irb_ire;
24444 		    first_ire != NULL;
24445 		    first_ire = first_ire->ire_next) {
24446 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24447 			    (first_ire->ire_addr == ire->ire_addr) &&
24448 			    !(first_ire->ire_marks &
24449 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24450 				break;
24451 		}
24452 
24453 		if (first_ire != NULL) {
24454 			if (first_ire != ire) {
24455 				IRE_REFHOLD(first_ire);
24456 				/*
24457 				 * Do not release the ire passed in
24458 				 * as the argument.
24459 				 */
24460 				ire = first_ire;
24461 			} else {
24462 				first_ire = NULL;
24463 			}
24464 		}
24465 		IRB_REFRELE(irb);
24466 
24467 		/*
24468 		 * Save the first ire; we will need to restore it
24469 		 * for the trailing frags.
24470 		 * We REFHOLD save_ire, as each iterated ire will be
24471 		 * REFRELEd.
24472 		 */
24473 		save_ire = ire;
24474 		IRE_REFHOLD(save_ire);
24475 	}
24476 
24477 	/*
24478 	 * First fragment emission loop.
24479 	 * In most cases, the emission loop below is entered only
24480 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24481 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24482 	 * bucket, and send the fragment through all crossed
24483 	 * RTF_MULTIRT routes.
24484 	 */
24485 	do {
24486 		if (ire->ire_flags & RTF_MULTIRT) {
24487 			/*
24488 			 * We are in a multiple send case, need to get
24489 			 * the next ire and make a copy of the packet.
24490 			 * ire1 holds here the next ire to process in the
24491 			 * bucket. If multirouting is expected,
24492 			 * any non-RTF_MULTIRT ire that has the
24493 			 * right destination address is ignored.
24494 			 *
24495 			 * We have to take into account the MTU of
24496 			 * each walked ire. max_frag is set by the
24497 			 * the caller and generally refers to
24498 			 * the primary ire entry. Here we ensure that
24499 			 * no route with a lower MTU will be used, as
24500 			 * fragments are carved once for all ires,
24501 			 * then replicated.
24502 			 */
24503 			ASSERT(irb != NULL);
24504 			IRB_REFHOLD(irb);
24505 			for (ire1 = ire->ire_next;
24506 			    ire1 != NULL;
24507 			    ire1 = ire1->ire_next) {
24508 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24509 					continue;
24510 				if (ire1->ire_addr != ire->ire_addr)
24511 					continue;
24512 				if (ire1->ire_marks &
24513 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24514 					continue;
24515 				/*
24516 				 * Ensure we do not exceed the MTU
24517 				 * of the next route.
24518 				 */
24519 				if (ire1->ire_max_frag < max_frag) {
24520 					ip_multirt_bad_mtu(ire1, max_frag);
24521 					continue;
24522 				}
24523 
24524 				/* Got one. */
24525 				IRE_REFHOLD(ire1);
24526 				break;
24527 			}
24528 			IRB_REFRELE(irb);
24529 
24530 			if (ire1 != NULL) {
24531 				next_mp = copyb(mp);
24532 				if ((next_mp == NULL) ||
24533 				    ((mp->b_cont != NULL) &&
24534 				    ((next_mp->b_cont =
24535 				    dupmsg(mp->b_cont)) == NULL))) {
24536 					freemsg(next_mp);
24537 					next_mp = NULL;
24538 					ire_refrele(ire1);
24539 					ire1 = NULL;
24540 				}
24541 			}
24542 
24543 			/* Last multiroute ire; don't loop anymore. */
24544 			if (ire1 == NULL) {
24545 				multirt_send = B_FALSE;
24546 			}
24547 		}
24548 
24549 		ll_hdr_len = 0;
24550 		LOCK_IRE_FP_MP(ire);
24551 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24552 		if (ll_hdr_mp != NULL) {
24553 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24554 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24555 		} else {
24556 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24557 		}
24558 
24559 		/* If there is a transmit header, get a copy for this frag. */
24560 		/*
24561 		 * TODO: should check db_ref before calling ip_carve_mp since
24562 		 * it might give us a dup.
24563 		 */
24564 		if (!ll_hdr_mp) {
24565 			/* No xmit header. */
24566 			xmit_mp = mp;
24567 
24568 		/* We have a link-layer header that can fit in our mblk. */
24569 		} else if (mp->b_datap->db_ref == 1 &&
24570 		    ll_hdr_len != 0 &&
24571 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24572 			/* M_DATA fastpath */
24573 			mp->b_rptr -= ll_hdr_len;
24574 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24575 			xmit_mp = mp;
24576 
24577 		/* Corner case if copyb has failed */
24578 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24579 			UNLOCK_IRE_FP_MP(ire);
24580 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24581 			freeb(hdr_mp);
24582 			freemsg(mp);
24583 			freemsg(mp_orig);
24584 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24585 			    "ip_wput_frag_end:(%S)",
24586 			    "discard");
24587 
24588 			if (multirt_send) {
24589 				ASSERT(ire1);
24590 				ASSERT(next_mp);
24591 
24592 				freemsg(next_mp);
24593 				ire_refrele(ire1);
24594 			}
24595 			if (save_ire != NULL)
24596 				IRE_REFRELE(save_ire);
24597 
24598 			if (first_ire != NULL)
24599 				ire_refrele(first_ire);
24600 			return;
24601 
24602 		/*
24603 		 * Case of res_mp OR the fastpath mp can't fit
24604 		 * in the mblk
24605 		 */
24606 		} else {
24607 			xmit_mp->b_cont = mp;
24608 
24609 			/*
24610 			 * Get priority marking, if any.
24611 			 * We propagate the CoS marking from the
24612 			 * original packet that went to QoS processing
24613 			 * in ip_wput_ire to the newly carved mp.
24614 			 */
24615 			if (DB_TYPE(xmit_mp) == M_DATA)
24616 				xmit_mp->b_band = mp->b_band;
24617 		}
24618 		UNLOCK_IRE_FP_MP(ire);
24619 
24620 		q = ire->ire_stq;
24621 		out_ill = (ill_t *)q->q_ptr;
24622 
24623 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24624 
24625 		DTRACE_PROBE4(ip4__physical__out__start,
24626 		    ill_t *, NULL, ill_t *, out_ill,
24627 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24628 
24629 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24630 		    ipst->ips_ipv4firewall_physical_out,
24631 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24632 
24633 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24634 
24635 		if (xmit_mp != NULL) {
24636 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24637 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24638 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24639 
24640 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24641 
24642 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24643 			UPDATE_MIB(out_ill->ill_ip_mib,
24644 			    ipIfStatsHCOutOctets, i1);
24645 
24646 			if (pkt_type != OB_PKT) {
24647 				/*
24648 				 * Update the packet count and MIB stats
24649 				 * of trailing RTF_MULTIRT ires.
24650 				 */
24651 				UPDATE_OB_PKT_COUNT(ire);
24652 				BUMP_MIB(out_ill->ill_ip_mib,
24653 				    ipIfStatsOutFragReqds);
24654 			}
24655 		}
24656 
24657 		if (multirt_send) {
24658 			/*
24659 			 * We are in a multiple send case; look for
24660 			 * the next ire and re-enter the loop.
24661 			 */
24662 			ASSERT(ire1);
24663 			ASSERT(next_mp);
24664 			/* REFRELE the current ire before looping */
24665 			ire_refrele(ire);
24666 			ire = ire1;
24667 			ire1 = NULL;
24668 			mp = next_mp;
24669 			next_mp = NULL;
24670 		}
24671 	} while (multirt_send);
24672 
24673 	ASSERT(ire1 == NULL);
24674 
24675 	/* Restore the original ire; we need it for the trailing frags */
24676 	if (save_ire != NULL) {
24677 		/* REFRELE the last iterated ire */
24678 		ire_refrele(ire);
24679 		/* save_ire has been REFHOLDed */
24680 		ire = save_ire;
24681 		save_ire = NULL;
24682 		q = ire->ire_stq;
24683 	}
24684 
24685 	if (pkt_type == OB_PKT) {
24686 		UPDATE_OB_PKT_COUNT(ire);
24687 	} else {
24688 		out_ill = (ill_t *)q->q_ptr;
24689 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24690 		UPDATE_IB_PKT_COUNT(ire);
24691 	}
24692 
24693 	/* Advance the offset to the second frag starting point. */
24694 	offset += len;
24695 	/*
24696 	 * Update hdr_len from the copied header - there might be less options
24697 	 * in the later fragments.
24698 	 */
24699 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24700 	/* Loop until done. */
24701 	for (;;) {
24702 		uint16_t	offset_and_flags;
24703 		uint16_t	ip_len;
24704 
24705 		if (ip_data_end - offset > len) {
24706 			/*
24707 			 * Carve off the appropriate amount from the original
24708 			 * datagram.
24709 			 */
24710 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24711 				mp = NULL;
24712 				break;
24713 			}
24714 			/*
24715 			 * More frags after this one.  Get another copy
24716 			 * of the header.
24717 			 */
24718 			if (carve_mp->b_datap->db_ref == 1 &&
24719 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24720 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24721 				/* Inline IP header */
24722 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24723 				    hdr_mp->b_rptr;
24724 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24725 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24726 				mp = carve_mp;
24727 			} else {
24728 				if (!(mp = copyb(hdr_mp))) {
24729 					freemsg(carve_mp);
24730 					break;
24731 				}
24732 				/* Get priority marking, if any. */
24733 				mp->b_band = carve_mp->b_band;
24734 				mp->b_cont = carve_mp;
24735 			}
24736 			ipha = (ipha_t *)mp->b_rptr;
24737 			offset_and_flags = IPH_MF;
24738 		} else {
24739 			/*
24740 			 * Last frag.  Consume the header. Set len to
24741 			 * the length of this last piece.
24742 			 */
24743 			len = ip_data_end - offset;
24744 
24745 			/*
24746 			 * Carve off the appropriate amount from the original
24747 			 * datagram.
24748 			 */
24749 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24750 				mp = NULL;
24751 				break;
24752 			}
24753 			if (carve_mp->b_datap->db_ref == 1 &&
24754 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24755 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24756 				/* Inline IP header */
24757 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24758 				    hdr_mp->b_rptr;
24759 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24760 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24761 				mp = carve_mp;
24762 				freeb(hdr_mp);
24763 				hdr_mp = mp;
24764 			} else {
24765 				mp = hdr_mp;
24766 				/* Get priority marking, if any. */
24767 				mp->b_band = carve_mp->b_band;
24768 				mp->b_cont = carve_mp;
24769 			}
24770 			ipha = (ipha_t *)mp->b_rptr;
24771 			/* A frag of a frag might have IPH_MF non-zero */
24772 			offset_and_flags =
24773 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24774 			    IPH_MF;
24775 		}
24776 		offset_and_flags |= (uint16_t)(offset >> 3);
24777 		offset_and_flags |= (uint16_t)frag_flag;
24778 		/* Store the offset and flags in the IP header. */
24779 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24780 
24781 		/* Store the length in the IP header. */
24782 		ip_len = (uint16_t)(len + hdr_len);
24783 		ipha->ipha_length = htons(ip_len);
24784 
24785 		/*
24786 		 * Set the IP header checksum.	Note that mp is just
24787 		 * the header, so this is easy to pass to ip_csum.
24788 		 */
24789 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24790 
24791 		/* Attach a transmit header, if any, and ship it. */
24792 		if (pkt_type == OB_PKT) {
24793 			UPDATE_OB_PKT_COUNT(ire);
24794 		} else {
24795 			out_ill = (ill_t *)q->q_ptr;
24796 			BUMP_MIB(out_ill->ill_ip_mib,
24797 			    ipIfStatsHCOutForwDatagrams);
24798 			UPDATE_IB_PKT_COUNT(ire);
24799 		}
24800 
24801 		if (ire->ire_flags & RTF_MULTIRT) {
24802 			irb = ire->ire_bucket;
24803 			ASSERT(irb != NULL);
24804 
24805 			multirt_send = B_TRUE;
24806 
24807 			/*
24808 			 * Save the original ire; we will need to restore it
24809 			 * for the tailing frags.
24810 			 */
24811 			save_ire = ire;
24812 			IRE_REFHOLD(save_ire);
24813 		}
24814 		/*
24815 		 * Emission loop for this fragment, similar
24816 		 * to what is done for the first fragment.
24817 		 */
24818 		do {
24819 			if (multirt_send) {
24820 				/*
24821 				 * We are in a multiple send case, need to get
24822 				 * the next ire and make a copy of the packet.
24823 				 */
24824 				ASSERT(irb != NULL);
24825 				IRB_REFHOLD(irb);
24826 				for (ire1 = ire->ire_next;
24827 				    ire1 != NULL;
24828 				    ire1 = ire1->ire_next) {
24829 					if (!(ire1->ire_flags & RTF_MULTIRT))
24830 						continue;
24831 					if (ire1->ire_addr != ire->ire_addr)
24832 						continue;
24833 					if (ire1->ire_marks &
24834 					    (IRE_MARK_CONDEMNED |
24835 					    IRE_MARK_TESTHIDDEN))
24836 						continue;
24837 					/*
24838 					 * Ensure we do not exceed the MTU
24839 					 * of the next route.
24840 					 */
24841 					if (ire1->ire_max_frag < max_frag) {
24842 						ip_multirt_bad_mtu(ire1,
24843 						    max_frag);
24844 						continue;
24845 					}
24846 
24847 					/* Got one. */
24848 					IRE_REFHOLD(ire1);
24849 					break;
24850 				}
24851 				IRB_REFRELE(irb);
24852 
24853 				if (ire1 != NULL) {
24854 					next_mp = copyb(mp);
24855 					if ((next_mp == NULL) ||
24856 					    ((mp->b_cont != NULL) &&
24857 					    ((next_mp->b_cont =
24858 					    dupmsg(mp->b_cont)) == NULL))) {
24859 						freemsg(next_mp);
24860 						next_mp = NULL;
24861 						ire_refrele(ire1);
24862 						ire1 = NULL;
24863 					}
24864 				}
24865 
24866 				/* Last multiroute ire; don't loop anymore. */
24867 				if (ire1 == NULL) {
24868 					multirt_send = B_FALSE;
24869 				}
24870 			}
24871 
24872 			/* Update transmit header */
24873 			ll_hdr_len = 0;
24874 			LOCK_IRE_FP_MP(ire);
24875 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24876 			if (ll_hdr_mp != NULL) {
24877 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24878 				ll_hdr_len = MBLKL(ll_hdr_mp);
24879 			} else {
24880 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24881 			}
24882 
24883 			if (!ll_hdr_mp) {
24884 				xmit_mp = mp;
24885 
24886 			/*
24887 			 * We have link-layer header that can fit in
24888 			 * our mblk.
24889 			 */
24890 			} else if (mp->b_datap->db_ref == 1 &&
24891 			    ll_hdr_len != 0 &&
24892 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24893 				/* M_DATA fastpath */
24894 				mp->b_rptr -= ll_hdr_len;
24895 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24896 				    ll_hdr_len);
24897 				xmit_mp = mp;
24898 
24899 			/*
24900 			 * Case of res_mp OR the fastpath mp can't fit
24901 			 * in the mblk
24902 			 */
24903 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24904 				xmit_mp->b_cont = mp;
24905 				/* Get priority marking, if any. */
24906 				if (DB_TYPE(xmit_mp) == M_DATA)
24907 					xmit_mp->b_band = mp->b_band;
24908 
24909 			/* Corner case if copyb failed */
24910 			} else {
24911 				/*
24912 				 * Exit both the replication and
24913 				 * fragmentation loops.
24914 				 */
24915 				UNLOCK_IRE_FP_MP(ire);
24916 				goto drop_pkt;
24917 			}
24918 			UNLOCK_IRE_FP_MP(ire);
24919 
24920 			mp1 = mp;
24921 			out_ill = (ill_t *)q->q_ptr;
24922 
24923 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24924 
24925 			DTRACE_PROBE4(ip4__physical__out__start,
24926 			    ill_t *, NULL, ill_t *, out_ill,
24927 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24928 
24929 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24930 			    ipst->ips_ipv4firewall_physical_out,
24931 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24932 
24933 			DTRACE_PROBE1(ip4__physical__out__end,
24934 			    mblk_t *, xmit_mp);
24935 
24936 			if (mp != mp1 && hdr_mp == mp1)
24937 				hdr_mp = mp;
24938 			if (mp != mp1 && mp_orig == mp1)
24939 				mp_orig = mp;
24940 
24941 			if (xmit_mp != NULL) {
24942 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24943 				    NULL, void_ip_t *, ipha,
24944 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24945 				    ipha, ip6_t *, NULL, int, 0);
24946 
24947 				ILL_SEND_TX(out_ill, ire, connp,
24948 				    xmit_mp, 0, connp);
24949 
24950 				BUMP_MIB(out_ill->ill_ip_mib,
24951 				    ipIfStatsHCOutTransmits);
24952 				UPDATE_MIB(out_ill->ill_ip_mib,
24953 				    ipIfStatsHCOutOctets, ip_len);
24954 
24955 				if (pkt_type != OB_PKT) {
24956 					/*
24957 					 * Update the packet count of trailing
24958 					 * RTF_MULTIRT ires.
24959 					 */
24960 					UPDATE_OB_PKT_COUNT(ire);
24961 				}
24962 			}
24963 
24964 			/* All done if we just consumed the hdr_mp. */
24965 			if (mp == hdr_mp) {
24966 				last_frag = B_TRUE;
24967 				BUMP_MIB(out_ill->ill_ip_mib,
24968 				    ipIfStatsOutFragOKs);
24969 			}
24970 
24971 			if (multirt_send) {
24972 				/*
24973 				 * We are in a multiple send case; look for
24974 				 * the next ire and re-enter the loop.
24975 				 */
24976 				ASSERT(ire1);
24977 				ASSERT(next_mp);
24978 				/* REFRELE the current ire before looping */
24979 				ire_refrele(ire);
24980 				ire = ire1;
24981 				ire1 = NULL;
24982 				q = ire->ire_stq;
24983 				mp = next_mp;
24984 				next_mp = NULL;
24985 			}
24986 		} while (multirt_send);
24987 		/*
24988 		 * Restore the original ire; we need it for the
24989 		 * trailing frags
24990 		 */
24991 		if (save_ire != NULL) {
24992 			ASSERT(ire1 == NULL);
24993 			/* REFRELE the last iterated ire */
24994 			ire_refrele(ire);
24995 			/* save_ire has been REFHOLDed */
24996 			ire = save_ire;
24997 			q = ire->ire_stq;
24998 			save_ire = NULL;
24999 		}
25000 
25001 		if (last_frag) {
25002 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25003 			    "ip_wput_frag_end:(%S)",
25004 			    "consumed hdr_mp");
25005 
25006 			if (first_ire != NULL)
25007 				ire_refrele(first_ire);
25008 			return;
25009 		}
25010 		/* Otherwise, advance and loop. */
25011 		offset += len;
25012 	}
25013 
25014 drop_pkt:
25015 	/* Clean up following allocation failure. */
25016 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25017 	freemsg(mp);
25018 	if (mp != hdr_mp)
25019 		freeb(hdr_mp);
25020 	if (mp != mp_orig)
25021 		freemsg(mp_orig);
25022 
25023 	if (save_ire != NULL)
25024 		IRE_REFRELE(save_ire);
25025 	if (first_ire != NULL)
25026 		ire_refrele(first_ire);
25027 
25028 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25029 	    "ip_wput_frag_end:(%S)",
25030 	    "end--alloc failure");
25031 }
25032 
25033 /*
25034  * Copy the header plus those options which have the copy bit set
25035  * src is the template to make sure we preserve the cred for TX purposes.
25036  */
25037 static mblk_t *
25038 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
25039     mblk_t *src)
25040 {
25041 	mblk_t	*mp;
25042 	uchar_t	*up;
25043 
25044 	/*
25045 	 * Quick check if we need to look for options without the copy bit
25046 	 * set
25047 	 */
25048 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
25049 	if (!mp)
25050 		return (mp);
25051 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25052 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25053 		bcopy(rptr, mp->b_rptr, hdr_len);
25054 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25055 		return (mp);
25056 	}
25057 	up  = mp->b_rptr;
25058 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25059 	up += IP_SIMPLE_HDR_LENGTH;
25060 	rptr += IP_SIMPLE_HDR_LENGTH;
25061 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25062 	while (hdr_len > 0) {
25063 		uint32_t optval;
25064 		uint32_t optlen;
25065 
25066 		optval = *rptr;
25067 		if (optval == IPOPT_EOL)
25068 			break;
25069 		if (optval == IPOPT_NOP)
25070 			optlen = 1;
25071 		else
25072 			optlen = rptr[1];
25073 		if (optval & IPOPT_COPY) {
25074 			bcopy(rptr, up, optlen);
25075 			up += optlen;
25076 		}
25077 		rptr += optlen;
25078 		hdr_len -= optlen;
25079 	}
25080 	/*
25081 	 * Make sure that we drop an even number of words by filling
25082 	 * with EOL to the next word boundary.
25083 	 */
25084 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25085 	    hdr_len & 0x3; hdr_len++)
25086 		*up++ = IPOPT_EOL;
25087 	mp->b_wptr = up;
25088 	/* Update header length */
25089 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25090 	return (mp);
25091 }
25092 
25093 /*
25094  * Delivery to local recipients including fanout to multiple recipients.
25095  * Does not do checksumming of UDP/TCP.
25096  * Note: q should be the read side queue for either the ill or conn.
25097  * Note: rq should be the read side q for the lower (ill) stream.
25098  * We don't send packets to IPPF processing, thus the last argument
25099  * to all the fanout calls are B_FALSE.
25100  */
25101 void
25102 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25103     int fanout_flags, zoneid_t zoneid)
25104 {
25105 	uint32_t	protocol;
25106 	mblk_t		*first_mp;
25107 	boolean_t	mctl_present;
25108 	int		ire_type;
25109 #define	rptr	((uchar_t *)ipha)
25110 	ip_stack_t	*ipst = ill->ill_ipst;
25111 
25112 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25113 	    "ip_wput_local_start: q %p", q);
25114 
25115 	if (ire != NULL) {
25116 		ire_type = ire->ire_type;
25117 	} else {
25118 		/*
25119 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25120 		 * packet is not multicast, we can't tell the ire type.
25121 		 */
25122 		ASSERT(CLASSD(ipha->ipha_dst));
25123 		ire_type = IRE_BROADCAST;
25124 	}
25125 
25126 	first_mp = mp;
25127 	if (first_mp->b_datap->db_type == M_CTL) {
25128 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25129 		if (!io->ipsec_out_secure) {
25130 			/*
25131 			 * This ipsec_out_t was allocated in ip_wput
25132 			 * for multicast packets to store the ill_index.
25133 			 * As this is being delivered locally, we don't
25134 			 * need this anymore.
25135 			 */
25136 			mp = first_mp->b_cont;
25137 			freeb(first_mp);
25138 			first_mp = mp;
25139 			mctl_present = B_FALSE;
25140 		} else {
25141 			/*
25142 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25143 			 * security properties for the looped-back packet.
25144 			 */
25145 			mctl_present = B_TRUE;
25146 			mp = first_mp->b_cont;
25147 			ASSERT(mp != NULL);
25148 			ipsec_out_to_in(first_mp);
25149 		}
25150 	} else {
25151 		mctl_present = B_FALSE;
25152 	}
25153 
25154 	DTRACE_PROBE4(ip4__loopback__in__start,
25155 	    ill_t *, ill, ill_t *, NULL,
25156 	    ipha_t *, ipha, mblk_t *, first_mp);
25157 
25158 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25159 	    ipst->ips_ipv4firewall_loopback_in,
25160 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25161 
25162 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25163 
25164 	if (first_mp == NULL)
25165 		return;
25166 
25167 	if (ipst->ips_ipobs_enabled) {
25168 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25169 		zoneid_t stackzoneid = netstackid_to_zoneid(
25170 		    ipst->ips_netstack->netstack_stackid);
25171 
25172 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25173 		/*
25174 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25175 		 * address.  Restrict the lookup below to the destination zone.
25176 		 */
25177 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25178 			lookup_zoneid = zoneid;
25179 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25180 		    lookup_zoneid);
25181 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25182 		    IPV4_VERSION, 0, ipst);
25183 	}
25184 
25185 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25186 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25187 	    int, 1);
25188 
25189 	ipst->ips_loopback_packets++;
25190 
25191 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25192 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25193 	if (!IS_SIMPLE_IPH(ipha)) {
25194 		ip_wput_local_options(ipha, ipst);
25195 	}
25196 
25197 	protocol = ipha->ipha_protocol;
25198 	switch (protocol) {
25199 	case IPPROTO_ICMP: {
25200 		ire_t		*ire_zone;
25201 		ilm_t		*ilm;
25202 		mblk_t		*mp1;
25203 		zoneid_t	last_zoneid;
25204 		ilm_walker_t	ilw;
25205 
25206 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25207 			ASSERT(ire_type == IRE_BROADCAST);
25208 			/*
25209 			 * In the multicast case, applications may have joined
25210 			 * the group from different zones, so we need to deliver
25211 			 * the packet to each of them. Loop through the
25212 			 * multicast memberships structures (ilm) on the receive
25213 			 * ill and send a copy of the packet up each matching
25214 			 * one. However, we don't do this for multicasts sent on
25215 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25216 			 * they must stay in the sender's zone.
25217 			 *
25218 			 * ilm_add_v6() ensures that ilms in the same zone are
25219 			 * contiguous in the ill_ilm list. We use this property
25220 			 * to avoid sending duplicates needed when two
25221 			 * applications in the same zone join the same group on
25222 			 * different logical interfaces: we ignore the ilm if
25223 			 * it's zoneid is the same as the last matching one.
25224 			 * In addition, the sending of the packet for
25225 			 * ire_zoneid is delayed until all of the other ilms
25226 			 * have been exhausted.
25227 			 */
25228 			last_zoneid = -1;
25229 			ilm = ilm_walker_start(&ilw, ill);
25230 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25231 				if (ipha->ipha_dst != ilm->ilm_addr ||
25232 				    ilm->ilm_zoneid == last_zoneid ||
25233 				    ilm->ilm_zoneid == zoneid ||
25234 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25235 					continue;
25236 				mp1 = ip_copymsg(first_mp);
25237 				if (mp1 == NULL)
25238 					continue;
25239 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25240 				    0, 0, mctl_present, B_FALSE, ill,
25241 				    ilm->ilm_zoneid);
25242 				last_zoneid = ilm->ilm_zoneid;
25243 			}
25244 			ilm_walker_finish(&ilw);
25245 			/*
25246 			 * Loopback case: the sending endpoint has
25247 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25248 			 * dispatch the multicast packet to the sending zone.
25249 			 */
25250 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25251 				freemsg(first_mp);
25252 				return;
25253 			}
25254 		} else if (ire_type == IRE_BROADCAST) {
25255 			/*
25256 			 * In the broadcast case, there may be many zones
25257 			 * which need a copy of the packet delivered to them.
25258 			 * There is one IRE_BROADCAST per broadcast address
25259 			 * and per zone; we walk those using a helper function.
25260 			 * In addition, the sending of the packet for zoneid is
25261 			 * delayed until all of the other ires have been
25262 			 * processed.
25263 			 */
25264 			IRB_REFHOLD(ire->ire_bucket);
25265 			ire_zone = NULL;
25266 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25267 			    ire)) != NULL) {
25268 				mp1 = ip_copymsg(first_mp);
25269 				if (mp1 == NULL)
25270 					continue;
25271 
25272 				UPDATE_IB_PKT_COUNT(ire_zone);
25273 				ire_zone->ire_last_used_time = lbolt;
25274 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25275 				    mctl_present, B_FALSE, ill,
25276 				    ire_zone->ire_zoneid);
25277 			}
25278 			IRB_REFRELE(ire->ire_bucket);
25279 		}
25280 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25281 		    0, mctl_present, B_FALSE, ill, zoneid);
25282 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25283 		    "ip_wput_local_end: q %p (%S)",
25284 		    q, "icmp");
25285 		return;
25286 	}
25287 	case IPPROTO_IGMP:
25288 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25289 			/* Bad packet - discarded by igmp_input */
25290 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25291 			    "ip_wput_local_end: q %p (%S)",
25292 			    q, "igmp_input--bad packet");
25293 			if (mctl_present)
25294 				freeb(first_mp);
25295 			return;
25296 		}
25297 		/*
25298 		 * igmp_input() may have returned the pulled up message.
25299 		 * So first_mp and ipha need to be reinitialized.
25300 		 */
25301 		ipha = (ipha_t *)mp->b_rptr;
25302 		if (mctl_present)
25303 			first_mp->b_cont = mp;
25304 		else
25305 			first_mp = mp;
25306 		/* deliver to local raw users */
25307 		break;
25308 	case IPPROTO_ENCAP:
25309 		/*
25310 		 * This case is covered by either ip_fanout_proto, or by
25311 		 * the above security processing for self-tunneled packets.
25312 		 */
25313 		break;
25314 	case IPPROTO_UDP: {
25315 		uint16_t	*up;
25316 		uint32_t	ports;
25317 
25318 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25319 		    UDP_PORTS_OFFSET);
25320 		/* Force a 'valid' checksum. */
25321 		up[3] = 0;
25322 
25323 		ports = *(uint32_t *)up;
25324 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25325 		    (ire_type == IRE_BROADCAST),
25326 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25327 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25328 		    ill, zoneid);
25329 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25330 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25331 		return;
25332 	}
25333 	case IPPROTO_TCP: {
25334 
25335 		/*
25336 		 * For TCP, discard broadcast packets.
25337 		 */
25338 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25339 			freemsg(first_mp);
25340 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25341 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25342 			return;
25343 		}
25344 
25345 		if (mp->b_datap->db_type == M_DATA) {
25346 			/*
25347 			 * M_DATA mblk, so init mblk (chain) for no struio().
25348 			 */
25349 			mblk_t	*mp1 = mp;
25350 
25351 			do {
25352 				mp1->b_datap->db_struioflag = 0;
25353 			} while ((mp1 = mp1->b_cont) != NULL);
25354 		}
25355 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25356 		    <= mp->b_wptr);
25357 		ip_fanout_tcp(q, first_mp, ill, ipha,
25358 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25359 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25360 		    mctl_present, B_FALSE, zoneid);
25361 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25362 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25363 		return;
25364 	}
25365 	case IPPROTO_SCTP:
25366 	{
25367 		uint32_t	ports;
25368 
25369 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25370 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25371 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25372 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25373 		return;
25374 	}
25375 
25376 	default:
25377 		break;
25378 	}
25379 	/*
25380 	 * Find a client for some other protocol.  We give
25381 	 * copies to multiple clients, if more than one is
25382 	 * bound.
25383 	 */
25384 	ip_fanout_proto(q, first_mp, ill, ipha,
25385 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25386 	    mctl_present, B_FALSE, ill, zoneid);
25387 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25388 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25389 #undef	rptr
25390 }
25391 
25392 /*
25393  * Update any source route, record route, or timestamp options.
25394  * Check that we are at end of strict source route.
25395  * The options have been sanity checked by ip_wput_options().
25396  */
25397 static void
25398 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25399 {
25400 	ipoptp_t	opts;
25401 	uchar_t		*opt;
25402 	uint8_t		optval;
25403 	uint8_t		optlen;
25404 	ipaddr_t	dst;
25405 	uint32_t	ts;
25406 	ire_t		*ire;
25407 	timestruc_t	now;
25408 
25409 	ip2dbg(("ip_wput_local_options\n"));
25410 	for (optval = ipoptp_first(&opts, ipha);
25411 	    optval != IPOPT_EOL;
25412 	    optval = ipoptp_next(&opts)) {
25413 		opt = opts.ipoptp_cur;
25414 		optlen = opts.ipoptp_len;
25415 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25416 		switch (optval) {
25417 			uint32_t off;
25418 		case IPOPT_SSRR:
25419 		case IPOPT_LSRR:
25420 			off = opt[IPOPT_OFFSET];
25421 			off--;
25422 			if (optlen < IP_ADDR_LEN ||
25423 			    off > optlen - IP_ADDR_LEN) {
25424 				/* End of source route */
25425 				break;
25426 			}
25427 			/*
25428 			 * This will only happen if two consecutive entries
25429 			 * in the source route contains our address or if
25430 			 * it is a packet with a loose source route which
25431 			 * reaches us before consuming the whole source route
25432 			 */
25433 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25434 			if (optval == IPOPT_SSRR) {
25435 				return;
25436 			}
25437 			/*
25438 			 * Hack: instead of dropping the packet truncate the
25439 			 * source route to what has been used by filling the
25440 			 * rest with IPOPT_NOP.
25441 			 */
25442 			opt[IPOPT_OLEN] = (uint8_t)off;
25443 			while (off < optlen) {
25444 				opt[off++] = IPOPT_NOP;
25445 			}
25446 			break;
25447 		case IPOPT_RR:
25448 			off = opt[IPOPT_OFFSET];
25449 			off--;
25450 			if (optlen < IP_ADDR_LEN ||
25451 			    off > optlen - IP_ADDR_LEN) {
25452 				/* No more room - ignore */
25453 				ip1dbg((
25454 				    "ip_wput_forward_options: end of RR\n"));
25455 				break;
25456 			}
25457 			dst = htonl(INADDR_LOOPBACK);
25458 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25459 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25460 			break;
25461 		case IPOPT_TS:
25462 			/* Insert timestamp if there is romm */
25463 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25464 			case IPOPT_TS_TSONLY:
25465 				off = IPOPT_TS_TIMELEN;
25466 				break;
25467 			case IPOPT_TS_PRESPEC:
25468 			case IPOPT_TS_PRESPEC_RFC791:
25469 				/* Verify that the address matched */
25470 				off = opt[IPOPT_OFFSET] - 1;
25471 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25472 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25473 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25474 				    ipst);
25475 				if (ire == NULL) {
25476 					/* Not for us */
25477 					break;
25478 				}
25479 				ire_refrele(ire);
25480 				/* FALLTHRU */
25481 			case IPOPT_TS_TSANDADDR:
25482 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25483 				break;
25484 			default:
25485 				/*
25486 				 * ip_*put_options should have already
25487 				 * dropped this packet.
25488 				 */
25489 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25490 				    "unknown IT - bug in ip_wput_options?\n");
25491 				return;	/* Keep "lint" happy */
25492 			}
25493 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25494 				/* Increase overflow counter */
25495 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25496 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25497 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25498 				    (off << 4);
25499 				break;
25500 			}
25501 			off = opt[IPOPT_OFFSET] - 1;
25502 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25503 			case IPOPT_TS_PRESPEC:
25504 			case IPOPT_TS_PRESPEC_RFC791:
25505 			case IPOPT_TS_TSANDADDR:
25506 				dst = htonl(INADDR_LOOPBACK);
25507 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25508 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25509 				/* FALLTHRU */
25510 			case IPOPT_TS_TSONLY:
25511 				off = opt[IPOPT_OFFSET] - 1;
25512 				/* Compute # of milliseconds since midnight */
25513 				gethrestime(&now);
25514 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25515 				    now.tv_nsec / (NANOSEC / MILLISEC);
25516 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25517 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25518 				break;
25519 			}
25520 			break;
25521 		}
25522 	}
25523 }
25524 
25525 /*
25526  * Send out a multicast packet on interface ipif.
25527  * The sender does not have an conn.
25528  * Caller verifies that this isn't a PHYI_LOOPBACK.
25529  */
25530 void
25531 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25532 {
25533 	ipha_t	*ipha;
25534 	ire_t	*ire;
25535 	ipaddr_t	dst;
25536 	mblk_t		*first_mp;
25537 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25538 
25539 	/* igmp_sendpkt always allocates a ipsec_out_t */
25540 	ASSERT(mp->b_datap->db_type == M_CTL);
25541 	ASSERT(!ipif->ipif_isv6);
25542 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25543 
25544 	first_mp = mp;
25545 	mp = first_mp->b_cont;
25546 	ASSERT(mp->b_datap->db_type == M_DATA);
25547 	ipha = (ipha_t *)mp->b_rptr;
25548 
25549 	/*
25550 	 * Find an IRE which matches the destination and the outgoing
25551 	 * queue (i.e. the outgoing interface.)
25552 	 */
25553 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25554 		dst = ipif->ipif_pp_dst_addr;
25555 	else
25556 		dst = ipha->ipha_dst;
25557 	/*
25558 	 * The source address has already been initialized by the
25559 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25560 	 * be sufficient rather than MATCH_IRE_IPIF.
25561 	 *
25562 	 * This function is used for sending IGMP packets.  For IPMP,
25563 	 * we sidestep IGMP snooping issues by sending all multicast
25564 	 * traffic on a single interface in the IPMP group.
25565 	 */
25566 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25567 	    MATCH_IRE_ILL, ipst);
25568 	if (!ire) {
25569 		/*
25570 		 * Mark this packet to make it be delivered to
25571 		 * ip_wput_ire after the new ire has been
25572 		 * created.
25573 		 */
25574 		mp->b_prev = NULL;
25575 		mp->b_next = NULL;
25576 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25577 		    zoneid, &zero_info);
25578 		return;
25579 	}
25580 
25581 	/*
25582 	 * Honor the RTF_SETSRC flag; this is the only case
25583 	 * where we force this addr whatever the current src addr is,
25584 	 * because this address is set by igmp_sendpkt(), and
25585 	 * cannot be specified by any user.
25586 	 */
25587 	if (ire->ire_flags & RTF_SETSRC) {
25588 		ipha->ipha_src = ire->ire_src_addr;
25589 	}
25590 
25591 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25592 }
25593 
25594 /*
25595  * NOTE : This function does not ire_refrele the ire argument passed in.
25596  *
25597  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25598  * failure. The nce_fp_mp can vanish any time in the case of
25599  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25600  * the ire_lock to access the nce_fp_mp in this case.
25601  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25602  * prepending a fastpath message IPQoS processing must precede it, we also set
25603  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25604  * (IPQoS might have set the b_band for CoS marking).
25605  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25606  * must follow it so that IPQoS can mark the dl_priority field for CoS
25607  * marking, if needed.
25608  */
25609 static mblk_t *
25610 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25611     uint32_t ill_index, ipha_t **iphap)
25612 {
25613 	uint_t	hlen;
25614 	ipha_t *ipha;
25615 	mblk_t *mp1;
25616 	boolean_t qos_done = B_FALSE;
25617 	uchar_t	*ll_hdr;
25618 	ip_stack_t	*ipst = ire->ire_ipst;
25619 
25620 #define	rptr	((uchar_t *)ipha)
25621 
25622 	ipha = (ipha_t *)mp->b_rptr;
25623 	hlen = 0;
25624 	LOCK_IRE_FP_MP(ire);
25625 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25626 		ASSERT(DB_TYPE(mp1) == M_DATA);
25627 		/* Initiate IPPF processing */
25628 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25629 			UNLOCK_IRE_FP_MP(ire);
25630 			ip_process(proc, &mp, ill_index);
25631 			if (mp == NULL)
25632 				return (NULL);
25633 
25634 			ipha = (ipha_t *)mp->b_rptr;
25635 			LOCK_IRE_FP_MP(ire);
25636 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25637 				qos_done = B_TRUE;
25638 				goto no_fp_mp;
25639 			}
25640 			ASSERT(DB_TYPE(mp1) == M_DATA);
25641 		}
25642 		hlen = MBLKL(mp1);
25643 		/*
25644 		 * Check if we have enough room to prepend fastpath
25645 		 * header
25646 		 */
25647 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25648 			ll_hdr = rptr - hlen;
25649 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25650 			/*
25651 			 * Set the b_rptr to the start of the link layer
25652 			 * header
25653 			 */
25654 			mp->b_rptr = ll_hdr;
25655 			mp1 = mp;
25656 		} else {
25657 			mp1 = copyb(mp1);
25658 			if (mp1 == NULL)
25659 				goto unlock_err;
25660 			mp1->b_band = mp->b_band;
25661 			mp1->b_cont = mp;
25662 			/*
25663 			 * XXX disable ICK_VALID and compute checksum
25664 			 * here; can happen if nce_fp_mp changes and
25665 			 * it can't be copied now due to insufficient
25666 			 * space. (unlikely, fp mp can change, but it
25667 			 * does not increase in length)
25668 			 */
25669 		}
25670 		UNLOCK_IRE_FP_MP(ire);
25671 	} else {
25672 no_fp_mp:
25673 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25674 		if (mp1 == NULL) {
25675 unlock_err:
25676 			UNLOCK_IRE_FP_MP(ire);
25677 			freemsg(mp);
25678 			return (NULL);
25679 		}
25680 		UNLOCK_IRE_FP_MP(ire);
25681 		mp1->b_cont = mp;
25682 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25683 			ip_process(proc, &mp1, ill_index);
25684 			if (mp1 == NULL)
25685 				return (NULL);
25686 
25687 			if (mp1->b_cont == NULL)
25688 				ipha = NULL;
25689 			else
25690 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25691 		}
25692 	}
25693 
25694 	*iphap = ipha;
25695 	return (mp1);
25696 #undef rptr
25697 }
25698 
25699 /*
25700  * Finish the outbound IPsec processing for an IPv6 packet. This function
25701  * is called from ipsec_out_process() if the IPsec packet was processed
25702  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25703  * asynchronously.
25704  */
25705 void
25706 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25707     ire_t *ire_arg)
25708 {
25709 	in6_addr_t *v6dstp;
25710 	ire_t *ire;
25711 	mblk_t *mp;
25712 	ip6_t *ip6h1;
25713 	uint_t	ill_index;
25714 	ipsec_out_t *io;
25715 	boolean_t hwaccel;
25716 	uint32_t flags = IP6_NO_IPPOLICY;
25717 	int match_flags;
25718 	zoneid_t zoneid;
25719 	boolean_t ill_need_rele = B_FALSE;
25720 	boolean_t ire_need_rele = B_FALSE;
25721 	ip_stack_t	*ipst;
25722 
25723 	mp = ipsec_mp->b_cont;
25724 	ip6h1 = (ip6_t *)mp->b_rptr;
25725 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25726 	ASSERT(io->ipsec_out_ns != NULL);
25727 	ipst = io->ipsec_out_ns->netstack_ip;
25728 	ill_index = io->ipsec_out_ill_index;
25729 	if (io->ipsec_out_reachable) {
25730 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25731 	}
25732 	hwaccel = io->ipsec_out_accelerated;
25733 	zoneid = io->ipsec_out_zoneid;
25734 	ASSERT(zoneid != ALL_ZONES);
25735 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25736 	/* Multicast addresses should have non-zero ill_index. */
25737 	v6dstp = &ip6h->ip6_dst;
25738 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25739 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25740 
25741 	if (ill == NULL && ill_index != 0) {
25742 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25743 		/* Failure case frees things for us. */
25744 		if (ill == NULL)
25745 			return;
25746 
25747 		ill_need_rele = B_TRUE;
25748 	}
25749 	ASSERT(mp != NULL);
25750 
25751 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25752 		boolean_t unspec_src;
25753 		ipif_t	*ipif;
25754 
25755 		/*
25756 		 * Use the ill_index to get the right ill.
25757 		 */
25758 		unspec_src = io->ipsec_out_unspec_src;
25759 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25760 		if (ipif == NULL) {
25761 			if (ill_need_rele)
25762 				ill_refrele(ill);
25763 			freemsg(ipsec_mp);
25764 			return;
25765 		}
25766 
25767 		if (ire_arg != NULL) {
25768 			ire = ire_arg;
25769 		} else {
25770 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25771 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25772 			ire_need_rele = B_TRUE;
25773 		}
25774 		if (ire != NULL) {
25775 			ipif_refrele(ipif);
25776 			/*
25777 			 * XXX Do the multicast forwarding now, as the IPsec
25778 			 * processing has been done.
25779 			 */
25780 			goto send;
25781 		}
25782 
25783 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25784 		mp->b_prev = NULL;
25785 		mp->b_next = NULL;
25786 
25787 		/*
25788 		 * If the IPsec packet was processed asynchronously,
25789 		 * drop it now.
25790 		 */
25791 		if (q == NULL) {
25792 			if (ill_need_rele)
25793 				ill_refrele(ill);
25794 			freemsg(ipsec_mp);
25795 			return;
25796 		}
25797 
25798 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25799 		    unspec_src, zoneid);
25800 		ipif_refrele(ipif);
25801 	} else {
25802 		if (ire_arg != NULL) {
25803 			ire = ire_arg;
25804 		} else {
25805 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25806 			ire_need_rele = B_TRUE;
25807 		}
25808 		if (ire != NULL)
25809 			goto send;
25810 		/*
25811 		 * ire disappeared underneath.
25812 		 *
25813 		 * What we need to do here is the ip_newroute
25814 		 * logic to get the ire without doing the IPsec
25815 		 * processing. Follow the same old path. But this
25816 		 * time, ip_wput or ire_add_then_send will call us
25817 		 * directly as all the IPsec operations are done.
25818 		 */
25819 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25820 		mp->b_prev = NULL;
25821 		mp->b_next = NULL;
25822 
25823 		/*
25824 		 * If the IPsec packet was processed asynchronously,
25825 		 * drop it now.
25826 		 */
25827 		if (q == NULL) {
25828 			if (ill_need_rele)
25829 				ill_refrele(ill);
25830 			freemsg(ipsec_mp);
25831 			return;
25832 		}
25833 
25834 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25835 		    zoneid, ipst);
25836 	}
25837 	if (ill != NULL && ill_need_rele)
25838 		ill_refrele(ill);
25839 	return;
25840 send:
25841 	if (ill != NULL && ill_need_rele)
25842 		ill_refrele(ill);
25843 
25844 	/* Local delivery */
25845 	if (ire->ire_stq == NULL) {
25846 		ill_t	*out_ill;
25847 		ASSERT(q != NULL);
25848 
25849 		/* PFHooks: LOOPBACK_OUT */
25850 		out_ill = ire_to_ill(ire);
25851 
25852 		/*
25853 		 * DTrace this as ip:::send.  A blocked packet will fire the
25854 		 * send probe, but not the receive probe.
25855 		 */
25856 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25857 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25858 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25859 
25860 		DTRACE_PROBE4(ip6__loopback__out__start,
25861 		    ill_t *, NULL, ill_t *, out_ill,
25862 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25863 
25864 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25865 		    ipst->ips_ipv6firewall_loopback_out,
25866 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25867 
25868 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25869 
25870 		if (ipsec_mp != NULL) {
25871 			ip_wput_local_v6(RD(q), out_ill,
25872 			    ip6h, ipsec_mp, ire, 0, zoneid);
25873 		}
25874 		if (ire_need_rele)
25875 			ire_refrele(ire);
25876 		return;
25877 	}
25878 	/*
25879 	 * Everything is done. Send it out on the wire.
25880 	 * We force the insertion of a fragment header using the
25881 	 * IPH_FRAG_HDR flag in two cases:
25882 	 * - after reception of an ICMPv6 "packet too big" message
25883 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25884 	 * - for multirouted IPv6 packets, so that the receiver can
25885 	 *   discard duplicates according to their fragment identifier
25886 	 */
25887 	/* XXX fix flow control problems. */
25888 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25889 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25890 		if (hwaccel) {
25891 			/*
25892 			 * hardware acceleration does not handle these
25893 			 * "slow path" cases.
25894 			 */
25895 			/* IPsec KSTATS: should bump bean counter here. */
25896 			if (ire_need_rele)
25897 				ire_refrele(ire);
25898 			freemsg(ipsec_mp);
25899 			return;
25900 		}
25901 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25902 		    (mp->b_cont ? msgdsize(mp) :
25903 		    mp->b_wptr - (uchar_t *)ip6h)) {
25904 			/* IPsec KSTATS: should bump bean counter here. */
25905 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25906 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25907 			    msgdsize(mp)));
25908 			if (ire_need_rele)
25909 				ire_refrele(ire);
25910 			freemsg(ipsec_mp);
25911 			return;
25912 		}
25913 		ASSERT(mp->b_prev == NULL);
25914 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25915 		    ntohs(ip6h->ip6_plen) +
25916 		    IPV6_HDR_LEN, ire->ire_max_frag));
25917 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25918 		    ire->ire_max_frag);
25919 	} else {
25920 		UPDATE_OB_PKT_COUNT(ire);
25921 		ire->ire_last_used_time = lbolt;
25922 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25923 	}
25924 	if (ire_need_rele)
25925 		ire_refrele(ire);
25926 	freeb(ipsec_mp);
25927 }
25928 
25929 void
25930 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25931 {
25932 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25933 	da_ipsec_t *hada;	/* data attributes */
25934 	ill_t *ill = (ill_t *)q->q_ptr;
25935 
25936 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25937 
25938 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25939 		/* IPsec KSTATS: Bump lose counter here! */
25940 		freemsg(mp);
25941 		return;
25942 	}
25943 
25944 	/*
25945 	 * It's an IPsec packet that must be
25946 	 * accelerated by the Provider, and the
25947 	 * outbound ill is IPsec acceleration capable.
25948 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25949 	 * to the ill.
25950 	 * IPsec KSTATS: should bump packet counter here.
25951 	 */
25952 
25953 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25954 	if (hada_mp == NULL) {
25955 		/* IPsec KSTATS: should bump packet counter here. */
25956 		freemsg(mp);
25957 		return;
25958 	}
25959 
25960 	hada_mp->b_datap->db_type = M_CTL;
25961 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25962 	hada_mp->b_cont = mp;
25963 
25964 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25965 	bzero(hada, sizeof (da_ipsec_t));
25966 	hada->da_type = IPHADA_M_CTL;
25967 
25968 	putnext(q, hada_mp);
25969 }
25970 
25971 /*
25972  * Finish the outbound IPsec processing. This function is called from
25973  * ipsec_out_process() if the IPsec packet was processed
25974  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25975  * asynchronously.
25976  */
25977 void
25978 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25979     ire_t *ire_arg)
25980 {
25981 	uint32_t v_hlen_tos_len;
25982 	ipaddr_t	dst;
25983 	ipif_t	*ipif = NULL;
25984 	ire_t *ire;
25985 	ire_t *ire1 = NULL;
25986 	mblk_t *next_mp = NULL;
25987 	uint32_t max_frag;
25988 	boolean_t multirt_send = B_FALSE;
25989 	mblk_t *mp;
25990 	ipha_t *ipha1;
25991 	uint_t	ill_index;
25992 	ipsec_out_t *io;
25993 	int match_flags;
25994 	irb_t *irb = NULL;
25995 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25996 	zoneid_t zoneid;
25997 	ipxmit_state_t	pktxmit_state;
25998 	ip_stack_t	*ipst;
25999 
26000 #ifdef	_BIG_ENDIAN
26001 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26002 #else
26003 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26004 #endif
26005 
26006 	mp = ipsec_mp->b_cont;
26007 	ipha1 = (ipha_t *)mp->b_rptr;
26008 	ASSERT(mp != NULL);
26009 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26010 	dst = ipha->ipha_dst;
26011 
26012 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26013 	ill_index = io->ipsec_out_ill_index;
26014 	zoneid = io->ipsec_out_zoneid;
26015 	ASSERT(zoneid != ALL_ZONES);
26016 	ipst = io->ipsec_out_ns->netstack_ip;
26017 	ASSERT(io->ipsec_out_ns != NULL);
26018 
26019 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26020 	if (ill == NULL && ill_index != 0) {
26021 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
26022 		/* Failure case frees things for us. */
26023 		if (ill == NULL)
26024 			return;
26025 
26026 		ill_need_rele = B_TRUE;
26027 	}
26028 
26029 	if (CLASSD(dst)) {
26030 		boolean_t conn_dontroute;
26031 		/*
26032 		 * Use the ill_index to get the right ipif.
26033 		 */
26034 		conn_dontroute = io->ipsec_out_dontroute;
26035 		if (ill_index == 0)
26036 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26037 		else
26038 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26039 		if (ipif == NULL) {
26040 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26041 			    " multicast\n"));
26042 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26043 			freemsg(ipsec_mp);
26044 			goto done;
26045 		}
26046 		/*
26047 		 * ipha_src has already been intialized with the
26048 		 * value of the ipif in ip_wput. All we need now is
26049 		 * an ire to send this downstream.
26050 		 */
26051 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26052 		    msg_getlabel(mp), match_flags, ipst);
26053 		if (ire != NULL) {
26054 			ill_t *ill1;
26055 			/*
26056 			 * Do the multicast forwarding now, as the IPsec
26057 			 * processing has been done.
26058 			 */
26059 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26060 			    (ill1 = ire_to_ill(ire))) {
26061 				if (ip_mforward(ill1, ipha, mp)) {
26062 					freemsg(ipsec_mp);
26063 					ip1dbg(("ip_wput_ipsec_out: mforward "
26064 					    "failed\n"));
26065 					ire_refrele(ire);
26066 					goto done;
26067 				}
26068 			}
26069 			goto send;
26070 		}
26071 
26072 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26073 		mp->b_prev = NULL;
26074 		mp->b_next = NULL;
26075 
26076 		/*
26077 		 * If the IPsec packet was processed asynchronously,
26078 		 * drop it now.
26079 		 */
26080 		if (q == NULL) {
26081 			freemsg(ipsec_mp);
26082 			goto done;
26083 		}
26084 
26085 		/*
26086 		 * We may be using a wrong ipif to create the ire.
26087 		 * But it is okay as the source address is assigned
26088 		 * for the packet already. Next outbound packet would
26089 		 * create the IRE with the right IPIF in ip_wput.
26090 		 *
26091 		 * Also handle RTF_MULTIRT routes.
26092 		 */
26093 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26094 		    zoneid, &zero_info);
26095 	} else {
26096 		if (ire_arg != NULL) {
26097 			ire = ire_arg;
26098 			ire_need_rele = B_FALSE;
26099 		} else {
26100 			ire = ire_cache_lookup(dst, zoneid,
26101 			    msg_getlabel(mp), ipst);
26102 		}
26103 		if (ire != NULL) {
26104 			goto send;
26105 		}
26106 
26107 		/*
26108 		 * ire disappeared underneath.
26109 		 *
26110 		 * What we need to do here is the ip_newroute
26111 		 * logic to get the ire without doing the IPsec
26112 		 * processing. Follow the same old path. But this
26113 		 * time, ip_wput or ire_add_then_put will call us
26114 		 * directly as all the IPsec operations are done.
26115 		 */
26116 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26117 		mp->b_prev = NULL;
26118 		mp->b_next = NULL;
26119 
26120 		/*
26121 		 * If the IPsec packet was processed asynchronously,
26122 		 * drop it now.
26123 		 */
26124 		if (q == NULL) {
26125 			freemsg(ipsec_mp);
26126 			goto done;
26127 		}
26128 
26129 		/*
26130 		 * Since we're going through ip_newroute() again, we
26131 		 * need to make sure we don't:
26132 		 *
26133 		 *	1.) Trigger the ASSERT() with the ipha_ident
26134 		 *	    overloading.
26135 		 *	2.) Redo transport-layer checksumming, since we've
26136 		 *	    already done all that to get this far.
26137 		 *
26138 		 * The easiest way not do either of the above is to set
26139 		 * the ipha_ident field to IP_HDR_INCLUDED.
26140 		 */
26141 		ipha->ipha_ident = IP_HDR_INCLUDED;
26142 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26143 		    zoneid, ipst);
26144 	}
26145 	goto done;
26146 send:
26147 	if (ire->ire_stq == NULL) {
26148 		ill_t	*out_ill;
26149 		/*
26150 		 * Loopbacks go through ip_wput_local except for one case.
26151 		 * We come here if we generate a icmp_frag_needed message
26152 		 * after IPsec processing is over. When this function calls
26153 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26154 		 * icmp_frag_needed. The message generated comes back here
26155 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26156 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26157 		 * source address as it is usually set in ip_wput_ire. As
26158 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26159 		 * and we end up here. We can't enter ip_wput_ire once the
26160 		 * IPsec processing is over and hence we need to do it here.
26161 		 */
26162 		ASSERT(q != NULL);
26163 		UPDATE_OB_PKT_COUNT(ire);
26164 		ire->ire_last_used_time = lbolt;
26165 		if (ipha->ipha_src == 0)
26166 			ipha->ipha_src = ire->ire_src_addr;
26167 
26168 		/* PFHooks: LOOPBACK_OUT */
26169 		out_ill = ire_to_ill(ire);
26170 
26171 		/*
26172 		 * DTrace this as ip:::send.  A blocked packet will fire the
26173 		 * send probe, but not the receive probe.
26174 		 */
26175 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26176 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26177 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26178 
26179 		DTRACE_PROBE4(ip4__loopback__out__start,
26180 		    ill_t *, NULL, ill_t *, out_ill,
26181 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26182 
26183 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26184 		    ipst->ips_ipv4firewall_loopback_out,
26185 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26186 
26187 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26188 
26189 		if (ipsec_mp != NULL)
26190 			ip_wput_local(RD(q), out_ill,
26191 			    ipha, ipsec_mp, ire, 0, zoneid);
26192 		if (ire_need_rele)
26193 			ire_refrele(ire);
26194 		goto done;
26195 	}
26196 
26197 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26198 		/*
26199 		 * We are through with IPsec processing.
26200 		 * Fragment this and send it on the wire.
26201 		 */
26202 		if (io->ipsec_out_accelerated) {
26203 			/*
26204 			 * The packet has been accelerated but must
26205 			 * be fragmented. This should not happen
26206 			 * since AH and ESP must not accelerate
26207 			 * packets that need fragmentation, however
26208 			 * the configuration could have changed
26209 			 * since the AH or ESP processing.
26210 			 * Drop packet.
26211 			 * IPsec KSTATS: bump bean counter here.
26212 			 */
26213 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26214 			    "fragmented accelerated packet!\n"));
26215 			freemsg(ipsec_mp);
26216 		} else {
26217 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26218 			    zoneid, ipst, NULL);
26219 		}
26220 		if (ire_need_rele)
26221 			ire_refrele(ire);
26222 		goto done;
26223 	}
26224 
26225 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26226 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26227 	    (void *)ire->ire_ipif, (void *)ipif));
26228 
26229 	/*
26230 	 * Multiroute the secured packet.
26231 	 */
26232 	if (ire->ire_flags & RTF_MULTIRT) {
26233 		ire_t *first_ire;
26234 		irb = ire->ire_bucket;
26235 		ASSERT(irb != NULL);
26236 		/*
26237 		 * This ire has been looked up as the one that
26238 		 * goes through the given ipif;
26239 		 * make sure we do not omit any other multiroute ire
26240 		 * that may be present in the bucket before this one.
26241 		 */
26242 		IRB_REFHOLD(irb);
26243 		for (first_ire = irb->irb_ire;
26244 		    first_ire != NULL;
26245 		    first_ire = first_ire->ire_next) {
26246 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26247 			    (first_ire->ire_addr == ire->ire_addr) &&
26248 			    !(first_ire->ire_marks &
26249 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26250 				break;
26251 		}
26252 
26253 		if ((first_ire != NULL) && (first_ire != ire)) {
26254 			/*
26255 			 * Don't change the ire if the packet must
26256 			 * be fragmented if sent via this new one.
26257 			 */
26258 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26259 				IRE_REFHOLD(first_ire);
26260 				if (ire_need_rele)
26261 					ire_refrele(ire);
26262 				else
26263 					ire_need_rele = B_TRUE;
26264 				ire = first_ire;
26265 			}
26266 		}
26267 		IRB_REFRELE(irb);
26268 
26269 		multirt_send = B_TRUE;
26270 		max_frag = ire->ire_max_frag;
26271 	}
26272 
26273 	/*
26274 	 * In most cases, the emission loop below is entered only once.
26275 	 * Only in the case where the ire holds the RTF_MULTIRT
26276 	 * flag, we loop to process all RTF_MULTIRT ires in the
26277 	 * bucket, and send the packet through all crossed
26278 	 * RTF_MULTIRT routes.
26279 	 */
26280 	do {
26281 		if (multirt_send) {
26282 			/*
26283 			 * ire1 holds here the next ire to process in the
26284 			 * bucket. If multirouting is expected,
26285 			 * any non-RTF_MULTIRT ire that has the
26286 			 * right destination address is ignored.
26287 			 */
26288 			ASSERT(irb != NULL);
26289 			IRB_REFHOLD(irb);
26290 			for (ire1 = ire->ire_next;
26291 			    ire1 != NULL;
26292 			    ire1 = ire1->ire_next) {
26293 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26294 					continue;
26295 				if (ire1->ire_addr != ire->ire_addr)
26296 					continue;
26297 				if (ire1->ire_marks &
26298 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26299 					continue;
26300 				/* No loopback here */
26301 				if (ire1->ire_stq == NULL)
26302 					continue;
26303 				/*
26304 				 * Ensure we do not exceed the MTU
26305 				 * of the next route.
26306 				 */
26307 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26308 					ip_multirt_bad_mtu(ire1, max_frag);
26309 					continue;
26310 				}
26311 
26312 				IRE_REFHOLD(ire1);
26313 				break;
26314 			}
26315 			IRB_REFRELE(irb);
26316 			if (ire1 != NULL) {
26317 				/*
26318 				 * We are in a multiple send case, need to
26319 				 * make a copy of the packet.
26320 				 */
26321 				next_mp = copymsg(ipsec_mp);
26322 				if (next_mp == NULL) {
26323 					ire_refrele(ire1);
26324 					ire1 = NULL;
26325 				}
26326 			}
26327 		}
26328 		/*
26329 		 * Everything is done. Send it out on the wire
26330 		 *
26331 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26332 		 * either send it on the wire or, in the case of
26333 		 * HW acceleration, call ipsec_hw_putnext.
26334 		 */
26335 		if (ire->ire_nce &&
26336 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26337 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26338 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26339 			/*
26340 			 * If ire's link-layer is unresolved (this
26341 			 * would only happen if the incomplete ire
26342 			 * was added to cachetable via forwarding path)
26343 			 * don't bother going to ip_xmit_v4. Just drop the
26344 			 * packet.
26345 			 * There is a slight risk here, in that, if we
26346 			 * have the forwarding path create an incomplete
26347 			 * IRE, then until the IRE is completed, any
26348 			 * transmitted IPsec packets will be dropped
26349 			 * instead of being queued waiting for resolution.
26350 			 *
26351 			 * But the likelihood of a forwarding packet and a wput
26352 			 * packet sending to the same dst at the same time
26353 			 * and there not yet be an ARP entry for it is small.
26354 			 * Furthermore, if this actually happens, it might
26355 			 * be likely that wput would generate multiple
26356 			 * packets (and forwarding would also have a train
26357 			 * of packets) for that destination. If this is
26358 			 * the case, some of them would have been dropped
26359 			 * anyway, since ARP only queues a few packets while
26360 			 * waiting for resolution
26361 			 *
26362 			 * NOTE: We should really call ip_xmit_v4,
26363 			 * and let it queue the packet and send the
26364 			 * ARP query and have ARP come back thus:
26365 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26366 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26367 			 * hw accel work. But it's too complex to get
26368 			 * the IPsec hw  acceleration approach to fit
26369 			 * well with ip_xmit_v4 doing ARP without
26370 			 * doing IPsec simplification. For now, we just
26371 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26372 			 * that we can continue with the send on the next
26373 			 * attempt.
26374 			 *
26375 			 * XXX THis should be revisited, when
26376 			 * the IPsec/IP interaction is cleaned up
26377 			 */
26378 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26379 			    " - dropping packet\n"));
26380 			freemsg(ipsec_mp);
26381 			/*
26382 			 * Call ip_xmit_v4() to trigger ARP query
26383 			 * in case the nce_state is ND_INITIAL
26384 			 */
26385 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26386 			goto drop_pkt;
26387 		}
26388 
26389 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26390 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26391 		    mblk_t *, ipsec_mp);
26392 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26393 		    ipst->ips_ipv4firewall_physical_out, NULL,
26394 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26395 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26396 		if (ipsec_mp == NULL)
26397 			goto drop_pkt;
26398 
26399 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26400 		pktxmit_state = ip_xmit_v4(mp, ire,
26401 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26402 
26403 		if ((pktxmit_state ==  SEND_FAILED) ||
26404 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26405 
26406 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26407 drop_pkt:
26408 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26409 			    ipIfStatsOutDiscards);
26410 			if (ire_need_rele)
26411 				ire_refrele(ire);
26412 			if (ire1 != NULL) {
26413 				ire_refrele(ire1);
26414 				freemsg(next_mp);
26415 			}
26416 			goto done;
26417 		}
26418 
26419 		freeb(ipsec_mp);
26420 		if (ire_need_rele)
26421 			ire_refrele(ire);
26422 
26423 		if (ire1 != NULL) {
26424 			ire = ire1;
26425 			ire_need_rele = B_TRUE;
26426 			ASSERT(next_mp);
26427 			ipsec_mp = next_mp;
26428 			mp = ipsec_mp->b_cont;
26429 			ire1 = NULL;
26430 			next_mp = NULL;
26431 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26432 		} else {
26433 			multirt_send = B_FALSE;
26434 		}
26435 	} while (multirt_send);
26436 done:
26437 	if (ill != NULL && ill_need_rele)
26438 		ill_refrele(ill);
26439 	if (ipif != NULL)
26440 		ipif_refrele(ipif);
26441 }
26442 
26443 /*
26444  * Get the ill corresponding to the specified ire, and compare its
26445  * capabilities with the protocol and algorithms specified by the
26446  * the SA obtained from ipsec_out. If they match, annotate the
26447  * ipsec_out structure to indicate that the packet needs acceleration.
26448  *
26449  *
26450  * A packet is eligible for outbound hardware acceleration if the
26451  * following conditions are satisfied:
26452  *
26453  * 1. the packet will not be fragmented
26454  * 2. the provider supports the algorithm
26455  * 3. there is no pending control message being exchanged
26456  * 4. snoop is not attached
26457  * 5. the destination address is not a broadcast or multicast address.
26458  *
26459  * Rationale:
26460  *	- Hardware drivers do not support fragmentation with
26461  *	  the current interface.
26462  *	- snoop, multicast, and broadcast may result in exposure of
26463  *	  a cleartext datagram.
26464  * We check all five of these conditions here.
26465  *
26466  * XXX would like to nuke "ire_t *" parameter here; problem is that
26467  * IRE is only way to figure out if a v4 address is a broadcast and
26468  * thus ineligible for acceleration...
26469  */
26470 static void
26471 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26472 {
26473 	ipsec_out_t *io;
26474 	mblk_t *data_mp;
26475 	uint_t plen, overhead;
26476 	ip_stack_t	*ipst;
26477 	phyint_t	*phyint;
26478 
26479 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26480 		return;
26481 
26482 	if (ill == NULL)
26483 		return;
26484 	ipst = ill->ill_ipst;
26485 	phyint = ill->ill_phyint;
26486 
26487 	/*
26488 	 * Destination address is a broadcast or multicast.  Punt.
26489 	 */
26490 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26491 	    IRE_LOCAL)))
26492 		return;
26493 
26494 	data_mp = ipsec_mp->b_cont;
26495 
26496 	if (ill->ill_isv6) {
26497 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26498 
26499 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26500 			return;
26501 
26502 		plen = ip6h->ip6_plen;
26503 	} else {
26504 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26505 
26506 		if (CLASSD(ipha->ipha_dst))
26507 			return;
26508 
26509 		plen = ipha->ipha_length;
26510 	}
26511 	/*
26512 	 * Is there a pending DLPI control message being exchanged
26513 	 * between IP/IPsec and the DLS Provider? If there is, it
26514 	 * could be a SADB update, and the state of the DLS Provider
26515 	 * SADB might not be in sync with the SADB maintained by
26516 	 * IPsec. To avoid dropping packets or using the wrong keying
26517 	 * material, we do not accelerate this packet.
26518 	 */
26519 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26520 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26521 		    "ill_dlpi_pending! don't accelerate packet\n"));
26522 		return;
26523 	}
26524 
26525 	/*
26526 	 * Is the Provider in promiscous mode? If it does, we don't
26527 	 * accelerate the packet since it will bounce back up to the
26528 	 * listeners in the clear.
26529 	 */
26530 	if (phyint->phyint_flags & PHYI_PROMISC) {
26531 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26532 		    "ill in promiscous mode, don't accelerate packet\n"));
26533 		return;
26534 	}
26535 
26536 	/*
26537 	 * Will the packet require fragmentation?
26538 	 */
26539 
26540 	/*
26541 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26542 	 * as is used elsewhere.
26543 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26544 	 *	+ 2-byte trailer
26545 	 */
26546 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26547 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26548 
26549 	if ((plen + overhead) > ill->ill_max_mtu)
26550 		return;
26551 
26552 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26553 
26554 	/*
26555 	 * Can the ill accelerate this IPsec protocol and algorithm
26556 	 * specified by the SA?
26557 	 */
26558 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26559 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26560 		return;
26561 	}
26562 
26563 	/*
26564 	 * Tell AH or ESP that the outbound ill is capable of
26565 	 * accelerating this packet.
26566 	 */
26567 	io->ipsec_out_is_capab_ill = B_TRUE;
26568 }
26569 
26570 /*
26571  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26572  *
26573  * If this function returns B_TRUE, the requested SA's have been filled
26574  * into the ipsec_out_*_sa pointers.
26575  *
26576  * If the function returns B_FALSE, the packet has been "consumed", most
26577  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26578  *
26579  * The SA references created by the protocol-specific "select"
26580  * function will be released when the ipsec_mp is freed, thanks to the
26581  * ipsec_out_free destructor -- see spd.c.
26582  */
26583 static boolean_t
26584 ipsec_out_select_sa(mblk_t *ipsec_mp)
26585 {
26586 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26587 	ipsec_out_t *io;
26588 	ipsec_policy_t *pp;
26589 	ipsec_action_t *ap;
26590 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26591 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26592 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26593 
26594 	if (!io->ipsec_out_secure) {
26595 		/*
26596 		 * We came here by mistake.
26597 		 * Don't bother with ipsec processing
26598 		 * We should "discourage" this path in the future.
26599 		 */
26600 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26601 		return (B_FALSE);
26602 	}
26603 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26604 	ASSERT((io->ipsec_out_policy != NULL) ||
26605 	    (io->ipsec_out_act != NULL));
26606 
26607 	ASSERT(io->ipsec_out_failed == B_FALSE);
26608 
26609 	/*
26610 	 * IPsec processing has started.
26611 	 */
26612 	io->ipsec_out_proc_begin = B_TRUE;
26613 	ap = io->ipsec_out_act;
26614 	if (ap == NULL) {
26615 		pp = io->ipsec_out_policy;
26616 		ASSERT(pp != NULL);
26617 		ap = pp->ipsp_act;
26618 		ASSERT(ap != NULL);
26619 	}
26620 
26621 	/*
26622 	 * We have an action.  now, let's select SA's.
26623 	 * (In the future, we can cache this in the conn_t..)
26624 	 */
26625 	if (ap->ipa_want_esp) {
26626 		if (io->ipsec_out_esp_sa == NULL) {
26627 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26628 			    IPPROTO_ESP);
26629 		}
26630 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26631 	}
26632 
26633 	if (ap->ipa_want_ah) {
26634 		if (io->ipsec_out_ah_sa == NULL) {
26635 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26636 			    IPPROTO_AH);
26637 		}
26638 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26639 		/*
26640 		 * The ESP and AH processing order needs to be preserved
26641 		 * when both protocols are required (ESP should be applied
26642 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26643 		 * when both ESP and AH are required, and an AH ACQUIRE
26644 		 * is needed.
26645 		 */
26646 		if (ap->ipa_want_esp && need_ah_acquire)
26647 			need_esp_acquire = B_TRUE;
26648 	}
26649 
26650 	/*
26651 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26652 	 * Release SAs that got referenced, but will not be used until we
26653 	 * acquire _all_ of the SAs we need.
26654 	 */
26655 	if (need_ah_acquire || need_esp_acquire) {
26656 		if (io->ipsec_out_ah_sa != NULL) {
26657 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26658 			io->ipsec_out_ah_sa = NULL;
26659 		}
26660 		if (io->ipsec_out_esp_sa != NULL) {
26661 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26662 			io->ipsec_out_esp_sa = NULL;
26663 		}
26664 
26665 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26666 		return (B_FALSE);
26667 	}
26668 
26669 	return (B_TRUE);
26670 }
26671 
26672 /*
26673  * Process an IPSEC_OUT message and see what you can
26674  * do with it.
26675  * IPQoS Notes:
26676  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26677  * IPsec.
26678  * XXX would like to nuke ire_t.
26679  * XXX ill_index better be "real"
26680  */
26681 void
26682 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26683 {
26684 	ipsec_out_t *io;
26685 	ipsec_policy_t *pp;
26686 	ipsec_action_t *ap;
26687 	ipha_t *ipha;
26688 	ip6_t *ip6h;
26689 	mblk_t *mp;
26690 	ill_t *ill;
26691 	zoneid_t zoneid;
26692 	ipsec_status_t ipsec_rc;
26693 	boolean_t ill_need_rele = B_FALSE;
26694 	ip_stack_t	*ipst;
26695 	ipsec_stack_t	*ipss;
26696 
26697 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26698 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26699 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26700 	ipst = io->ipsec_out_ns->netstack_ip;
26701 	mp = ipsec_mp->b_cont;
26702 
26703 	/*
26704 	 * Initiate IPPF processing. We do it here to account for packets
26705 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26706 	 * We can check for ipsec_out_proc_begin even for such packets, as
26707 	 * they will always be false (asserted below).
26708 	 */
26709 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26710 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26711 		    io->ipsec_out_ill_index : ill_index);
26712 		if (mp == NULL) {
26713 			ip2dbg(("ipsec_out_process: packet dropped "\
26714 			    "during IPPF processing\n"));
26715 			freeb(ipsec_mp);
26716 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26717 			return;
26718 		}
26719 	}
26720 
26721 	if (!io->ipsec_out_secure) {
26722 		/*
26723 		 * We came here by mistake.
26724 		 * Don't bother with ipsec processing
26725 		 * Should "discourage" this path in the future.
26726 		 */
26727 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26728 		goto done;
26729 	}
26730 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26731 	ASSERT((io->ipsec_out_policy != NULL) ||
26732 	    (io->ipsec_out_act != NULL));
26733 	ASSERT(io->ipsec_out_failed == B_FALSE);
26734 
26735 	ipss = ipst->ips_netstack->netstack_ipsec;
26736 	if (!ipsec_loaded(ipss)) {
26737 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26738 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26739 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26740 		} else {
26741 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26742 		}
26743 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26744 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26745 		    &ipss->ipsec_dropper);
26746 		return;
26747 	}
26748 
26749 	/*
26750 	 * IPsec processing has started.
26751 	 */
26752 	io->ipsec_out_proc_begin = B_TRUE;
26753 	ap = io->ipsec_out_act;
26754 	if (ap == NULL) {
26755 		pp = io->ipsec_out_policy;
26756 		ASSERT(pp != NULL);
26757 		ap = pp->ipsp_act;
26758 		ASSERT(ap != NULL);
26759 	}
26760 
26761 	/*
26762 	 * Save the outbound ill index. When the packet comes back
26763 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26764 	 * before sending it the accelerated packet.
26765 	 */
26766 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26767 		ill = ire_to_ill(ire);
26768 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26769 	}
26770 
26771 	/*
26772 	 * The order of processing is first insert a IP header if needed.
26773 	 * Then insert the ESP header and then the AH header.
26774 	 */
26775 	if ((io->ipsec_out_se_done == B_FALSE) &&
26776 	    (ap->ipa_want_se)) {
26777 		/*
26778 		 * First get the outer IP header before sending
26779 		 * it to ESP.
26780 		 */
26781 		ipha_t *oipha, *iipha;
26782 		mblk_t *outer_mp, *inner_mp;
26783 
26784 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26785 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26786 			    "ipsec_out_process: "
26787 			    "Self-Encapsulation failed: Out of memory\n");
26788 			freemsg(ipsec_mp);
26789 			if (ill != NULL) {
26790 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26791 			} else {
26792 				BUMP_MIB(&ipst->ips_ip_mib,
26793 				    ipIfStatsOutDiscards);
26794 			}
26795 			return;
26796 		}
26797 		inner_mp = ipsec_mp->b_cont;
26798 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26799 		oipha = (ipha_t *)outer_mp->b_rptr;
26800 		iipha = (ipha_t *)inner_mp->b_rptr;
26801 		*oipha = *iipha;
26802 		outer_mp->b_wptr += sizeof (ipha_t);
26803 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26804 		    sizeof (ipha_t));
26805 		oipha->ipha_protocol = IPPROTO_ENCAP;
26806 		oipha->ipha_version_and_hdr_length =
26807 		    IP_SIMPLE_HDR_VERSION;
26808 		oipha->ipha_hdr_checksum = 0;
26809 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26810 		outer_mp->b_cont = inner_mp;
26811 		ipsec_mp->b_cont = outer_mp;
26812 
26813 		io->ipsec_out_se_done = B_TRUE;
26814 		io->ipsec_out_tunnel = B_TRUE;
26815 	}
26816 
26817 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26818 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26819 	    !ipsec_out_select_sa(ipsec_mp))
26820 		return;
26821 
26822 	/*
26823 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26824 	 * to do the heavy lifting.
26825 	 */
26826 	zoneid = io->ipsec_out_zoneid;
26827 	ASSERT(zoneid != ALL_ZONES);
26828 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26829 		ASSERT(io->ipsec_out_esp_sa != NULL);
26830 		io->ipsec_out_esp_done = B_TRUE;
26831 		/*
26832 		 * Note that since hw accel can only apply one transform,
26833 		 * not two, we skip hw accel for ESP if we also have AH
26834 		 * This is an design limitation of the interface
26835 		 * which should be revisited.
26836 		 */
26837 		ASSERT(ire != NULL);
26838 		if (io->ipsec_out_ah_sa == NULL) {
26839 			ill = (ill_t *)ire->ire_stq->q_ptr;
26840 			ipsec_out_is_accelerated(ipsec_mp,
26841 			    io->ipsec_out_esp_sa, ill, ire);
26842 		}
26843 
26844 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26845 		switch (ipsec_rc) {
26846 		case IPSEC_STATUS_SUCCESS:
26847 			break;
26848 		case IPSEC_STATUS_FAILED:
26849 			if (ill != NULL) {
26850 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26851 			} else {
26852 				BUMP_MIB(&ipst->ips_ip_mib,
26853 				    ipIfStatsOutDiscards);
26854 			}
26855 			/* FALLTHRU */
26856 		case IPSEC_STATUS_PENDING:
26857 			return;
26858 		}
26859 	}
26860 
26861 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26862 		ASSERT(io->ipsec_out_ah_sa != NULL);
26863 		io->ipsec_out_ah_done = B_TRUE;
26864 		if (ire == NULL) {
26865 			int idx = io->ipsec_out_capab_ill_index;
26866 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26867 			    NULL, NULL, NULL, NULL, ipst);
26868 			ill_need_rele = B_TRUE;
26869 		} else {
26870 			ill = (ill_t *)ire->ire_stq->q_ptr;
26871 		}
26872 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26873 		    ire);
26874 
26875 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26876 		switch (ipsec_rc) {
26877 		case IPSEC_STATUS_SUCCESS:
26878 			break;
26879 		case IPSEC_STATUS_FAILED:
26880 			if (ill != NULL) {
26881 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26882 			} else {
26883 				BUMP_MIB(&ipst->ips_ip_mib,
26884 				    ipIfStatsOutDiscards);
26885 			}
26886 			/* FALLTHRU */
26887 		case IPSEC_STATUS_PENDING:
26888 			if (ill != NULL && ill_need_rele)
26889 				ill_refrele(ill);
26890 			return;
26891 		}
26892 	}
26893 	/*
26894 	 * We are done with IPsec processing. Send it over the wire.
26895 	 */
26896 done:
26897 	mp = ipsec_mp->b_cont;
26898 	ipha = (ipha_t *)mp->b_rptr;
26899 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26900 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26901 		    ire);
26902 	} else {
26903 		ip6h = (ip6_t *)ipha;
26904 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26905 		    ire);
26906 	}
26907 	if (ill != NULL && ill_need_rele)
26908 		ill_refrele(ill);
26909 }
26910 
26911 /* ARGSUSED */
26912 void
26913 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26914 {
26915 	opt_restart_t	*or;
26916 	int	err;
26917 	conn_t	*connp;
26918 	cred_t	*cr;
26919 
26920 	ASSERT(CONN_Q(q));
26921 	connp = Q_TO_CONN(q);
26922 
26923 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26924 	or = (opt_restart_t *)first_mp->b_rptr;
26925 	/*
26926 	 * We checked for a db_credp the first time svr4_optcom_req
26927 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26928 	 */
26929 	cr = msg_getcred(first_mp, NULL);
26930 	ASSERT(cr != NULL);
26931 
26932 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26933 		err = svr4_optcom_req(q, first_mp, cr,
26934 		    &ip_opt_obj, B_FALSE);
26935 	} else {
26936 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26937 		err = tpi_optcom_req(q, first_mp, cr,
26938 		    &ip_opt_obj, B_FALSE);
26939 	}
26940 	if (err != EINPROGRESS) {
26941 		/* operation is done */
26942 		CONN_OPER_PENDING_DONE(connp);
26943 	}
26944 }
26945 
26946 /*
26947  * ioctls that go through a down/up sequence may need to wait for the down
26948  * to complete. This involves waiting for the ire and ipif refcnts to go down
26949  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26950  */
26951 /* ARGSUSED */
26952 void
26953 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26954 {
26955 	struct iocblk *iocp;
26956 	mblk_t *mp1;
26957 	ip_ioctl_cmd_t *ipip;
26958 	int err;
26959 	sin_t	*sin;
26960 	struct lifreq *lifr;
26961 	struct ifreq *ifr;
26962 
26963 	iocp = (struct iocblk *)mp->b_rptr;
26964 	ASSERT(ipsq != NULL);
26965 	/* Existence of mp1 verified in ip_wput_nondata */
26966 	mp1 = mp->b_cont->b_cont;
26967 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26968 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26969 		/*
26970 		 * Special case where ipx_current_ipif is not set:
26971 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26972 		 * We are here as were not able to complete the operation in
26973 		 * ipif_set_values because we could not become exclusive on
26974 		 * the new ipsq.
26975 		 */
26976 		ill_t *ill = q->q_ptr;
26977 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26978 	}
26979 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26980 
26981 	if (ipip->ipi_cmd_type == IF_CMD) {
26982 		/* This a old style SIOC[GS]IF* command */
26983 		ifr = (struct ifreq *)mp1->b_rptr;
26984 		sin = (sin_t *)&ifr->ifr_addr;
26985 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26986 		/* This a new style SIOC[GS]LIF* command */
26987 		lifr = (struct lifreq *)mp1->b_rptr;
26988 		sin = (sin_t *)&lifr->lifr_addr;
26989 	} else {
26990 		sin = NULL;
26991 	}
26992 
26993 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26994 	    q, mp, ipip, mp1->b_rptr);
26995 
26996 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26997 }
26998 
26999 /*
27000  * ioctl processing
27001  *
27002  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27003  * the ioctl command in the ioctl tables, determines the copyin data size
27004  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27005  *
27006  * ioctl processing then continues when the M_IOCDATA makes its way down to
27007  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27008  * associated 'conn' is refheld till the end of the ioctl and the general
27009  * ioctl processing function ip_process_ioctl() is called to extract the
27010  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27011  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27012  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27013  * is used to extract the ioctl's arguments.
27014  *
27015  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27016  * so goes thru the serialization primitive ipsq_try_enter. Then the
27017  * appropriate function to handle the ioctl is called based on the entry in
27018  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27019  * which also refreleases the 'conn' that was refheld at the start of the
27020  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27021  *
27022  * Many exclusive ioctls go thru an internal down up sequence as part of
27023  * the operation. For example an attempt to change the IP address of an
27024  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27025  * does all the cleanup such as deleting all ires that use this address.
27026  * Then we need to wait till all references to the interface go away.
27027  */
27028 void
27029 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27030 {
27031 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27032 	ip_ioctl_cmd_t *ipip = arg;
27033 	ip_extract_func_t *extract_funcp;
27034 	cmd_info_t ci;
27035 	int err;
27036 	boolean_t entered_ipsq = B_FALSE;
27037 
27038 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27039 
27040 	if (ipip == NULL)
27041 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27042 
27043 	/*
27044 	 * SIOCLIFADDIF needs to go thru a special path since the
27045 	 * ill may not exist yet. This happens in the case of lo0
27046 	 * which is created using this ioctl.
27047 	 */
27048 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27049 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27050 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27051 		return;
27052 	}
27053 
27054 	ci.ci_ipif = NULL;
27055 	if (ipip->ipi_cmd_type == MISC_CMD) {
27056 		/*
27057 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27058 		 */
27059 		if (ipip->ipi_cmd == IF_UNITSEL) {
27060 			/* ioctl comes down the ill */
27061 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27062 			ipif_refhold(ci.ci_ipif);
27063 		}
27064 		err = 0;
27065 		ci.ci_sin = NULL;
27066 		ci.ci_sin6 = NULL;
27067 		ci.ci_lifr = NULL;
27068 	} else {
27069 		switch (ipip->ipi_cmd_type) {
27070 		case IF_CMD:
27071 		case LIF_CMD:
27072 			extract_funcp = ip_extract_lifreq;
27073 			break;
27074 
27075 		case ARP_CMD:
27076 		case XARP_CMD:
27077 			extract_funcp = ip_extract_arpreq;
27078 			break;
27079 
27080 		case TUN_CMD:
27081 			extract_funcp = ip_extract_tunreq;
27082 			break;
27083 
27084 		case MSFILT_CMD:
27085 			extract_funcp = ip_extract_msfilter;
27086 			break;
27087 
27088 		default:
27089 			ASSERT(0);
27090 		}
27091 
27092 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27093 		if (err != 0) {
27094 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27095 			return;
27096 		}
27097 
27098 		/*
27099 		 * All of the extraction functions return a refheld ipif.
27100 		 */
27101 		ASSERT(ci.ci_ipif != NULL);
27102 	}
27103 
27104 	if (!(ipip->ipi_flags & IPI_WR)) {
27105 		/*
27106 		 * A return value of EINPROGRESS means the ioctl is
27107 		 * either queued and waiting for some reason or has
27108 		 * already completed.
27109 		 */
27110 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27111 		    ci.ci_lifr);
27112 		if (ci.ci_ipif != NULL)
27113 			ipif_refrele(ci.ci_ipif);
27114 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27115 		return;
27116 	}
27117 
27118 	ASSERT(ci.ci_ipif != NULL);
27119 
27120 	/*
27121 	 * If ipsq is non-NULL, we are already being called exclusively.
27122 	 */
27123 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27124 	if (ipsq == NULL) {
27125 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27126 		    NEW_OP, B_TRUE);
27127 		if (ipsq == NULL) {
27128 			ipif_refrele(ci.ci_ipif);
27129 			return;
27130 		}
27131 		entered_ipsq = B_TRUE;
27132 	}
27133 
27134 	/*
27135 	 * Release the ipif so that ipif_down and friends that wait for
27136 	 * references to go away are not misled about the current ipif_refcnt
27137 	 * values. We are writer so we can access the ipif even after releasing
27138 	 * the ipif.
27139 	 */
27140 	ipif_refrele(ci.ci_ipif);
27141 
27142 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27143 
27144 	/*
27145 	 * A return value of EINPROGRESS means the ioctl is
27146 	 * either queued and waiting for some reason or has
27147 	 * already completed.
27148 	 */
27149 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27150 
27151 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27152 
27153 	if (entered_ipsq)
27154 		ipsq_exit(ipsq);
27155 }
27156 
27157 /*
27158  * Complete the ioctl. Typically ioctls use the mi package and need to
27159  * do mi_copyout/mi_copy_done.
27160  */
27161 void
27162 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27163 {
27164 	conn_t	*connp = NULL;
27165 
27166 	if (err == EINPROGRESS)
27167 		return;
27168 
27169 	if (CONN_Q(q)) {
27170 		connp = Q_TO_CONN(q);
27171 		ASSERT(connp->conn_ref >= 2);
27172 	}
27173 
27174 	switch (mode) {
27175 	case COPYOUT:
27176 		if (err == 0)
27177 			mi_copyout(q, mp);
27178 		else
27179 			mi_copy_done(q, mp, err);
27180 		break;
27181 
27182 	case NO_COPYOUT:
27183 		mi_copy_done(q, mp, err);
27184 		break;
27185 
27186 	default:
27187 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27188 		break;
27189 	}
27190 
27191 	/*
27192 	 * The refhold placed at the start of the ioctl is released here.
27193 	 */
27194 	if (connp != NULL)
27195 		CONN_OPER_PENDING_DONE(connp);
27196 
27197 	if (ipsq != NULL)
27198 		ipsq_current_finish(ipsq);
27199 }
27200 
27201 /* Called from ip_wput for all non data messages */
27202 /* ARGSUSED */
27203 void
27204 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27205 {
27206 	mblk_t		*mp1;
27207 	ire_t		*ire, *fake_ire;
27208 	ill_t		*ill;
27209 	struct iocblk	*iocp;
27210 	ip_ioctl_cmd_t	*ipip;
27211 	cred_t		*cr;
27212 	conn_t		*connp;
27213 	int		err;
27214 	nce_t		*nce;
27215 	ipif_t		*ipif;
27216 	ip_stack_t	*ipst;
27217 	char		*proto_str;
27218 
27219 	if (CONN_Q(q)) {
27220 		connp = Q_TO_CONN(q);
27221 		ipst = connp->conn_netstack->netstack_ip;
27222 	} else {
27223 		connp = NULL;
27224 		ipst = ILLQ_TO_IPST(q);
27225 	}
27226 
27227 	switch (DB_TYPE(mp)) {
27228 	case M_IOCTL:
27229 		/*
27230 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27231 		 * will arrange to copy in associated control structures.
27232 		 */
27233 		ip_sioctl_copyin_setup(q, mp);
27234 		return;
27235 	case M_IOCDATA:
27236 		/*
27237 		 * Ensure that this is associated with one of our trans-
27238 		 * parent ioctls.  If it's not ours, discard it if we're
27239 		 * running as a driver, or pass it on if we're a module.
27240 		 */
27241 		iocp = (struct iocblk *)mp->b_rptr;
27242 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27243 		if (ipip == NULL) {
27244 			if (q->q_next == NULL) {
27245 				goto nak;
27246 			} else {
27247 				putnext(q, mp);
27248 			}
27249 			return;
27250 		}
27251 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27252 			/*
27253 			 * the ioctl is one we recognise, but is not
27254 			 * consumed by IP as a module, pass M_IOCDATA
27255 			 * for processing downstream, but only for
27256 			 * common Streams ioctls.
27257 			 */
27258 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27259 				putnext(q, mp);
27260 				return;
27261 			} else {
27262 				goto nak;
27263 			}
27264 		}
27265 
27266 		/* IOCTL continuation following copyin or copyout. */
27267 		if (mi_copy_state(q, mp, NULL) == -1) {
27268 			/*
27269 			 * The copy operation failed.  mi_copy_state already
27270 			 * cleaned up, so we're out of here.
27271 			 */
27272 			return;
27273 		}
27274 		/*
27275 		 * If we just completed a copy in, we become writer and
27276 		 * continue processing in ip_sioctl_copyin_done.  If it
27277 		 * was a copy out, we call mi_copyout again.  If there is
27278 		 * nothing more to copy out, it will complete the IOCTL.
27279 		 */
27280 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27281 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27282 				mi_copy_done(q, mp, EPROTO);
27283 				return;
27284 			}
27285 			/*
27286 			 * Check for cases that need more copying.  A return
27287 			 * value of 0 means a second copyin has been started,
27288 			 * so we return; a return value of 1 means no more
27289 			 * copying is needed, so we continue.
27290 			 */
27291 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27292 			    MI_COPY_COUNT(mp) == 1) {
27293 				if (ip_copyin_msfilter(q, mp) == 0)
27294 					return;
27295 			}
27296 			/*
27297 			 * Refhold the conn, till the ioctl completes. This is
27298 			 * needed in case the ioctl ends up in the pending mp
27299 			 * list. Every mp in the ill_pending_mp list and
27300 			 * the ipx_pending_mp must have a refhold on the conn
27301 			 * to resume processing. The refhold is released when
27302 			 * the ioctl completes. (normally or abnormally)
27303 			 * In all cases ip_ioctl_finish is called to finish
27304 			 * the ioctl.
27305 			 */
27306 			if (connp != NULL) {
27307 				/* This is not a reentry */
27308 				ASSERT(ipsq == NULL);
27309 				CONN_INC_REF(connp);
27310 			} else {
27311 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27312 					mi_copy_done(q, mp, EINVAL);
27313 					return;
27314 				}
27315 			}
27316 
27317 			ip_process_ioctl(ipsq, q, mp, ipip);
27318 
27319 		} else {
27320 			mi_copyout(q, mp);
27321 		}
27322 		return;
27323 nak:
27324 		iocp->ioc_error = EINVAL;
27325 		mp->b_datap->db_type = M_IOCNAK;
27326 		iocp->ioc_count = 0;
27327 		qreply(q, mp);
27328 		return;
27329 
27330 	case M_IOCNAK:
27331 		/*
27332 		 * The only way we could get here is if a resolver didn't like
27333 		 * an IOCTL we sent it.	 This shouldn't happen.
27334 		 */
27335 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27336 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27337 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27338 		freemsg(mp);
27339 		return;
27340 	case M_IOCACK:
27341 		/* /dev/ip shouldn't see this */
27342 		if (CONN_Q(q))
27343 			goto nak;
27344 
27345 		/*
27346 		 * Finish socket ioctls passed through to ARP.  We use the
27347 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27348 		 * we need to become writer before calling ip_sioctl_iocack().
27349 		 * Note that qwriter_ip() will release the refhold, and that a
27350 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27351 		 * ill stream.
27352 		 */
27353 		iocp = (struct iocblk *)mp->b_rptr;
27354 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27355 			ip_sioctl_iocack(NULL, q, mp, NULL);
27356 			return;
27357 		}
27358 
27359 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27360 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27361 		ill = q->q_ptr;
27362 		ill_refhold(ill);
27363 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27364 		return;
27365 	case M_FLUSH:
27366 		if (*mp->b_rptr & FLUSHW)
27367 			flushq(q, FLUSHALL);
27368 		if (q->q_next) {
27369 			putnext(q, mp);
27370 			return;
27371 		}
27372 		if (*mp->b_rptr & FLUSHR) {
27373 			*mp->b_rptr &= ~FLUSHW;
27374 			qreply(q, mp);
27375 			return;
27376 		}
27377 		freemsg(mp);
27378 		return;
27379 	case IRE_DB_REQ_TYPE:
27380 		if (connp == NULL) {
27381 			proto_str = "IRE_DB_REQ_TYPE";
27382 			goto protonak;
27383 		}
27384 		/* An Upper Level Protocol wants a copy of an IRE. */
27385 		ip_ire_req(q, mp);
27386 		return;
27387 	case M_CTL:
27388 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27389 			break;
27390 
27391 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27392 		    TUN_HELLO) {
27393 			ASSERT(connp != NULL);
27394 			connp->conn_flags |= IPCL_IPTUN;
27395 			freeb(mp);
27396 			return;
27397 		}
27398 
27399 		/* M_CTL messages are used by ARP to tell us things. */
27400 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27401 			break;
27402 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27403 		case AR_ENTRY_SQUERY:
27404 			putnext(q, mp);
27405 			return;
27406 		case AR_CLIENT_NOTIFY:
27407 			ip_arp_news(q, mp);
27408 			return;
27409 		case AR_DLPIOP_DONE:
27410 			ASSERT(q->q_next != NULL);
27411 			ill = (ill_t *)q->q_ptr;
27412 			/* qwriter_ip releases the refhold */
27413 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27414 			ill_refhold(ill);
27415 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27416 			return;
27417 		case AR_ARP_CLOSING:
27418 			/*
27419 			 * ARP (above us) is closing. If no ARP bringup is
27420 			 * currently pending, ack the message so that ARP
27421 			 * can complete its close. Also mark ill_arp_closing
27422 			 * so that new ARP bringups will fail. If any
27423 			 * ARP bringup is currently in progress, we will
27424 			 * ack this when the current ARP bringup completes.
27425 			 */
27426 			ASSERT(q->q_next != NULL);
27427 			ill = (ill_t *)q->q_ptr;
27428 			mutex_enter(&ill->ill_lock);
27429 			ill->ill_arp_closing = 1;
27430 			if (!ill->ill_arp_bringup_pending) {
27431 				mutex_exit(&ill->ill_lock);
27432 				qreply(q, mp);
27433 			} else {
27434 				mutex_exit(&ill->ill_lock);
27435 				freemsg(mp);
27436 			}
27437 			return;
27438 		case AR_ARP_EXTEND:
27439 			/*
27440 			 * The ARP module above us is capable of duplicate
27441 			 * address detection.  Old ATM drivers will not send
27442 			 * this message.
27443 			 */
27444 			ASSERT(q->q_next != NULL);
27445 			ill = (ill_t *)q->q_ptr;
27446 			ill->ill_arp_extend = B_TRUE;
27447 			freemsg(mp);
27448 			return;
27449 		default:
27450 			break;
27451 		}
27452 		break;
27453 	case M_PROTO:
27454 	case M_PCPROTO:
27455 		/*
27456 		 * The only PROTO messages we expect are copies of option
27457 		 * negotiation acknowledgements, AH and ESP bind requests
27458 		 * are also expected.
27459 		 */
27460 		switch (((union T_primitives *)mp->b_rptr)->type) {
27461 		case O_T_BIND_REQ:
27462 		case T_BIND_REQ: {
27463 			/* Request can get queued in bind */
27464 			if (connp == NULL) {
27465 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27466 				goto protonak;
27467 			}
27468 			/*
27469 			 * The transports except SCTP call ip_bind_{v4,v6}()
27470 			 * directly instead of a a putnext. SCTP doesn't
27471 			 * generate any T_BIND_REQ since it has its own
27472 			 * fanout data structures. However, ESP and AH
27473 			 * come in for regular binds; all other cases are
27474 			 * bind retries.
27475 			 */
27476 			ASSERT(!IPCL_IS_SCTP(connp));
27477 
27478 			/* Don't increment refcnt if this is a re-entry */
27479 			if (ipsq == NULL)
27480 				CONN_INC_REF(connp);
27481 
27482 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27483 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27484 			ASSERT(mp != NULL);
27485 
27486 			ASSERT(!IPCL_IS_TCP(connp));
27487 			ASSERT(!IPCL_IS_UDP(connp));
27488 			ASSERT(!IPCL_IS_RAWIP(connp));
27489 
27490 			/* The case of AH and ESP */
27491 			qreply(q, mp);
27492 			CONN_OPER_PENDING_DONE(connp);
27493 			return;
27494 		}
27495 		case T_SVR4_OPTMGMT_REQ:
27496 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27497 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27498 
27499 			if (connp == NULL) {
27500 				proto_str = "T_SVR4_OPTMGMT_REQ";
27501 				goto protonak;
27502 			}
27503 
27504 			/*
27505 			 * All Solaris components should pass a db_credp
27506 			 * for this TPI message, hence we ASSERT.
27507 			 * But in case there is some other M_PROTO that looks
27508 			 * like a TPI message sent by some other kernel
27509 			 * component, we check and return an error.
27510 			 */
27511 			cr = msg_getcred(mp, NULL);
27512 			ASSERT(cr != NULL);
27513 			if (cr == NULL) {
27514 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27515 				if (mp != NULL)
27516 					qreply(q, mp);
27517 				return;
27518 			}
27519 
27520 			if (!snmpcom_req(q, mp, ip_snmp_set,
27521 			    ip_snmp_get, cr)) {
27522 				/*
27523 				 * Call svr4_optcom_req so that it can
27524 				 * generate the ack. We don't come here
27525 				 * if this operation is being restarted.
27526 				 * ip_restart_optmgmt will drop the conn ref.
27527 				 * In the case of ipsec option after the ipsec
27528 				 * load is complete conn_restart_ipsec_waiter
27529 				 * drops the conn ref.
27530 				 */
27531 				ASSERT(ipsq == NULL);
27532 				CONN_INC_REF(connp);
27533 				if (ip_check_for_ipsec_opt(q, mp))
27534 					return;
27535 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27536 				    B_FALSE);
27537 				if (err != EINPROGRESS) {
27538 					/* Operation is done */
27539 					CONN_OPER_PENDING_DONE(connp);
27540 				}
27541 			}
27542 			return;
27543 		case T_OPTMGMT_REQ:
27544 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27545 			/*
27546 			 * Note: No snmpcom_req support through new
27547 			 * T_OPTMGMT_REQ.
27548 			 * Call tpi_optcom_req so that it can
27549 			 * generate the ack.
27550 			 */
27551 			if (connp == NULL) {
27552 				proto_str = "T_OPTMGMT_REQ";
27553 				goto protonak;
27554 			}
27555 
27556 			/*
27557 			 * All Solaris components should pass a db_credp
27558 			 * for this TPI message, hence we ASSERT.
27559 			 * But in case there is some other M_PROTO that looks
27560 			 * like a TPI message sent by some other kernel
27561 			 * component, we check and return an error.
27562 			 */
27563 			cr = msg_getcred(mp, NULL);
27564 			ASSERT(cr != NULL);
27565 			if (cr == NULL) {
27566 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27567 				if (mp != NULL)
27568 					qreply(q, mp);
27569 				return;
27570 			}
27571 			ASSERT(ipsq == NULL);
27572 			/*
27573 			 * We don't come here for restart. ip_restart_optmgmt
27574 			 * will drop the conn ref. In the case of ipsec option
27575 			 * after the ipsec load is complete
27576 			 * conn_restart_ipsec_waiter drops the conn ref.
27577 			 */
27578 			CONN_INC_REF(connp);
27579 			if (ip_check_for_ipsec_opt(q, mp))
27580 				return;
27581 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27582 			if (err != EINPROGRESS) {
27583 				/* Operation is done */
27584 				CONN_OPER_PENDING_DONE(connp);
27585 			}
27586 			return;
27587 		case T_UNBIND_REQ:
27588 			if (connp == NULL) {
27589 				proto_str = "T_UNBIND_REQ";
27590 				goto protonak;
27591 			}
27592 			ip_unbind(Q_TO_CONN(q));
27593 			mp = mi_tpi_ok_ack_alloc(mp);
27594 			qreply(q, mp);
27595 			return;
27596 		default:
27597 			/*
27598 			 * Have to drop any DLPI messages coming down from
27599 			 * arp (such as an info_req which would cause ip
27600 			 * to receive an extra info_ack if it was passed
27601 			 * through.
27602 			 */
27603 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27604 			    (int)*(uint_t *)mp->b_rptr));
27605 			freemsg(mp);
27606 			return;
27607 		}
27608 		/* NOTREACHED */
27609 	case IRE_DB_TYPE: {
27610 		nce_t		*nce;
27611 		ill_t		*ill;
27612 		in6_addr_t	gw_addr_v6;
27613 
27614 		/*
27615 		 * This is a response back from a resolver.  It
27616 		 * consists of a message chain containing:
27617 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27618 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27619 		 * The LL_HDR_MBLK is the DLPI header to use to get
27620 		 * the attached packet, and subsequent ones for the
27621 		 * same destination, transmitted.
27622 		 */
27623 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27624 			break;
27625 		/*
27626 		 * First, check to make sure the resolution succeeded.
27627 		 * If it failed, the second mblk will be empty.
27628 		 * If it is, free the chain, dropping the packet.
27629 		 * (We must ire_delete the ire; that frees the ire mblk)
27630 		 * We're doing this now to support PVCs for ATM; it's
27631 		 * a partial xresolv implementation. When we fully implement
27632 		 * xresolv interfaces, instead of freeing everything here
27633 		 * we'll initiate neighbor discovery.
27634 		 *
27635 		 * For v4 (ARP and other external resolvers) the resolver
27636 		 * frees the message, so no check is needed. This check
27637 		 * is required, though, for a full xresolve implementation.
27638 		 * Including this code here now both shows how external
27639 		 * resolvers can NACK a resolution request using an
27640 		 * existing design that has no specific provisions for NACKs,
27641 		 * and also takes into account that the current non-ARP
27642 		 * external resolver has been coded to use this method of
27643 		 * NACKing for all IPv6 (xresolv) cases,
27644 		 * whether our xresolv implementation is complete or not.
27645 		 *
27646 		 */
27647 		ire = (ire_t *)mp->b_rptr;
27648 		ill = ire_to_ill(ire);
27649 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27650 		if (mp1->b_rptr == mp1->b_wptr) {
27651 			if (ire->ire_ipversion == IPV6_VERSION) {
27652 				/*
27653 				 * XRESOLV interface.
27654 				 */
27655 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27656 				mutex_enter(&ire->ire_lock);
27657 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27658 				mutex_exit(&ire->ire_lock);
27659 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27660 					nce = ndp_lookup_v6(ill, B_FALSE,
27661 					    &ire->ire_addr_v6, B_FALSE);
27662 				} else {
27663 					nce = ndp_lookup_v6(ill, B_FALSE,
27664 					    &gw_addr_v6, B_FALSE);
27665 				}
27666 				if (nce != NULL) {
27667 					nce_resolv_failed(nce);
27668 					ndp_delete(nce);
27669 					NCE_REFRELE(nce);
27670 				}
27671 			}
27672 			mp->b_cont = NULL;
27673 			freemsg(mp1);		/* frees the pkt as well */
27674 			ASSERT(ire->ire_nce == NULL);
27675 			ire_delete((ire_t *)mp->b_rptr);
27676 			return;
27677 		}
27678 
27679 		/*
27680 		 * Split them into IRE_MBLK and pkt and feed it into
27681 		 * ire_add_then_send. Then in ire_add_then_send
27682 		 * the IRE will be added, and then the packet will be
27683 		 * run back through ip_wput. This time it will make
27684 		 * it to the wire.
27685 		 */
27686 		mp->b_cont = NULL;
27687 		mp = mp1->b_cont;		/* now, mp points to pkt */
27688 		mp1->b_cont = NULL;
27689 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27690 		if (ire->ire_ipversion == IPV6_VERSION) {
27691 			/*
27692 			 * XRESOLV interface. Find the nce and put a copy
27693 			 * of the dl_unitdata_req in nce_res_mp
27694 			 */
27695 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27696 			mutex_enter(&ire->ire_lock);
27697 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27698 			mutex_exit(&ire->ire_lock);
27699 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27700 				nce = ndp_lookup_v6(ill, B_FALSE,
27701 				    &ire->ire_addr_v6, B_FALSE);
27702 			} else {
27703 				nce = ndp_lookup_v6(ill, B_FALSE,
27704 				    &gw_addr_v6, B_FALSE);
27705 			}
27706 			if (nce != NULL) {
27707 				/*
27708 				 * We have to protect nce_res_mp here
27709 				 * from being accessed by other threads
27710 				 * while we change the mblk pointer.
27711 				 * Other functions will also lock the nce when
27712 				 * accessing nce_res_mp.
27713 				 *
27714 				 * The reason we change the mblk pointer
27715 				 * here rather than copying the resolved address
27716 				 * into the template is that, unlike with
27717 				 * ethernet, we have no guarantee that the
27718 				 * resolved address length will be
27719 				 * smaller than or equal to the lla length
27720 				 * with which the template was allocated,
27721 				 * (for ethernet, they're equal)
27722 				 * so we have to use the actual resolved
27723 				 * address mblk - which holds the real
27724 				 * dl_unitdata_req with the resolved address.
27725 				 *
27726 				 * Doing this is the same behavior as was
27727 				 * previously used in the v4 ARP case.
27728 				 */
27729 				mutex_enter(&nce->nce_lock);
27730 				if (nce->nce_res_mp != NULL)
27731 					freemsg(nce->nce_res_mp);
27732 				nce->nce_res_mp = mp1;
27733 				mutex_exit(&nce->nce_lock);
27734 				/*
27735 				 * We do a fastpath probe here because
27736 				 * we have resolved the address without
27737 				 * using Neighbor Discovery.
27738 				 * In the non-XRESOLV v6 case, the fastpath
27739 				 * probe is done right after neighbor
27740 				 * discovery completes.
27741 				 */
27742 				if (nce->nce_res_mp != NULL) {
27743 					int res;
27744 					nce_fastpath_list_add(nce);
27745 					res = ill_fastpath_probe(ill,
27746 					    nce->nce_res_mp);
27747 					if (res != 0 && res != EAGAIN)
27748 						nce_fastpath_list_delete(nce);
27749 				}
27750 
27751 				ire_add_then_send(q, ire, mp);
27752 				/*
27753 				 * Now we have to clean out any packets
27754 				 * that may have been queued on the nce
27755 				 * while it was waiting for address resolution
27756 				 * to complete.
27757 				 */
27758 				mutex_enter(&nce->nce_lock);
27759 				mp1 = nce->nce_qd_mp;
27760 				nce->nce_qd_mp = NULL;
27761 				mutex_exit(&nce->nce_lock);
27762 				while (mp1 != NULL) {
27763 					mblk_t *nxt_mp;
27764 					queue_t *fwdq = NULL;
27765 					ill_t   *inbound_ill;
27766 					uint_t ifindex;
27767 
27768 					nxt_mp = mp1->b_next;
27769 					mp1->b_next = NULL;
27770 					/*
27771 					 * Retrieve ifindex stored in
27772 					 * ip_rput_data_v6()
27773 					 */
27774 					ifindex =
27775 					    (uint_t)(uintptr_t)mp1->b_prev;
27776 					inbound_ill =
27777 					    ill_lookup_on_ifindex(ifindex,
27778 					    B_TRUE, NULL, NULL, NULL,
27779 					    NULL, ipst);
27780 					mp1->b_prev = NULL;
27781 					if (inbound_ill != NULL)
27782 						fwdq = inbound_ill->ill_rq;
27783 
27784 					if (fwdq != NULL) {
27785 						put(fwdq, mp1);
27786 						ill_refrele(inbound_ill);
27787 					} else
27788 						put(WR(ill->ill_rq), mp1);
27789 					mp1 = nxt_mp;
27790 				}
27791 				NCE_REFRELE(nce);
27792 			} else {	/* nce is NULL; clean up */
27793 				ire_delete(ire);
27794 				freemsg(mp);
27795 				freemsg(mp1);
27796 				return;
27797 			}
27798 		} else {
27799 			nce_t *arpce;
27800 			/*
27801 			 * Link layer resolution succeeded. Recompute the
27802 			 * ire_nce.
27803 			 */
27804 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27805 			if ((arpce = ndp_lookup_v4(ill,
27806 			    (ire->ire_gateway_addr != INADDR_ANY ?
27807 			    &ire->ire_gateway_addr : &ire->ire_addr),
27808 			    B_FALSE)) == NULL) {
27809 				freeb(ire->ire_mp);
27810 				freeb(mp1);
27811 				freemsg(mp);
27812 				return;
27813 			}
27814 			mutex_enter(&arpce->nce_lock);
27815 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27816 			if (arpce->nce_state == ND_REACHABLE) {
27817 				/*
27818 				 * Someone resolved this before us;
27819 				 * cleanup the res_mp. Since ire has
27820 				 * not been added yet, the call to ire_add_v4
27821 				 * from ire_add_then_send (when a dup is
27822 				 * detected) will clean up the ire.
27823 				 */
27824 				freeb(mp1);
27825 			} else {
27826 				ASSERT(arpce->nce_res_mp == NULL);
27827 				arpce->nce_res_mp = mp1;
27828 				arpce->nce_state = ND_REACHABLE;
27829 			}
27830 			mutex_exit(&arpce->nce_lock);
27831 			if (ire->ire_marks & IRE_MARK_NOADD) {
27832 				/*
27833 				 * this ire will not be added to the ire
27834 				 * cache table, so we can set the ire_nce
27835 				 * here, as there are no atomicity constraints.
27836 				 */
27837 				ire->ire_nce = arpce;
27838 				/*
27839 				 * We are associating this nce with the ire
27840 				 * so change the nce ref taken in
27841 				 * ndp_lookup_v4() from
27842 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27843 				 */
27844 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27845 			} else {
27846 				NCE_REFRELE(arpce);
27847 			}
27848 			ire_add_then_send(q, ire, mp);
27849 		}
27850 		return;	/* All is well, the packet has been sent. */
27851 	}
27852 	case IRE_ARPRESOLVE_TYPE: {
27853 
27854 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27855 			break;
27856 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27857 		mp->b_cont = NULL;
27858 		/*
27859 		 * First, check to make sure the resolution succeeded.
27860 		 * If it failed, the second mblk will be empty.
27861 		 */
27862 		if (mp1->b_rptr == mp1->b_wptr) {
27863 			/* cleanup  the incomplete ire, free queued packets */
27864 			freemsg(mp); /* fake ire */
27865 			freeb(mp1);  /* dl_unitdata response */
27866 			return;
27867 		}
27868 
27869 		/*
27870 		 * Update any incomplete nce_t found. We search the ctable
27871 		 * and find the nce from the ire->ire_nce because we need
27872 		 * to pass the ire to ip_xmit_v4 later, and can find both
27873 		 * ire and nce in one lookup.
27874 		 */
27875 		fake_ire = (ire_t *)mp->b_rptr;
27876 
27877 		/*
27878 		 * By the time we come back here from ARP the logical outgoing
27879 		 * interface of the incomplete ire we added in ire_forward()
27880 		 * could have disappeared, causing the incomplete ire to also
27881 		 * disappear.  So we need to retreive the proper ipif for the
27882 		 * ire before looking in ctable.  In the case of IPMP, the
27883 		 * ipif may be on the IPMP ill, so look it up based on the
27884 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27885 		 * Then, we can verify that ire_ipif_seqid still exists.
27886 		 */
27887 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27888 		    NULL, NULL, NULL, NULL, ipst);
27889 		if (ill == NULL) {
27890 			ip1dbg(("ill for incomplete ire vanished\n"));
27891 			freemsg(mp); /* fake ire */
27892 			freeb(mp1);  /* dl_unitdata response */
27893 			return;
27894 		}
27895 
27896 		/* Get the outgoing ipif */
27897 		mutex_enter(&ill->ill_lock);
27898 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27899 		if (ipif == NULL) {
27900 			mutex_exit(&ill->ill_lock);
27901 			ill_refrele(ill);
27902 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27903 			freemsg(mp); /* fake_ire */
27904 			freeb(mp1);  /* dl_unitdata response */
27905 			return;
27906 		}
27907 
27908 		ipif_refhold_locked(ipif);
27909 		mutex_exit(&ill->ill_lock);
27910 		ill_refrele(ill);
27911 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27912 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27913 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27914 		ipif_refrele(ipif);
27915 		if (ire == NULL) {
27916 			/*
27917 			 * no ire was found; check if there is an nce
27918 			 * for this lookup; if it has no ire's pointing at it
27919 			 * cleanup.
27920 			 */
27921 			if ((nce = ndp_lookup_v4(q->q_ptr,
27922 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27923 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27924 			    B_FALSE)) != NULL) {
27925 				/*
27926 				 * cleanup:
27927 				 * We check for refcnt 2 (one for the nce
27928 				 * hash list + 1 for the ref taken by
27929 				 * ndp_lookup_v4) to check that there are
27930 				 * no ire's pointing at the nce.
27931 				 */
27932 				if (nce->nce_refcnt == 2)
27933 					ndp_delete(nce);
27934 				NCE_REFRELE(nce);
27935 			}
27936 			freeb(mp1);  /* dl_unitdata response */
27937 			freemsg(mp); /* fake ire */
27938 			return;
27939 		}
27940 
27941 		nce = ire->ire_nce;
27942 		DTRACE_PROBE2(ire__arpresolve__type,
27943 		    ire_t *, ire, nce_t *, nce);
27944 		mutex_enter(&nce->nce_lock);
27945 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27946 		if (nce->nce_state == ND_REACHABLE) {
27947 			/*
27948 			 * Someone resolved this before us;
27949 			 * our response is not needed any more.
27950 			 */
27951 			mutex_exit(&nce->nce_lock);
27952 			freeb(mp1);  /* dl_unitdata response */
27953 		} else {
27954 			ASSERT(nce->nce_res_mp == NULL);
27955 			nce->nce_res_mp = mp1;
27956 			nce->nce_state = ND_REACHABLE;
27957 			mutex_exit(&nce->nce_lock);
27958 			nce_fastpath(nce);
27959 		}
27960 		/*
27961 		 * The cached nce_t has been updated to be reachable;
27962 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27963 		 */
27964 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27965 		freemsg(mp);
27966 		/*
27967 		 * send out queued packets.
27968 		 */
27969 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27970 
27971 		IRE_REFRELE(ire);
27972 		return;
27973 	}
27974 	default:
27975 		break;
27976 	}
27977 	if (q->q_next) {
27978 		putnext(q, mp);
27979 	} else
27980 		freemsg(mp);
27981 	return;
27982 
27983 protonak:
27984 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27985 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27986 		qreply(q, mp);
27987 }
27988 
27989 /*
27990  * Process IP options in an outbound packet.  Modify the destination if there
27991  * is a source route option.
27992  * Returns non-zero if something fails in which case an ICMP error has been
27993  * sent and mp freed.
27994  */
27995 static int
27996 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27997     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27998 {
27999 	ipoptp_t	opts;
28000 	uchar_t		*opt;
28001 	uint8_t		optval;
28002 	uint8_t		optlen;
28003 	ipaddr_t	dst;
28004 	intptr_t	code = 0;
28005 	mblk_t		*mp;
28006 	ire_t		*ire = NULL;
28007 
28008 	ip2dbg(("ip_wput_options\n"));
28009 	mp = ipsec_mp;
28010 	if (mctl_present) {
28011 		mp = ipsec_mp->b_cont;
28012 	}
28013 
28014 	dst = ipha->ipha_dst;
28015 	for (optval = ipoptp_first(&opts, ipha);
28016 	    optval != IPOPT_EOL;
28017 	    optval = ipoptp_next(&opts)) {
28018 		opt = opts.ipoptp_cur;
28019 		optlen = opts.ipoptp_len;
28020 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28021 		    optval, optlen));
28022 		switch (optval) {
28023 			uint32_t off;
28024 		case IPOPT_SSRR:
28025 		case IPOPT_LSRR:
28026 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28027 				ip1dbg((
28028 				    "ip_wput_options: bad option offset\n"));
28029 				code = (char *)&opt[IPOPT_OLEN] -
28030 				    (char *)ipha;
28031 				goto param_prob;
28032 			}
28033 			off = opt[IPOPT_OFFSET];
28034 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28035 			    ntohl(dst)));
28036 			/*
28037 			 * For strict: verify that dst is directly
28038 			 * reachable.
28039 			 */
28040 			if (optval == IPOPT_SSRR) {
28041 				ire = ire_ftable_lookup(dst, 0, 0,
28042 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28043 				    msg_getlabel(mp),
28044 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28045 				if (ire == NULL) {
28046 					ip1dbg(("ip_wput_options: SSRR not"
28047 					    " directly reachable: 0x%x\n",
28048 					    ntohl(dst)));
28049 					goto bad_src_route;
28050 				}
28051 				ire_refrele(ire);
28052 			}
28053 			break;
28054 		case IPOPT_RR:
28055 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28056 				ip1dbg((
28057 				    "ip_wput_options: bad option offset\n"));
28058 				code = (char *)&opt[IPOPT_OLEN] -
28059 				    (char *)ipha;
28060 				goto param_prob;
28061 			}
28062 			break;
28063 		case IPOPT_TS:
28064 			/*
28065 			 * Verify that length >=5 and that there is either
28066 			 * room for another timestamp or that the overflow
28067 			 * counter is not maxed out.
28068 			 */
28069 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28070 			if (optlen < IPOPT_MINLEN_IT) {
28071 				goto param_prob;
28072 			}
28073 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28074 				ip1dbg((
28075 				    "ip_wput_options: bad option offset\n"));
28076 				code = (char *)&opt[IPOPT_OFFSET] -
28077 				    (char *)ipha;
28078 				goto param_prob;
28079 			}
28080 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28081 			case IPOPT_TS_TSONLY:
28082 				off = IPOPT_TS_TIMELEN;
28083 				break;
28084 			case IPOPT_TS_TSANDADDR:
28085 			case IPOPT_TS_PRESPEC:
28086 			case IPOPT_TS_PRESPEC_RFC791:
28087 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28088 				break;
28089 			default:
28090 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28091 				    (char *)ipha;
28092 				goto param_prob;
28093 			}
28094 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28095 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28096 				/*
28097 				 * No room and the overflow counter is 15
28098 				 * already.
28099 				 */
28100 				goto param_prob;
28101 			}
28102 			break;
28103 		}
28104 	}
28105 
28106 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28107 		return (0);
28108 
28109 	ip1dbg(("ip_wput_options: error processing IP options."));
28110 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28111 
28112 param_prob:
28113 	/*
28114 	 * Since ip_wput() isn't close to finished, we fill
28115 	 * in enough of the header for credible error reporting.
28116 	 */
28117 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28118 		/* Failed */
28119 		freemsg(ipsec_mp);
28120 		return (-1);
28121 	}
28122 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28123 	return (-1);
28124 
28125 bad_src_route:
28126 	/*
28127 	 * Since ip_wput() isn't close to finished, we fill
28128 	 * in enough of the header for credible error reporting.
28129 	 */
28130 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28131 		/* Failed */
28132 		freemsg(ipsec_mp);
28133 		return (-1);
28134 	}
28135 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28136 	return (-1);
28137 }
28138 
28139 /*
28140  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28141  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28142  * thru /etc/system.
28143  */
28144 #define	CONN_MAXDRAINCNT	64
28145 
28146 static void
28147 conn_drain_init(ip_stack_t *ipst)
28148 {
28149 	int i, j;
28150 	idl_tx_list_t *itl_tx;
28151 
28152 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28153 
28154 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28155 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28156 		/*
28157 		 * Default value of the number of drainers is the
28158 		 * number of cpus, subject to maximum of 8 drainers.
28159 		 */
28160 		if (boot_max_ncpus != -1)
28161 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28162 		else
28163 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28164 	}
28165 
28166 	ipst->ips_idl_tx_list =
28167 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28168 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28169 		itl_tx =  &ipst->ips_idl_tx_list[i];
28170 		itl_tx->txl_drain_list =
28171 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28172 		    sizeof (idl_t), KM_SLEEP);
28173 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28174 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28175 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28176 			    MUTEX_DEFAULT, NULL);
28177 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28178 		}
28179 	}
28180 }
28181 
28182 static void
28183 conn_drain_fini(ip_stack_t *ipst)
28184 {
28185 	int i;
28186 	idl_tx_list_t *itl_tx;
28187 
28188 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28189 		itl_tx =  &ipst->ips_idl_tx_list[i];
28190 		kmem_free(itl_tx->txl_drain_list,
28191 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28192 	}
28193 	kmem_free(ipst->ips_idl_tx_list,
28194 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28195 	ipst->ips_idl_tx_list = NULL;
28196 }
28197 
28198 /*
28199  * Note: For an overview of how flowcontrol is handled in IP please see the
28200  * IP Flowcontrol notes at the top of this file.
28201  *
28202  * Flow control has blocked us from proceeding. Insert the given conn in one
28203  * of the conn drain lists. These conn wq's will be qenabled later on when
28204  * STREAMS flow control does a backenable. conn_walk_drain will enable
28205  * the first conn in each of these drain lists. Each of these qenabled conns
28206  * in turn enables the next in the list, after it runs, or when it closes,
28207  * thus sustaining the drain process.
28208  */
28209 void
28210 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28211 {
28212 	idl_t	*idl = tx_list->txl_drain_list;
28213 	uint_t	index;
28214 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28215 
28216 	mutex_enter(&connp->conn_lock);
28217 	if (connp->conn_state_flags & CONN_CLOSING) {
28218 		/*
28219 		 * The conn is closing as a result of which CONN_CLOSING
28220 		 * is set. Return.
28221 		 */
28222 		mutex_exit(&connp->conn_lock);
28223 		return;
28224 	} else if (connp->conn_idl == NULL) {
28225 		/*
28226 		 * Assign the next drain list round robin. We dont' use
28227 		 * a lock, and thus it may not be strictly round robin.
28228 		 * Atomicity of load/stores is enough to make sure that
28229 		 * conn_drain_list_index is always within bounds.
28230 		 */
28231 		index = tx_list->txl_drain_index;
28232 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28233 		connp->conn_idl = &tx_list->txl_drain_list[index];
28234 		index++;
28235 		if (index == ipst->ips_conn_drain_list_cnt)
28236 			index = 0;
28237 		tx_list->txl_drain_index = index;
28238 	}
28239 	mutex_exit(&connp->conn_lock);
28240 
28241 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28242 	if ((connp->conn_drain_prev != NULL) ||
28243 	    (connp->conn_state_flags & CONN_CLOSING)) {
28244 		/*
28245 		 * The conn is already in the drain list, OR
28246 		 * the conn is closing. We need to check again for
28247 		 * the closing case again since close can happen
28248 		 * after we drop the conn_lock, and before we
28249 		 * acquire the CONN_DRAIN_LIST_LOCK.
28250 		 */
28251 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28252 		return;
28253 	} else {
28254 		idl = connp->conn_idl;
28255 	}
28256 
28257 	/*
28258 	 * The conn is not in the drain list. Insert it at the
28259 	 * tail of the drain list. The drain list is circular
28260 	 * and doubly linked. idl_conn points to the 1st element
28261 	 * in the list.
28262 	 */
28263 	if (idl->idl_conn == NULL) {
28264 		idl->idl_conn = connp;
28265 		connp->conn_drain_next = connp;
28266 		connp->conn_drain_prev = connp;
28267 	} else {
28268 		conn_t *head = idl->idl_conn;
28269 
28270 		connp->conn_drain_next = head;
28271 		connp->conn_drain_prev = head->conn_drain_prev;
28272 		head->conn_drain_prev->conn_drain_next = connp;
28273 		head->conn_drain_prev = connp;
28274 	}
28275 	/*
28276 	 * For non streams based sockets assert flow control.
28277 	 */
28278 	if (IPCL_IS_NONSTR(connp)) {
28279 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28280 		(*connp->conn_upcalls->su_txq_full)
28281 		    (connp->conn_upper_handle, B_TRUE);
28282 	} else {
28283 		conn_setqfull(connp);
28284 		noenable(connp->conn_wq);
28285 	}
28286 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28287 }
28288 
28289 /*
28290  * This conn is closing, and we are called from ip_close. OR
28291  * This conn has been serviced by ip_wsrv, and we need to do the tail
28292  * processing.
28293  * If this conn is part of the drain list, we may need to sustain the drain
28294  * process by qenabling the next conn in the drain list. We may also need to
28295  * remove this conn from the list, if it is done.
28296  */
28297 static void
28298 conn_drain_tail(conn_t *connp, boolean_t closing)
28299 {
28300 	idl_t *idl;
28301 
28302 	/*
28303 	 * connp->conn_idl is stable at this point, and no lock is needed
28304 	 * to check it. If we are called from ip_close, close has already
28305 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28306 	 * called us only because conn_idl is non-null. If we are called thru
28307 	 * service, conn_idl could be null, but it cannot change because
28308 	 * service is single-threaded per queue, and there cannot be another
28309 	 * instance of service trying to call conn_drain_insert on this conn
28310 	 * now.
28311 	 */
28312 	ASSERT(!closing || (connp->conn_idl != NULL));
28313 
28314 	/*
28315 	 * If connp->conn_idl is null, the conn has not been inserted into any
28316 	 * drain list even once since creation of the conn. Just return.
28317 	 */
28318 	if (connp->conn_idl == NULL)
28319 		return;
28320 
28321 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28322 
28323 	if (connp->conn_drain_prev == NULL) {
28324 		/* This conn is currently not in the drain list.  */
28325 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28326 		return;
28327 	}
28328 	idl = connp->conn_idl;
28329 	if (idl->idl_conn_draining == connp) {
28330 		/*
28331 		 * This conn is the current drainer. If this is the last conn
28332 		 * in the drain list, we need to do more checks, in the 'if'
28333 		 * below. Otherwwise we need to just qenable the next conn,
28334 		 * to sustain the draining, and is handled in the 'else'
28335 		 * below.
28336 		 */
28337 		if (connp->conn_drain_next == idl->idl_conn) {
28338 			/*
28339 			 * This conn is the last in this list. This round
28340 			 * of draining is complete. If idl_repeat is set,
28341 			 * it means another flow enabling has happened from
28342 			 * the driver/streams and we need to another round
28343 			 * of draining.
28344 			 * If there are more than 2 conns in the drain list,
28345 			 * do a left rotate by 1, so that all conns except the
28346 			 * conn at the head move towards the head by 1, and the
28347 			 * the conn at the head goes to the tail. This attempts
28348 			 * a more even share for all queues that are being
28349 			 * drained.
28350 			 */
28351 			if ((connp->conn_drain_next != connp) &&
28352 			    (idl->idl_conn->conn_drain_next != connp)) {
28353 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28354 			}
28355 			if (idl->idl_repeat) {
28356 				qenable(idl->idl_conn->conn_wq);
28357 				idl->idl_conn_draining = idl->idl_conn;
28358 				idl->idl_repeat = 0;
28359 			} else {
28360 				idl->idl_conn_draining = NULL;
28361 			}
28362 		} else {
28363 			/*
28364 			 * If the next queue that we are now qenable'ing,
28365 			 * is closing, it will remove itself from this list
28366 			 * and qenable the subsequent queue in ip_close().
28367 			 * Serialization is acheived thru idl_lock.
28368 			 */
28369 			qenable(connp->conn_drain_next->conn_wq);
28370 			idl->idl_conn_draining = connp->conn_drain_next;
28371 		}
28372 	}
28373 	if (!connp->conn_did_putbq || closing) {
28374 		/*
28375 		 * Remove ourself from the drain list, if we did not do
28376 		 * a putbq, or if the conn is closing.
28377 		 * Note: It is possible that q->q_first is non-null. It means
28378 		 * that these messages landed after we did a enableok() in
28379 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28380 		 * service them.
28381 		 */
28382 		if (connp->conn_drain_next == connp) {
28383 			/* Singleton in the list */
28384 			ASSERT(connp->conn_drain_prev == connp);
28385 			idl->idl_conn = NULL;
28386 			idl->idl_conn_draining = NULL;
28387 		} else {
28388 			connp->conn_drain_prev->conn_drain_next =
28389 			    connp->conn_drain_next;
28390 			connp->conn_drain_next->conn_drain_prev =
28391 			    connp->conn_drain_prev;
28392 			if (idl->idl_conn == connp)
28393 				idl->idl_conn = connp->conn_drain_next;
28394 			ASSERT(idl->idl_conn_draining != connp);
28395 
28396 		}
28397 		connp->conn_drain_next = NULL;
28398 		connp->conn_drain_prev = NULL;
28399 
28400 		/*
28401 		 * For non streams based sockets open up flow control.
28402 		 */
28403 		if (IPCL_IS_NONSTR(connp)) {
28404 			(*connp->conn_upcalls->su_txq_full)
28405 			    (connp->conn_upper_handle, B_FALSE);
28406 		} else {
28407 			conn_clrqfull(connp);
28408 			enableok(connp->conn_wq);
28409 		}
28410 	}
28411 
28412 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28413 }
28414 
28415 /*
28416  * Write service routine. Shared perimeter entry point.
28417  * ip_wsrv can be called in any of the following ways.
28418  * 1. The device queue's messages has fallen below the low water mark
28419  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28420  *    the drain lists and backenable the first conn in each list.
28421  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28422  *    qenabled non-tcp upper layers. We start dequeing messages and call
28423  *    ip_wput for each message.
28424  */
28425 
28426 void
28427 ip_wsrv(queue_t *q)
28428 {
28429 	conn_t	*connp;
28430 	ill_t	*ill;
28431 	mblk_t	*mp;
28432 
28433 	if (q->q_next) {
28434 		ill = (ill_t *)q->q_ptr;
28435 		if (ill->ill_state_flags == 0) {
28436 			ip_stack_t *ipst = ill->ill_ipst;
28437 
28438 			/*
28439 			 * The device flow control has opened up.
28440 			 * Walk through conn drain lists and qenable the
28441 			 * first conn in each list. This makes sense only
28442 			 * if the stream is fully plumbed and setup.
28443 			 * Hence the if check above.
28444 			 */
28445 			ip1dbg(("ip_wsrv: walking\n"));
28446 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28447 		}
28448 		return;
28449 	}
28450 
28451 	connp = Q_TO_CONN(q);
28452 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28453 
28454 	/*
28455 	 * 1. Set conn_draining flag to signal that service is active.
28456 	 *
28457 	 * 2. ip_output determines whether it has been called from service,
28458 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28459 	 *    has been called from service.
28460 	 *
28461 	 * 3. Message ordering is preserved by the following logic.
28462 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28463 	 *    the message at the tail, if conn_draining is set (i.e. service
28464 	 *    is running) or if q->q_first is non-null.
28465 	 *
28466 	 *    ii. If ip_output is called from service, and if ip_output cannot
28467 	 *    putnext due to flow control, it does a putbq.
28468 	 *
28469 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28470 	 *    (causing an infinite loop).
28471 	 */
28472 	ASSERT(!connp->conn_did_putbq);
28473 
28474 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28475 		connp->conn_draining = 1;
28476 		noenable(q);
28477 		while ((mp = getq(q)) != NULL) {
28478 			ASSERT(CONN_Q(q));
28479 
28480 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28481 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28482 			if (connp->conn_did_putbq) {
28483 				/* ip_wput did a putbq */
28484 				break;
28485 			}
28486 		}
28487 		/*
28488 		 * At this point, a thread coming down from top, calling
28489 		 * ip_wput, may end up queueing the message. We have not yet
28490 		 * enabled the queue, so ip_wsrv won't be called again.
28491 		 * To avoid this race, check q->q_first again (in the loop)
28492 		 * If the other thread queued the message before we call
28493 		 * enableok(), we will catch it in the q->q_first check.
28494 		 * If the other thread queues the message after we call
28495 		 * enableok(), ip_wsrv will be called again by STREAMS.
28496 		 */
28497 		connp->conn_draining = 0;
28498 		enableok(q);
28499 	}
28500 
28501 	/* Enable the next conn for draining */
28502 	conn_drain_tail(connp, B_FALSE);
28503 
28504 	/*
28505 	 * conn_direct_blocked is used to indicate blocked
28506 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28507 	 * This is the only place where it is set without
28508 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28509 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28510 	 */
28511 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28512 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28513 		connp->conn_direct_blocked = B_FALSE;
28514 	}
28515 
28516 	connp->conn_did_putbq = 0;
28517 }
28518 
28519 /*
28520  * Callback to disable flow control in IP.
28521  *
28522  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28523  * is enabled.
28524  *
28525  * When MAC_TX() is not able to send any more packets, dld sets its queue
28526  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28527  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28528  * function and wakes up corresponding mac worker threads, which in turn
28529  * calls this callback function, and disables flow control.
28530  */
28531 void
28532 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28533 {
28534 	ill_t *ill = (ill_t *)arg;
28535 	ip_stack_t *ipst = ill->ill_ipst;
28536 	idl_tx_list_t *idl_txl;
28537 
28538 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28539 	mutex_enter(&idl_txl->txl_lock);
28540 	/* add code to to set a flag to indicate idl_txl is enabled */
28541 	conn_walk_drain(ipst, idl_txl);
28542 	mutex_exit(&idl_txl->txl_lock);
28543 }
28544 
28545 /*
28546  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28547  * of conns that need to be drained, check if drain is already in progress.
28548  * If so set the idl_repeat bit, indicating that the last conn in the list
28549  * needs to reinitiate the drain once again, for the list. If drain is not
28550  * in progress for the list, initiate the draining, by qenabling the 1st
28551  * conn in the list. The drain is self-sustaining, each qenabled conn will
28552  * in turn qenable the next conn, when it is done/blocked/closing.
28553  */
28554 static void
28555 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28556 {
28557 	int i;
28558 	idl_t *idl;
28559 
28560 	IP_STAT(ipst, ip_conn_walk_drain);
28561 
28562 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28563 		idl = &tx_list->txl_drain_list[i];
28564 		mutex_enter(&idl->idl_lock);
28565 		if (idl->idl_conn == NULL) {
28566 			mutex_exit(&idl->idl_lock);
28567 			continue;
28568 		}
28569 		/*
28570 		 * If this list is not being drained currently by
28571 		 * an ip_wsrv thread, start the process.
28572 		 */
28573 		if (idl->idl_conn_draining == NULL) {
28574 			ASSERT(idl->idl_repeat == 0);
28575 			qenable(idl->idl_conn->conn_wq);
28576 			idl->idl_conn_draining = idl->idl_conn;
28577 		} else {
28578 			idl->idl_repeat = 1;
28579 		}
28580 		mutex_exit(&idl->idl_lock);
28581 	}
28582 }
28583 
28584 /*
28585  * Determine if the ill and multicast aspects of that packets
28586  * "matches" the conn.
28587  */
28588 boolean_t
28589 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28590     zoneid_t zoneid)
28591 {
28592 	ill_t *bound_ill;
28593 	boolean_t found;
28594 	ipif_t *ipif;
28595 	ire_t *ire;
28596 	ipaddr_t dst, src;
28597 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28598 
28599 	dst = ipha->ipha_dst;
28600 	src = ipha->ipha_src;
28601 
28602 	/*
28603 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28604 	 * unicast, broadcast and multicast reception to
28605 	 * conn_incoming_ill. conn_wantpacket itself is called
28606 	 * only for BROADCAST and multicast.
28607 	 */
28608 	bound_ill = connp->conn_incoming_ill;
28609 	if (bound_ill != NULL) {
28610 		if (IS_IPMP(bound_ill)) {
28611 			if (bound_ill->ill_grp != ill->ill_grp)
28612 				return (B_FALSE);
28613 		} else {
28614 			if (bound_ill != ill)
28615 				return (B_FALSE);
28616 		}
28617 	}
28618 
28619 	if (!CLASSD(dst)) {
28620 		if (IPCL_ZONE_MATCH(connp, zoneid))
28621 			return (B_TRUE);
28622 		/*
28623 		 * The conn is in a different zone; we need to check that this
28624 		 * broadcast address is configured in the application's zone.
28625 		 */
28626 		ipif = ipif_get_next_ipif(NULL, ill);
28627 		if (ipif == NULL)
28628 			return (B_FALSE);
28629 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28630 		    connp->conn_zoneid, NULL,
28631 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28632 		ipif_refrele(ipif);
28633 		if (ire != NULL) {
28634 			ire_refrele(ire);
28635 			return (B_TRUE);
28636 		} else {
28637 			return (B_FALSE);
28638 		}
28639 	}
28640 
28641 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28642 	    connp->conn_zoneid == zoneid) {
28643 		/*
28644 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28645 		 * disabled, therefore we don't dispatch the multicast packet to
28646 		 * the sending zone.
28647 		 */
28648 		return (B_FALSE);
28649 	}
28650 
28651 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28652 		/*
28653 		 * Multicast packet on the loopback interface: we only match
28654 		 * conns who joined the group in the specified zone.
28655 		 */
28656 		return (B_FALSE);
28657 	}
28658 
28659 	if (connp->conn_multi_router) {
28660 		/* multicast packet and multicast router socket: send up */
28661 		return (B_TRUE);
28662 	}
28663 
28664 	mutex_enter(&connp->conn_lock);
28665 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28666 	mutex_exit(&connp->conn_lock);
28667 	return (found);
28668 }
28669 
28670 static void
28671 conn_setqfull(conn_t *connp)
28672 {
28673 	queue_t *q = connp->conn_wq;
28674 
28675 	if (!(q->q_flag & QFULL)) {
28676 		mutex_enter(QLOCK(q));
28677 		if (!(q->q_flag & QFULL)) {
28678 			/* still need to set QFULL */
28679 			q->q_flag |= QFULL;
28680 			mutex_exit(QLOCK(q));
28681 		} else {
28682 			mutex_exit(QLOCK(q));
28683 		}
28684 	}
28685 }
28686 
28687 static void
28688 conn_clrqfull(conn_t *connp)
28689 {
28690 	queue_t *q = connp->conn_wq;
28691 
28692 	if (q->q_flag & QFULL) {
28693 		mutex_enter(QLOCK(q));
28694 		if (q->q_flag & QFULL) {
28695 			q->q_flag &= ~QFULL;
28696 			mutex_exit(QLOCK(q));
28697 			if (q->q_flag & QWANTW)
28698 				qbackenable(q, 0);
28699 		} else {
28700 			mutex_exit(QLOCK(q));
28701 		}
28702 	}
28703 }
28704 
28705 /*
28706  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28707  */
28708 /* ARGSUSED */
28709 static void
28710 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28711 {
28712 	ill_t *ill = (ill_t *)q->q_ptr;
28713 	mblk_t	*mp1, *mp2;
28714 	ipif_t  *ipif;
28715 	int err = 0;
28716 	conn_t *connp = NULL;
28717 	ipsq_t	*ipsq;
28718 	arc_t	*arc;
28719 
28720 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28721 
28722 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28723 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28724 
28725 	ASSERT(IAM_WRITER_ILL(ill));
28726 	mp2 = mp->b_cont;
28727 	mp->b_cont = NULL;
28728 
28729 	/*
28730 	 * We have now received the arp bringup completion message
28731 	 * from ARP. Mark the arp bringup as done. Also if the arp
28732 	 * stream has already started closing, send up the AR_ARP_CLOSING
28733 	 * ack now since ARP is waiting in close for this ack.
28734 	 */
28735 	mutex_enter(&ill->ill_lock);
28736 	ill->ill_arp_bringup_pending = 0;
28737 	if (ill->ill_arp_closing) {
28738 		mutex_exit(&ill->ill_lock);
28739 		/* Let's reuse the mp for sending the ack */
28740 		arc = (arc_t *)mp->b_rptr;
28741 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28742 		arc->arc_cmd = AR_ARP_CLOSING;
28743 		qreply(q, mp);
28744 	} else {
28745 		mutex_exit(&ill->ill_lock);
28746 		freeb(mp);
28747 	}
28748 
28749 	ipsq = ill->ill_phyint->phyint_ipsq;
28750 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28751 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28752 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28753 	if (mp1 == NULL) {
28754 		/* bringup was aborted by the user */
28755 		freemsg(mp2);
28756 		return;
28757 	}
28758 
28759 	/*
28760 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28761 	 * must have an associated conn_t.  Otherwise, we're bringing this
28762 	 * interface back up as part of handling an asynchronous event (e.g.,
28763 	 * physical address change).
28764 	 */
28765 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28766 		ASSERT(connp != NULL);
28767 		q = CONNP_TO_WQ(connp);
28768 	} else {
28769 		ASSERT(connp == NULL);
28770 		q = ill->ill_rq;
28771 	}
28772 
28773 	/*
28774 	 * If the DL_BIND_REQ fails, it is noted
28775 	 * in arc_name_offset.
28776 	 */
28777 	err = *((int *)mp2->b_rptr);
28778 	if (err == 0) {
28779 		if (ipif->ipif_isv6) {
28780 			if ((err = ipif_up_done_v6(ipif)) != 0)
28781 				ip0dbg(("ip_arp_done: init failed\n"));
28782 		} else {
28783 			if ((err = ipif_up_done(ipif)) != 0)
28784 				ip0dbg(("ip_arp_done: init failed\n"));
28785 		}
28786 	} else {
28787 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28788 	}
28789 
28790 	freemsg(mp2);
28791 
28792 	if ((err == 0) && (ill->ill_up_ipifs)) {
28793 		err = ill_up_ipifs(ill, q, mp1);
28794 		if (err == EINPROGRESS)
28795 			return;
28796 	}
28797 
28798 	/*
28799 	 * If we have a moved ipif to bring up, and everything has succeeded
28800 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28801 	 * down -- the admin can try to bring it up by hand if need be.
28802 	 */
28803 	if (ill->ill_move_ipif != NULL) {
28804 		ipif = ill->ill_move_ipif;
28805 		ill->ill_move_ipif = NULL;
28806 		if (err == 0) {
28807 			err = ipif_up(ipif, q, mp1);
28808 			if (err == EINPROGRESS)
28809 				return;
28810 		}
28811 	}
28812 
28813 	/*
28814 	 * The operation must complete without EINPROGRESS since
28815 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28816 	 * operation will be stuck forever in the ipsq.
28817 	 */
28818 	ASSERT(err != EINPROGRESS);
28819 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28820 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28821 	else
28822 		ipsq_current_finish(ipsq);
28823 }
28824 
28825 /* Allocate the private structure */
28826 static int
28827 ip_priv_alloc(void **bufp)
28828 {
28829 	void	*buf;
28830 
28831 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28832 		return (ENOMEM);
28833 
28834 	*bufp = buf;
28835 	return (0);
28836 }
28837 
28838 /* Function to delete the private structure */
28839 void
28840 ip_priv_free(void *buf)
28841 {
28842 	ASSERT(buf != NULL);
28843 	kmem_free(buf, sizeof (ip_priv_t));
28844 }
28845 
28846 /*
28847  * The entry point for IPPF processing.
28848  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28849  * routine just returns.
28850  *
28851  * When called, ip_process generates an ipp_packet_t structure
28852  * which holds the state information for this packet and invokes the
28853  * the classifier (via ipp_packet_process). The classification, depending on
28854  * configured filters, results in a list of actions for this packet. Invoking
28855  * an action may cause the packet to be dropped, in which case the resulting
28856  * mblk (*mpp) is NULL. proc indicates the callout position for
28857  * this packet and ill_index is the interface this packet on or will leave
28858  * on (inbound and outbound resp.).
28859  */
28860 void
28861 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28862 {
28863 	mblk_t		*mp;
28864 	ip_priv_t	*priv;
28865 	ipp_action_id_t	aid;
28866 	int		rc = 0;
28867 	ipp_packet_t	*pp;
28868 #define	IP_CLASS	"ip"
28869 
28870 	/* If the classifier is not loaded, return  */
28871 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28872 		return;
28873 	}
28874 
28875 	mp = *mpp;
28876 	ASSERT(mp != NULL);
28877 
28878 	/* Allocate the packet structure */
28879 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28880 	if (rc != 0) {
28881 		*mpp = NULL;
28882 		freemsg(mp);
28883 		return;
28884 	}
28885 
28886 	/* Allocate the private structure */
28887 	rc = ip_priv_alloc((void **)&priv);
28888 	if (rc != 0) {
28889 		*mpp = NULL;
28890 		freemsg(mp);
28891 		ipp_packet_free(pp);
28892 		return;
28893 	}
28894 	priv->proc = proc;
28895 	priv->ill_index = ill_index;
28896 	ipp_packet_set_private(pp, priv, ip_priv_free);
28897 	ipp_packet_set_data(pp, mp);
28898 
28899 	/* Invoke the classifier */
28900 	rc = ipp_packet_process(&pp);
28901 	if (pp != NULL) {
28902 		mp = ipp_packet_get_data(pp);
28903 		ipp_packet_free(pp);
28904 		if (rc != 0) {
28905 			freemsg(mp);
28906 			*mpp = NULL;
28907 		}
28908 	} else {
28909 		*mpp = NULL;
28910 	}
28911 #undef	IP_CLASS
28912 }
28913 
28914 /*
28915  * Propagate a multicast group membership operation (add/drop) on
28916  * all the interfaces crossed by the related multirt routes.
28917  * The call is considered successful if the operation succeeds
28918  * on at least one interface.
28919  */
28920 static int
28921 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28922     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28923     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28924     mblk_t *first_mp)
28925 {
28926 	ire_t		*ire_gw;
28927 	irb_t		*irb;
28928 	int		error = 0;
28929 	opt_restart_t	*or;
28930 	ip_stack_t	*ipst = ire->ire_ipst;
28931 
28932 	irb = ire->ire_bucket;
28933 	ASSERT(irb != NULL);
28934 
28935 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28936 
28937 	or = (opt_restart_t *)first_mp->b_rptr;
28938 	IRB_REFHOLD(irb);
28939 	for (; ire != NULL; ire = ire->ire_next) {
28940 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28941 			continue;
28942 		if (ire->ire_addr != group)
28943 			continue;
28944 
28945 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28946 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28947 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28948 		/* No resolver exists for the gateway; skip this ire. */
28949 		if (ire_gw == NULL)
28950 			continue;
28951 
28952 		/*
28953 		 * This function can return EINPROGRESS. If so the operation
28954 		 * will be restarted from ip_restart_optmgmt which will
28955 		 * call ip_opt_set and option processing will restart for
28956 		 * this option. So we may end up calling 'fn' more than once.
28957 		 * This requires that 'fn' is idempotent except for the
28958 		 * return value. The operation is considered a success if
28959 		 * it succeeds at least once on any one interface.
28960 		 */
28961 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28962 		    NULL, fmode, src, first_mp);
28963 		if (error == 0)
28964 			or->or_private = CGTP_MCAST_SUCCESS;
28965 
28966 		if (ip_debug > 0) {
28967 			ulong_t	off;
28968 			char	*ksym;
28969 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28970 			ip2dbg(("ip_multirt_apply_membership: "
28971 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28972 			    "error %d [success %u]\n",
28973 			    ksym ? ksym : "?",
28974 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28975 			    error, or->or_private));
28976 		}
28977 
28978 		ire_refrele(ire_gw);
28979 		if (error == EINPROGRESS) {
28980 			IRB_REFRELE(irb);
28981 			return (error);
28982 		}
28983 	}
28984 	IRB_REFRELE(irb);
28985 	/*
28986 	 * Consider the call as successful if we succeeded on at least
28987 	 * one interface. Otherwise, return the last encountered error.
28988 	 */
28989 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28990 }
28991 
28992 /*
28993  * Issue a warning regarding a route crossing an interface with an
28994  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28995  * amount of time is logged.
28996  */
28997 static void
28998 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28999 {
29000 	hrtime_t	current = gethrtime();
29001 	char		buf[INET_ADDRSTRLEN];
29002 	ip_stack_t	*ipst = ire->ire_ipst;
29003 
29004 	/* Convert interval in ms to hrtime in ns */
29005 	if (ipst->ips_multirt_bad_mtu_last_time +
29006 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29007 	    current) {
29008 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29009 		    "to %s, incorrect MTU %u (expected %u)\n",
29010 		    ip_dot_addr(ire->ire_addr, buf),
29011 		    ire->ire_max_frag, max_frag);
29012 
29013 		ipst->ips_multirt_bad_mtu_last_time = current;
29014 	}
29015 }
29016 
29017 /*
29018  * Get the CGTP (multirouting) filtering status.
29019  * If 0, the CGTP hooks are transparent.
29020  */
29021 /* ARGSUSED */
29022 static int
29023 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29024 {
29025 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29026 
29027 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29028 	return (0);
29029 }
29030 
29031 /*
29032  * Set the CGTP (multirouting) filtering status.
29033  * If the status is changed from active to transparent
29034  * or from transparent to active, forward the new status
29035  * to the filtering module (if loaded).
29036  */
29037 /* ARGSUSED */
29038 static int
29039 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29040     cred_t *ioc_cr)
29041 {
29042 	long		new_value;
29043 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29044 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29045 
29046 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29047 		return (EPERM);
29048 
29049 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29050 	    new_value < 0 || new_value > 1) {
29051 		return (EINVAL);
29052 	}
29053 
29054 	if ((!*ip_cgtp_filter_value) && new_value) {
29055 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29056 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29057 		    " (module not loaded)" : "");
29058 	}
29059 	if (*ip_cgtp_filter_value && (!new_value)) {
29060 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29061 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29062 		    " (module not loaded)" : "");
29063 	}
29064 
29065 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29066 		int	res;
29067 		netstackid_t stackid;
29068 
29069 		stackid = ipst->ips_netstack->netstack_stackid;
29070 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29071 		    new_value);
29072 		if (res)
29073 			return (res);
29074 	}
29075 
29076 	*ip_cgtp_filter_value = (boolean_t)new_value;
29077 
29078 	return (0);
29079 }
29080 
29081 /*
29082  * Return the expected CGTP hooks version number.
29083  */
29084 int
29085 ip_cgtp_filter_supported(void)
29086 {
29087 	return (ip_cgtp_filter_rev);
29088 }
29089 
29090 /*
29091  * CGTP hooks can be registered by invoking this function.
29092  * Checks that the version number matches.
29093  */
29094 int
29095 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29096 {
29097 	netstack_t *ns;
29098 	ip_stack_t *ipst;
29099 
29100 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29101 		return (ENOTSUP);
29102 
29103 	ns = netstack_find_by_stackid(stackid);
29104 	if (ns == NULL)
29105 		return (EINVAL);
29106 	ipst = ns->netstack_ip;
29107 	ASSERT(ipst != NULL);
29108 
29109 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29110 		netstack_rele(ns);
29111 		return (EALREADY);
29112 	}
29113 
29114 	ipst->ips_ip_cgtp_filter_ops = ops;
29115 	netstack_rele(ns);
29116 	return (0);
29117 }
29118 
29119 /*
29120  * CGTP hooks can be unregistered by invoking this function.
29121  * Returns ENXIO if there was no registration.
29122  * Returns EBUSY if the ndd variable has not been turned off.
29123  */
29124 int
29125 ip_cgtp_filter_unregister(netstackid_t stackid)
29126 {
29127 	netstack_t *ns;
29128 	ip_stack_t *ipst;
29129 
29130 	ns = netstack_find_by_stackid(stackid);
29131 	if (ns == NULL)
29132 		return (EINVAL);
29133 	ipst = ns->netstack_ip;
29134 	ASSERT(ipst != NULL);
29135 
29136 	if (ipst->ips_ip_cgtp_filter) {
29137 		netstack_rele(ns);
29138 		return (EBUSY);
29139 	}
29140 
29141 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29142 		netstack_rele(ns);
29143 		return (ENXIO);
29144 	}
29145 	ipst->ips_ip_cgtp_filter_ops = NULL;
29146 	netstack_rele(ns);
29147 	return (0);
29148 }
29149 
29150 /*
29151  * Check whether there is a CGTP filter registration.
29152  * Returns non-zero if there is a registration, otherwise returns zero.
29153  * Note: returns zero if bad stackid.
29154  */
29155 int
29156 ip_cgtp_filter_is_registered(netstackid_t stackid)
29157 {
29158 	netstack_t *ns;
29159 	ip_stack_t *ipst;
29160 	int ret;
29161 
29162 	ns = netstack_find_by_stackid(stackid);
29163 	if (ns == NULL)
29164 		return (0);
29165 	ipst = ns->netstack_ip;
29166 	ASSERT(ipst != NULL);
29167 
29168 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29169 		ret = 1;
29170 	else
29171 		ret = 0;
29172 
29173 	netstack_rele(ns);
29174 	return (ret);
29175 }
29176 
29177 static int
29178 ip_squeue_switch(int val)
29179 {
29180 	int rval = SQ_FILL;
29181 
29182 	switch (val) {
29183 	case IP_SQUEUE_ENTER_NODRAIN:
29184 		rval = SQ_NODRAIN;
29185 		break;
29186 	case IP_SQUEUE_ENTER:
29187 		rval = SQ_PROCESS;
29188 		break;
29189 	default:
29190 		break;
29191 	}
29192 	return (rval);
29193 }
29194 
29195 /* ARGSUSED */
29196 static int
29197 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29198     caddr_t addr, cred_t *cr)
29199 {
29200 	int *v = (int *)addr;
29201 	long new_value;
29202 
29203 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29204 		return (EPERM);
29205 
29206 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29207 		return (EINVAL);
29208 
29209 	ip_squeue_flag = ip_squeue_switch(new_value);
29210 	*v = new_value;
29211 	return (0);
29212 }
29213 
29214 /*
29215  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29216  * ip_debug.
29217  */
29218 /* ARGSUSED */
29219 static int
29220 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29221     caddr_t addr, cred_t *cr)
29222 {
29223 	int *v = (int *)addr;
29224 	long new_value;
29225 
29226 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29227 		return (EPERM);
29228 
29229 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29230 		return (EINVAL);
29231 
29232 	*v = new_value;
29233 	return (0);
29234 }
29235 
29236 static void *
29237 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29238 {
29239 	kstat_t *ksp;
29240 
29241 	ip_stat_t template = {
29242 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29243 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29244 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29245 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29246 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29247 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29248 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29249 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29250 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29251 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29252 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29253 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29254 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29255 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29256 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29257 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29258 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29259 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29260 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29261 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29262 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29263 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29264 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29265 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29266 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29267 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29268 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29269 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29270 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29271 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29272 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29273 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29274 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29275 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29276 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29277 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29278 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29279 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29280 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29281 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29282 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29283 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29284 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29285 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29286 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29287 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29288 	};
29289 
29290 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29291 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29292 	    KSTAT_FLAG_VIRTUAL, stackid);
29293 
29294 	if (ksp == NULL)
29295 		return (NULL);
29296 
29297 	bcopy(&template, ip_statisticsp, sizeof (template));
29298 	ksp->ks_data = (void *)ip_statisticsp;
29299 	ksp->ks_private = (void *)(uintptr_t)stackid;
29300 
29301 	kstat_install(ksp);
29302 	return (ksp);
29303 }
29304 
29305 static void
29306 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29307 {
29308 	if (ksp != NULL) {
29309 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29310 		kstat_delete_netstack(ksp, stackid);
29311 	}
29312 }
29313 
29314 static void *
29315 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29316 {
29317 	kstat_t	*ksp;
29318 
29319 	ip_named_kstat_t template = {
29320 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29321 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29322 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29323 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29324 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29325 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29326 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29327 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29328 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29329 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29330 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29331 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29332 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29333 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29334 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29335 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29336 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29337 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29338 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29339 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29340 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29341 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29342 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29343 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29344 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29345 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29346 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29347 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29348 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29349 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29350 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29351 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29352 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29353 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29354 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29355 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29356 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29357 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29358 	};
29359 
29360 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29361 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29362 	if (ksp == NULL || ksp->ks_data == NULL)
29363 		return (NULL);
29364 
29365 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29366 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29367 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29368 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29369 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29370 
29371 	template.netToMediaEntrySize.value.i32 =
29372 	    sizeof (mib2_ipNetToMediaEntry_t);
29373 
29374 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29375 
29376 	bcopy(&template, ksp->ks_data, sizeof (template));
29377 	ksp->ks_update = ip_kstat_update;
29378 	ksp->ks_private = (void *)(uintptr_t)stackid;
29379 
29380 	kstat_install(ksp);
29381 	return (ksp);
29382 }
29383 
29384 static void
29385 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29386 {
29387 	if (ksp != NULL) {
29388 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29389 		kstat_delete_netstack(ksp, stackid);
29390 	}
29391 }
29392 
29393 static int
29394 ip_kstat_update(kstat_t *kp, int rw)
29395 {
29396 	ip_named_kstat_t *ipkp;
29397 	mib2_ipIfStatsEntry_t ipmib;
29398 	ill_walk_context_t ctx;
29399 	ill_t *ill;
29400 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29401 	netstack_t	*ns;
29402 	ip_stack_t	*ipst;
29403 
29404 	if (kp == NULL || kp->ks_data == NULL)
29405 		return (EIO);
29406 
29407 	if (rw == KSTAT_WRITE)
29408 		return (EACCES);
29409 
29410 	ns = netstack_find_by_stackid(stackid);
29411 	if (ns == NULL)
29412 		return (-1);
29413 	ipst = ns->netstack_ip;
29414 	if (ipst == NULL) {
29415 		netstack_rele(ns);
29416 		return (-1);
29417 	}
29418 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29419 
29420 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29421 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29422 	ill = ILL_START_WALK_V4(&ctx, ipst);
29423 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29424 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29425 	rw_exit(&ipst->ips_ill_g_lock);
29426 
29427 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29428 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29429 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29430 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29431 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29432 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29433 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29434 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29435 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29436 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29437 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29438 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29439 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29440 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29441 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29442 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29443 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29444 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29445 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29446 
29447 	ipkp->routingDiscards.value.ui32 =	0;
29448 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29449 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29450 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29451 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29452 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29453 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29454 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29455 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29456 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29457 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29458 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29459 
29460 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29461 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29462 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29463 
29464 	netstack_rele(ns);
29465 
29466 	return (0);
29467 }
29468 
29469 static void *
29470 icmp_kstat_init(netstackid_t stackid)
29471 {
29472 	kstat_t	*ksp;
29473 
29474 	icmp_named_kstat_t template = {
29475 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29476 		{ "inErrors",		KSTAT_DATA_UINT32 },
29477 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29478 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29479 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29480 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29481 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29482 		{ "inEchos",		KSTAT_DATA_UINT32 },
29483 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29484 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29485 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29486 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29487 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29488 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29489 		{ "outErrors",		KSTAT_DATA_UINT32 },
29490 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29491 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29492 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29493 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29494 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29495 		{ "outEchos",		KSTAT_DATA_UINT32 },
29496 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29497 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29498 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29499 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29500 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29501 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29502 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29503 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29504 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29505 		{ "outDrops",		KSTAT_DATA_UINT32 },
29506 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29507 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29508 	};
29509 
29510 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29511 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29512 	if (ksp == NULL || ksp->ks_data == NULL)
29513 		return (NULL);
29514 
29515 	bcopy(&template, ksp->ks_data, sizeof (template));
29516 
29517 	ksp->ks_update = icmp_kstat_update;
29518 	ksp->ks_private = (void *)(uintptr_t)stackid;
29519 
29520 	kstat_install(ksp);
29521 	return (ksp);
29522 }
29523 
29524 static void
29525 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29526 {
29527 	if (ksp != NULL) {
29528 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29529 		kstat_delete_netstack(ksp, stackid);
29530 	}
29531 }
29532 
29533 static int
29534 icmp_kstat_update(kstat_t *kp, int rw)
29535 {
29536 	icmp_named_kstat_t *icmpkp;
29537 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29538 	netstack_t	*ns;
29539 	ip_stack_t	*ipst;
29540 
29541 	if ((kp == NULL) || (kp->ks_data == NULL))
29542 		return (EIO);
29543 
29544 	if (rw == KSTAT_WRITE)
29545 		return (EACCES);
29546 
29547 	ns = netstack_find_by_stackid(stackid);
29548 	if (ns == NULL)
29549 		return (-1);
29550 	ipst = ns->netstack_ip;
29551 	if (ipst == NULL) {
29552 		netstack_rele(ns);
29553 		return (-1);
29554 	}
29555 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29556 
29557 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29558 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29559 	icmpkp->inDestUnreachs.value.ui32 =
29560 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29561 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29562 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29563 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29564 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29565 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29566 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29567 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29568 	icmpkp->inTimestampReps.value.ui32 =
29569 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29570 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29571 	icmpkp->inAddrMaskReps.value.ui32 =
29572 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29573 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29574 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29575 	icmpkp->outDestUnreachs.value.ui32 =
29576 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29577 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29578 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29579 	icmpkp->outSrcQuenchs.value.ui32 =
29580 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29581 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29582 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29583 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29584 	icmpkp->outTimestamps.value.ui32 =
29585 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29586 	icmpkp->outTimestampReps.value.ui32 =
29587 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29588 	icmpkp->outAddrMasks.value.ui32 =
29589 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29590 	icmpkp->outAddrMaskReps.value.ui32 =
29591 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29592 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29593 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29594 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29595 	icmpkp->outFragNeeded.value.ui32 =
29596 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29597 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29598 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29599 	icmpkp->inBadRedirects.value.ui32 =
29600 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29601 
29602 	netstack_rele(ns);
29603 	return (0);
29604 }
29605 
29606 /*
29607  * This is the fanout function for raw socket opened for SCTP.  Note
29608  * that it is called after SCTP checks that there is no socket which
29609  * wants a packet.  Then before SCTP handles this out of the blue packet,
29610  * this function is called to see if there is any raw socket for SCTP.
29611  * If there is and it is bound to the correct address, the packet will
29612  * be sent to that socket.  Note that only one raw socket can be bound to
29613  * a port.  This is assured in ipcl_sctp_hash_insert();
29614  */
29615 void
29616 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29617     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29618     zoneid_t zoneid)
29619 {
29620 	conn_t		*connp;
29621 	queue_t		*rq;
29622 	mblk_t		*first_mp;
29623 	boolean_t	secure;
29624 	ip6_t		*ip6h;
29625 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29626 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29627 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29628 	boolean_t	sctp_csum_err = B_FALSE;
29629 
29630 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29631 		sctp_csum_err = B_TRUE;
29632 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29633 	}
29634 
29635 	first_mp = mp;
29636 	if (mctl_present) {
29637 		mp = first_mp->b_cont;
29638 		secure = ipsec_in_is_secure(first_mp);
29639 		ASSERT(mp != NULL);
29640 	} else {
29641 		secure = B_FALSE;
29642 	}
29643 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29644 
29645 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29646 	if (connp == NULL) {
29647 		/*
29648 		 * Although raw sctp is not summed, OOB chunks must be.
29649 		 * Drop the packet here if the sctp checksum failed.
29650 		 */
29651 		if (sctp_csum_err) {
29652 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29653 			freemsg(first_mp);
29654 			return;
29655 		}
29656 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29657 		return;
29658 	}
29659 	rq = connp->conn_rq;
29660 	if (!canputnext(rq)) {
29661 		CONN_DEC_REF(connp);
29662 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29663 		freemsg(first_mp);
29664 		return;
29665 	}
29666 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29667 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29668 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29669 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29670 		if (first_mp == NULL) {
29671 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29672 			CONN_DEC_REF(connp);
29673 			return;
29674 		}
29675 	}
29676 	/*
29677 	 * We probably should not send M_CTL message up to
29678 	 * raw socket.
29679 	 */
29680 	if (mctl_present)
29681 		freeb(first_mp);
29682 
29683 	/* Initiate IPPF processing here if needed. */
29684 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29685 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29686 		ip_process(IPP_LOCAL_IN, &mp,
29687 		    recv_ill->ill_phyint->phyint_ifindex);
29688 		if (mp == NULL) {
29689 			CONN_DEC_REF(connp);
29690 			return;
29691 		}
29692 	}
29693 
29694 	if (connp->conn_recvif || connp->conn_recvslla ||
29695 	    ((connp->conn_ip_recvpktinfo ||
29696 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29697 	    (flags & IP_FF_IPINFO))) {
29698 		int in_flags = 0;
29699 
29700 		/*
29701 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29702 		 * IPF_RECVIF.
29703 		 */
29704 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29705 			in_flags = IPF_RECVIF;
29706 		}
29707 		if (connp->conn_recvslla) {
29708 			in_flags |= IPF_RECVSLLA;
29709 		}
29710 		if (isv4) {
29711 			mp = ip_add_info(mp, recv_ill, in_flags,
29712 			    IPCL_ZONEID(connp), ipst);
29713 		} else {
29714 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29715 			if (mp == NULL) {
29716 				BUMP_MIB(recv_ill->ill_ip_mib,
29717 				    ipIfStatsInDiscards);
29718 				CONN_DEC_REF(connp);
29719 				return;
29720 			}
29721 		}
29722 	}
29723 
29724 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29725 	/*
29726 	 * We are sending the IPSEC_IN message also up. Refer
29727 	 * to comments above this function.
29728 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29729 	 */
29730 	(connp->conn_recv)(connp, mp, NULL);
29731 	CONN_DEC_REF(connp);
29732 }
29733 
29734 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29735 {									\
29736 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29737 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29738 }
29739 /*
29740  * This function should be called only if all packet processing
29741  * including fragmentation is complete. Callers of this function
29742  * must set mp->b_prev to one of these values:
29743  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29744  * prior to handing over the mp as first argument to this function.
29745  *
29746  * If the ire passed by caller is incomplete, this function
29747  * queues the packet and if necessary, sends ARP request and bails.
29748  * If the ire passed is fully resolved, we simply prepend
29749  * the link-layer header to the packet, do ipsec hw acceleration
29750  * work if necessary, and send the packet out on the wire.
29751  *
29752  * NOTE: IPsec will only call this function with fully resolved
29753  * ires if hw acceleration is involved.
29754  * TODO list :
29755  * 	a Handle M_MULTIDATA so that
29756  *	  tcp_multisend->tcp_multisend_data can
29757  *	  call ip_xmit_v4 directly
29758  *	b Handle post-ARP work for fragments so that
29759  *	  ip_wput_frag can call this function.
29760  */
29761 ipxmit_state_t
29762 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29763     boolean_t flow_ctl_enabled, conn_t *connp)
29764 {
29765 	nce_t		*arpce;
29766 	ipha_t		*ipha;
29767 	queue_t		*q;
29768 	int		ill_index;
29769 	mblk_t		*nxt_mp, *first_mp;
29770 	boolean_t	xmit_drop = B_FALSE;
29771 	ip_proc_t	proc;
29772 	ill_t		*out_ill;
29773 	int		pkt_len;
29774 
29775 	arpce = ire->ire_nce;
29776 	ASSERT(arpce != NULL);
29777 
29778 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29779 
29780 	mutex_enter(&arpce->nce_lock);
29781 	switch (arpce->nce_state) {
29782 	case ND_REACHABLE:
29783 		/* If there are other queued packets, queue this packet */
29784 		if (arpce->nce_qd_mp != NULL) {
29785 			if (mp != NULL)
29786 				nce_queue_mp_common(arpce, mp, B_FALSE);
29787 			mp = arpce->nce_qd_mp;
29788 		}
29789 		arpce->nce_qd_mp = NULL;
29790 		mutex_exit(&arpce->nce_lock);
29791 
29792 		/*
29793 		 * Flush the queue.  In the common case, where the
29794 		 * ARP is already resolved,  it will go through the
29795 		 * while loop only once.
29796 		 */
29797 		while (mp != NULL) {
29798 
29799 			nxt_mp = mp->b_next;
29800 			mp->b_next = NULL;
29801 			ASSERT(mp->b_datap->db_type != M_CTL);
29802 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29803 			/*
29804 			 * This info is needed for IPQOS to do COS marking
29805 			 * in ip_wput_attach_llhdr->ip_process.
29806 			 */
29807 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29808 			mp->b_prev = NULL;
29809 
29810 			/* set up ill index for outbound qos processing */
29811 			out_ill = ire_to_ill(ire);
29812 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29813 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29814 			    ill_index, &ipha);
29815 			if (first_mp == NULL) {
29816 				xmit_drop = B_TRUE;
29817 				BUMP_MIB(out_ill->ill_ip_mib,
29818 				    ipIfStatsOutDiscards);
29819 				goto next_mp;
29820 			}
29821 
29822 			/* non-ipsec hw accel case */
29823 			if (io == NULL || !io->ipsec_out_accelerated) {
29824 				/* send it */
29825 				q = ire->ire_stq;
29826 				if (proc == IPP_FWD_OUT) {
29827 					UPDATE_IB_PKT_COUNT(ire);
29828 				} else {
29829 					UPDATE_OB_PKT_COUNT(ire);
29830 				}
29831 				ire->ire_last_used_time = lbolt;
29832 
29833 				if (flow_ctl_enabled || canputnext(q)) {
29834 					if (proc == IPP_FWD_OUT) {
29835 
29836 					BUMP_MIB(out_ill->ill_ip_mib,
29837 					    ipIfStatsHCOutForwDatagrams);
29838 
29839 					}
29840 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29841 					    pkt_len);
29842 
29843 					DTRACE_IP7(send, mblk_t *, first_mp,
29844 					    conn_t *, NULL, void_ip_t *, ipha,
29845 					    __dtrace_ipsr_ill_t *, out_ill,
29846 					    ipha_t *, ipha, ip6_t *, NULL, int,
29847 					    0);
29848 
29849 					ILL_SEND_TX(out_ill,
29850 					    ire, connp, first_mp, 0, connp);
29851 				} else {
29852 					BUMP_MIB(out_ill->ill_ip_mib,
29853 					    ipIfStatsOutDiscards);
29854 					xmit_drop = B_TRUE;
29855 					freemsg(first_mp);
29856 				}
29857 			} else {
29858 				/*
29859 				 * Safety Pup says: make sure this
29860 				 *  is going to the right interface!
29861 				 */
29862 				ill_t *ill1 =
29863 				    (ill_t *)ire->ire_stq->q_ptr;
29864 				int ifindex =
29865 				    ill1->ill_phyint->phyint_ifindex;
29866 				if (ifindex !=
29867 				    io->ipsec_out_capab_ill_index) {
29868 					xmit_drop = B_TRUE;
29869 					freemsg(mp);
29870 				} else {
29871 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29872 					    pkt_len);
29873 
29874 					DTRACE_IP7(send, mblk_t *, first_mp,
29875 					    conn_t *, NULL, void_ip_t *, ipha,
29876 					    __dtrace_ipsr_ill_t *, ill1,
29877 					    ipha_t *, ipha, ip6_t *, NULL,
29878 					    int, 0);
29879 
29880 					ipsec_hw_putnext(ire->ire_stq, mp);
29881 				}
29882 			}
29883 next_mp:
29884 			mp = nxt_mp;
29885 		} /* while (mp != NULL) */
29886 		if (xmit_drop)
29887 			return (SEND_FAILED);
29888 		else
29889 			return (SEND_PASSED);
29890 
29891 	case ND_INITIAL:
29892 	case ND_INCOMPLETE:
29893 
29894 		/*
29895 		 * While we do send off packets to dests that
29896 		 * use fully-resolved CGTP routes, we do not
29897 		 * handle unresolved CGTP routes.
29898 		 */
29899 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29900 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29901 
29902 		if (mp != NULL) {
29903 			/* queue the packet */
29904 			nce_queue_mp_common(arpce, mp, B_FALSE);
29905 		}
29906 
29907 		if (arpce->nce_state == ND_INCOMPLETE) {
29908 			mutex_exit(&arpce->nce_lock);
29909 			DTRACE_PROBE3(ip__xmit__incomplete,
29910 			    (ire_t *), ire, (mblk_t *), mp,
29911 			    (ipsec_out_t *), io);
29912 			return (LOOKUP_IN_PROGRESS);
29913 		}
29914 
29915 		arpce->nce_state = ND_INCOMPLETE;
29916 		mutex_exit(&arpce->nce_lock);
29917 
29918 		/*
29919 		 * Note that ire_add() (called from ire_forward())
29920 		 * holds a ref on the ire until ARP is completed.
29921 		 */
29922 		ire_arpresolve(ire);
29923 		return (LOOKUP_IN_PROGRESS);
29924 	default:
29925 		ASSERT(0);
29926 		mutex_exit(&arpce->nce_lock);
29927 		return (LLHDR_RESLV_FAILED);
29928 	}
29929 }
29930 
29931 #undef	UPDATE_IP_MIB_OB_COUNTERS
29932 
29933 /*
29934  * Return B_TRUE if the buffers differ in length or content.
29935  * This is used for comparing extension header buffers.
29936  * Note that an extension header would be declared different
29937  * even if all that changed was the next header value in that header i.e.
29938  * what really changed is the next extension header.
29939  */
29940 boolean_t
29941 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29942     uint_t blen)
29943 {
29944 	if (!b_valid)
29945 		blen = 0;
29946 
29947 	if (alen != blen)
29948 		return (B_TRUE);
29949 	if (alen == 0)
29950 		return (B_FALSE);	/* Both zero length */
29951 	return (bcmp(abuf, bbuf, alen));
29952 }
29953 
29954 /*
29955  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29956  * Return B_FALSE if memory allocation fails - don't change any state!
29957  */
29958 boolean_t
29959 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29960     const void *src, uint_t srclen)
29961 {
29962 	void *dst;
29963 
29964 	if (!src_valid)
29965 		srclen = 0;
29966 
29967 	ASSERT(*dstlenp == 0);
29968 	if (src != NULL && srclen != 0) {
29969 		dst = mi_alloc(srclen, BPRI_MED);
29970 		if (dst == NULL)
29971 			return (B_FALSE);
29972 	} else {
29973 		dst = NULL;
29974 	}
29975 	if (*dstp != NULL)
29976 		mi_free(*dstp);
29977 	*dstp = dst;
29978 	*dstlenp = dst == NULL ? 0 : srclen;
29979 	return (B_TRUE);
29980 }
29981 
29982 /*
29983  * Replace what is in *dst, *dstlen with the source.
29984  * Assumes ip_allocbuf has already been called.
29985  */
29986 void
29987 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29988     const void *src, uint_t srclen)
29989 {
29990 	if (!src_valid)
29991 		srclen = 0;
29992 
29993 	ASSERT(*dstlenp == srclen);
29994 	if (src != NULL && srclen != 0)
29995 		bcopy(src, *dstp, srclen);
29996 }
29997 
29998 /*
29999  * Free the storage pointed to by the members of an ip6_pkt_t.
30000  */
30001 void
30002 ip6_pkt_free(ip6_pkt_t *ipp)
30003 {
30004 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30005 
30006 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30007 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30008 		ipp->ipp_hopopts = NULL;
30009 		ipp->ipp_hopoptslen = 0;
30010 	}
30011 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30012 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30013 		ipp->ipp_rtdstopts = NULL;
30014 		ipp->ipp_rtdstoptslen = 0;
30015 	}
30016 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30017 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30018 		ipp->ipp_dstopts = NULL;
30019 		ipp->ipp_dstoptslen = 0;
30020 	}
30021 	if (ipp->ipp_fields & IPPF_RTHDR) {
30022 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30023 		ipp->ipp_rthdr = NULL;
30024 		ipp->ipp_rthdrlen = 0;
30025 	}
30026 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30027 	    IPPF_RTHDR);
30028 }
30029 
30030 zoneid_t
30031 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30032     zoneid_t lookup_zoneid)
30033 {
30034 	ire_t		*ire;
30035 	int		ire_flags = MATCH_IRE_TYPE;
30036 	zoneid_t	zoneid = ALL_ZONES;
30037 
30038 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30039 		return (ALL_ZONES);
30040 
30041 	if (lookup_zoneid != ALL_ZONES)
30042 		ire_flags |= MATCH_IRE_ZONEONLY;
30043 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30044 	    lookup_zoneid, NULL, ire_flags, ipst);
30045 	if (ire != NULL) {
30046 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30047 		ire_refrele(ire);
30048 	}
30049 	return (zoneid);
30050 }
30051 
30052 zoneid_t
30053 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30054     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30055 {
30056 	ire_t		*ire;
30057 	int		ire_flags = MATCH_IRE_TYPE;
30058 	zoneid_t	zoneid = ALL_ZONES;
30059 	ipif_t		*ipif_arg = NULL;
30060 
30061 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30062 		return (ALL_ZONES);
30063 
30064 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30065 		ire_flags |= MATCH_IRE_ILL;
30066 		ipif_arg = ill->ill_ipif;
30067 	}
30068 	if (lookup_zoneid != ALL_ZONES)
30069 		ire_flags |= MATCH_IRE_ZONEONLY;
30070 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30071 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30072 	if (ire != NULL) {
30073 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30074 		ire_refrele(ire);
30075 	}
30076 	return (zoneid);
30077 }
30078 
30079 /*
30080  * IP obserability hook support functions.
30081  */
30082 
30083 static void
30084 ipobs_init(ip_stack_t *ipst)
30085 {
30086 	ipst->ips_ipobs_enabled = B_FALSE;
30087 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30088 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30089 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30090 	ipst->ips_ipobs_cb_nwalkers = 0;
30091 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30092 }
30093 
30094 static void
30095 ipobs_fini(ip_stack_t *ipst)
30096 {
30097 	ipobs_cb_t *cb;
30098 
30099 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30100 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30101 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30102 
30103 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30104 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30105 		kmem_free(cb, sizeof (*cb));
30106 	}
30107 	list_destroy(&ipst->ips_ipobs_cb_list);
30108 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30109 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30110 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30111 }
30112 
30113 void
30114 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30115     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30116 {
30117 	mblk_t *mp2;
30118 	ipobs_cb_t *ipobs_cb;
30119 	ipobs_hook_data_t *ihd;
30120 	uint64_t grifindex = 0;
30121 
30122 	ASSERT(DB_TYPE(mp) == M_DATA);
30123 
30124 	if (IS_UNDER_IPMP(ill))
30125 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30126 
30127 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30128 	ipst->ips_ipobs_cb_nwalkers++;
30129 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30130 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30131 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30132 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30133 		if (mp2 != NULL) {
30134 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30135 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30136 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30137 				freemsg(mp2);
30138 				continue;
30139 			}
30140 			ihd->ihd_mp->b_rptr += hlen;
30141 			ihd->ihd_htype = htype;
30142 			ihd->ihd_ipver = ipver;
30143 			ihd->ihd_zsrc = zsrc;
30144 			ihd->ihd_zdst = zdst;
30145 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30146 			ihd->ihd_grifindex = grifindex;
30147 			ihd->ihd_stack = ipst->ips_netstack;
30148 			mp2->b_wptr += sizeof (*ihd);
30149 			ipobs_cb->ipobs_cbfunc(mp2);
30150 		}
30151 	}
30152 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30153 	ipst->ips_ipobs_cb_nwalkers--;
30154 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30155 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30156 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30157 }
30158 
30159 void
30160 ipobs_register_hook(netstack_t *ns, pfv_t func)
30161 {
30162 	ipobs_cb_t   *cb;
30163 	ip_stack_t *ipst = ns->netstack_ip;
30164 
30165 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30166 
30167 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30168 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30169 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30170 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30171 
30172 	cb->ipobs_cbfunc = func;
30173 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30174 	ipst->ips_ipobs_enabled = B_TRUE;
30175 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30176 }
30177 
30178 void
30179 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30180 {
30181 	ipobs_cb_t	*curcb;
30182 	ip_stack_t	*ipst = ns->netstack_ip;
30183 
30184 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30185 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30186 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30187 
30188 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30189 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30190 		if (func == curcb->ipobs_cbfunc) {
30191 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30192 			kmem_free(curcb, sizeof (*curcb));
30193 			break;
30194 		}
30195 	}
30196 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30197 		ipst->ips_ipobs_enabled = B_FALSE;
30198 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30199 }
30200