xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 19193bb6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
823     zoneid_t);
824 static void	conn_setqfull(conn_t *);
825 static void	conn_clrqfull(conn_t *);
826 
827 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
828 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
829 static void	ip_stack_fini(netstackid_t stackid, void *arg);
830 
831 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
832     zoneid_t);
833 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
834     void *dummy_arg);
835 
836 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
837 
838 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
839     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
840     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
841 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
842 
843 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
844 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
845     caddr_t, cred_t *);
846 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
847     cred_t *, boolean_t);
848 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
849     caddr_t cp, cred_t *cr);
850 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
851     cred_t *);
852 static int	ip_squeue_switch(int);
853 
854 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
855 static void	ip_kstat_fini(netstackid_t, kstat_t *);
856 static int	ip_kstat_update(kstat_t *kp, int rw);
857 static void	*icmp_kstat_init(netstackid_t);
858 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
859 static int	icmp_kstat_update(kstat_t *kp, int rw);
860 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
861 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
862 
863 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
864 
865 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
866     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
867 
868 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
869     ipha_t *, ill_t *, boolean_t, boolean_t);
870 
871 static void ipobs_init(ip_stack_t *);
872 static void ipobs_fini(ip_stack_t *);
873 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
874 
875 /* How long, in seconds, we allow frags to hang around. */
876 #define	IP_FRAG_TIMEOUT	15
877 
878 /*
879  * Threshold which determines whether MDT should be used when
880  * generating IP fragments; payload size must be greater than
881  * this threshold for MDT to take place.
882  */
883 #define	IP_WPUT_FRAG_MDT_MIN	32768
884 
885 /* Setable in /etc/system only */
886 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
887 
888 static long ip_rput_pullups;
889 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
890 
891 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
892 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
893 
894 int	ip_debug;
895 
896 #ifdef DEBUG
897 uint32_t ipsechw_debug = 0;
898 #endif
899 
900 /*
901  * Multirouting/CGTP stuff
902  */
903 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
904 
905 /*
906  * XXX following really should only be in a header. Would need more
907  * header and .c clean up first.
908  */
909 extern optdb_obj_t	ip_opt_obj;
910 
911 ulong_t ip_squeue_enter_unbound = 0;
912 
913 /*
914  * Named Dispatch Parameter Table.
915  * All of these are alterable, within the min/max values given, at run time.
916  */
917 static ipparam_t	lcl_param_arr[] = {
918 	/* min	max	value	name */
919 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
920 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
921 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
922 	{  0,	1,	0,	"ip_respond_to_timestamp"},
923 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
924 	{  0,	1,	1,	"ip_send_redirects"},
925 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
926 	{  0,	10,	0,	"ip_mrtdebug"},
927 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
928 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
929 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
930 	{  1,	255,	255,	"ip_def_ttl" },
931 	{  0,	1,	0,	"ip_forward_src_routed"},
932 	{  0,	256,	32,	"ip_wroff_extra" },
933 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
934 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
935 	{  0,	1,	1,	"ip_path_mtu_discovery" },
936 	{  0,	240,	30,	"ip_ignore_delete_time" },
937 	{  0,	1,	0,	"ip_ignore_redirect" },
938 	{  0,	1,	1,	"ip_output_queue" },
939 	{  1,	254,	1,	"ip_broadcast_ttl" },
940 	{  0,	99999,	100,	"ip_icmp_err_interval" },
941 	{  1,	99999,	10,	"ip_icmp_err_burst" },
942 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
943 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
944 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
945 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
946 	{  0,	1,	1,	"icmp_accept_clear_messages" },
947 	{  0,	1,	1,	"igmp_accept_clear_messages" },
948 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
949 				"ip_ndp_delay_first_probe_time"},
950 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
951 				"ip_ndp_max_unicast_solicit"},
952 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
953 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
954 	{  0,	1,	0,	"ip6_forward_src_routed"},
955 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
956 	{  0,	1,	1,	"ip6_send_redirects"},
957 	{  0,	1,	0,	"ip6_ignore_redirect" },
958 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
959 
960 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
961 
962 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
963 
964 	{  0,	1,	1,	"pim_accept_clear_messages" },
965 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
966 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
967 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
968 	{  0,	15,	0,	"ip_policy_mask" },
969 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
970 	{  0,	255,	1,	"ip_multirt_ttl" },
971 	{  0,	1,	1,	"ip_multidata_outbound" },
972 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
973 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
974 	{  0,	1000,	1,	"ip_max_temp_defend" },
975 	{  0,	1000,	3,	"ip_max_defend" },
976 	{  0,	999999,	30,	"ip_defend_interval" },
977 	{  0,	3600000, 300000, "ip_dup_recovery" },
978 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
979 	{  0,	1,	1,	"ip_lso_outbound" },
980 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
981 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
982 	{ 68,	65535,	576,	"ip_pmtu_min" },
983 #ifdef DEBUG
984 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
985 #else
986 	{  0,	0,	0,	"" },
987 #endif
988 };
989 
990 /*
991  * Extended NDP table
992  * The addresses for the first two are filled in to be ips_ip_g_forward
993  * and ips_ipv6_forward at init time.
994  */
995 static ipndp_t	lcl_ndp_arr[] = {
996 	/* getf			setf		data			name */
997 #define	IPNDP_IP_FORWARDING_OFFSET	0
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip_forwarding" },
1000 #define	IPNDP_IP6_FORWARDING_OFFSET	1
1001 	{  ip_param_generic_get,	ip_forward_set,	NULL,
1002 	    "ip6_forwarding" },
1003 	{  ip_ill_report,	NULL,		NULL,
1004 	    "ip_ill_status" },
1005 	{  ip_ipif_report,	NULL,		NULL,
1006 	    "ip_ipif_status" },
1007 	{  ip_conn_report,	NULL,		NULL,
1008 	    "ip_conn_status" },
1009 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1010 	    "ip_rput_pullups" },
1011 	{  ip_srcid_report,	NULL,		NULL,
1012 	    "ip_srcid_status" },
1013 	{ ip_param_generic_get, ip_input_proc_set,
1014 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1015 	{ ip_param_generic_get, ip_int_set,
1016 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1017 #define	IPNDP_CGTP_FILTER_OFFSET	9
1018 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1019 	    "ip_cgtp_filter" },
1020 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1021 	    "ip_debug" },
1022 };
1023 
1024 /*
1025  * Table of IP ioctls encoding the various properties of the ioctl and
1026  * indexed based on the last byte of the ioctl command. Occasionally there
1027  * is a clash, and there is more than 1 ioctl with the same last byte.
1028  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1029  * ioctls are encoded in the misc table. An entry in the ndx table is
1030  * retrieved by indexing on the last byte of the ioctl command and comparing
1031  * the ioctl command with the value in the ndx table. In the event of a
1032  * mismatch the misc table is then searched sequentially for the desired
1033  * ioctl command.
1034  *
1035  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1036  */
1037 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1038 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 
1049 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1050 			MISC_CMD, ip_siocaddrt, NULL },
1051 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1052 			MISC_CMD, ip_siocdelrt, NULL },
1053 
1054 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1055 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1056 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1057 			IF_CMD, ip_sioctl_get_addr, NULL },
1058 
1059 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1060 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1061 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1062 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1063 
1064 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1065 			IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1067 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1068 			IPI_MODOK | IPI_GET_CMD,
1069 			IF_CMD, ip_sioctl_get_flags, NULL },
1070 
1071 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 
1074 	/* copyin size cannot be coded for SIOCGIFCONF */
1075 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1076 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1077 
1078 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1079 			IF_CMD, ip_sioctl_mtu, NULL },
1080 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1081 			IF_CMD, ip_sioctl_get_mtu, NULL },
1082 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1083 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1084 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1085 			IF_CMD, ip_sioctl_brdaddr, NULL },
1086 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1087 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1088 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1089 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1090 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1091 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1092 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1093 			IF_CMD, ip_sioctl_metric, NULL },
1094 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 
1096 	/* See 166-168 below for extended SIOC*XARP ioctls */
1097 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1098 			ARP_CMD, ip_sioctl_arp, NULL },
1099 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1100 			ARP_CMD, ip_sioctl_arp, NULL },
1101 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1102 			ARP_CMD, ip_sioctl_arp, NULL },
1103 
1104 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 
1126 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1127 			MISC_CMD, if_unitsel, if_unitsel_restart },
1128 
1129 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 
1148 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1149 			IPI_PRIV | IPI_WR | IPI_MODOK,
1150 			IF_CMD, ip_sioctl_sifname, NULL },
1151 
1152 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 
1166 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1167 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1168 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1169 			IF_CMD, ip_sioctl_get_muxid, NULL },
1170 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1171 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1172 
1173 	/* Both if and lif variants share same func */
1174 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1175 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1176 	/* Both if and lif variants share same func */
1177 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1178 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1179 
1180 	/* copyin size cannot be coded for SIOCGIFCONF */
1181 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1182 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1183 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 
1201 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1202 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1203 			ip_sioctl_removeif_restart },
1204 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1205 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1206 			LIF_CMD, ip_sioctl_addif, NULL },
1207 #define	SIOCLIFADDR_NDX 112
1208 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1209 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1210 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1211 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1212 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1213 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1214 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1215 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1216 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1217 			IPI_PRIV | IPI_WR,
1218 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1219 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1220 			IPI_GET_CMD | IPI_MODOK,
1221 			LIF_CMD, ip_sioctl_get_flags, NULL },
1222 
1223 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 
1226 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1227 			ip_sioctl_get_lifconf, NULL },
1228 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_mtu, NULL },
1230 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1231 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1232 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1233 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1234 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1235 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1236 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1237 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1238 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1239 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1240 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1241 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1242 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 			LIF_CMD, ip_sioctl_metric, NULL },
1244 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR | IPI_MODOK,
1246 			LIF_CMD, ip_sioctl_slifname,
1247 			ip_sioctl_slifname_restart },
1248 
1249 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1250 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1251 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1252 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1253 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1255 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1256 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1257 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1258 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1259 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1260 			LIF_CMD, ip_sioctl_token, NULL },
1261 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1262 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1263 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1264 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1265 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1266 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1267 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1268 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1269 
1270 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1271 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1272 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1273 			LIF_CMD, ip_siocdelndp_v6, NULL },
1274 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1275 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1276 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1277 			LIF_CMD, ip_siocsetndp_v6, NULL },
1278 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1279 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1280 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1281 			MISC_CMD, ip_sioctl_tonlink, NULL },
1282 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1283 			MISC_CMD, ip_sioctl_tmysite, NULL },
1284 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1285 			TUN_CMD, ip_sioctl_tunparam, NULL },
1286 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1287 		    IPI_PRIV | IPI_WR,
1288 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1289 
1290 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1291 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1292 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1293 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1294 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1295 
1296 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 
1298 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1299 			LIF_CMD, ip_sioctl_get_binding, NULL },
1300 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR,
1302 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1303 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1304 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1305 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1306 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1307 
1308 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1309 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1310 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1311 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1312 
1313 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1314 
1315 	/* These are handled in ip_sioctl_copyin_setup itself */
1316 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1317 			MISC_CMD, NULL, NULL },
1318 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1319 			MISC_CMD, NULL, NULL },
1320 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1321 
1322 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1323 			ip_sioctl_get_lifconf, NULL },
1324 
1325 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1326 			XARP_CMD, ip_sioctl_arp, NULL },
1327 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1328 			XARP_CMD, ip_sioctl_arp, NULL },
1329 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1330 			XARP_CMD, ip_sioctl_arp, NULL },
1331 
1332 	/* SIOCPOPSOCKFS is not handled by IP */
1333 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1334 
1335 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1336 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1337 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1338 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1339 			ip_sioctl_slifzone_restart },
1340 	/* 172-174 are SCTP ioctls and not handled by IP */
1341 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1342 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1343 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1344 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1345 			IPI_GET_CMD, LIF_CMD,
1346 			ip_sioctl_get_lifusesrc, 0 },
1347 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1348 			IPI_PRIV | IPI_WR,
1349 			LIF_CMD, ip_sioctl_slifusesrc,
1350 			NULL },
1351 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1352 			ip_sioctl_get_lifsrcof, NULL },
1353 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1354 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1355 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1356 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1357 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1358 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1359 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1360 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1361 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* SIOCSENABLESDP is handled by SDP */
1363 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1364 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1365 };
1366 
1367 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1368 
1369 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1370 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1371 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1372 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1373 		TUN_CMD, ip_sioctl_tunparam, NULL },
1374 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1375 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1376 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1377 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1378 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1379 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1380 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1381 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1382 		MISC_CMD, mrt_ioctl},
1383 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1384 		MISC_CMD, mrt_ioctl},
1385 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1386 		MISC_CMD, mrt_ioctl}
1387 };
1388 
1389 int ip_misc_ioctl_count =
1390     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1391 
1392 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1393 					/* Settable in /etc/system */
1394 /* Defined in ip_ire.c */
1395 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1396 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1397 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1398 
1399 static nv_t	ire_nv_arr[] = {
1400 	{ IRE_BROADCAST, "BROADCAST" },
1401 	{ IRE_LOCAL, "LOCAL" },
1402 	{ IRE_LOOPBACK, "LOOPBACK" },
1403 	{ IRE_CACHE, "CACHE" },
1404 	{ IRE_DEFAULT, "DEFAULT" },
1405 	{ IRE_PREFIX, "PREFIX" },
1406 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1407 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1408 	{ IRE_HOST, "HOST" },
1409 	{ 0 }
1410 };
1411 
1412 nv_t	*ire_nv_tbl = ire_nv_arr;
1413 
1414 /* Simple ICMP IP Header Template */
1415 static ipha_t icmp_ipha = {
1416 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1417 };
1418 
1419 struct module_info ip_mod_info = {
1420 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1421 	IP_MOD_LOWAT
1422 };
1423 
1424 /*
1425  * Duplicate static symbols within a module confuses mdb; so we avoid the
1426  * problem by making the symbols here distinct from those in udp.c.
1427  */
1428 
1429 /*
1430  * Entry points for IP as a device and as a module.
1431  * FIXME: down the road we might want a separate module and driver qinit.
1432  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1433  */
1434 static struct qinit iprinitv4 = {
1435 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1436 	&ip_mod_info
1437 };
1438 
1439 struct qinit iprinitv6 = {
1440 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1441 	&ip_mod_info
1442 };
1443 
1444 static struct qinit ipwinitv4 = {
1445 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1446 	&ip_mod_info
1447 };
1448 
1449 struct qinit ipwinitv6 = {
1450 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1451 	&ip_mod_info
1452 };
1453 
1454 static struct qinit iplrinit = {
1455 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1456 	&ip_mod_info
1457 };
1458 
1459 static struct qinit iplwinit = {
1460 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1461 	&ip_mod_info
1462 };
1463 
1464 /* For AF_INET aka /dev/ip */
1465 struct streamtab ipinfov4 = {
1466 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1467 };
1468 
1469 /* For AF_INET6 aka /dev/ip6 */
1470 struct streamtab ipinfov6 = {
1471 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1472 };
1473 
1474 #ifdef	DEBUG
1475 static boolean_t skip_sctp_cksum = B_FALSE;
1476 #endif
1477 
1478 /*
1479  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1480  * ip_rput_v6(), ip_output(), etc.  If the message
1481  * block already has a M_CTL at the front of it, then simply set the zoneid
1482  * appropriately.
1483  */
1484 mblk_t *
1485 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1486 {
1487 	mblk_t		*first_mp;
1488 	ipsec_out_t	*io;
1489 
1490 	ASSERT(zoneid != ALL_ZONES);
1491 	if (mp->b_datap->db_type == M_CTL) {
1492 		io = (ipsec_out_t *)mp->b_rptr;
1493 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1494 		io->ipsec_out_zoneid = zoneid;
1495 		return (mp);
1496 	}
1497 
1498 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1499 	if (first_mp == NULL)
1500 		return (NULL);
1501 	io = (ipsec_out_t *)first_mp->b_rptr;
1502 	/* This is not a secure packet */
1503 	io->ipsec_out_secure = B_FALSE;
1504 	io->ipsec_out_zoneid = zoneid;
1505 	first_mp->b_cont = mp;
1506 	return (first_mp);
1507 }
1508 
1509 /*
1510  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1511  */
1512 mblk_t *
1513 ip_copymsg(mblk_t *mp)
1514 {
1515 	mblk_t *nmp;
1516 	ipsec_info_t *in;
1517 
1518 	if (mp->b_datap->db_type != M_CTL)
1519 		return (copymsg(mp));
1520 
1521 	in = (ipsec_info_t *)mp->b_rptr;
1522 
1523 	/*
1524 	 * Note that M_CTL is also used for delivering ICMP error messages
1525 	 * upstream to transport layers.
1526 	 */
1527 	if (in->ipsec_info_type != IPSEC_OUT &&
1528 	    in->ipsec_info_type != IPSEC_IN)
1529 		return (copymsg(mp));
1530 
1531 	nmp = copymsg(mp->b_cont);
1532 
1533 	if (in->ipsec_info_type == IPSEC_OUT) {
1534 		return (ipsec_out_tag(mp, nmp,
1535 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1536 	} else {
1537 		return (ipsec_in_tag(mp, nmp,
1538 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1539 	}
1540 }
1541 
1542 /* Generate an ICMP fragmentation needed message. */
1543 static void
1544 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1545     ip_stack_t *ipst)
1546 {
1547 	icmph_t	icmph;
1548 	mblk_t *first_mp;
1549 	boolean_t mctl_present;
1550 
1551 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1552 
1553 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1554 		if (mctl_present)
1555 			freeb(first_mp);
1556 		return;
1557 	}
1558 
1559 	bzero(&icmph, sizeof (icmph_t));
1560 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1561 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1562 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1563 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1564 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1565 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1566 	    ipst);
1567 }
1568 
1569 /*
1570  * icmp_inbound deals with ICMP messages in the following ways.
1571  *
1572  * 1) It needs to send a reply back and possibly delivering it
1573  *    to the "interested" upper clients.
1574  * 2) It needs to send it to the upper clients only.
1575  * 3) It needs to change some values in IP only.
1576  * 4) It needs to change some values in IP and upper layers e.g TCP.
1577  *
1578  * We need to accomodate icmp messages coming in clear until we get
1579  * everything secure from the wire. If icmp_accept_clear_messages
1580  * is zero we check with the global policy and act accordingly. If
1581  * it is non-zero, we accept the message without any checks. But
1582  * *this does not mean* that this will be delivered to the upper
1583  * clients. By accepting we might send replies back, change our MTU
1584  * value etc. but delivery to the ULP/clients depends on their policy
1585  * dispositions.
1586  *
1587  * We handle the above 4 cases in the context of IPsec in the
1588  * following way :
1589  *
1590  * 1) Send the reply back in the same way as the request came in.
1591  *    If it came in encrypted, it goes out encrypted. If it came in
1592  *    clear, it goes out in clear. Thus, this will prevent chosen
1593  *    plain text attack.
1594  * 2) The client may or may not expect things to come in secure.
1595  *    If it comes in secure, the policy constraints are checked
1596  *    before delivering it to the upper layers. If it comes in
1597  *    clear, ipsec_inbound_accept_clear will decide whether to
1598  *    accept this in clear or not. In both the cases, if the returned
1599  *    message (IP header + 8 bytes) that caused the icmp message has
1600  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1601  *    sending up. If there are only 8 bytes of returned message, then
1602  *    upper client will not be notified.
1603  * 3) Check with global policy to see whether it matches the constaints.
1604  *    But this will be done only if icmp_accept_messages_in_clear is
1605  *    zero.
1606  * 4) If we need to change both in IP and ULP, then the decision taken
1607  *    while affecting the values in IP and while delivering up to TCP
1608  *    should be the same.
1609  *
1610  * 	There are two cases.
1611  *
1612  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1613  *	   failed), we will not deliver it to the ULP, even though they
1614  *	   are *willing* to accept in *clear*. This is fine as our global
1615  *	   disposition to icmp messages asks us reject the datagram.
1616  *
1617  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1618  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1619  *	   to deliver it to ULP (policy failed), it can lead to
1620  *	   consistency problems. The cases known at this time are
1621  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1622  *	   values :
1623  *
1624  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1625  *	     and Upper layer rejects. Then the communication will
1626  *	     come to a stop. This is solved by making similar decisions
1627  *	     at both levels. Currently, when we are unable to deliver
1628  *	     to the Upper Layer (due to policy failures) while IP has
1629  *	     adjusted ire_max_frag, the next outbound datagram would
1630  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1631  *	     will be with the right level of protection. Thus the right
1632  *	     value will be communicated even if we are not able to
1633  *	     communicate when we get from the wire initially. But this
1634  *	     assumes there would be at least one outbound datagram after
1635  *	     IP has adjusted its ire_max_frag value. To make things
1636  *	     simpler, we accept in clear after the validation of
1637  *	     AH/ESP headers.
1638  *
1639  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1640  *	     upper layer depending on the level of protection the upper
1641  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1642  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1643  *	     should be accepted in clear when the Upper layer expects secure.
1644  *	     Thus the communication may get aborted by some bad ICMP
1645  *	     packets.
1646  *
1647  * IPQoS Notes:
1648  * The only instance when a packet is sent for processing is when there
1649  * isn't an ICMP client and if we are interested in it.
1650  * If there is a client, IPPF processing will take place in the
1651  * ip_fanout_proto routine.
1652  *
1653  * Zones notes:
1654  * The packet is only processed in the context of the specified zone: typically
1655  * only this zone will reply to an echo request, and only interested clients in
1656  * this zone will receive a copy of the packet. This means that the caller must
1657  * call icmp_inbound() for each relevant zone.
1658  */
1659 static void
1660 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1661     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1662     ill_t *recv_ill, zoneid_t zoneid)
1663 {
1664 	icmph_t	*icmph;
1665 	ipha_t	*ipha;
1666 	int	iph_hdr_length;
1667 	int	hdr_length;
1668 	boolean_t	interested;
1669 	uint32_t	ts;
1670 	uchar_t	*wptr;
1671 	ipif_t	*ipif;
1672 	mblk_t *first_mp;
1673 	ipsec_in_t *ii;
1674 	timestruc_t now;
1675 	uint32_t ill_index;
1676 	ip_stack_t *ipst;
1677 
1678 	ASSERT(ill != NULL);
1679 	ipst = ill->ill_ipst;
1680 
1681 	first_mp = mp;
1682 	if (mctl_present) {
1683 		mp = first_mp->b_cont;
1684 		ASSERT(mp != NULL);
1685 	}
1686 
1687 	ipha = (ipha_t *)mp->b_rptr;
1688 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1689 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1690 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1691 		if (first_mp == NULL)
1692 			return;
1693 	}
1694 
1695 	/*
1696 	 * On a labeled system, we have to check whether the zone itself is
1697 	 * permitted to receive raw traffic.
1698 	 */
1699 	if (is_system_labeled()) {
1700 		if (zoneid == ALL_ZONES)
1701 			zoneid = tsol_packet_to_zoneid(mp);
1702 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1703 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1704 			    zoneid));
1705 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1706 			freemsg(first_mp);
1707 			return;
1708 		}
1709 	}
1710 
1711 	/*
1712 	 * We have accepted the ICMP message. It means that we will
1713 	 * respond to the packet if needed. It may not be delivered
1714 	 * to the upper client depending on the policy constraints
1715 	 * and the disposition in ipsec_inbound_accept_clear.
1716 	 */
1717 
1718 	ASSERT(ill != NULL);
1719 
1720 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1721 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1722 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1723 		/* Last chance to get real. */
1724 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1725 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1726 			freemsg(first_mp);
1727 			return;
1728 		}
1729 		/* Refresh iph following the pullup. */
1730 		ipha = (ipha_t *)mp->b_rptr;
1731 	}
1732 	/* ICMP header checksum, including checksum field, should be zero. */
1733 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1734 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1736 		freemsg(first_mp);
1737 		return;
1738 	}
1739 	/* The IP header will always be a multiple of four bytes */
1740 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1741 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1742 	    icmph->icmph_code));
1743 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1744 	/* We will set "interested" to "true" if we want a copy */
1745 	interested = B_FALSE;
1746 	switch (icmph->icmph_type) {
1747 	case ICMP_ECHO_REPLY:
1748 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1749 		break;
1750 	case ICMP_DEST_UNREACHABLE:
1751 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1752 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1753 		interested = B_TRUE;	/* Pass up to transport */
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1755 		break;
1756 	case ICMP_SOURCE_QUENCH:
1757 		interested = B_TRUE;	/* Pass up to transport */
1758 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1759 		break;
1760 	case ICMP_REDIRECT:
1761 		if (!ipst->ips_ip_ignore_redirect)
1762 			interested = B_TRUE;
1763 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1764 		break;
1765 	case ICMP_ECHO_REQUEST:
1766 		/*
1767 		 * Whether to respond to echo requests that come in as IP
1768 		 * broadcasts or as IP multicast is subject to debate
1769 		 * (what isn't?).  We aim to please, you pick it.
1770 		 * Default is do it.
1771 		 */
1772 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1773 			/* unicast: always respond */
1774 			interested = B_TRUE;
1775 		} else if (CLASSD(ipha->ipha_dst)) {
1776 			/* multicast: respond based on tunable */
1777 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1778 		} else if (broadcast) {
1779 			/* broadcast: respond based on tunable */
1780 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1781 		}
1782 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1783 		break;
1784 	case ICMP_ROUTER_ADVERTISEMENT:
1785 	case ICMP_ROUTER_SOLICITATION:
1786 		break;
1787 	case ICMP_TIME_EXCEEDED:
1788 		interested = B_TRUE;	/* Pass up to transport */
1789 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1790 		break;
1791 	case ICMP_PARAM_PROBLEM:
1792 		interested = B_TRUE;	/* Pass up to transport */
1793 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1794 		break;
1795 	case ICMP_TIME_STAMP_REQUEST:
1796 		/* Response to Time Stamp Requests is local policy. */
1797 		if (ipst->ips_ip_g_resp_to_timestamp &&
1798 		    /* So is whether to respond if it was an IP broadcast. */
1799 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1800 			int tstamp_len = 3 * sizeof (uint32_t);
1801 
1802 			if (wptr +  tstamp_len > mp->b_wptr) {
1803 				if (!pullupmsg(mp, wptr + tstamp_len -
1804 				    mp->b_rptr)) {
1805 					BUMP_MIB(ill->ill_ip_mib,
1806 					    ipIfStatsInDiscards);
1807 					freemsg(first_mp);
1808 					return;
1809 				}
1810 				/* Refresh ipha following the pullup. */
1811 				ipha = (ipha_t *)mp->b_rptr;
1812 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1813 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1814 			}
1815 			interested = B_TRUE;
1816 		}
1817 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1818 		break;
1819 	case ICMP_TIME_STAMP_REPLY:
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1821 		break;
1822 	case ICMP_INFO_REQUEST:
1823 		/* Per RFC 1122 3.2.2.7, ignore this. */
1824 	case ICMP_INFO_REPLY:
1825 		break;
1826 	case ICMP_ADDRESS_MASK_REQUEST:
1827 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1828 		    !broadcast) &&
1829 		    /* TODO m_pullup of complete header? */
1830 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1831 			interested = B_TRUE;
1832 		}
1833 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1834 		break;
1835 	case ICMP_ADDRESS_MASK_REPLY:
1836 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1837 		break;
1838 	default:
1839 		interested = B_TRUE;	/* Pass up to transport */
1840 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1841 		break;
1842 	}
1843 	/* See if there is an ICMP client. */
1844 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1845 		/* If there is an ICMP client and we want one too, copy it. */
1846 		mblk_t *first_mp1;
1847 
1848 		if (!interested) {
1849 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1850 			    ip_policy, recv_ill, zoneid);
1851 			return;
1852 		}
1853 		first_mp1 = ip_copymsg(first_mp);
1854 		if (first_mp1 != NULL) {
1855 			ip_fanout_proto(q, first_mp1, ill, ipha,
1856 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1857 		}
1858 	} else if (!interested) {
1859 		freemsg(first_mp);
1860 		return;
1861 	} else {
1862 		/*
1863 		 * Initiate policy processing for this packet if ip_policy
1864 		 * is true.
1865 		 */
1866 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1867 			ill_index = ill->ill_phyint->phyint_ifindex;
1868 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1869 			if (mp == NULL) {
1870 				if (mctl_present) {
1871 					freeb(first_mp);
1872 				}
1873 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1874 				return;
1875 			}
1876 		}
1877 	}
1878 	/* We want to do something with it. */
1879 	/* Check db_ref to make sure we can modify the packet. */
1880 	if (mp->b_datap->db_ref > 1) {
1881 		mblk_t	*first_mp1;
1882 
1883 		first_mp1 = ip_copymsg(first_mp);
1884 		freemsg(first_mp);
1885 		if (!first_mp1) {
1886 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1887 			return;
1888 		}
1889 		first_mp = first_mp1;
1890 		if (mctl_present) {
1891 			mp = first_mp->b_cont;
1892 			ASSERT(mp != NULL);
1893 		} else {
1894 			mp = first_mp;
1895 		}
1896 		ipha = (ipha_t *)mp->b_rptr;
1897 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1898 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1899 	}
1900 	switch (icmph->icmph_type) {
1901 	case ICMP_ADDRESS_MASK_REQUEST:
1902 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1903 		if (ipif == NULL) {
1904 			freemsg(first_mp);
1905 			return;
1906 		}
1907 		/*
1908 		 * outging interface must be IPv4
1909 		 */
1910 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1911 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1912 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1913 		ipif_refrele(ipif);
1914 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1915 		break;
1916 	case ICMP_ECHO_REQUEST:
1917 		icmph->icmph_type = ICMP_ECHO_REPLY;
1918 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1919 		break;
1920 	case ICMP_TIME_STAMP_REQUEST: {
1921 		uint32_t *tsp;
1922 
1923 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1924 		tsp = (uint32_t *)wptr;
1925 		tsp++;		/* Skip past 'originate time' */
1926 		/* Compute # of milliseconds since midnight */
1927 		gethrestime(&now);
1928 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1929 		    now.tv_nsec / (NANOSEC / MILLISEC);
1930 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1931 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1932 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1933 		break;
1934 	}
1935 	default:
1936 		ipha = (ipha_t *)&icmph[1];
1937 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1938 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1939 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1940 				freemsg(first_mp);
1941 				return;
1942 			}
1943 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1944 			ipha = (ipha_t *)&icmph[1];
1945 		}
1946 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1947 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 			freemsg(first_mp);
1949 			return;
1950 		}
1951 		hdr_length = IPH_HDR_LENGTH(ipha);
1952 		if (hdr_length < sizeof (ipha_t)) {
1953 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1954 			freemsg(first_mp);
1955 			return;
1956 		}
1957 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1958 			if (!pullupmsg(mp,
1959 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1960 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1961 				freemsg(first_mp);
1962 				return;
1963 			}
1964 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1965 			ipha = (ipha_t *)&icmph[1];
1966 		}
1967 		switch (icmph->icmph_type) {
1968 		case ICMP_REDIRECT:
1969 			/*
1970 			 * As there is no upper client to deliver, we don't
1971 			 * need the first_mp any more.
1972 			 */
1973 			if (mctl_present) {
1974 				freeb(first_mp);
1975 			}
1976 			icmp_redirect(ill, mp);
1977 			return;
1978 		case ICMP_DEST_UNREACHABLE:
1979 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1980 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1981 				    zoneid, mp, iph_hdr_length, ipst)) {
1982 					freemsg(first_mp);
1983 					return;
1984 				}
1985 				/*
1986 				 * icmp_inbound_too_big() may alter mp.
1987 				 * Resynch ipha and icmph accordingly.
1988 				 */
1989 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1990 				ipha = (ipha_t *)&icmph[1];
1991 			}
1992 			/* FALLTHRU */
1993 		default :
1994 			/*
1995 			 * IPQoS notes: Since we have already done IPQoS
1996 			 * processing we don't want to do it again in
1997 			 * the fanout routines called by
1998 			 * icmp_inbound_error_fanout, hence the last
1999 			 * argument, ip_policy, is B_FALSE.
2000 			 */
2001 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2002 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2003 			    B_FALSE, recv_ill, zoneid);
2004 		}
2005 		return;
2006 	}
2007 	/* Send out an ICMP packet */
2008 	icmph->icmph_checksum = 0;
2009 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2010 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2011 		ipif_t	*ipif_chosen;
2012 		/*
2013 		 * Make it look like it was directed to us, so we don't look
2014 		 * like a fool with a broadcast or multicast source address.
2015 		 */
2016 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2017 		/*
2018 		 * Make sure that we haven't grabbed an interface that's DOWN.
2019 		 */
2020 		if (ipif != NULL) {
2021 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2022 			    ipha->ipha_src, zoneid);
2023 			if (ipif_chosen != NULL) {
2024 				ipif_refrele(ipif);
2025 				ipif = ipif_chosen;
2026 			}
2027 		}
2028 		if (ipif == NULL) {
2029 			ip0dbg(("icmp_inbound: "
2030 			    "No source for broadcast/multicast:\n"
2031 			    "\tsrc 0x%x dst 0x%x ill %p "
2032 			    "ipif_lcl_addr 0x%x\n",
2033 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2034 			    (void *)ill,
2035 			    ill->ill_ipif->ipif_lcl_addr));
2036 			freemsg(first_mp);
2037 			return;
2038 		}
2039 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2040 		ipha->ipha_dst = ipif->ipif_src_addr;
2041 		ipif_refrele(ipif);
2042 	}
2043 	/* Reset time to live. */
2044 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2045 	{
2046 		/* Swap source and destination addresses */
2047 		ipaddr_t tmp;
2048 
2049 		tmp = ipha->ipha_src;
2050 		ipha->ipha_src = ipha->ipha_dst;
2051 		ipha->ipha_dst = tmp;
2052 	}
2053 	ipha->ipha_ident = 0;
2054 	if (!IS_SIMPLE_IPH(ipha))
2055 		icmp_options_update(ipha);
2056 
2057 	if (!mctl_present) {
2058 		/*
2059 		 * This packet should go out the same way as it
2060 		 * came in i.e in clear. To make sure that global
2061 		 * policy will not be applied to this in ip_wput_ire,
2062 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2063 		 */
2064 		ASSERT(first_mp == mp);
2065 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2066 		if (first_mp == NULL) {
2067 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2068 			freemsg(mp);
2069 			return;
2070 		}
2071 		ii = (ipsec_in_t *)first_mp->b_rptr;
2072 
2073 		/* This is not a secure packet */
2074 		ii->ipsec_in_secure = B_FALSE;
2075 		first_mp->b_cont = mp;
2076 	} else {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2079 	}
2080 	ii->ipsec_in_zoneid = zoneid;
2081 	ASSERT(zoneid != ALL_ZONES);
2082 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2083 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2084 		return;
2085 	}
2086 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2087 	put(WR(q), first_mp);
2088 }
2089 
2090 static ipaddr_t
2091 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2092 {
2093 	conn_t *connp;
2094 	connf_t *connfp;
2095 	ipaddr_t nexthop_addr = INADDR_ANY;
2096 	int hdr_length = IPH_HDR_LENGTH(ipha);
2097 	uint16_t *up;
2098 	uint32_t ports;
2099 	ip_stack_t *ipst = ill->ill_ipst;
2100 
2101 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 	switch (ipha->ipha_protocol) {
2103 		case IPPROTO_TCP:
2104 		{
2105 			tcph_t *tcph;
2106 
2107 			/* do a reverse lookup */
2108 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2109 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2110 			    TCPS_LISTEN, ipst);
2111 			break;
2112 		}
2113 		case IPPROTO_UDP:
2114 		{
2115 			uint32_t dstport, srcport;
2116 
2117 			((uint16_t *)&ports)[0] = up[1];
2118 			((uint16_t *)&ports)[1] = up[0];
2119 
2120 			/* Extract ports in net byte order */
2121 			dstport = htons(ntohl(ports) & 0xFFFF);
2122 			srcport = htons(ntohl(ports) >> 16);
2123 
2124 			connfp = &ipst->ips_ipcl_udp_fanout[
2125 			    IPCL_UDP_HASH(dstport, ipst)];
2126 			mutex_enter(&connfp->connf_lock);
2127 			connp = connfp->connf_head;
2128 
2129 			/* do a reverse lookup */
2130 			while ((connp != NULL) &&
2131 			    (!IPCL_UDP_MATCH(connp, dstport,
2132 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2133 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2134 				connp = connp->conn_next;
2135 			}
2136 			if (connp != NULL)
2137 				CONN_INC_REF(connp);
2138 			mutex_exit(&connfp->connf_lock);
2139 			break;
2140 		}
2141 		case IPPROTO_SCTP:
2142 		{
2143 			in6_addr_t map_src, map_dst;
2144 
2145 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2146 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2147 			((uint16_t *)&ports)[0] = up[1];
2148 			((uint16_t *)&ports)[1] = up[0];
2149 
2150 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2151 			    zoneid, ipst->ips_netstack->netstack_sctp);
2152 			if (connp == NULL) {
2153 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2154 				    zoneid, ports, ipha, ipst);
2155 			} else {
2156 				CONN_INC_REF(connp);
2157 				SCTP_REFRELE(CONN2SCTP(connp));
2158 			}
2159 			break;
2160 		}
2161 		default:
2162 		{
2163 			ipha_t ripha;
2164 
2165 			ripha.ipha_src = ipha->ipha_dst;
2166 			ripha.ipha_dst = ipha->ipha_src;
2167 			ripha.ipha_protocol = ipha->ipha_protocol;
2168 
2169 			connfp = &ipst->ips_ipcl_proto_fanout[
2170 			    ipha->ipha_protocol];
2171 			mutex_enter(&connfp->connf_lock);
2172 			connp = connfp->connf_head;
2173 			for (connp = connfp->connf_head; connp != NULL;
2174 			    connp = connp->conn_next) {
2175 				if (IPCL_PROTO_MATCH(connp,
2176 				    ipha->ipha_protocol, &ripha, ill,
2177 				    0, zoneid)) {
2178 					CONN_INC_REF(connp);
2179 					break;
2180 				}
2181 			}
2182 			mutex_exit(&connfp->connf_lock);
2183 		}
2184 	}
2185 	if (connp != NULL) {
2186 		if (connp->conn_nexthop_set)
2187 			nexthop_addr = connp->conn_nexthop_v4;
2188 		CONN_DEC_REF(connp);
2189 	}
2190 	return (nexthop_addr);
2191 }
2192 
2193 /* Table from RFC 1191 */
2194 static int icmp_frag_size_table[] =
2195 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2196 
2197 /*
2198  * Process received ICMP Packet too big.
2199  * After updating any IRE it does the fanout to any matching transport streams.
2200  * Assumes the message has been pulled up till the IP header that caused
2201  * the error.
2202  *
2203  * Returns B_FALSE on failure and B_TRUE on success.
2204  */
2205 static boolean_t
2206 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2207     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2208     ip_stack_t *ipst)
2209 {
2210 	ire_t	*ire, *first_ire;
2211 	int	mtu, orig_mtu;
2212 	int	hdr_length;
2213 	ipaddr_t nexthop_addr;
2214 	boolean_t disable_pmtud;
2215 
2216 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2217 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2218 	ASSERT(ill != NULL);
2219 
2220 	hdr_length = IPH_HDR_LENGTH(ipha);
2221 
2222 	/* Drop if the original packet contained a source route */
2223 	if (ip_source_route_included(ipha)) {
2224 		return (B_FALSE);
2225 	}
2226 	/*
2227 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2228 	 * header.
2229 	 */
2230 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2231 	    mp->b_wptr) {
2232 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2233 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2234 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2235 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2236 			return (B_FALSE);
2237 		}
2238 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2239 		ipha = (ipha_t *)&icmph[1];
2240 	}
2241 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2242 	if (nexthop_addr != INADDR_ANY) {
2243 		/* nexthop set */
2244 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2245 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2246 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2247 	} else {
2248 		/* nexthop not set */
2249 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2250 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2251 	}
2252 
2253 	if (!first_ire) {
2254 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2255 		    ntohl(ipha->ipha_dst)));
2256 		return (B_FALSE);
2257 	}
2258 
2259 	/* Check for MTU discovery advice as described in RFC 1191 */
2260 	mtu = ntohs(icmph->icmph_du_mtu);
2261 	orig_mtu = mtu;
2262 	disable_pmtud = B_FALSE;
2263 
2264 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2265 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2266 	    ire = ire->ire_next) {
2267 		/*
2268 		 * Look for the connection to which this ICMP message is
2269 		 * directed. If it has the IP_NEXTHOP option set, then the
2270 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2271 		 * option. Else the search is limited to regular IREs.
2272 		 */
2273 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2274 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2275 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2276 		    (nexthop_addr != INADDR_ANY)))
2277 			continue;
2278 
2279 		mutex_enter(&ire->ire_lock);
2280 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2281 			uint32_t length;
2282 			int	i;
2283 
2284 			/*
2285 			 * Use the table from RFC 1191 to figure out
2286 			 * the next "plateau" based on the length in
2287 			 * the original IP packet.
2288 			 */
2289 			length = ntohs(ipha->ipha_length);
2290 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2291 			    uint32_t, length);
2292 			if (ire->ire_max_frag <= length &&
2293 			    ire->ire_max_frag >= length - hdr_length) {
2294 				/*
2295 				 * Handle broken BSD 4.2 systems that
2296 				 * return the wrong iph_length in ICMP
2297 				 * errors.
2298 				 */
2299 				length -= hdr_length;
2300 			}
2301 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2302 				if (length > icmp_frag_size_table[i])
2303 					break;
2304 			}
2305 			if (i == A_CNT(icmp_frag_size_table)) {
2306 				/* Smaller than 68! */
2307 				disable_pmtud = B_TRUE;
2308 				mtu = ipst->ips_ip_pmtu_min;
2309 			} else {
2310 				mtu = icmp_frag_size_table[i];
2311 				if (mtu < ipst->ips_ip_pmtu_min) {
2312 					mtu = ipst->ips_ip_pmtu_min;
2313 					disable_pmtud = B_TRUE;
2314 				}
2315 			}
2316 			/* Fool the ULP into believing our guessed PMTU. */
2317 			icmph->icmph_du_zero = 0;
2318 			icmph->icmph_du_mtu = htons(mtu);
2319 		}
2320 		if (disable_pmtud)
2321 			ire->ire_frag_flag = 0;
2322 		/* Reduce the IRE max frag value as advised. */
2323 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2324 		mutex_exit(&ire->ire_lock);
2325 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2326 		    ire, int, orig_mtu, int, mtu);
2327 	}
2328 	rw_exit(&first_ire->ire_bucket->irb_lock);
2329 	ire_refrele(first_ire);
2330 	return (B_TRUE);
2331 }
2332 
2333 /*
2334  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2335  * calls this function.
2336  */
2337 static mblk_t *
2338 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2339 {
2340 	ipha_t *ipha;
2341 	icmph_t *icmph;
2342 	ipha_t *in_ipha;
2343 	int length;
2344 
2345 	ASSERT(mp->b_datap->db_type == M_DATA);
2346 
2347 	/*
2348 	 * For Self-encapsulated packets, we added an extra IP header
2349 	 * without the options. Inner IP header is the one from which
2350 	 * the outer IP header was formed. Thus, we need to remove the
2351 	 * outer IP header. To do this, we pullup the whole message
2352 	 * and overlay whatever follows the outer IP header over the
2353 	 * outer IP header.
2354 	 */
2355 
2356 	if (!pullupmsg(mp, -1))
2357 		return (NULL);
2358 
2359 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2360 	ipha = (ipha_t *)&icmph[1];
2361 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2362 
2363 	/*
2364 	 * The length that we want to overlay is following the inner
2365 	 * IP header. Subtracting the IP header + icmp header + outer
2366 	 * IP header's length should give us the length that we want to
2367 	 * overlay.
2368 	 */
2369 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2370 	    hdr_length;
2371 	/*
2372 	 * Overlay whatever follows the inner header over the
2373 	 * outer header.
2374 	 */
2375 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2376 
2377 	/* Set the wptr to account for the outer header */
2378 	mp->b_wptr -= hdr_length;
2379 	return (mp);
2380 }
2381 
2382 /*
2383  * Try to pass the ICMP message upstream in case the ULP cares.
2384  *
2385  * If the packet that caused the ICMP error is secure, we send
2386  * it to AH/ESP to make sure that the attached packet has a
2387  * valid association. ipha in the code below points to the
2388  * IP header of the packet that caused the error.
2389  *
2390  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2391  * in the context of IPsec. Normally we tell the upper layer
2392  * whenever we send the ire (including ip_bind), the IPsec header
2393  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2394  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2395  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2396  * same thing. As TCP has the IPsec options size that needs to be
2397  * adjusted, we just pass the MTU unchanged.
2398  *
2399  * IFN could have been generated locally or by some router.
2400  *
2401  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2402  *	    This happens because IP adjusted its value of MTU on an
2403  *	    earlier IFN message and could not tell the upper layer,
2404  *	    the new adjusted value of MTU e.g. Packet was encrypted
2405  *	    or there was not enough information to fanout to upper
2406  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2407  *	    generates the IFN, where IPsec processing has *not* been
2408  *	    done.
2409  *
2410  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2411  *	    could have generated this. This happens because ire_max_frag
2412  *	    value in IP was set to a new value, while the IPsec processing
2413  *	    was being done and after we made the fragmentation check in
2414  *	    ip_wput_ire. Thus on return from IPsec processing,
2415  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2416  *	    and generates the IFN. As IPsec processing is over, we fanout
2417  *	    to AH/ESP to remove the header.
2418  *
2419  *	    In both these cases, ipsec_in_loopback will be set indicating
2420  *	    that IFN was generated locally.
2421  *
2422  * ROUTER : IFN could be secure or non-secure.
2423  *
2424  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2425  *	      packet in error has AH/ESP headers to validate the AH/ESP
2426  *	      headers. AH/ESP will verify whether there is a valid SA or
2427  *	      not and send it back. We will fanout again if we have more
2428  *	      data in the packet.
2429  *
2430  *	      If the packet in error does not have AH/ESP, we handle it
2431  *	      like any other case.
2432  *
2433  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2434  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2435  *	      for validation. AH/ESP will verify whether there is a
2436  *	      valid SA or not and send it back. We will fanout again if
2437  *	      we have more data in the packet.
2438  *
2439  *	      If the packet in error does not have AH/ESP, we handle it
2440  *	      like any other case.
2441  */
2442 static void
2443 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2444     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2445     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2446     zoneid_t zoneid)
2447 {
2448 	uint16_t *up;	/* Pointer to ports in ULP header */
2449 	uint32_t ports;	/* reversed ports for fanout */
2450 	ipha_t ripha;	/* With reversed addresses */
2451 	mblk_t *first_mp;
2452 	ipsec_in_t *ii;
2453 	tcph_t	*tcph;
2454 	conn_t	*connp;
2455 	ip_stack_t *ipst;
2456 
2457 	ASSERT(ill != NULL);
2458 
2459 	ASSERT(recv_ill != NULL);
2460 	ipst = recv_ill->ill_ipst;
2461 
2462 	first_mp = mp;
2463 	if (mctl_present) {
2464 		mp = first_mp->b_cont;
2465 		ASSERT(mp != NULL);
2466 
2467 		ii = (ipsec_in_t *)first_mp->b_rptr;
2468 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2469 	} else {
2470 		ii = NULL;
2471 	}
2472 
2473 	switch (ipha->ipha_protocol) {
2474 	case IPPROTO_UDP:
2475 		/*
2476 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2477 		 * transport header.
2478 		 */
2479 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2480 		    mp->b_wptr) {
2481 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2482 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2483 				goto discard_pkt;
2484 			}
2485 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2486 			ipha = (ipha_t *)&icmph[1];
2487 		}
2488 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2489 
2490 		/*
2491 		 * Attempt to find a client stream based on port.
2492 		 * Note that we do a reverse lookup since the header is
2493 		 * in the form we sent it out.
2494 		 * The ripha header is only used for the IP_UDP_MATCH and we
2495 		 * only set the src and dst addresses and protocol.
2496 		 */
2497 		ripha.ipha_src = ipha->ipha_dst;
2498 		ripha.ipha_dst = ipha->ipha_src;
2499 		ripha.ipha_protocol = ipha->ipha_protocol;
2500 		((uint16_t *)&ports)[0] = up[1];
2501 		((uint16_t *)&ports)[1] = up[0];
2502 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2503 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2504 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2505 		    icmph->icmph_type, icmph->icmph_code));
2506 
2507 		/* Have to change db_type after any pullupmsg */
2508 		DB_TYPE(mp) = M_CTL;
2509 
2510 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2511 		    mctl_present, ip_policy, recv_ill, zoneid);
2512 		return;
2513 
2514 	case IPPROTO_TCP:
2515 		/*
2516 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2517 		 * transport header.
2518 		 */
2519 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2520 		    mp->b_wptr) {
2521 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2522 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2523 				goto discard_pkt;
2524 			}
2525 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2526 			ipha = (ipha_t *)&icmph[1];
2527 		}
2528 		/*
2529 		 * Find a TCP client stream for this packet.
2530 		 * Note that we do a reverse lookup since the header is
2531 		 * in the form we sent it out.
2532 		 */
2533 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2534 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2535 		    ipst);
2536 		if (connp == NULL)
2537 			goto discard_pkt;
2538 
2539 		/* Have to change db_type after any pullupmsg */
2540 		DB_TYPE(mp) = M_CTL;
2541 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2542 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2543 		return;
2544 
2545 	case IPPROTO_SCTP:
2546 		/*
2547 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2548 		 * transport header.
2549 		 */
2550 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2551 		    mp->b_wptr) {
2552 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2553 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2554 				goto discard_pkt;
2555 			}
2556 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2557 			ipha = (ipha_t *)&icmph[1];
2558 		}
2559 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2560 		/*
2561 		 * Find a SCTP client stream for this packet.
2562 		 * Note that we do a reverse lookup since the header is
2563 		 * in the form we sent it out.
2564 		 * The ripha header is only used for the matching and we
2565 		 * only set the src and dst addresses, protocol, and version.
2566 		 */
2567 		ripha.ipha_src = ipha->ipha_dst;
2568 		ripha.ipha_dst = ipha->ipha_src;
2569 		ripha.ipha_protocol = ipha->ipha_protocol;
2570 		ripha.ipha_version_and_hdr_length =
2571 		    ipha->ipha_version_and_hdr_length;
2572 		((uint16_t *)&ports)[0] = up[1];
2573 		((uint16_t *)&ports)[1] = up[0];
2574 
2575 		/* Have to change db_type after any pullupmsg */
2576 		DB_TYPE(mp) = M_CTL;
2577 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2578 		    mctl_present, ip_policy, zoneid);
2579 		return;
2580 
2581 	case IPPROTO_ESP:
2582 	case IPPROTO_AH: {
2583 		int ipsec_rc;
2584 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2585 
2586 		/*
2587 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2588 		 * We will re-use the IPSEC_IN if it is already present as
2589 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2590 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2591 		 * one and attach it in the front.
2592 		 */
2593 		if (ii != NULL) {
2594 			/*
2595 			 * ip_fanout_proto_again converts the ICMP errors
2596 			 * that come back from AH/ESP to M_DATA so that
2597 			 * if it is non-AH/ESP and we do a pullupmsg in
2598 			 * this function, it would work. Convert it back
2599 			 * to M_CTL before we send up as this is a ICMP
2600 			 * error. This could have been generated locally or
2601 			 * by some router. Validate the inner IPsec
2602 			 * headers.
2603 			 *
2604 			 * NOTE : ill_index is used by ip_fanout_proto_again
2605 			 * to locate the ill.
2606 			 */
2607 			ASSERT(ill != NULL);
2608 			ii->ipsec_in_ill_index =
2609 			    ill->ill_phyint->phyint_ifindex;
2610 			ii->ipsec_in_rill_index =
2611 			    recv_ill->ill_phyint->phyint_ifindex;
2612 			DB_TYPE(first_mp->b_cont) = M_CTL;
2613 		} else {
2614 			/*
2615 			 * IPSEC_IN is not present. We attach a ipsec_in
2616 			 * message and send up to IPsec for validating
2617 			 * and removing the IPsec headers. Clear
2618 			 * ipsec_in_secure so that when we return
2619 			 * from IPsec, we don't mistakenly think that this
2620 			 * is a secure packet came from the network.
2621 			 *
2622 			 * NOTE : ill_index is used by ip_fanout_proto_again
2623 			 * to locate the ill.
2624 			 */
2625 			ASSERT(first_mp == mp);
2626 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2627 			if (first_mp == NULL) {
2628 				freemsg(mp);
2629 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2630 				return;
2631 			}
2632 			ii = (ipsec_in_t *)first_mp->b_rptr;
2633 
2634 			/* This is not a secure packet */
2635 			ii->ipsec_in_secure = B_FALSE;
2636 			first_mp->b_cont = mp;
2637 			DB_TYPE(mp) = M_CTL;
2638 			ASSERT(ill != NULL);
2639 			ii->ipsec_in_ill_index =
2640 			    ill->ill_phyint->phyint_ifindex;
2641 			ii->ipsec_in_rill_index =
2642 			    recv_ill->ill_phyint->phyint_ifindex;
2643 		}
2644 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2645 
2646 		if (!ipsec_loaded(ipss)) {
2647 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2648 			return;
2649 		}
2650 
2651 		if (ipha->ipha_protocol == IPPROTO_ESP)
2652 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2653 		else
2654 			ipsec_rc = ipsecah_icmp_error(first_mp);
2655 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2656 			return;
2657 
2658 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2659 		return;
2660 	}
2661 	default:
2662 		/*
2663 		 * The ripha header is only used for the lookup and we
2664 		 * only set the src and dst addresses and protocol.
2665 		 */
2666 		ripha.ipha_src = ipha->ipha_dst;
2667 		ripha.ipha_dst = ipha->ipha_src;
2668 		ripha.ipha_protocol = ipha->ipha_protocol;
2669 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2670 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2671 		    ntohl(ipha->ipha_dst),
2672 		    icmph->icmph_type, icmph->icmph_code));
2673 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2674 			ipha_t *in_ipha;
2675 
2676 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2677 			    mp->b_wptr) {
2678 				if (!pullupmsg(mp, (uchar_t *)ipha +
2679 				    hdr_length + sizeof (ipha_t) -
2680 				    mp->b_rptr)) {
2681 					goto discard_pkt;
2682 				}
2683 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2684 				ipha = (ipha_t *)&icmph[1];
2685 			}
2686 			/*
2687 			 * Caller has verified that length has to be
2688 			 * at least the size of IP header.
2689 			 */
2690 			ASSERT(hdr_length >= sizeof (ipha_t));
2691 			/*
2692 			 * Check the sanity of the inner IP header like
2693 			 * we did for the outer header.
2694 			 */
2695 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2696 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2697 				goto discard_pkt;
2698 			}
2699 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2700 				goto discard_pkt;
2701 			}
2702 			/* Check for Self-encapsulated tunnels */
2703 			if (in_ipha->ipha_src == ipha->ipha_src &&
2704 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2705 
2706 				mp = icmp_inbound_self_encap_error(mp,
2707 				    iph_hdr_length, hdr_length);
2708 				if (mp == NULL)
2709 					goto discard_pkt;
2710 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2711 				ipha = (ipha_t *)&icmph[1];
2712 				hdr_length = IPH_HDR_LENGTH(ipha);
2713 				/*
2714 				 * The packet in error is self-encapsualted.
2715 				 * And we are finding it further encapsulated
2716 				 * which we could not have possibly generated.
2717 				 */
2718 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2719 					goto discard_pkt;
2720 				}
2721 				icmp_inbound_error_fanout(q, ill, first_mp,
2722 				    icmph, ipha, iph_hdr_length, hdr_length,
2723 				    mctl_present, ip_policy, recv_ill, zoneid);
2724 				return;
2725 			}
2726 		}
2727 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2728 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2729 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2730 		    ii != NULL &&
2731 		    ii->ipsec_in_loopback &&
2732 		    ii->ipsec_in_secure) {
2733 			/*
2734 			 * For IP tunnels that get a looped-back
2735 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2736 			 * reported new MTU to take into account the IPsec
2737 			 * headers protecting this configured tunnel.
2738 			 *
2739 			 * This allows the tunnel module (tun.c) to blindly
2740 			 * accept the MTU reported in an ICMP "too big"
2741 			 * message.
2742 			 *
2743 			 * Non-looped back ICMP messages will just be
2744 			 * handled by the security protocols (if needed),
2745 			 * and the first subsequent packet will hit this
2746 			 * path.
2747 			 */
2748 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2749 			    ipsec_in_extra_length(first_mp));
2750 		}
2751 		/* Have to change db_type after any pullupmsg */
2752 		DB_TYPE(mp) = M_CTL;
2753 
2754 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2755 		    ip_policy, recv_ill, zoneid);
2756 		return;
2757 	}
2758 	/* NOTREACHED */
2759 discard_pkt:
2760 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2761 drop_pkt:;
2762 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2763 	freemsg(first_mp);
2764 }
2765 
2766 /*
2767  * Common IP options parser.
2768  *
2769  * Setup routine: fill in *optp with options-parsing state, then
2770  * tail-call ipoptp_next to return the first option.
2771  */
2772 uint8_t
2773 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2774 {
2775 	uint32_t totallen; /* total length of all options */
2776 
2777 	totallen = ipha->ipha_version_and_hdr_length -
2778 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2779 	totallen <<= 2;
2780 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2781 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2782 	optp->ipoptp_flags = 0;
2783 	return (ipoptp_next(optp));
2784 }
2785 
2786 /*
2787  * Common IP options parser: extract next option.
2788  */
2789 uint8_t
2790 ipoptp_next(ipoptp_t *optp)
2791 {
2792 	uint8_t *end = optp->ipoptp_end;
2793 	uint8_t *cur = optp->ipoptp_next;
2794 	uint8_t opt, len, pointer;
2795 
2796 	/*
2797 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2798 	 * has been corrupted.
2799 	 */
2800 	ASSERT(cur <= end);
2801 
2802 	if (cur == end)
2803 		return (IPOPT_EOL);
2804 
2805 	opt = cur[IPOPT_OPTVAL];
2806 
2807 	/*
2808 	 * Skip any NOP options.
2809 	 */
2810 	while (opt == IPOPT_NOP) {
2811 		cur++;
2812 		if (cur == end)
2813 			return (IPOPT_EOL);
2814 		opt = cur[IPOPT_OPTVAL];
2815 	}
2816 
2817 	if (opt == IPOPT_EOL)
2818 		return (IPOPT_EOL);
2819 
2820 	/*
2821 	 * Option requiring a length.
2822 	 */
2823 	if ((cur + 1) >= end) {
2824 		optp->ipoptp_flags |= IPOPTP_ERROR;
2825 		return (IPOPT_EOL);
2826 	}
2827 	len = cur[IPOPT_OLEN];
2828 	if (len < 2) {
2829 		optp->ipoptp_flags |= IPOPTP_ERROR;
2830 		return (IPOPT_EOL);
2831 	}
2832 	optp->ipoptp_cur = cur;
2833 	optp->ipoptp_len = len;
2834 	optp->ipoptp_next = cur + len;
2835 	if (cur + len > end) {
2836 		optp->ipoptp_flags |= IPOPTP_ERROR;
2837 		return (IPOPT_EOL);
2838 	}
2839 
2840 	/*
2841 	 * For the options which require a pointer field, make sure
2842 	 * its there, and make sure it points to either something
2843 	 * inside this option, or the end of the option.
2844 	 */
2845 	switch (opt) {
2846 	case IPOPT_RR:
2847 	case IPOPT_TS:
2848 	case IPOPT_LSRR:
2849 	case IPOPT_SSRR:
2850 		if (len <= IPOPT_OFFSET) {
2851 			optp->ipoptp_flags |= IPOPTP_ERROR;
2852 			return (opt);
2853 		}
2854 		pointer = cur[IPOPT_OFFSET];
2855 		if (pointer - 1 > len) {
2856 			optp->ipoptp_flags |= IPOPTP_ERROR;
2857 			return (opt);
2858 		}
2859 		break;
2860 	}
2861 
2862 	/*
2863 	 * Sanity check the pointer field based on the type of the
2864 	 * option.
2865 	 */
2866 	switch (opt) {
2867 	case IPOPT_RR:
2868 	case IPOPT_SSRR:
2869 	case IPOPT_LSRR:
2870 		if (pointer < IPOPT_MINOFF_SR)
2871 			optp->ipoptp_flags |= IPOPTP_ERROR;
2872 		break;
2873 	case IPOPT_TS:
2874 		if (pointer < IPOPT_MINOFF_IT)
2875 			optp->ipoptp_flags |= IPOPTP_ERROR;
2876 		/*
2877 		 * Note that the Internet Timestamp option also
2878 		 * contains two four bit fields (the Overflow field,
2879 		 * and the Flag field), which follow the pointer
2880 		 * field.  We don't need to check that these fields
2881 		 * fall within the length of the option because this
2882 		 * was implicitely done above.  We've checked that the
2883 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2884 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2885 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2886 		 */
2887 		ASSERT(len > IPOPT_POS_OV_FLG);
2888 		break;
2889 	}
2890 
2891 	return (opt);
2892 }
2893 
2894 /*
2895  * Use the outgoing IP header to create an IP_OPTIONS option the way
2896  * it was passed down from the application.
2897  */
2898 int
2899 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2900 {
2901 	ipoptp_t	opts;
2902 	const uchar_t	*opt;
2903 	uint8_t		optval;
2904 	uint8_t		optlen;
2905 	uint32_t	len = 0;
2906 	uchar_t	*buf1 = buf;
2907 
2908 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2909 	len += IP_ADDR_LEN;
2910 	bzero(buf1, IP_ADDR_LEN);
2911 
2912 	/*
2913 	 * OK to cast away const here, as we don't store through the returned
2914 	 * opts.ipoptp_cur pointer.
2915 	 */
2916 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2917 	    optval != IPOPT_EOL;
2918 	    optval = ipoptp_next(&opts)) {
2919 		int	off;
2920 
2921 		opt = opts.ipoptp_cur;
2922 		optlen = opts.ipoptp_len;
2923 		switch (optval) {
2924 		case IPOPT_SSRR:
2925 		case IPOPT_LSRR:
2926 
2927 			/*
2928 			 * Insert ipha_dst as the first entry in the source
2929 			 * route and move down the entries on step.
2930 			 * The last entry gets placed at buf1.
2931 			 */
2932 			buf[IPOPT_OPTVAL] = optval;
2933 			buf[IPOPT_OLEN] = optlen;
2934 			buf[IPOPT_OFFSET] = optlen;
2935 
2936 			off = optlen - IP_ADDR_LEN;
2937 			if (off < 0) {
2938 				/* No entries in source route */
2939 				break;
2940 			}
2941 			/* Last entry in source route */
2942 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2943 			off -= IP_ADDR_LEN;
2944 
2945 			while (off > 0) {
2946 				bcopy(opt + off,
2947 				    buf + off + IP_ADDR_LEN,
2948 				    IP_ADDR_LEN);
2949 				off -= IP_ADDR_LEN;
2950 			}
2951 			/* ipha_dst into first slot */
2952 			bcopy(&ipha->ipha_dst,
2953 			    buf + off + IP_ADDR_LEN,
2954 			    IP_ADDR_LEN);
2955 			buf += optlen;
2956 			len += optlen;
2957 			break;
2958 
2959 		case IPOPT_COMSEC:
2960 		case IPOPT_SECURITY:
2961 			/* if passing up a label is not ok, then remove */
2962 			if (is_system_labeled())
2963 				break;
2964 			/* FALLTHROUGH */
2965 		default:
2966 			bcopy(opt, buf, optlen);
2967 			buf += optlen;
2968 			len += optlen;
2969 			break;
2970 		}
2971 	}
2972 done:
2973 	/* Pad the resulting options */
2974 	while (len & 0x3) {
2975 		*buf++ = IPOPT_EOL;
2976 		len++;
2977 	}
2978 	return (len);
2979 }
2980 
2981 /*
2982  * Update any record route or timestamp options to include this host.
2983  * Reverse any source route option.
2984  * This routine assumes that the options are well formed i.e. that they
2985  * have already been checked.
2986  */
2987 static void
2988 icmp_options_update(ipha_t *ipha)
2989 {
2990 	ipoptp_t	opts;
2991 	uchar_t		*opt;
2992 	uint8_t		optval;
2993 	ipaddr_t	src;		/* Our local address */
2994 	ipaddr_t	dst;
2995 
2996 	ip2dbg(("icmp_options_update\n"));
2997 	src = ipha->ipha_src;
2998 	dst = ipha->ipha_dst;
2999 
3000 	for (optval = ipoptp_first(&opts, ipha);
3001 	    optval != IPOPT_EOL;
3002 	    optval = ipoptp_next(&opts)) {
3003 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3004 		opt = opts.ipoptp_cur;
3005 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3006 		    optval, opts.ipoptp_len));
3007 		switch (optval) {
3008 			int off1, off2;
3009 		case IPOPT_SSRR:
3010 		case IPOPT_LSRR:
3011 			/*
3012 			 * Reverse the source route.  The first entry
3013 			 * should be the next to last one in the current
3014 			 * source route (the last entry is our address).
3015 			 * The last entry should be the final destination.
3016 			 */
3017 			off1 = IPOPT_MINOFF_SR - 1;
3018 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3019 			if (off2 < 0) {
3020 				/* No entries in source route */
3021 				ip1dbg((
3022 				    "icmp_options_update: bad src route\n"));
3023 				break;
3024 			}
3025 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3026 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3027 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3028 			off2 -= IP_ADDR_LEN;
3029 
3030 			while (off1 < off2) {
3031 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3032 				bcopy((char *)opt + off2, (char *)opt + off1,
3033 				    IP_ADDR_LEN);
3034 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3035 				off1 += IP_ADDR_LEN;
3036 				off2 -= IP_ADDR_LEN;
3037 			}
3038 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3039 			break;
3040 		}
3041 	}
3042 }
3043 
3044 /*
3045  * Process received ICMP Redirect messages.
3046  */
3047 static void
3048 icmp_redirect(ill_t *ill, mblk_t *mp)
3049 {
3050 	ipha_t	*ipha;
3051 	int	iph_hdr_length;
3052 	icmph_t	*icmph;
3053 	ipha_t	*ipha_err;
3054 	ire_t	*ire;
3055 	ire_t	*prev_ire;
3056 	ire_t	*save_ire;
3057 	ipaddr_t  src, dst, gateway;
3058 	iulp_t	ulp_info = { 0 };
3059 	int	error;
3060 	ip_stack_t *ipst;
3061 
3062 	ASSERT(ill != NULL);
3063 	ipst = ill->ill_ipst;
3064 
3065 	ipha = (ipha_t *)mp->b_rptr;
3066 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3067 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3068 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3069 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3070 		freemsg(mp);
3071 		return;
3072 	}
3073 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3074 	ipha_err = (ipha_t *)&icmph[1];
3075 	src = ipha->ipha_src;
3076 	dst = ipha_err->ipha_dst;
3077 	gateway = icmph->icmph_rd_gateway;
3078 	/* Make sure the new gateway is reachable somehow. */
3079 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3080 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3081 	/*
3082 	 * Make sure we had a route for the dest in question and that
3083 	 * that route was pointing to the old gateway (the source of the
3084 	 * redirect packet.)
3085 	 */
3086 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3087 	    NULL, MATCH_IRE_GW, ipst);
3088 	/*
3089 	 * Check that
3090 	 *	the redirect was not from ourselves
3091 	 *	the new gateway and the old gateway are directly reachable
3092 	 */
3093 	if (!prev_ire ||
3094 	    !ire ||
3095 	    ire->ire_type == IRE_LOCAL) {
3096 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3097 		freemsg(mp);
3098 		if (ire != NULL)
3099 			ire_refrele(ire);
3100 		if (prev_ire != NULL)
3101 			ire_refrele(prev_ire);
3102 		return;
3103 	}
3104 
3105 	/*
3106 	 * Should we use the old ULP info to create the new gateway?  From
3107 	 * a user's perspective, we should inherit the info so that it
3108 	 * is a "smooth" transition.  If we do not do that, then new
3109 	 * connections going thru the new gateway will have no route metrics,
3110 	 * which is counter-intuitive to user.  From a network point of
3111 	 * view, this may or may not make sense even though the new gateway
3112 	 * is still directly connected to us so the route metrics should not
3113 	 * change much.
3114 	 *
3115 	 * But if the old ire_uinfo is not initialized, we do another
3116 	 * recursive lookup on the dest using the new gateway.  There may
3117 	 * be a route to that.  If so, use it to initialize the redirect
3118 	 * route.
3119 	 */
3120 	if (prev_ire->ire_uinfo.iulp_set) {
3121 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3122 	} else {
3123 		ire_t *tmp_ire;
3124 		ire_t *sire;
3125 
3126 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3127 		    ALL_ZONES, 0, NULL,
3128 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3129 		    ipst);
3130 		if (sire != NULL) {
3131 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3132 			/*
3133 			 * If sire != NULL, ire_ftable_lookup() should not
3134 			 * return a NULL value.
3135 			 */
3136 			ASSERT(tmp_ire != NULL);
3137 			ire_refrele(tmp_ire);
3138 			ire_refrele(sire);
3139 		} else if (tmp_ire != NULL) {
3140 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3141 			    sizeof (iulp_t));
3142 			ire_refrele(tmp_ire);
3143 		}
3144 	}
3145 	if (prev_ire->ire_type == IRE_CACHE)
3146 		ire_delete(prev_ire);
3147 	ire_refrele(prev_ire);
3148 	/*
3149 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3150 	 * require TOS routing
3151 	 */
3152 	switch (icmph->icmph_code) {
3153 	case 0:
3154 	case 1:
3155 		/* TODO: TOS specificity for cases 2 and 3 */
3156 	case 2:
3157 	case 3:
3158 		break;
3159 	default:
3160 		freemsg(mp);
3161 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3162 		ire_refrele(ire);
3163 		return;
3164 	}
3165 	/*
3166 	 * Create a Route Association.  This will allow us to remember that
3167 	 * someone we believe told us to use the particular gateway.
3168 	 */
3169 	save_ire = ire;
3170 	ire = ire_create(
3171 	    (uchar_t *)&dst,			/* dest addr */
3172 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3173 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3174 	    (uchar_t *)&gateway,		/* gateway addr */
3175 	    &save_ire->ire_max_frag,		/* max frag */
3176 	    NULL,				/* no src nce */
3177 	    NULL,				/* no rfq */
3178 	    NULL,				/* no stq */
3179 	    IRE_HOST,
3180 	    NULL,				/* ipif */
3181 	    0,					/* cmask */
3182 	    0,					/* phandle */
3183 	    0,					/* ihandle */
3184 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3185 	    &ulp_info,
3186 	    NULL,				/* tsol_gc_t */
3187 	    NULL,				/* gcgrp */
3188 	    ipst);
3189 
3190 	if (ire == NULL) {
3191 		freemsg(mp);
3192 		ire_refrele(save_ire);
3193 		return;
3194 	}
3195 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3196 	ire_refrele(save_ire);
3197 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3198 
3199 	if (error == 0) {
3200 		ire_refrele(ire);		/* Held in ire_add_v4 */
3201 		/* tell routing sockets that we received a redirect */
3202 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3203 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3204 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3205 	}
3206 
3207 	/*
3208 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3209 	 * This together with the added IRE has the effect of
3210 	 * modifying an existing redirect.
3211 	 */
3212 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3213 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3214 	if (prev_ire != NULL) {
3215 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3216 			ire_delete(prev_ire);
3217 		ire_refrele(prev_ire);
3218 	}
3219 
3220 	freemsg(mp);
3221 }
3222 
3223 /*
3224  * Generate an ICMP parameter problem message.
3225  */
3226 static void
3227 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3228 	ip_stack_t *ipst)
3229 {
3230 	icmph_t	icmph;
3231 	boolean_t mctl_present;
3232 	mblk_t *first_mp;
3233 
3234 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3235 
3236 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3237 		if (mctl_present)
3238 			freeb(first_mp);
3239 		return;
3240 	}
3241 
3242 	bzero(&icmph, sizeof (icmph_t));
3243 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3244 	icmph.icmph_pp_ptr = ptr;
3245 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3246 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3247 	    ipst);
3248 }
3249 
3250 /*
3251  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3252  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3253  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3254  * an icmp error packet can be sent.
3255  * Assigns an appropriate source address to the packet. If ipha_dst is
3256  * one of our addresses use it for source. Otherwise pick a source based
3257  * on a route lookup back to ipha_src.
3258  * Note that ipha_src must be set here since the
3259  * packet is likely to arrive on an ill queue in ip_wput() which will
3260  * not set a source address.
3261  */
3262 static void
3263 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3264     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3265 {
3266 	ipaddr_t dst;
3267 	icmph_t	*icmph;
3268 	ipha_t	*ipha;
3269 	uint_t	len_needed;
3270 	size_t	msg_len;
3271 	mblk_t	*mp1;
3272 	ipaddr_t src;
3273 	ire_t	*ire;
3274 	mblk_t *ipsec_mp;
3275 	ipsec_out_t	*io = NULL;
3276 
3277 	if (mctl_present) {
3278 		/*
3279 		 * If it is :
3280 		 *
3281 		 * 1) a IPSEC_OUT, then this is caused by outbound
3282 		 *    datagram originating on this host. IPsec processing
3283 		 *    may or may not have been done. Refer to comments above
3284 		 *    icmp_inbound_error_fanout for details.
3285 		 *
3286 		 * 2) a IPSEC_IN if we are generating a icmp_message
3287 		 *    for an incoming datagram destined for us i.e called
3288 		 *    from ip_fanout_send_icmp.
3289 		 */
3290 		ipsec_info_t *in;
3291 		ipsec_mp = mp;
3292 		mp = ipsec_mp->b_cont;
3293 
3294 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3295 		ipha = (ipha_t *)mp->b_rptr;
3296 
3297 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3298 		    in->ipsec_info_type == IPSEC_IN);
3299 
3300 		if (in->ipsec_info_type == IPSEC_IN) {
3301 			/*
3302 			 * Convert the IPSEC_IN to IPSEC_OUT.
3303 			 */
3304 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3305 				BUMP_MIB(&ipst->ips_ip_mib,
3306 				    ipIfStatsOutDiscards);
3307 				return;
3308 			}
3309 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3310 		} else {
3311 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3312 			io = (ipsec_out_t *)in;
3313 			/*
3314 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3315 			 * ire lookup.
3316 			 */
3317 			io->ipsec_out_proc_begin = B_FALSE;
3318 		}
3319 		ASSERT(zoneid == io->ipsec_out_zoneid);
3320 		ASSERT(zoneid != ALL_ZONES);
3321 	} else {
3322 		/*
3323 		 * This is in clear. The icmp message we are building
3324 		 * here should go out in clear.
3325 		 *
3326 		 * Pardon the convolution of it all, but it's easier to
3327 		 * allocate a "use cleartext" IPSEC_IN message and convert
3328 		 * it than it is to allocate a new one.
3329 		 */
3330 		ipsec_in_t *ii;
3331 		ASSERT(DB_TYPE(mp) == M_DATA);
3332 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3333 		if (ipsec_mp == NULL) {
3334 			freemsg(mp);
3335 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3336 			return;
3337 		}
3338 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3339 
3340 		/* This is not a secure packet */
3341 		ii->ipsec_in_secure = B_FALSE;
3342 		/*
3343 		 * For trusted extensions using a shared IP address we can
3344 		 * send using any zoneid.
3345 		 */
3346 		if (zoneid == ALL_ZONES)
3347 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3348 		else
3349 			ii->ipsec_in_zoneid = zoneid;
3350 		ipsec_mp->b_cont = mp;
3351 		ipha = (ipha_t *)mp->b_rptr;
3352 		/*
3353 		 * Convert the IPSEC_IN to IPSEC_OUT.
3354 		 */
3355 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3356 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3357 			return;
3358 		}
3359 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3360 	}
3361 
3362 	/* Remember our eventual destination */
3363 	dst = ipha->ipha_src;
3364 
3365 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3366 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3367 	if (ire != NULL &&
3368 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3369 		src = ipha->ipha_dst;
3370 	} else {
3371 		if (ire != NULL)
3372 			ire_refrele(ire);
3373 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3374 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3375 		    ipst);
3376 		if (ire == NULL) {
3377 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3378 			freemsg(ipsec_mp);
3379 			return;
3380 		}
3381 		src = ire->ire_src_addr;
3382 	}
3383 
3384 	if (ire != NULL)
3385 		ire_refrele(ire);
3386 
3387 	/*
3388 	 * Check if we can send back more then 8 bytes in addition to
3389 	 * the IP header.  We try to send 64 bytes of data and the internal
3390 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3391 	 */
3392 	len_needed = IPH_HDR_LENGTH(ipha);
3393 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3394 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3395 
3396 		if (!pullupmsg(mp, -1)) {
3397 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3398 			freemsg(ipsec_mp);
3399 			return;
3400 		}
3401 		ipha = (ipha_t *)mp->b_rptr;
3402 
3403 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3404 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3405 			    len_needed));
3406 		} else {
3407 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3408 
3409 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3410 			len_needed += ip_hdr_length_v6(mp, ip6h);
3411 		}
3412 	}
3413 	len_needed += ipst->ips_ip_icmp_return;
3414 	msg_len = msgdsize(mp);
3415 	if (msg_len > len_needed) {
3416 		(void) adjmsg(mp, len_needed - msg_len);
3417 		msg_len = len_needed;
3418 	}
3419 	/* Make sure we propagate the cred/label for TX */
3420 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3421 	if (mp1 == NULL) {
3422 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3423 		freemsg(ipsec_mp);
3424 		return;
3425 	}
3426 	mp1->b_cont = mp;
3427 	mp = mp1;
3428 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3429 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3430 	    io->ipsec_out_type == IPSEC_OUT);
3431 	ipsec_mp->b_cont = mp;
3432 
3433 	/*
3434 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3435 	 * node generates be accepted in peace by all on-host destinations.
3436 	 * If we do NOT assume that all on-host destinations trust
3437 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3438 	 * (Look for ipsec_out_icmp_loopback).
3439 	 */
3440 	io->ipsec_out_icmp_loopback = B_TRUE;
3441 
3442 	ipha = (ipha_t *)mp->b_rptr;
3443 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3444 	*ipha = icmp_ipha;
3445 	ipha->ipha_src = src;
3446 	ipha->ipha_dst = dst;
3447 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3448 	msg_len += sizeof (icmp_ipha) + len;
3449 	if (msg_len > IP_MAXPACKET) {
3450 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3451 		msg_len = IP_MAXPACKET;
3452 	}
3453 	ipha->ipha_length = htons((uint16_t)msg_len);
3454 	icmph = (icmph_t *)&ipha[1];
3455 	bcopy(stuff, icmph, len);
3456 	icmph->icmph_checksum = 0;
3457 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3458 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3459 	put(q, ipsec_mp);
3460 }
3461 
3462 /*
3463  * Determine if an ICMP error packet can be sent given the rate limit.
3464  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3465  * in milliseconds) and a burst size. Burst size number of packets can
3466  * be sent arbitrarely closely spaced.
3467  * The state is tracked using two variables to implement an approximate
3468  * token bucket filter:
3469  *	icmp_pkt_err_last - lbolt value when the last burst started
3470  *	icmp_pkt_err_sent - number of packets sent in current burst
3471  */
3472 boolean_t
3473 icmp_err_rate_limit(ip_stack_t *ipst)
3474 {
3475 	clock_t now = TICK_TO_MSEC(lbolt);
3476 	uint_t refilled; /* Number of packets refilled in tbf since last */
3477 	/* Guard against changes by loading into local variable */
3478 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3479 
3480 	if (err_interval == 0)
3481 		return (B_FALSE);
3482 
3483 	if (ipst->ips_icmp_pkt_err_last > now) {
3484 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3485 		ipst->ips_icmp_pkt_err_last = 0;
3486 		ipst->ips_icmp_pkt_err_sent = 0;
3487 	}
3488 	/*
3489 	 * If we are in a burst update the token bucket filter.
3490 	 * Update the "last" time to be close to "now" but make sure
3491 	 * we don't loose precision.
3492 	 */
3493 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3494 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3495 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3496 			ipst->ips_icmp_pkt_err_sent = 0;
3497 		} else {
3498 			ipst->ips_icmp_pkt_err_sent -= refilled;
3499 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3500 		}
3501 	}
3502 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3503 		/* Start of new burst */
3504 		ipst->ips_icmp_pkt_err_last = now;
3505 	}
3506 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3507 		ipst->ips_icmp_pkt_err_sent++;
3508 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3509 		    ipst->ips_icmp_pkt_err_sent));
3510 		return (B_FALSE);
3511 	}
3512 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3513 	return (B_TRUE);
3514 }
3515 
3516 /*
3517  * Check if it is ok to send an IPv4 ICMP error packet in
3518  * response to the IPv4 packet in mp.
3519  * Free the message and return null if no
3520  * ICMP error packet should be sent.
3521  */
3522 static mblk_t *
3523 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3524 {
3525 	icmph_t	*icmph;
3526 	ipha_t	*ipha;
3527 	uint_t	len_needed;
3528 	ire_t	*src_ire;
3529 	ire_t	*dst_ire;
3530 
3531 	if (!mp)
3532 		return (NULL);
3533 	ipha = (ipha_t *)mp->b_rptr;
3534 	if (ip_csum_hdr(ipha)) {
3535 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3536 		freemsg(mp);
3537 		return (NULL);
3538 	}
3539 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3540 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3541 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3542 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3543 	if (src_ire != NULL || dst_ire != NULL ||
3544 	    CLASSD(ipha->ipha_dst) ||
3545 	    CLASSD(ipha->ipha_src) ||
3546 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3547 		/* Note: only errors to the fragment with offset 0 */
3548 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3549 		freemsg(mp);
3550 		if (src_ire != NULL)
3551 			ire_refrele(src_ire);
3552 		if (dst_ire != NULL)
3553 			ire_refrele(dst_ire);
3554 		return (NULL);
3555 	}
3556 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3557 		/*
3558 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3559 		 * errors in response to any ICMP errors.
3560 		 */
3561 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3562 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3563 			if (!pullupmsg(mp, len_needed)) {
3564 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3565 				freemsg(mp);
3566 				return (NULL);
3567 			}
3568 			ipha = (ipha_t *)mp->b_rptr;
3569 		}
3570 		icmph = (icmph_t *)
3571 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3572 		switch (icmph->icmph_type) {
3573 		case ICMP_DEST_UNREACHABLE:
3574 		case ICMP_SOURCE_QUENCH:
3575 		case ICMP_TIME_EXCEEDED:
3576 		case ICMP_PARAM_PROBLEM:
3577 		case ICMP_REDIRECT:
3578 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3579 			freemsg(mp);
3580 			return (NULL);
3581 		default:
3582 			break;
3583 		}
3584 	}
3585 	/*
3586 	 * If this is a labeled system, then check to see if we're allowed to
3587 	 * send a response to this particular sender.  If not, then just drop.
3588 	 */
3589 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3590 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3591 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3592 		freemsg(mp);
3593 		return (NULL);
3594 	}
3595 	if (icmp_err_rate_limit(ipst)) {
3596 		/*
3597 		 * Only send ICMP error packets every so often.
3598 		 * This should be done on a per port/source basis,
3599 		 * but for now this will suffice.
3600 		 */
3601 		freemsg(mp);
3602 		return (NULL);
3603 	}
3604 	return (mp);
3605 }
3606 
3607 /*
3608  * Generate an ICMP redirect message.
3609  */
3610 static void
3611 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3612 {
3613 	icmph_t	icmph;
3614 
3615 	/*
3616 	 * We are called from ip_rput where we could
3617 	 * not have attached an IPSEC_IN.
3618 	 */
3619 	ASSERT(mp->b_datap->db_type == M_DATA);
3620 
3621 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3622 		return;
3623 	}
3624 
3625 	bzero(&icmph, sizeof (icmph_t));
3626 	icmph.icmph_type = ICMP_REDIRECT;
3627 	icmph.icmph_code = 1;
3628 	icmph.icmph_rd_gateway = gateway;
3629 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3630 	/* Redirects sent by router, and router is global zone */
3631 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3632 }
3633 
3634 /*
3635  * Generate an ICMP time exceeded message.
3636  */
3637 void
3638 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3639     ip_stack_t *ipst)
3640 {
3641 	icmph_t	icmph;
3642 	boolean_t mctl_present;
3643 	mblk_t *first_mp;
3644 
3645 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3646 
3647 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3648 		if (mctl_present)
3649 			freeb(first_mp);
3650 		return;
3651 	}
3652 
3653 	bzero(&icmph, sizeof (icmph_t));
3654 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3655 	icmph.icmph_code = code;
3656 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3657 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3658 	    ipst);
3659 }
3660 
3661 /*
3662  * Generate an ICMP unreachable message.
3663  */
3664 void
3665 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3666     ip_stack_t *ipst)
3667 {
3668 	icmph_t	icmph;
3669 	mblk_t *first_mp;
3670 	boolean_t mctl_present;
3671 
3672 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3673 
3674 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3675 		if (mctl_present)
3676 			freeb(first_mp);
3677 		return;
3678 	}
3679 
3680 	bzero(&icmph, sizeof (icmph_t));
3681 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3682 	icmph.icmph_code = code;
3683 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3684 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3685 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3686 	    zoneid, ipst);
3687 }
3688 
3689 /*
3690  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3691  * duplicate.  As long as someone else holds the address, the interface will
3692  * stay down.  When that conflict goes away, the interface is brought back up.
3693  * This is done so that accidental shutdowns of addresses aren't made
3694  * permanent.  Your server will recover from a failure.
3695  *
3696  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3697  * user space process (dhcpagent).
3698  *
3699  * Recovery completes if ARP reports that the address is now ours (via
3700  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3701  *
3702  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3703  */
3704 static void
3705 ipif_dup_recovery(void *arg)
3706 {
3707 	ipif_t *ipif = arg;
3708 	ill_t *ill = ipif->ipif_ill;
3709 	mblk_t *arp_add_mp;
3710 	mblk_t *arp_del_mp;
3711 	ip_stack_t *ipst = ill->ill_ipst;
3712 
3713 	ipif->ipif_recovery_id = 0;
3714 
3715 	/*
3716 	 * No lock needed for moving or condemned check, as this is just an
3717 	 * optimization.
3718 	 */
3719 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3720 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3721 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3722 		/* No reason to try to bring this address back. */
3723 		return;
3724 	}
3725 
3726 	/* ACE_F_UNVERIFIED restarts DAD */
3727 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3728 		goto alloc_fail;
3729 
3730 	if (ipif->ipif_arp_del_mp == NULL) {
3731 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3732 			goto alloc_fail;
3733 		ipif->ipif_arp_del_mp = arp_del_mp;
3734 	}
3735 
3736 	putnext(ill->ill_rq, arp_add_mp);
3737 	return;
3738 
3739 alloc_fail:
3740 	/*
3741 	 * On allocation failure, just restart the timer.  Note that the ipif
3742 	 * is down here, so no other thread could be trying to start a recovery
3743 	 * timer.  The ill_lock protects the condemned flag and the recovery
3744 	 * timer ID.
3745 	 */
3746 	freemsg(arp_add_mp);
3747 	mutex_enter(&ill->ill_lock);
3748 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3749 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3750 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3751 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3752 	}
3753 	mutex_exit(&ill->ill_lock);
3754 }
3755 
3756 /*
3757  * This is for exclusive changes due to ARP.  Either tear down an interface due
3758  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3759  */
3760 /* ARGSUSED */
3761 static void
3762 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3763 {
3764 	ill_t	*ill = rq->q_ptr;
3765 	arh_t *arh;
3766 	ipaddr_t src;
3767 	ipif_t	*ipif;
3768 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3769 	char hbuf[MAC_STR_LEN];
3770 	char sbuf[INET_ADDRSTRLEN];
3771 	const char *failtype;
3772 	boolean_t bring_up;
3773 	ip_stack_t *ipst = ill->ill_ipst;
3774 
3775 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3776 	case AR_CN_READY:
3777 		failtype = NULL;
3778 		bring_up = B_TRUE;
3779 		break;
3780 	case AR_CN_FAILED:
3781 		failtype = "in use";
3782 		bring_up = B_FALSE;
3783 		break;
3784 	default:
3785 		failtype = "claimed";
3786 		bring_up = B_FALSE;
3787 		break;
3788 	}
3789 
3790 	arh = (arh_t *)mp->b_cont->b_rptr;
3791 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3792 
3793 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3794 	    sizeof (hbuf));
3795 	(void) ip_dot_addr(src, sbuf);
3796 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3797 
3798 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3799 		    ipif->ipif_lcl_addr != src) {
3800 			continue;
3801 		}
3802 
3803 		/*
3804 		 * If we failed on a recovery probe, then restart the timer to
3805 		 * try again later.
3806 		 */
3807 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3808 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3809 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3810 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3811 		    ipst->ips_ip_dup_recovery > 0 &&
3812 		    ipif->ipif_recovery_id == 0) {
3813 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3814 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3815 			continue;
3816 		}
3817 
3818 		/*
3819 		 * If what we're trying to do has already been done, then do
3820 		 * nothing.
3821 		 */
3822 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3823 			continue;
3824 
3825 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3826 
3827 		if (failtype == NULL) {
3828 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3829 			    ibuf);
3830 		} else {
3831 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3832 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3833 		}
3834 
3835 		if (bring_up) {
3836 			ASSERT(ill->ill_dl_up);
3837 			/*
3838 			 * Free up the ARP delete message so we can allocate
3839 			 * a fresh one through the normal path.
3840 			 */
3841 			freemsg(ipif->ipif_arp_del_mp);
3842 			ipif->ipif_arp_del_mp = NULL;
3843 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3844 			    EINPROGRESS) {
3845 				ipif->ipif_addr_ready = 1;
3846 				(void) ipif_up_done(ipif);
3847 				ASSERT(ill->ill_move_ipif == NULL);
3848 			}
3849 			continue;
3850 		}
3851 
3852 		mutex_enter(&ill->ill_lock);
3853 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3854 		ipif->ipif_flags |= IPIF_DUPLICATE;
3855 		ill->ill_ipif_dup_count++;
3856 		mutex_exit(&ill->ill_lock);
3857 		/*
3858 		 * Already exclusive on the ill; no need to handle deferred
3859 		 * processing here.
3860 		 */
3861 		(void) ipif_down(ipif, NULL, NULL);
3862 		ipif_down_tail(ipif);
3863 		mutex_enter(&ill->ill_lock);
3864 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3865 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3866 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3867 		    ipst->ips_ip_dup_recovery > 0) {
3868 			ASSERT(ipif->ipif_recovery_id == 0);
3869 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3870 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3871 		}
3872 		mutex_exit(&ill->ill_lock);
3873 	}
3874 	freemsg(mp);
3875 }
3876 
3877 /* ARGSUSED */
3878 static void
3879 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3880 {
3881 	ill_t	*ill = rq->q_ptr;
3882 	arh_t *arh;
3883 	ipaddr_t src;
3884 	ipif_t	*ipif;
3885 
3886 	arh = (arh_t *)mp->b_cont->b_rptr;
3887 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3888 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3889 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3890 			(void) ipif_resolver_up(ipif, Res_act_defend);
3891 	}
3892 	freemsg(mp);
3893 }
3894 
3895 /*
3896  * News from ARP.  ARP sends notification of interesting events down
3897  * to its clients using M_CTL messages with the interesting ARP packet
3898  * attached via b_cont.
3899  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3900  * queue as opposed to ARP sending the message to all the clients, i.e. all
3901  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3902  * table if a cache IRE is found to delete all the entries for the address in
3903  * the packet.
3904  */
3905 static void
3906 ip_arp_news(queue_t *q, mblk_t *mp)
3907 {
3908 	arcn_t		*arcn;
3909 	arh_t		*arh;
3910 	ire_t		*ire = NULL;
3911 	char		hbuf[MAC_STR_LEN];
3912 	char		sbuf[INET_ADDRSTRLEN];
3913 	ipaddr_t	src;
3914 	in6_addr_t	v6src;
3915 	boolean_t	isv6 = B_FALSE;
3916 	ipif_t		*ipif;
3917 	ill_t		*ill;
3918 	ip_stack_t	*ipst;
3919 
3920 	if (CONN_Q(q)) {
3921 		conn_t *connp = Q_TO_CONN(q);
3922 
3923 		ipst = connp->conn_netstack->netstack_ip;
3924 	} else {
3925 		ill_t *ill = (ill_t *)q->q_ptr;
3926 
3927 		ipst = ill->ill_ipst;
3928 	}
3929 
3930 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3931 		if (q->q_next) {
3932 			putnext(q, mp);
3933 		} else
3934 			freemsg(mp);
3935 		return;
3936 	}
3937 	arh = (arh_t *)mp->b_cont->b_rptr;
3938 	/* Is it one we are interested in? */
3939 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3940 		isv6 = B_TRUE;
3941 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3942 		    IPV6_ADDR_LEN);
3943 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3944 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3945 		    IP_ADDR_LEN);
3946 	} else {
3947 		freemsg(mp);
3948 		return;
3949 	}
3950 
3951 	ill = q->q_ptr;
3952 
3953 	arcn = (arcn_t *)mp->b_rptr;
3954 	switch (arcn->arcn_code) {
3955 	case AR_CN_BOGON:
3956 		/*
3957 		 * Someone is sending ARP packets with a source protocol
3958 		 * address that we have published and for which we believe our
3959 		 * entry is authoritative and (when ill_arp_extend is set)
3960 		 * verified to be unique on the network.
3961 		 *
3962 		 * The ARP module internally handles the cases where the sender
3963 		 * is just probing (for DAD) and where the hardware address of
3964 		 * a non-authoritative entry has changed.  Thus, these are the
3965 		 * real conflicts, and we have to do resolution.
3966 		 *
3967 		 * We back away quickly from the address if it's from DHCP or
3968 		 * otherwise temporary and hasn't been used recently (or at
3969 		 * all).  We'd like to include "deprecated" addresses here as
3970 		 * well (as there's no real reason to defend something we're
3971 		 * discarding), but IPMP "reuses" this flag to mean something
3972 		 * other than the standard meaning.
3973 		 *
3974 		 * If the ARP module above is not extended (meaning that it
3975 		 * doesn't know how to defend the address), then we just log
3976 		 * the problem as we always did and continue on.  It's not
3977 		 * right, but there's little else we can do, and those old ATM
3978 		 * users are going away anyway.
3979 		 */
3980 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3981 		    hbuf, sizeof (hbuf));
3982 		(void) ip_dot_addr(src, sbuf);
3983 		if (isv6) {
3984 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3985 			    ipst);
3986 		} else {
3987 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3988 		}
3989 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3990 			uint32_t now;
3991 			uint32_t maxage;
3992 			clock_t lused;
3993 			uint_t maxdefense;
3994 			uint_t defs;
3995 
3996 			/*
3997 			 * First, figure out if this address hasn't been used
3998 			 * in a while.  If it hasn't, then it's a better
3999 			 * candidate for abandoning.
4000 			 */
4001 			ipif = ire->ire_ipif;
4002 			ASSERT(ipif != NULL);
4003 			now = gethrestime_sec();
4004 			maxage = now - ire->ire_create_time;
4005 			if (maxage > ipst->ips_ip_max_temp_idle)
4006 				maxage = ipst->ips_ip_max_temp_idle;
4007 			lused = drv_hztousec(ddi_get_lbolt() -
4008 			    ire->ire_last_used_time) / MICROSEC + 1;
4009 			if (lused >= maxage && (ipif->ipif_flags &
4010 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4011 				maxdefense = ipst->ips_ip_max_temp_defend;
4012 			else
4013 				maxdefense = ipst->ips_ip_max_defend;
4014 
4015 			/*
4016 			 * Now figure out how many times we've defended
4017 			 * ourselves.  Ignore defenses that happened long in
4018 			 * the past.
4019 			 */
4020 			mutex_enter(&ire->ire_lock);
4021 			if ((defs = ire->ire_defense_count) > 0 &&
4022 			    now - ire->ire_defense_time >
4023 			    ipst->ips_ip_defend_interval) {
4024 				ire->ire_defense_count = defs = 0;
4025 			}
4026 			ire->ire_defense_count++;
4027 			ire->ire_defense_time = now;
4028 			mutex_exit(&ire->ire_lock);
4029 			ill_refhold(ill);
4030 			ire_refrele(ire);
4031 
4032 			/*
4033 			 * If we've defended ourselves too many times already,
4034 			 * then give up and tear down the interface(s) using
4035 			 * this address.  Otherwise, defend by sending out a
4036 			 * gratuitous ARP.
4037 			 */
4038 			if (defs >= maxdefense && ill->ill_arp_extend) {
4039 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4040 				    B_FALSE);
4041 			} else {
4042 				cmn_err(CE_WARN,
4043 				    "node %s is using our IP address %s on %s",
4044 				    hbuf, sbuf, ill->ill_name);
4045 				/*
4046 				 * If this is an old (ATM) ARP module, then
4047 				 * don't try to defend the address.  Remain
4048 				 * compatible with the old behavior.  Defend
4049 				 * only with new ARP.
4050 				 */
4051 				if (ill->ill_arp_extend) {
4052 					qwriter_ip(ill, q, mp, ip_arp_defend,
4053 					    NEW_OP, B_FALSE);
4054 				} else {
4055 					ill_refrele(ill);
4056 				}
4057 			}
4058 			return;
4059 		}
4060 		cmn_err(CE_WARN,
4061 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4062 		    hbuf, sbuf, ill->ill_name);
4063 		if (ire != NULL)
4064 			ire_refrele(ire);
4065 		break;
4066 	case AR_CN_ANNOUNCE:
4067 		if (isv6) {
4068 			/*
4069 			 * For XRESOLV interfaces.
4070 			 * Delete the IRE cache entry and NCE for this
4071 			 * v6 address
4072 			 */
4073 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4074 			/*
4075 			 * If v6src is a non-zero, it's a router address
4076 			 * as below. Do the same sort of thing to clean
4077 			 * out off-net IRE_CACHE entries that go through
4078 			 * the router.
4079 			 */
4080 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4081 				ire_walk_v6(ire_delete_cache_gw_v6,
4082 				    (char *)&v6src, ALL_ZONES, ipst);
4083 			}
4084 		} else {
4085 			nce_hw_map_t hwm;
4086 
4087 			/*
4088 			 * ARP gives us a copy of any packet where it thinks
4089 			 * the address has changed, so that we can update our
4090 			 * caches.  We're responsible for caching known answers
4091 			 * in the current design.  We check whether the
4092 			 * hardware address really has changed in all of our
4093 			 * entries that have cached this mapping, and if so, we
4094 			 * blow them away.  This way we will immediately pick
4095 			 * up the rare case of a host changing hardware
4096 			 * address.
4097 			 */
4098 			if (src == 0)
4099 				break;
4100 			hwm.hwm_addr = src;
4101 			hwm.hwm_hwlen = arh->arh_hlen;
4102 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4103 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4104 			ndp_walk_common(ipst->ips_ndp4, NULL,
4105 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4106 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4107 		}
4108 		break;
4109 	case AR_CN_READY:
4110 		/* No external v6 resolver has a contract to use this */
4111 		if (isv6)
4112 			break;
4113 		/* If the link is down, we'll retry this later */
4114 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4115 			break;
4116 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4117 		    NULL, NULL, ipst);
4118 		if (ipif != NULL) {
4119 			/*
4120 			 * If this is a duplicate recovery, then we now need to
4121 			 * go exclusive to bring this thing back up.
4122 			 */
4123 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4124 			    IPIF_DUPLICATE) {
4125 				ipif_refrele(ipif);
4126 				ill_refhold(ill);
4127 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4128 				    B_FALSE);
4129 				return;
4130 			}
4131 			/*
4132 			 * If this is the first notice that this address is
4133 			 * ready, then let the user know now.
4134 			 */
4135 			if ((ipif->ipif_flags & IPIF_UP) &&
4136 			    !ipif->ipif_addr_ready) {
4137 				ipif_mask_reply(ipif);
4138 				ipif_up_notify(ipif);
4139 			}
4140 			ipif->ipif_addr_ready = 1;
4141 			ipif_refrele(ipif);
4142 		}
4143 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4144 		if (ire != NULL) {
4145 			ire->ire_defense_count = 0;
4146 			ire_refrele(ire);
4147 		}
4148 		break;
4149 	case AR_CN_FAILED:
4150 		/* No external v6 resolver has a contract to use this */
4151 		if (isv6)
4152 			break;
4153 		if (!ill->ill_arp_extend) {
4154 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4155 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4156 			(void) ip_dot_addr(src, sbuf);
4157 
4158 			cmn_err(CE_WARN,
4159 			    "node %s is using our IP address %s on %s",
4160 			    hbuf, sbuf, ill->ill_name);
4161 			break;
4162 		}
4163 		ill_refhold(ill);
4164 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4165 		return;
4166 	}
4167 	freemsg(mp);
4168 }
4169 
4170 /*
4171  * Create a mblk suitable for carrying the interface index and/or source link
4172  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4173  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4174  * application.
4175  */
4176 mblk_t *
4177 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4178     ip_stack_t *ipst)
4179 {
4180 	mblk_t		*mp;
4181 	ip_pktinfo_t	*pinfo;
4182 	ipha_t 		*ipha;
4183 	struct ether_header *pether;
4184 	boolean_t	ipmp_ill_held = B_FALSE;
4185 
4186 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4187 	if (mp == NULL) {
4188 		ip1dbg(("ip_add_info: allocation failure.\n"));
4189 		return (data_mp);
4190 	}
4191 
4192 	ipha = (ipha_t *)data_mp->b_rptr;
4193 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4194 	bzero(pinfo, sizeof (ip_pktinfo_t));
4195 	pinfo->ip_pkt_flags = (uchar_t)flags;
4196 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4197 
4198 	pether = (struct ether_header *)((char *)ipha
4199 	    - sizeof (struct ether_header));
4200 
4201 	/*
4202 	 * Make sure the interface is an ethernet type, since this option
4203 	 * is currently supported only on this type of interface. Also make
4204 	 * sure we are pointing correctly above db_base.
4205 	 */
4206 	if ((flags & IPF_RECVSLLA) &&
4207 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4208 	    (ill->ill_type == IFT_ETHER) &&
4209 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4210 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4211 		bcopy(pether->ether_shost.ether_addr_octet,
4212 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4213 	} else {
4214 		/*
4215 		 * Clear the bit. Indicate to upper layer that IP is not
4216 		 * sending this ancillary info.
4217 		 */
4218 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4219 	}
4220 
4221 	/*
4222 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4223 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4224 	 * IPF_RECVADDR support on test addresses is not needed.)
4225 	 *
4226 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4227 	 * processing a packet looped back to an IPMP data address
4228 	 * (since those IRE_LOCALs are tied to IPMP ills).
4229 	 */
4230 	if (IS_UNDER_IPMP(ill)) {
4231 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4232 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4233 			freemsg(mp);
4234 			return (data_mp);
4235 		}
4236 		ipmp_ill_held = B_TRUE;
4237 	}
4238 
4239 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4240 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4241 	if (flags & IPF_RECVADDR) {
4242 		ipif_t	*ipif;
4243 		ire_t	*ire;
4244 
4245 		/*
4246 		 * Only valid for V4
4247 		 */
4248 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4249 		    (IPV4_VERSION << 4));
4250 
4251 		ipif = ipif_get_next_ipif(NULL, ill);
4252 		if (ipif != NULL) {
4253 			/*
4254 			 * Since a decision has already been made to deliver the
4255 			 * packet, there is no need to test for SECATTR and
4256 			 * ZONEONLY.
4257 			 * When a multicast packet is transmitted
4258 			 * a cache entry is created for the multicast address.
4259 			 * When delivering a copy of the packet or when new
4260 			 * packets are received we do not want to match on the
4261 			 * cached entry so explicitly match on
4262 			 * IRE_LOCAL and IRE_LOOPBACK
4263 			 */
4264 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4265 			    IRE_LOCAL | IRE_LOOPBACK,
4266 			    ipif, zoneid, NULL,
4267 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4268 			if (ire == NULL) {
4269 				/*
4270 				 * packet must have come on a different
4271 				 * interface.
4272 				 * Since a decision has already been made to
4273 				 * deliver the packet, there is no need to test
4274 				 * for SECATTR and ZONEONLY.
4275 				 * Only match on local and broadcast ire's.
4276 				 * See detailed comment above.
4277 				 */
4278 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4279 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4280 				    NULL, MATCH_IRE_TYPE, ipst);
4281 			}
4282 
4283 			if (ire == NULL) {
4284 				/*
4285 				 * This is either a multicast packet or
4286 				 * the address has been removed since
4287 				 * the packet was received.
4288 				 * Return INADDR_ANY so that normal source
4289 				 * selection occurs for the response.
4290 				 */
4291 
4292 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4293 			} else {
4294 				pinfo->ip_pkt_match_addr.s_addr =
4295 				    ire->ire_src_addr;
4296 				ire_refrele(ire);
4297 			}
4298 			ipif_refrele(ipif);
4299 		} else {
4300 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4301 		}
4302 	}
4303 
4304 	if (ipmp_ill_held)
4305 		ill_refrele(ill);
4306 
4307 	mp->b_datap->db_type = M_CTL;
4308 	mp->b_wptr += sizeof (ip_pktinfo_t);
4309 	mp->b_cont = data_mp;
4310 
4311 	return (mp);
4312 }
4313 
4314 /*
4315  * Used to determine the most accurate cred_t to use for TX.
4316  * First priority is SCM_UCRED having set the label in the message,
4317  * which is used for MLP on UDP. Second priority is the peers label (aka
4318  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4319  * open credentials.
4320  */
4321 cred_t *
4322 ip_best_cred(mblk_t *mp, conn_t *connp)
4323 {
4324 	cred_t *cr;
4325 
4326 	cr = msg_getcred(mp, NULL);
4327 	if (cr != NULL && crgetlabel(cr) != NULL)
4328 		return (cr);
4329 	return (CONN_CRED(connp));
4330 }
4331 
4332 /*
4333  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4334  * part of the bind request.
4335  */
4336 
4337 boolean_t
4338 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4339 {
4340 	ipsec_in_t *ii;
4341 
4342 	ASSERT(policy_mp != NULL);
4343 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4344 
4345 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4346 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4347 
4348 	connp->conn_policy = ii->ipsec_in_policy;
4349 	ii->ipsec_in_policy = NULL;
4350 
4351 	if (ii->ipsec_in_action != NULL) {
4352 		if (connp->conn_latch == NULL) {
4353 			connp->conn_latch = iplatch_create();
4354 			if (connp->conn_latch == NULL)
4355 				return (B_FALSE);
4356 		}
4357 		ipsec_latch_inbound(connp->conn_latch, ii);
4358 	}
4359 	return (B_TRUE);
4360 }
4361 
4362 static void
4363 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4364 {
4365 	/*
4366 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4367 	 * We can't do this in ip_bind_get_ire because the policy
4368 	 * may not have been inherited at that point in time and hence
4369 	 * conn_out_enforce_policy may not be set.
4370 	 */
4371 	if (ire_requested && connp->conn_out_enforce_policy &&
4372 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4373 		ire_t *ire = (ire_t *)mp->b_rptr;
4374 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4375 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4376 	}
4377 }
4378 
4379 /*
4380  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4381  * and to arrange for power-fanout assist.  The ULP is identified by
4382  * adding a single byte at the end of the original bind message.
4383  * A ULP other than UDP or TCP that wishes to be recognized passes
4384  * down a bind with a zero length address.
4385  *
4386  * The binding works as follows:
4387  * - A zero byte address means just bind to the protocol.
4388  * - A four byte address is treated as a request to validate
4389  *   that the address is a valid local address, appropriate for
4390  *   an application to bind to. This does not affect any fanout
4391  *   information in IP.
4392  * - A sizeof sin_t byte address is used to bind to only the local address
4393  *   and port.
4394  * - A sizeof ipa_conn_t byte address contains complete fanout information
4395  *   consisting of local and remote addresses and ports.  In
4396  *   this case, the addresses are both validated as appropriate
4397  *   for this operation, and, if so, the information is retained
4398  *   for use in the inbound fanout.
4399  *
4400  * The ULP (except in the zero-length bind) can append an
4401  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4402  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4403  * a copy of the source or destination IRE (source for local bind;
4404  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4405  * policy information contained should be copied on to the conn.
4406  *
4407  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4408  */
4409 mblk_t *
4410 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4411 {
4412 	ssize_t		len;
4413 	struct T_bind_req	*tbr;
4414 	sin_t		*sin;
4415 	ipa_conn_t	*ac;
4416 	uchar_t		*ucp;
4417 	mblk_t		*mp1;
4418 	boolean_t	ire_requested;
4419 	int		error = 0;
4420 	int		protocol;
4421 	ipa_conn_x_t	*acx;
4422 	cred_t		*cr;
4423 
4424 	/*
4425 	 * All Solaris components should pass a db_credp
4426 	 * for this TPI message, hence we ASSERT.
4427 	 * But in case there is some other M_PROTO that looks
4428 	 * like a TPI message sent by some other kernel
4429 	 * component, we check and return an error.
4430 	 */
4431 	cr = msg_getcred(mp, NULL);
4432 	ASSERT(cr != NULL);
4433 	if (cr == NULL) {
4434 		error = EINVAL;
4435 		goto bad_addr;
4436 	}
4437 
4438 	ASSERT(!connp->conn_af_isv6);
4439 	connp->conn_pkt_isv6 = B_FALSE;
4440 
4441 	len = MBLKL(mp);
4442 	if (len < (sizeof (*tbr) + 1)) {
4443 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4444 		    "ip_bind: bogus msg, len %ld", len);
4445 		/* XXX: Need to return something better */
4446 		goto bad_addr;
4447 	}
4448 	/* Back up and extract the protocol identifier. */
4449 	mp->b_wptr--;
4450 	protocol = *mp->b_wptr & 0xFF;
4451 	tbr = (struct T_bind_req *)mp->b_rptr;
4452 	/* Reset the message type in preparation for shipping it back. */
4453 	DB_TYPE(mp) = M_PCPROTO;
4454 
4455 	connp->conn_ulp = (uint8_t)protocol;
4456 
4457 	/*
4458 	 * Check for a zero length address.  This is from a protocol that
4459 	 * wants to register to receive all packets of its type.
4460 	 */
4461 	if (tbr->ADDR_length == 0) {
4462 		/*
4463 		 * These protocols are now intercepted in ip_bind_v6().
4464 		 * Reject protocol-level binds here for now.
4465 		 *
4466 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4467 		 * so that the protocol type cannot be SCTP.
4468 		 */
4469 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4470 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4471 			goto bad_addr;
4472 		}
4473 
4474 		/*
4475 		 *
4476 		 * The udp module never sends down a zero-length address,
4477 		 * and allowing this on a labeled system will break MLP
4478 		 * functionality.
4479 		 */
4480 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4481 			goto bad_addr;
4482 
4483 		if (connp->conn_mac_exempt)
4484 			goto bad_addr;
4485 
4486 		/* No hash here really.  The table is big enough. */
4487 		connp->conn_srcv6 = ipv6_all_zeros;
4488 
4489 		ipcl_proto_insert(connp, protocol);
4490 
4491 		tbr->PRIM_type = T_BIND_ACK;
4492 		return (mp);
4493 	}
4494 
4495 	/* Extract the address pointer from the message. */
4496 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4497 	    tbr->ADDR_length);
4498 	if (ucp == NULL) {
4499 		ip1dbg(("ip_bind: no address\n"));
4500 		goto bad_addr;
4501 	}
4502 	if (!OK_32PTR(ucp)) {
4503 		ip1dbg(("ip_bind: unaligned address\n"));
4504 		goto bad_addr;
4505 	}
4506 	/*
4507 	 * Check for trailing mps.
4508 	 */
4509 
4510 	mp1 = mp->b_cont;
4511 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4512 
4513 	switch (tbr->ADDR_length) {
4514 	default:
4515 		ip1dbg(("ip_bind: bad address length %d\n",
4516 		    (int)tbr->ADDR_length));
4517 		goto bad_addr;
4518 
4519 	case IP_ADDR_LEN:
4520 		/* Verification of local address only */
4521 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4522 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4523 		break;
4524 
4525 	case sizeof (sin_t):
4526 		sin = (sin_t *)ucp;
4527 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4528 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4529 		break;
4530 
4531 	case sizeof (ipa_conn_t):
4532 		ac = (ipa_conn_t *)ucp;
4533 		/* For raw socket, the local port is not set. */
4534 		if (ac->ac_lport == 0)
4535 			ac->ac_lport = connp->conn_lport;
4536 		/* Always verify destination reachability. */
4537 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4538 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4539 		    B_TRUE, B_TRUE, cr);
4540 		break;
4541 
4542 	case sizeof (ipa_conn_x_t):
4543 		acx = (ipa_conn_x_t *)ucp;
4544 		/*
4545 		 * Whether or not to verify destination reachability depends
4546 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4547 		 */
4548 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4549 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4550 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4551 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4552 		break;
4553 	}
4554 	ASSERT(error != EINPROGRESS);
4555 	if (error != 0)
4556 		goto bad_addr;
4557 
4558 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4559 
4560 	/* Send it home. */
4561 	mp->b_datap->db_type = M_PCPROTO;
4562 	tbr->PRIM_type = T_BIND_ACK;
4563 	return (mp);
4564 
4565 bad_addr:
4566 	/*
4567 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4568 	 * a unix errno.
4569 	 */
4570 	if (error > 0)
4571 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4572 	else
4573 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4574 	return (mp);
4575 }
4576 
4577 /*
4578  * Here address is verified to be a valid local address.
4579  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4580  * address is also considered a valid local address.
4581  * In the case of a broadcast/multicast address, however, the
4582  * upper protocol is expected to reset the src address
4583  * to 0 if it sees a IRE_BROADCAST type returned so that
4584  * no packets are emitted with broadcast/multicast address as
4585  * source address (that violates hosts requirements RFC 1122)
4586  * The addresses valid for bind are:
4587  *	(1) - INADDR_ANY (0)
4588  *	(2) - IP address of an UP interface
4589  *	(3) - IP address of a DOWN interface
4590  *	(4) - valid local IP broadcast addresses. In this case
4591  *	the conn will only receive packets destined to
4592  *	the specified broadcast address.
4593  *	(5) - a multicast address. In this case
4594  *	the conn will only receive packets destined to
4595  *	the specified multicast address. Note: the
4596  *	application still has to issue an
4597  *	IP_ADD_MEMBERSHIP socket option.
4598  *
4599  * On error, return -1 for TBADADDR otherwise pass the
4600  * errno with TSYSERR reply.
4601  *
4602  * In all the above cases, the bound address must be valid in the current zone.
4603  * When the address is loopback, multicast or broadcast, there might be many
4604  * matching IREs so bind has to look up based on the zone.
4605  *
4606  * Note: lport is in network byte order.
4607  *
4608  */
4609 int
4610 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4611     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4612 {
4613 	int		error = 0;
4614 	ire_t		*src_ire;
4615 	zoneid_t	zoneid;
4616 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4617 	mblk_t		*mp = NULL;
4618 	boolean_t	ire_requested = B_FALSE;
4619 	boolean_t	ipsec_policy_set = B_FALSE;
4620 
4621 	if (mpp)
4622 		mp = *mpp;
4623 
4624 	if (mp != NULL) {
4625 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4626 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4627 	}
4628 
4629 	/*
4630 	 * If it was previously connected, conn_fully_bound would have
4631 	 * been set.
4632 	 */
4633 	connp->conn_fully_bound = B_FALSE;
4634 
4635 	src_ire = NULL;
4636 
4637 	zoneid = IPCL_ZONEID(connp);
4638 
4639 	if (src_addr) {
4640 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4641 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4642 		/*
4643 		 * If an address other than 0.0.0.0 is requested,
4644 		 * we verify that it is a valid address for bind
4645 		 * Note: Following code is in if-else-if form for
4646 		 * readability compared to a condition check.
4647 		 */
4648 		/* LINTED - statement has no consequence */
4649 		if (IRE_IS_LOCAL(src_ire)) {
4650 			/*
4651 			 * (2) Bind to address of local UP interface
4652 			 */
4653 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4654 			/*
4655 			 * (4) Bind to broadcast address
4656 			 * Note: permitted only from transports that
4657 			 * request IRE
4658 			 */
4659 			if (!ire_requested)
4660 				error = EADDRNOTAVAIL;
4661 		} else {
4662 			/*
4663 			 * (3) Bind to address of local DOWN interface
4664 			 * (ipif_lookup_addr() looks up all interfaces
4665 			 * but we do not get here for UP interfaces
4666 			 * - case (2) above)
4667 			 */
4668 			/* LINTED - statement has no consequent */
4669 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4670 				/* The address exists */
4671 			} else if (CLASSD(src_addr)) {
4672 				error = 0;
4673 				if (src_ire != NULL)
4674 					ire_refrele(src_ire);
4675 				/*
4676 				 * (5) bind to multicast address.
4677 				 * Fake out the IRE returned to upper
4678 				 * layer to be a broadcast IRE.
4679 				 */
4680 				src_ire = ire_ctable_lookup(
4681 				    INADDR_BROADCAST, INADDR_ANY,
4682 				    IRE_BROADCAST, NULL, zoneid, NULL,
4683 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4684 				    ipst);
4685 				if (src_ire == NULL || !ire_requested)
4686 					error = EADDRNOTAVAIL;
4687 			} else {
4688 				/*
4689 				 * Not a valid address for bind
4690 				 */
4691 				error = EADDRNOTAVAIL;
4692 			}
4693 		}
4694 		if (error) {
4695 			/* Red Alert!  Attempting to be a bogon! */
4696 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4697 			    ntohl(src_addr)));
4698 			goto bad_addr;
4699 		}
4700 	}
4701 
4702 	/*
4703 	 * Allow setting new policies. For example, disconnects come
4704 	 * down as ipa_t bind. As we would have set conn_policy_cached
4705 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4706 	 * can change after the disconnect.
4707 	 */
4708 	connp->conn_policy_cached = B_FALSE;
4709 
4710 	/*
4711 	 * If not fanout_insert this was just an address verification
4712 	 */
4713 	if (fanout_insert) {
4714 		/*
4715 		 * The addresses have been verified. Time to insert in
4716 		 * the correct fanout list.
4717 		 */
4718 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4719 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4720 		connp->conn_lport = lport;
4721 		connp->conn_fport = 0;
4722 		/*
4723 		 * Do we need to add a check to reject Multicast packets
4724 		 */
4725 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4726 	}
4727 
4728 	if (error == 0) {
4729 		if (ire_requested) {
4730 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4731 				error = -1;
4732 				/* Falls through to bad_addr */
4733 			}
4734 		} else if (ipsec_policy_set) {
4735 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4736 				error = -1;
4737 				/* Falls through to bad_addr */
4738 			}
4739 		}
4740 	}
4741 bad_addr:
4742 	if (error != 0) {
4743 		if (connp->conn_anon_port) {
4744 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4745 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4746 			    B_FALSE);
4747 		}
4748 		connp->conn_mlp_type = mlptSingle;
4749 	}
4750 	if (src_ire != NULL)
4751 		IRE_REFRELE(src_ire);
4752 	return (error);
4753 }
4754 
4755 int
4756 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4757     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4758 {
4759 	int error;
4760 	mblk_t	*mp = NULL;
4761 	boolean_t ire_requested;
4762 
4763 	if (ire_mpp)
4764 		mp = *ire_mpp;
4765 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4766 
4767 	ASSERT(!connp->conn_af_isv6);
4768 	connp->conn_pkt_isv6 = B_FALSE;
4769 	connp->conn_ulp = protocol;
4770 
4771 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4772 	    fanout_insert);
4773 	if (error == 0) {
4774 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4775 		    ire_requested);
4776 	} else if (error < 0) {
4777 		error = -TBADADDR;
4778 	}
4779 	return (error);
4780 }
4781 
4782 /*
4783  * Verify that both the source and destination addresses
4784  * are valid.  If verify_dst is false, then the destination address may be
4785  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4786  * destination reachability, while tunnels do not.
4787  * Note that we allow connect to broadcast and multicast
4788  * addresses when ire_requested is set. Thus the ULP
4789  * has to check for IRE_BROADCAST and multicast.
4790  *
4791  * Returns zero if ok.
4792  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4793  * (for use with TSYSERR reply).
4794  *
4795  * Note: lport and fport are in network byte order.
4796  */
4797 int
4798 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4799     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4800     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4801 {
4802 
4803 	ire_t		*src_ire;
4804 	ire_t		*dst_ire;
4805 	int		error = 0;
4806 	ire_t		*sire = NULL;
4807 	ire_t		*md_dst_ire = NULL;
4808 	ire_t		*lso_dst_ire = NULL;
4809 	ill_t		*ill = NULL;
4810 	zoneid_t	zoneid;
4811 	ipaddr_t	src_addr = *src_addrp;
4812 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4813 	mblk_t		*mp = NULL;
4814 	boolean_t	ire_requested = B_FALSE;
4815 	boolean_t	ipsec_policy_set = B_FALSE;
4816 	ts_label_t	*tsl = NULL;
4817 
4818 	if (mpp)
4819 		mp = *mpp;
4820 
4821 	if (mp != NULL) {
4822 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4823 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4824 	}
4825 	if (cr != NULL)
4826 		tsl = crgetlabel(cr);
4827 
4828 	src_ire = dst_ire = NULL;
4829 
4830 	/*
4831 	 * If we never got a disconnect before, clear it now.
4832 	 */
4833 	connp->conn_fully_bound = B_FALSE;
4834 
4835 	zoneid = IPCL_ZONEID(connp);
4836 
4837 	if (CLASSD(dst_addr)) {
4838 		/* Pick up an IRE_BROADCAST */
4839 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4840 		    NULL, zoneid, tsl,
4841 		    (MATCH_IRE_RECURSIVE |
4842 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4843 		    MATCH_IRE_SECATTR), ipst);
4844 	} else {
4845 		/*
4846 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4847 		 * and onlink ipif is not found set ENETUNREACH error.
4848 		 */
4849 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4850 			ipif_t *ipif;
4851 
4852 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4853 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4854 			if (ipif == NULL) {
4855 				error = ENETUNREACH;
4856 				goto bad_addr;
4857 			}
4858 			ipif_refrele(ipif);
4859 		}
4860 
4861 		if (connp->conn_nexthop_set) {
4862 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4863 			    0, 0, NULL, NULL, zoneid, tsl,
4864 			    MATCH_IRE_SECATTR, ipst);
4865 		} else {
4866 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4867 			    &sire, zoneid, tsl,
4868 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4869 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4870 			    MATCH_IRE_SECATTR), ipst);
4871 		}
4872 	}
4873 	/*
4874 	 * dst_ire can't be a broadcast when not ire_requested.
4875 	 * We also prevent ire's with src address INADDR_ANY to
4876 	 * be used, which are created temporarily for
4877 	 * sending out packets from endpoints that have
4878 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4879 	 * reachable.  If verify_dst is false, the destination needn't be
4880 	 * reachable.
4881 	 *
4882 	 * If we match on a reject or black hole, then we've got a
4883 	 * local failure.  May as well fail out the connect() attempt,
4884 	 * since it's never going to succeed.
4885 	 */
4886 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4887 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4888 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4889 		/*
4890 		 * If we're verifying destination reachability, we always want
4891 		 * to complain here.
4892 		 *
4893 		 * If we're not verifying destination reachability but the
4894 		 * destination has a route, we still want to fail on the
4895 		 * temporary address and broadcast address tests.
4896 		 */
4897 		if (verify_dst || (dst_ire != NULL)) {
4898 			if (ip_debug > 2) {
4899 				pr_addr_dbg("ip_bind_connected_v4:"
4900 				    "bad connected dst %s\n",
4901 				    AF_INET, &dst_addr);
4902 			}
4903 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4904 				error = ENETUNREACH;
4905 			else
4906 				error = EHOSTUNREACH;
4907 			goto bad_addr;
4908 		}
4909 	}
4910 
4911 	/*
4912 	 * We now know that routing will allow us to reach the destination.
4913 	 * Check whether Trusted Solaris policy allows communication with this
4914 	 * host, and pretend that the destination is unreachable if not.
4915 	 *
4916 	 * This is never a problem for TCP, since that transport is known to
4917 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4918 	 * handling.  If the remote is unreachable, it will be detected at that
4919 	 * point, so there's no reason to check it here.
4920 	 *
4921 	 * Note that for sendto (and other datagram-oriented friends), this
4922 	 * check is done as part of the data path label computation instead.
4923 	 * The check here is just to make non-TCP connect() report the right
4924 	 * error.
4925 	 */
4926 	if (dst_ire != NULL && is_system_labeled() &&
4927 	    !IPCL_IS_TCP(connp) &&
4928 	    tsol_compute_label(cr, dst_addr, NULL,
4929 	    connp->conn_mac_exempt, ipst) != 0) {
4930 		error = EHOSTUNREACH;
4931 		if (ip_debug > 2) {
4932 			pr_addr_dbg("ip_bind_connected_v4:"
4933 			    " no label for dst %s\n",
4934 			    AF_INET, &dst_addr);
4935 		}
4936 		goto bad_addr;
4937 	}
4938 
4939 	/*
4940 	 * If the app does a connect(), it means that it will most likely
4941 	 * send more than 1 packet to the destination.  It makes sense
4942 	 * to clear the temporary flag.
4943 	 */
4944 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4945 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4946 		irb_t *irb = dst_ire->ire_bucket;
4947 
4948 		rw_enter(&irb->irb_lock, RW_WRITER);
4949 		/*
4950 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4951 		 * the lock to guarantee irb_tmp_ire_cnt.
4952 		 */
4953 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4954 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4955 			irb->irb_tmp_ire_cnt--;
4956 		}
4957 		rw_exit(&irb->irb_lock);
4958 	}
4959 
4960 	/*
4961 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4962 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4963 	 * eligibility tests for passive connects are handled separately
4964 	 * through tcp_adapt_ire().  We do this before the source address
4965 	 * selection, because dst_ire may change after a call to
4966 	 * ipif_select_source().  This is a best-effort check, as the
4967 	 * packet for this connection may not actually go through
4968 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4969 	 * calling ip_newroute().  This is why we further check on the
4970 	 * IRE during LSO/Multidata packet transmission in
4971 	 * tcp_lsosend()/tcp_multisend().
4972 	 */
4973 	if (!ipsec_policy_set && dst_ire != NULL &&
4974 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4975 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4976 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4977 			lso_dst_ire = dst_ire;
4978 			IRE_REFHOLD(lso_dst_ire);
4979 		} else if (ipst->ips_ip_multidata_outbound &&
4980 		    ILL_MDT_CAPABLE(ill)) {
4981 			md_dst_ire = dst_ire;
4982 			IRE_REFHOLD(md_dst_ire);
4983 		}
4984 	}
4985 
4986 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4987 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4988 		/*
4989 		 * If the IRE belongs to a different zone, look for a matching
4990 		 * route in the forwarding table and use the source address from
4991 		 * that route.
4992 		 */
4993 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4994 		    zoneid, 0, NULL,
4995 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4996 		    MATCH_IRE_RJ_BHOLE, ipst);
4997 		if (src_ire == NULL) {
4998 			error = EHOSTUNREACH;
4999 			goto bad_addr;
5000 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5001 			if (!(src_ire->ire_type & IRE_HOST))
5002 				error = ENETUNREACH;
5003 			else
5004 				error = EHOSTUNREACH;
5005 			goto bad_addr;
5006 		}
5007 		if (src_addr == INADDR_ANY)
5008 			src_addr = src_ire->ire_src_addr;
5009 		ire_refrele(src_ire);
5010 		src_ire = NULL;
5011 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5012 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5013 			src_addr = sire->ire_src_addr;
5014 			ire_refrele(dst_ire);
5015 			dst_ire = sire;
5016 			sire = NULL;
5017 		} else {
5018 			/*
5019 			 * Pick a source address so that a proper inbound
5020 			 * load spreading would happen.
5021 			 */
5022 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5023 			ipif_t *src_ipif = NULL;
5024 			ire_t *ipif_ire;
5025 
5026 			/*
5027 			 * Supply a local source address such that inbound
5028 			 * load spreading happens.
5029 			 *
5030 			 * Determine the best source address on this ill for
5031 			 * the destination.
5032 			 *
5033 			 * 1) For broadcast, we should return a broadcast ire
5034 			 *    found above so that upper layers know that the
5035 			 *    destination address is a broadcast address.
5036 			 *
5037 			 * 2) If the ipif is DEPRECATED, select a better
5038 			 *    source address.  Similarly, if the ipif is on
5039 			 *    the IPMP meta-interface, pick a source address
5040 			 *    at random to improve inbound load spreading.
5041 			 *
5042 			 * 3) If the outgoing interface is part of a usesrc
5043 			 *    group, then try selecting a source address from
5044 			 *    the usesrc ILL.
5045 			 */
5046 			if ((dst_ire->ire_zoneid != zoneid &&
5047 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5048 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5049 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5050 			    (IS_IPMP(ire_ill) ||
5051 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5052 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5053 				/*
5054 				 * If the destination is reachable via a
5055 				 * given gateway, the selected source address
5056 				 * should be in the same subnet as the gateway.
5057 				 * Otherwise, the destination is not reachable.
5058 				 *
5059 				 * If there are no interfaces on the same subnet
5060 				 * as the destination, ipif_select_source gives
5061 				 * first non-deprecated interface which might be
5062 				 * on a different subnet than the gateway.
5063 				 * This is not desirable. Hence pass the dst_ire
5064 				 * source address to ipif_select_source.
5065 				 * It is sure that the destination is reachable
5066 				 * with the dst_ire source address subnet.
5067 				 * So passing dst_ire source address to
5068 				 * ipif_select_source will make sure that the
5069 				 * selected source will be on the same subnet
5070 				 * as dst_ire source address.
5071 				 */
5072 				ipaddr_t saddr =
5073 				    dst_ire->ire_ipif->ipif_src_addr;
5074 				src_ipif = ipif_select_source(ire_ill,
5075 				    saddr, zoneid);
5076 				if (src_ipif != NULL) {
5077 					if (IS_VNI(src_ipif->ipif_ill)) {
5078 						/*
5079 						 * For VNI there is no
5080 						 * interface route
5081 						 */
5082 						src_addr =
5083 						    src_ipif->ipif_src_addr;
5084 					} else {
5085 						ipif_ire =
5086 						    ipif_to_ire(src_ipif);
5087 						if (ipif_ire != NULL) {
5088 							IRE_REFRELE(dst_ire);
5089 							dst_ire = ipif_ire;
5090 						}
5091 						src_addr =
5092 						    dst_ire->ire_src_addr;
5093 					}
5094 					ipif_refrele(src_ipif);
5095 				} else {
5096 					src_addr = dst_ire->ire_src_addr;
5097 				}
5098 			} else {
5099 				src_addr = dst_ire->ire_src_addr;
5100 			}
5101 		}
5102 	}
5103 
5104 	/*
5105 	 * We do ire_route_lookup() here (and not
5106 	 * interface lookup as we assert that
5107 	 * src_addr should only come from an
5108 	 * UP interface for hard binding.
5109 	 */
5110 	ASSERT(src_ire == NULL);
5111 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5112 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5113 	/* src_ire must be a local|loopback */
5114 	if (!IRE_IS_LOCAL(src_ire)) {
5115 		if (ip_debug > 2) {
5116 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5117 			    "src %s\n", AF_INET, &src_addr);
5118 		}
5119 		error = EADDRNOTAVAIL;
5120 		goto bad_addr;
5121 	}
5122 
5123 	/*
5124 	 * If the source address is a loopback address, the
5125 	 * destination had best be local or multicast.
5126 	 * The transports that can't handle multicast will reject
5127 	 * those addresses.
5128 	 */
5129 	if (src_ire->ire_type == IRE_LOOPBACK &&
5130 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5131 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5132 		error = -1;
5133 		goto bad_addr;
5134 	}
5135 
5136 	/*
5137 	 * Allow setting new policies. For example, disconnects come
5138 	 * down as ipa_t bind. As we would have set conn_policy_cached
5139 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5140 	 * can change after the disconnect.
5141 	 */
5142 	connp->conn_policy_cached = B_FALSE;
5143 
5144 	/*
5145 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5146 	 * can handle their passed-in conn's.
5147 	 */
5148 
5149 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5150 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5151 	connp->conn_lport = lport;
5152 	connp->conn_fport = fport;
5153 	*src_addrp = src_addr;
5154 
5155 	ASSERT(!(ipsec_policy_set && ire_requested));
5156 	if (ire_requested) {
5157 		iulp_t *ulp_info = NULL;
5158 
5159 		/*
5160 		 * Note that sire will not be NULL if this is an off-link
5161 		 * connection and there is not cache for that dest yet.
5162 		 *
5163 		 * XXX Because of an existing bug, if there are multiple
5164 		 * default routes, the IRE returned now may not be the actual
5165 		 * default route used (default routes are chosen in a
5166 		 * round robin fashion).  So if the metrics for different
5167 		 * default routes are different, we may return the wrong
5168 		 * metrics.  This will not be a problem if the existing
5169 		 * bug is fixed.
5170 		 */
5171 		if (sire != NULL) {
5172 			ulp_info = &(sire->ire_uinfo);
5173 		}
5174 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5175 			error = -1;
5176 			goto bad_addr;
5177 		}
5178 		mp = *mpp;
5179 	} else if (ipsec_policy_set) {
5180 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5181 			error = -1;
5182 			goto bad_addr;
5183 		}
5184 	}
5185 
5186 	/*
5187 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5188 	 * we'll cache that.  If we don't, we'll inherit global policy.
5189 	 *
5190 	 * We can't insert until the conn reflects the policy. Note that
5191 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5192 	 * connections where we don't have a policy. This is to prevent
5193 	 * global policy lookups in the inbound path.
5194 	 *
5195 	 * If we insert before we set conn_policy_cached,
5196 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5197 	 * because global policy cound be non-empty. We normally call
5198 	 * ipsec_check_policy() for conn_policy_cached connections only if
5199 	 * ipc_in_enforce_policy is set. But in this case,
5200 	 * conn_policy_cached can get set anytime since we made the
5201 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5202 	 * called, which will make the above assumption false.  Thus, we
5203 	 * need to insert after we set conn_policy_cached.
5204 	 */
5205 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5206 		goto bad_addr;
5207 
5208 	if (fanout_insert) {
5209 		/*
5210 		 * The addresses have been verified. Time to insert in
5211 		 * the correct fanout list.
5212 		 */
5213 		error = ipcl_conn_insert(connp, protocol, src_addr,
5214 		    dst_addr, connp->conn_ports);
5215 	}
5216 
5217 	if (error == 0) {
5218 		connp->conn_fully_bound = B_TRUE;
5219 		/*
5220 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5221 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5222 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5223 		 * ip_xxinfo_return(), which performs further checks
5224 		 * against them and upon success, returns the LSO/MDT info
5225 		 * mblk which we will attach to the bind acknowledgment.
5226 		 */
5227 		if (lso_dst_ire != NULL) {
5228 			mblk_t *lsoinfo_mp;
5229 
5230 			ASSERT(ill->ill_lso_capab != NULL);
5231 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5232 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5233 				if (mp == NULL) {
5234 					*mpp = lsoinfo_mp;
5235 				} else {
5236 					linkb(mp, lsoinfo_mp);
5237 				}
5238 			}
5239 		} else if (md_dst_ire != NULL) {
5240 			mblk_t *mdinfo_mp;
5241 
5242 			ASSERT(ill->ill_mdt_capab != NULL);
5243 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5244 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5245 				if (mp == NULL) {
5246 					*mpp = mdinfo_mp;
5247 				} else {
5248 					linkb(mp, mdinfo_mp);
5249 				}
5250 			}
5251 		}
5252 	}
5253 bad_addr:
5254 	if (ipsec_policy_set) {
5255 		ASSERT(mp != NULL);
5256 		freeb(mp);
5257 		/*
5258 		 * As of now assume that nothing else accompanies
5259 		 * IPSEC_POLICY_SET.
5260 		 */
5261 		*mpp = NULL;
5262 	}
5263 	if (src_ire != NULL)
5264 		IRE_REFRELE(src_ire);
5265 	if (dst_ire != NULL)
5266 		IRE_REFRELE(dst_ire);
5267 	if (sire != NULL)
5268 		IRE_REFRELE(sire);
5269 	if (md_dst_ire != NULL)
5270 		IRE_REFRELE(md_dst_ire);
5271 	if (lso_dst_ire != NULL)
5272 		IRE_REFRELE(lso_dst_ire);
5273 	return (error);
5274 }
5275 
5276 int
5277 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5278     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5279     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5280 {
5281 	int error;
5282 	mblk_t	*mp = NULL;
5283 	boolean_t ire_requested;
5284 
5285 	if (ire_mpp)
5286 		mp = *ire_mpp;
5287 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5288 
5289 	ASSERT(!connp->conn_af_isv6);
5290 	connp->conn_pkt_isv6 = B_FALSE;
5291 	connp->conn_ulp = protocol;
5292 
5293 	/* For raw socket, the local port is not set. */
5294 	if (lport == 0)
5295 		lport = connp->conn_lport;
5296 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5297 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5298 	if (error == 0) {
5299 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5300 		    ire_requested);
5301 	} else if (error < 0) {
5302 		error = -TBADADDR;
5303 	}
5304 	return (error);
5305 }
5306 
5307 /*
5308  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5309  * Prefers dst_ire over src_ire.
5310  */
5311 static boolean_t
5312 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5313 {
5314 	mblk_t	*mp = *mpp;
5315 	ire_t	*ret_ire;
5316 
5317 	ASSERT(mp != NULL);
5318 
5319 	if (ire != NULL) {
5320 		/*
5321 		 * mp initialized above to IRE_DB_REQ_TYPE
5322 		 * appended mblk. Its <upper protocol>'s
5323 		 * job to make sure there is room.
5324 		 */
5325 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5326 			return (B_FALSE);
5327 
5328 		mp->b_datap->db_type = IRE_DB_TYPE;
5329 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5330 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5331 		ret_ire = (ire_t *)mp->b_rptr;
5332 		/*
5333 		 * Pass the latest setting of the ip_path_mtu_discovery and
5334 		 * copy the ulp info if any.
5335 		 */
5336 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5337 		    IPH_DF : 0;
5338 		if (ulp_info != NULL) {
5339 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5340 			    sizeof (iulp_t));
5341 		}
5342 		ret_ire->ire_mp = mp;
5343 	} else {
5344 		/*
5345 		 * No IRE was found. Remove IRE mblk.
5346 		 */
5347 		*mpp = mp->b_cont;
5348 		freeb(mp);
5349 	}
5350 	return (B_TRUE);
5351 }
5352 
5353 /*
5354  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5355  * the final piece where we don't.  Return a pointer to the first mblk in the
5356  * result, and update the pointer to the next mblk to chew on.  If anything
5357  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5358  * NULL pointer.
5359  */
5360 mblk_t *
5361 ip_carve_mp(mblk_t **mpp, ssize_t len)
5362 {
5363 	mblk_t	*mp0;
5364 	mblk_t	*mp1;
5365 	mblk_t	*mp2;
5366 
5367 	if (!len || !mpp || !(mp0 = *mpp))
5368 		return (NULL);
5369 	/* If we aren't going to consume the first mblk, we need a dup. */
5370 	if (mp0->b_wptr - mp0->b_rptr > len) {
5371 		mp1 = dupb(mp0);
5372 		if (mp1) {
5373 			/* Partition the data between the two mblks. */
5374 			mp1->b_wptr = mp1->b_rptr + len;
5375 			mp0->b_rptr = mp1->b_wptr;
5376 			/*
5377 			 * after adjustments if mblk not consumed is now
5378 			 * unaligned, try to align it. If this fails free
5379 			 * all messages and let upper layer recover.
5380 			 */
5381 			if (!OK_32PTR(mp0->b_rptr)) {
5382 				if (!pullupmsg(mp0, -1)) {
5383 					freemsg(mp0);
5384 					freemsg(mp1);
5385 					*mpp = NULL;
5386 					return (NULL);
5387 				}
5388 			}
5389 		}
5390 		return (mp1);
5391 	}
5392 	/* Eat through as many mblks as we need to get len bytes. */
5393 	len -= mp0->b_wptr - mp0->b_rptr;
5394 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5395 		if (mp2->b_wptr - mp2->b_rptr > len) {
5396 			/*
5397 			 * We won't consume the entire last mblk.  Like
5398 			 * above, dup and partition it.
5399 			 */
5400 			mp1->b_cont = dupb(mp2);
5401 			mp1 = mp1->b_cont;
5402 			if (!mp1) {
5403 				/*
5404 				 * Trouble.  Rather than go to a lot of
5405 				 * trouble to clean up, we free the messages.
5406 				 * This won't be any worse than losing it on
5407 				 * the wire.
5408 				 */
5409 				freemsg(mp0);
5410 				freemsg(mp2);
5411 				*mpp = NULL;
5412 				return (NULL);
5413 			}
5414 			mp1->b_wptr = mp1->b_rptr + len;
5415 			mp2->b_rptr = mp1->b_wptr;
5416 			/*
5417 			 * after adjustments if mblk not consumed is now
5418 			 * unaligned, try to align it. If this fails free
5419 			 * all messages and let upper layer recover.
5420 			 */
5421 			if (!OK_32PTR(mp2->b_rptr)) {
5422 				if (!pullupmsg(mp2, -1)) {
5423 					freemsg(mp0);
5424 					freemsg(mp2);
5425 					*mpp = NULL;
5426 					return (NULL);
5427 				}
5428 			}
5429 			*mpp = mp2;
5430 			return (mp0);
5431 		}
5432 		/* Decrement len by the amount we just got. */
5433 		len -= mp2->b_wptr - mp2->b_rptr;
5434 	}
5435 	/*
5436 	 * len should be reduced to zero now.  If not our caller has
5437 	 * screwed up.
5438 	 */
5439 	if (len) {
5440 		/* Shouldn't happen! */
5441 		freemsg(mp0);
5442 		*mpp = NULL;
5443 		return (NULL);
5444 	}
5445 	/*
5446 	 * We consumed up to exactly the end of an mblk.  Detach the part
5447 	 * we are returning from the rest of the chain.
5448 	 */
5449 	mp1->b_cont = NULL;
5450 	*mpp = mp2;
5451 	return (mp0);
5452 }
5453 
5454 /* The ill stream is being unplumbed. Called from ip_close */
5455 int
5456 ip_modclose(ill_t *ill)
5457 {
5458 	boolean_t success;
5459 	ipsq_t	*ipsq;
5460 	ipif_t	*ipif;
5461 	queue_t	*q = ill->ill_rq;
5462 	ip_stack_t	*ipst = ill->ill_ipst;
5463 	int	i;
5464 
5465 	/*
5466 	 * The punlink prior to this may have initiated a capability
5467 	 * negotiation. But ipsq_enter will block until that finishes or
5468 	 * times out.
5469 	 */
5470 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5471 
5472 	/*
5473 	 * Open/close/push/pop is guaranteed to be single threaded
5474 	 * per stream by STREAMS. FS guarantees that all references
5475 	 * from top are gone before close is called. So there can't
5476 	 * be another close thread that has set CONDEMNED on this ill.
5477 	 * and cause ipsq_enter to return failure.
5478 	 */
5479 	ASSERT(success);
5480 	ipsq = ill->ill_phyint->phyint_ipsq;
5481 
5482 	/*
5483 	 * Mark it condemned. No new reference will be made to this ill.
5484 	 * Lookup functions will return an error. Threads that try to
5485 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5486 	 * that the refcnt will drop down to zero.
5487 	 */
5488 	mutex_enter(&ill->ill_lock);
5489 	ill->ill_state_flags |= ILL_CONDEMNED;
5490 	for (ipif = ill->ill_ipif; ipif != NULL;
5491 	    ipif = ipif->ipif_next) {
5492 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5493 	}
5494 	/*
5495 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5496 	 * returns  error if ILL_CONDEMNED is set
5497 	 */
5498 	cv_broadcast(&ill->ill_cv);
5499 	mutex_exit(&ill->ill_lock);
5500 
5501 	/*
5502 	 * Send all the deferred DLPI messages downstream which came in
5503 	 * during the small window right before ipsq_enter(). We do this
5504 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5505 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5506 	 */
5507 	ill_dlpi_send_deferred(ill);
5508 
5509 	/*
5510 	 * Shut down fragmentation reassembly.
5511 	 * ill_frag_timer won't start a timer again.
5512 	 * Now cancel any existing timer
5513 	 */
5514 	(void) untimeout(ill->ill_frag_timer_id);
5515 	(void) ill_frag_timeout(ill, 0);
5516 
5517 	/*
5518 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5519 	 * this ill. Then wait for the refcnts to drop to zero.
5520 	 * ill_is_freeable checks whether the ill is really quiescent.
5521 	 * Then make sure that threads that are waiting to enter the
5522 	 * ipsq have seen the error returned by ipsq_enter and have
5523 	 * gone away. Then we call ill_delete_tail which does the
5524 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5525 	 */
5526 	ill_delete(ill);
5527 	mutex_enter(&ill->ill_lock);
5528 	while (!ill_is_freeable(ill))
5529 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5530 	while (ill->ill_waiters)
5531 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5532 
5533 	mutex_exit(&ill->ill_lock);
5534 
5535 	/*
5536 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5537 	 * it held until the end of the function since the cleanup
5538 	 * below needs to be able to use the ip_stack_t.
5539 	 */
5540 	netstack_hold(ipst->ips_netstack);
5541 
5542 	/* qprocsoff is done via ill_delete_tail */
5543 	ill_delete_tail(ill);
5544 	ASSERT(ill->ill_ipst == NULL);
5545 
5546 	/*
5547 	 * Walk through all upper (conn) streams and qenable
5548 	 * those that have queued data.
5549 	 * close synchronization needs this to
5550 	 * be done to ensure that all upper layers blocked
5551 	 * due to flow control to the closing device
5552 	 * get unblocked.
5553 	 */
5554 	ip1dbg(("ip_wsrv: walking\n"));
5555 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5556 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5557 	}
5558 
5559 	mutex_enter(&ipst->ips_ip_mi_lock);
5560 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5561 	mutex_exit(&ipst->ips_ip_mi_lock);
5562 
5563 	/*
5564 	 * credp could be null if the open didn't succeed and ip_modopen
5565 	 * itself calls ip_close.
5566 	 */
5567 	if (ill->ill_credp != NULL)
5568 		crfree(ill->ill_credp);
5569 
5570 	/*
5571 	 * Now we are done with the module close pieces that
5572 	 * need the netstack_t.
5573 	 */
5574 	netstack_rele(ipst->ips_netstack);
5575 
5576 	mi_close_free((IDP)ill);
5577 	q->q_ptr = WR(q)->q_ptr = NULL;
5578 
5579 	ipsq_exit(ipsq);
5580 
5581 	return (0);
5582 }
5583 
5584 /*
5585  * This is called as part of close() for IP, UDP, ICMP, and RTS
5586  * in order to quiesce the conn.
5587  */
5588 void
5589 ip_quiesce_conn(conn_t *connp)
5590 {
5591 	boolean_t	drain_cleanup_reqd = B_FALSE;
5592 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5593 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5594 	ip_stack_t	*ipst;
5595 
5596 	ASSERT(!IPCL_IS_TCP(connp));
5597 	ipst = connp->conn_netstack->netstack_ip;
5598 
5599 	/*
5600 	 * Mark the conn as closing, and this conn must not be
5601 	 * inserted in future into any list. Eg. conn_drain_insert(),
5602 	 * won't insert this conn into the conn_drain_list.
5603 	 * Similarly ill_pending_mp_add() will not add any mp to
5604 	 * the pending mp list, after this conn has started closing.
5605 	 *
5606 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5607 	 * cannot get set henceforth.
5608 	 */
5609 	mutex_enter(&connp->conn_lock);
5610 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5611 	connp->conn_state_flags |= CONN_CLOSING;
5612 	if (connp->conn_idl != NULL)
5613 		drain_cleanup_reqd = B_TRUE;
5614 	if (connp->conn_oper_pending_ill != NULL)
5615 		conn_ioctl_cleanup_reqd = B_TRUE;
5616 	if (connp->conn_dhcpinit_ill != NULL) {
5617 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5618 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5619 		connp->conn_dhcpinit_ill = NULL;
5620 	}
5621 	if (connp->conn_ilg_inuse != 0)
5622 		ilg_cleanup_reqd = B_TRUE;
5623 	mutex_exit(&connp->conn_lock);
5624 
5625 	if (conn_ioctl_cleanup_reqd)
5626 		conn_ioctl_cleanup(connp);
5627 
5628 	if (is_system_labeled() && connp->conn_anon_port) {
5629 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5630 		    connp->conn_mlp_type, connp->conn_ulp,
5631 		    ntohs(connp->conn_lport), B_FALSE);
5632 		connp->conn_anon_port = 0;
5633 	}
5634 	connp->conn_mlp_type = mlptSingle;
5635 
5636 	/*
5637 	 * Remove this conn from any fanout list it is on.
5638 	 * and then wait for any threads currently operating
5639 	 * on this endpoint to finish
5640 	 */
5641 	ipcl_hash_remove(connp);
5642 
5643 	/*
5644 	 * Remove this conn from the drain list, and do
5645 	 * any other cleanup that may be required.
5646 	 * (Only non-tcp streams may have a non-null conn_idl.
5647 	 * TCP streams are never flow controlled, and
5648 	 * conn_idl will be null)
5649 	 */
5650 	if (drain_cleanup_reqd)
5651 		conn_drain_tail(connp, B_TRUE);
5652 
5653 	if (connp == ipst->ips_ip_g_mrouter)
5654 		(void) ip_mrouter_done(NULL, ipst);
5655 
5656 	if (ilg_cleanup_reqd)
5657 		ilg_delete_all(connp);
5658 
5659 	conn_delete_ire(connp, NULL);
5660 
5661 	/*
5662 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5663 	 * callers from write side can't be there now because close
5664 	 * is in progress. The only other caller is ipcl_walk
5665 	 * which checks for the condemned flag.
5666 	 */
5667 	mutex_enter(&connp->conn_lock);
5668 	connp->conn_state_flags |= CONN_CONDEMNED;
5669 	while (connp->conn_ref != 1)
5670 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5671 	connp->conn_state_flags |= CONN_QUIESCED;
5672 	mutex_exit(&connp->conn_lock);
5673 }
5674 
5675 /* ARGSUSED */
5676 int
5677 ip_close(queue_t *q, int flags)
5678 {
5679 	conn_t		*connp;
5680 
5681 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5682 
5683 	/*
5684 	 * Call the appropriate delete routine depending on whether this is
5685 	 * a module or device.
5686 	 */
5687 	if (WR(q)->q_next != NULL) {
5688 		/* This is a module close */
5689 		return (ip_modclose((ill_t *)q->q_ptr));
5690 	}
5691 
5692 	connp = q->q_ptr;
5693 	ip_quiesce_conn(connp);
5694 
5695 	qprocsoff(q);
5696 
5697 	/*
5698 	 * Now we are truly single threaded on this stream, and can
5699 	 * delete the things hanging off the connp, and finally the connp.
5700 	 * We removed this connp from the fanout list, it cannot be
5701 	 * accessed thru the fanouts, and we already waited for the
5702 	 * conn_ref to drop to 0. We are already in close, so
5703 	 * there cannot be any other thread from the top. qprocsoff
5704 	 * has completed, and service has completed or won't run in
5705 	 * future.
5706 	 */
5707 	ASSERT(connp->conn_ref == 1);
5708 
5709 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5710 
5711 	connp->conn_ref--;
5712 	ipcl_conn_destroy(connp);
5713 
5714 	q->q_ptr = WR(q)->q_ptr = NULL;
5715 	return (0);
5716 }
5717 
5718 /*
5719  * Wapper around putnext() so that ip_rts_request can merely use
5720  * conn_recv.
5721  */
5722 /*ARGSUSED2*/
5723 static void
5724 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5725 {
5726 	conn_t *connp = (conn_t *)arg1;
5727 
5728 	putnext(connp->conn_rq, mp);
5729 }
5730 
5731 /*
5732  * Called when the module is about to be unloaded
5733  */
5734 void
5735 ip_ddi_destroy(void)
5736 {
5737 	tnet_fini();
5738 
5739 	icmp_ddi_g_destroy();
5740 	rts_ddi_g_destroy();
5741 	udp_ddi_g_destroy();
5742 	sctp_ddi_g_destroy();
5743 	tcp_ddi_g_destroy();
5744 	ipsec_policy_g_destroy();
5745 	ipcl_g_destroy();
5746 	ip_net_g_destroy();
5747 	ip_ire_g_fini();
5748 	inet_minor_destroy(ip_minor_arena_sa);
5749 #if defined(_LP64)
5750 	inet_minor_destroy(ip_minor_arena_la);
5751 #endif
5752 
5753 #ifdef DEBUG
5754 	list_destroy(&ip_thread_list);
5755 	rw_destroy(&ip_thread_rwlock);
5756 	tsd_destroy(&ip_thread_data);
5757 #endif
5758 
5759 	netstack_unregister(NS_IP);
5760 }
5761 
5762 /*
5763  * First step in cleanup.
5764  */
5765 /* ARGSUSED */
5766 static void
5767 ip_stack_shutdown(netstackid_t stackid, void *arg)
5768 {
5769 	ip_stack_t *ipst = (ip_stack_t *)arg;
5770 
5771 #ifdef NS_DEBUG
5772 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5773 #endif
5774 
5775 	/* Get rid of loopback interfaces and their IREs */
5776 	ip_loopback_cleanup(ipst);
5777 
5778 	/*
5779 	 * The *_hook_shutdown()s start the process of notifying any
5780 	 * consumers that things are going away.... nothing is destroyed.
5781 	 */
5782 	ipv4_hook_shutdown(ipst);
5783 	ipv6_hook_shutdown(ipst);
5784 
5785 	mutex_enter(&ipst->ips_capab_taskq_lock);
5786 	ipst->ips_capab_taskq_quit = B_TRUE;
5787 	cv_signal(&ipst->ips_capab_taskq_cv);
5788 	mutex_exit(&ipst->ips_capab_taskq_lock);
5789 
5790 	mutex_enter(&ipst->ips_mrt_lock);
5791 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5792 	cv_signal(&ipst->ips_mrt_cv);
5793 	mutex_exit(&ipst->ips_mrt_lock);
5794 }
5795 
5796 /*
5797  * Free the IP stack instance.
5798  */
5799 static void
5800 ip_stack_fini(netstackid_t stackid, void *arg)
5801 {
5802 	ip_stack_t *ipst = (ip_stack_t *)arg;
5803 	int ret;
5804 
5805 #ifdef NS_DEBUG
5806 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5807 #endif
5808 	/*
5809 	 * At this point, all of the notifications that the events and
5810 	 * protocols are going away have been run, meaning that we can
5811 	 * now set about starting to clean things up.
5812 	 */
5813 	ipv4_hook_destroy(ipst);
5814 	ipv6_hook_destroy(ipst);
5815 	ip_net_destroy(ipst);
5816 
5817 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5818 	cv_destroy(&ipst->ips_capab_taskq_cv);
5819 	list_destroy(&ipst->ips_capab_taskq_list);
5820 
5821 	mutex_enter(&ipst->ips_mrt_lock);
5822 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5823 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5824 	mutex_destroy(&ipst->ips_mrt_lock);
5825 	cv_destroy(&ipst->ips_mrt_cv);
5826 	cv_destroy(&ipst->ips_mrt_done_cv);
5827 
5828 	ipmp_destroy(ipst);
5829 	rw_destroy(&ipst->ips_srcid_lock);
5830 
5831 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5832 	ipst->ips_ip_mibkp = NULL;
5833 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5834 	ipst->ips_icmp_mibkp = NULL;
5835 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5836 	ipst->ips_ip_kstat = NULL;
5837 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5838 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5839 	ipst->ips_ip6_kstat = NULL;
5840 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5841 
5842 	nd_free(&ipst->ips_ip_g_nd);
5843 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5844 	ipst->ips_param_arr = NULL;
5845 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5846 	ipst->ips_ndp_arr = NULL;
5847 
5848 	ip_mrouter_stack_destroy(ipst);
5849 
5850 	mutex_destroy(&ipst->ips_ip_mi_lock);
5851 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5852 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5853 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5854 
5855 	ret = untimeout(ipst->ips_igmp_timeout_id);
5856 	if (ret == -1) {
5857 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5858 	} else {
5859 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5860 		ipst->ips_igmp_timeout_id = 0;
5861 	}
5862 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5867 		ipst->ips_igmp_slowtimeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_mld_timeout_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_mld_timeout_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_mld_timeout_id != 0);
5874 		ipst->ips_mld_timeout_id = 0;
5875 	}
5876 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5877 	if (ret == -1) {
5878 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5879 	} else {
5880 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5881 		ipst->ips_mld_slowtimeout_id = 0;
5882 	}
5883 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5884 	if (ret == -1) {
5885 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5886 	} else {
5887 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5888 		ipst->ips_ip_ire_expire_id = 0;
5889 	}
5890 
5891 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5892 	mutex_destroy(&ipst->ips_mld_timer_lock);
5893 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5894 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5895 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5896 	rw_destroy(&ipst->ips_ill_g_lock);
5897 
5898 	ipobs_fini(ipst);
5899 	ip_ire_fini(ipst);
5900 	ip6_asp_free(ipst);
5901 	conn_drain_fini(ipst);
5902 	ipcl_destroy(ipst);
5903 
5904 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5905 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5906 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5907 	ipst->ips_ndp4 = NULL;
5908 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5909 	ipst->ips_ndp6 = NULL;
5910 
5911 	if (ipst->ips_loopback_ksp != NULL) {
5912 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5913 		ipst->ips_loopback_ksp = NULL;
5914 	}
5915 
5916 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5917 	ipst->ips_phyint_g_list = NULL;
5918 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5919 	ipst->ips_ill_g_heads = NULL;
5920 
5921 	ldi_ident_release(ipst->ips_ldi_ident);
5922 	kmem_free(ipst, sizeof (*ipst));
5923 }
5924 
5925 /*
5926  * This function is called from the TSD destructor, and is used to debug
5927  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5928  * details.
5929  */
5930 static void
5931 ip_thread_exit(void *phash)
5932 {
5933 	th_hash_t *thh = phash;
5934 
5935 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5936 	list_remove(&ip_thread_list, thh);
5937 	rw_exit(&ip_thread_rwlock);
5938 	mod_hash_destroy_hash(thh->thh_hash);
5939 	kmem_free(thh, sizeof (*thh));
5940 }
5941 
5942 /*
5943  * Called when the IP kernel module is loaded into the kernel
5944  */
5945 void
5946 ip_ddi_init(void)
5947 {
5948 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5949 
5950 	/*
5951 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5952 	 * initial devices: ip, ip6, tcp, tcp6.
5953 	 */
5954 	/*
5955 	 * If this is a 64-bit kernel, then create two separate arenas -
5956 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5957 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5958 	 */
5959 	ip_minor_arena_la = NULL;
5960 	ip_minor_arena_sa = NULL;
5961 #if defined(_LP64)
5962 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5963 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5964 		cmn_err(CE_PANIC,
5965 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5966 	}
5967 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5968 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5969 		cmn_err(CE_PANIC,
5970 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5971 	}
5972 #else
5973 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5974 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5975 		cmn_err(CE_PANIC,
5976 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5977 	}
5978 #endif
5979 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5980 
5981 	ipcl_g_init();
5982 	ip_ire_g_init();
5983 	ip_net_g_init();
5984 
5985 #ifdef DEBUG
5986 	tsd_create(&ip_thread_data, ip_thread_exit);
5987 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5988 	list_create(&ip_thread_list, sizeof (th_hash_t),
5989 	    offsetof(th_hash_t, thh_link));
5990 #endif
5991 
5992 	/*
5993 	 * We want to be informed each time a stack is created or
5994 	 * destroyed in the kernel, so we can maintain the
5995 	 * set of udp_stack_t's.
5996 	 */
5997 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5998 	    ip_stack_fini);
5999 
6000 	ipsec_policy_g_init();
6001 	tcp_ddi_g_init();
6002 	sctp_ddi_g_init();
6003 
6004 	tnet_init();
6005 
6006 	udp_ddi_g_init();
6007 	rts_ddi_g_init();
6008 	icmp_ddi_g_init();
6009 }
6010 
6011 /*
6012  * Initialize the IP stack instance.
6013  */
6014 static void *
6015 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6016 {
6017 	ip_stack_t	*ipst;
6018 	ipparam_t	*pa;
6019 	ipndp_t		*na;
6020 	major_t		major;
6021 
6022 #ifdef NS_DEBUG
6023 	printf("ip_stack_init(stack %d)\n", stackid);
6024 #endif
6025 
6026 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6027 	ipst->ips_netstack = ns;
6028 
6029 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6030 	    KM_SLEEP);
6031 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6032 	    KM_SLEEP);
6033 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6034 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6035 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6036 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6037 
6038 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6039 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6040 	ipst->ips_igmp_deferred_next = INFINITY;
6041 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6042 	ipst->ips_mld_deferred_next = INFINITY;
6043 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6044 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6045 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6046 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6048 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6049 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6050 
6051 	ipcl_init(ipst);
6052 	ip_ire_init(ipst);
6053 	ip6_asp_init(ipst);
6054 	ipif_init(ipst);
6055 	conn_drain_init(ipst);
6056 	ip_mrouter_stack_init(ipst);
6057 
6058 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6059 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6060 
6061 	ipst->ips_ip_multirt_log_interval = 1000;
6062 
6063 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6064 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6065 	ipst->ips_ill_index = 1;
6066 
6067 	ipst->ips_saved_ip_g_forward = -1;
6068 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6069 
6070 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6071 	ipst->ips_param_arr = pa;
6072 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6073 
6074 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6075 	ipst->ips_ndp_arr = na;
6076 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6077 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6078 	    (caddr_t)&ipst->ips_ip_g_forward;
6079 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6080 	    (caddr_t)&ipst->ips_ipv6_forward;
6081 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6082 	    "ip_cgtp_filter") == 0);
6083 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6084 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6085 
6086 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6087 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6088 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6089 
6090 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6091 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6092 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6093 	ipst->ips_ip6_kstat =
6094 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6095 
6096 	ipst->ips_ip_src_id = 1;
6097 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6098 
6099 	ipobs_init(ipst);
6100 	ip_net_init(ipst, ns);
6101 	ipv4_hook_init(ipst);
6102 	ipv6_hook_init(ipst);
6103 	ipmp_init(ipst);
6104 
6105 	/*
6106 	 * Create the taskq dispatcher thread and initialize related stuff.
6107 	 */
6108 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6109 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6110 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6111 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6112 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6113 	    offsetof(mblk_t, b_next));
6114 
6115 	/*
6116 	 * Create the mcast_restart_timers_thread() worker thread.
6117 	 */
6118 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6119 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6120 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6121 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6122 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6123 
6124 	major = mod_name_to_major(INET_NAME);
6125 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6126 	return (ipst);
6127 }
6128 
6129 /*
6130  * Allocate and initialize a DLPI template of the specified length.  (May be
6131  * called as writer.)
6132  */
6133 mblk_t *
6134 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6135 {
6136 	mblk_t	*mp;
6137 
6138 	mp = allocb(len, BPRI_MED);
6139 	if (!mp)
6140 		return (NULL);
6141 
6142 	/*
6143 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6144 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6145 	 * that other DLPI are M_PROTO.
6146 	 */
6147 	if (prim == DL_INFO_REQ) {
6148 		mp->b_datap->db_type = M_PCPROTO;
6149 	} else {
6150 		mp->b_datap->db_type = M_PROTO;
6151 	}
6152 
6153 	mp->b_wptr = mp->b_rptr + len;
6154 	bzero(mp->b_rptr, len);
6155 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6156 	return (mp);
6157 }
6158 
6159 /*
6160  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6161  */
6162 mblk_t *
6163 ip_dlnotify_alloc(uint_t notification, uint_t data)
6164 {
6165 	dl_notify_ind_t	*notifyp;
6166 	mblk_t		*mp;
6167 
6168 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6169 		return (NULL);
6170 
6171 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6172 	notifyp->dl_notification = notification;
6173 	notifyp->dl_data = data;
6174 	return (mp);
6175 }
6176 
6177 /*
6178  * Debug formatting routine.  Returns a character string representation of the
6179  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6180  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6181  *
6182  * Once the ndd table-printing interfaces are removed, this can be changed to
6183  * standard dotted-decimal form.
6184  */
6185 char *
6186 ip_dot_addr(ipaddr_t addr, char *buf)
6187 {
6188 	uint8_t *ap = (uint8_t *)&addr;
6189 
6190 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6191 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6192 	return (buf);
6193 }
6194 
6195 /*
6196  * Write the given MAC address as a printable string in the usual colon-
6197  * separated format.
6198  */
6199 const char *
6200 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6201 {
6202 	char *bp;
6203 
6204 	if (alen == 0 || buflen < 4)
6205 		return ("?");
6206 	bp = buf;
6207 	for (;;) {
6208 		/*
6209 		 * If there are more MAC address bytes available, but we won't
6210 		 * have any room to print them, then add "..." to the string
6211 		 * instead.  See below for the 'magic number' explanation.
6212 		 */
6213 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6214 			(void) strcpy(bp, "...");
6215 			break;
6216 		}
6217 		(void) sprintf(bp, "%02x", *addr++);
6218 		bp += 2;
6219 		if (--alen == 0)
6220 			break;
6221 		*bp++ = ':';
6222 		buflen -= 3;
6223 		/*
6224 		 * At this point, based on the first 'if' statement above,
6225 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6226 		 * buflen >= 4.  The first case leaves room for the final "xx"
6227 		 * number and trailing NUL byte.  The second leaves room for at
6228 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6229 		 * that statement.
6230 		 */
6231 	}
6232 	return (buf);
6233 }
6234 
6235 /*
6236  * Send an ICMP error after patching up the packet appropriately.  Returns
6237  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6238  */
6239 static boolean_t
6240 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6241     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6242     zoneid_t zoneid, ip_stack_t *ipst)
6243 {
6244 	ipha_t *ipha;
6245 	mblk_t *first_mp;
6246 	boolean_t secure;
6247 	unsigned char db_type;
6248 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6249 
6250 	first_mp = mp;
6251 	if (mctl_present) {
6252 		mp = mp->b_cont;
6253 		secure = ipsec_in_is_secure(first_mp);
6254 		ASSERT(mp != NULL);
6255 	} else {
6256 		/*
6257 		 * If this is an ICMP error being reported - which goes
6258 		 * up as M_CTLs, we need to convert them to M_DATA till
6259 		 * we finish checking with global policy because
6260 		 * ipsec_check_global_policy() assumes M_DATA as clear
6261 		 * and M_CTL as secure.
6262 		 */
6263 		db_type = DB_TYPE(mp);
6264 		DB_TYPE(mp) = M_DATA;
6265 		secure = B_FALSE;
6266 	}
6267 	/*
6268 	 * We are generating an icmp error for some inbound packet.
6269 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6270 	 * Before we generate an error, check with global policy
6271 	 * to see whether this is allowed to enter the system. As
6272 	 * there is no "conn", we are checking with global policy.
6273 	 */
6274 	ipha = (ipha_t *)mp->b_rptr;
6275 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6276 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6277 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6278 		if (first_mp == NULL)
6279 			return (B_FALSE);
6280 	}
6281 
6282 	if (!mctl_present)
6283 		DB_TYPE(mp) = db_type;
6284 
6285 	if (flags & IP_FF_SEND_ICMP) {
6286 		if (flags & IP_FF_HDR_COMPLETE) {
6287 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6288 				freemsg(first_mp);
6289 				return (B_TRUE);
6290 			}
6291 		}
6292 		if (flags & IP_FF_CKSUM) {
6293 			/*
6294 			 * Have to correct checksum since
6295 			 * the packet might have been
6296 			 * fragmented and the reassembly code in ip_rput
6297 			 * does not restore the IP checksum.
6298 			 */
6299 			ipha->ipha_hdr_checksum = 0;
6300 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6301 		}
6302 		switch (icmp_type) {
6303 		case ICMP_DEST_UNREACHABLE:
6304 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6305 			    ipst);
6306 			break;
6307 		default:
6308 			freemsg(first_mp);
6309 			break;
6310 		}
6311 	} else {
6312 		freemsg(first_mp);
6313 		return (B_FALSE);
6314 	}
6315 
6316 	return (B_TRUE);
6317 }
6318 
6319 /*
6320  * Used to send an ICMP error message when a packet is received for
6321  * a protocol that is not supported. The mblk passed as argument
6322  * is consumed by this function.
6323  */
6324 void
6325 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6326     ip_stack_t *ipst)
6327 {
6328 	mblk_t *mp;
6329 	ipha_t *ipha;
6330 	ill_t *ill;
6331 	ipsec_in_t *ii;
6332 
6333 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6334 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6335 
6336 	mp = ipsec_mp->b_cont;
6337 	ipsec_mp->b_cont = NULL;
6338 	ipha = (ipha_t *)mp->b_rptr;
6339 	/* Get ill from index in ipsec_in_t. */
6340 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6341 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6342 	    ipst);
6343 	if (ill != NULL) {
6344 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6345 			if (ip_fanout_send_icmp(q, mp, flags,
6346 			    ICMP_DEST_UNREACHABLE,
6347 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6348 				BUMP_MIB(ill->ill_ip_mib,
6349 				    ipIfStatsInUnknownProtos);
6350 			}
6351 		} else {
6352 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6353 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6354 			    0, B_FALSE, zoneid, ipst)) {
6355 				BUMP_MIB(ill->ill_ip_mib,
6356 				    ipIfStatsInUnknownProtos);
6357 			}
6358 		}
6359 		ill_refrele(ill);
6360 	} else { /* re-link for the freemsg() below. */
6361 		ipsec_mp->b_cont = mp;
6362 	}
6363 
6364 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6365 	freemsg(ipsec_mp);
6366 }
6367 
6368 /*
6369  * See if the inbound datagram has had IPsec processing applied to it.
6370  */
6371 boolean_t
6372 ipsec_in_is_secure(mblk_t *ipsec_mp)
6373 {
6374 	ipsec_in_t *ii;
6375 
6376 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6377 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6378 
6379 	if (ii->ipsec_in_loopback) {
6380 		return (ii->ipsec_in_secure);
6381 	} else {
6382 		return (ii->ipsec_in_ah_sa != NULL ||
6383 		    ii->ipsec_in_esp_sa != NULL ||
6384 		    ii->ipsec_in_decaps);
6385 	}
6386 }
6387 
6388 /*
6389  * Handle protocols with which IP is less intimate.  There
6390  * can be more than one stream bound to a particular
6391  * protocol.  When this is the case, normally each one gets a copy
6392  * of any incoming packets.
6393  *
6394  * IPsec NOTE :
6395  *
6396  * Don't allow a secure packet going up a non-secure connection.
6397  * We don't allow this because
6398  *
6399  * 1) Reply might go out in clear which will be dropped at
6400  *    the sending side.
6401  * 2) If the reply goes out in clear it will give the
6402  *    adversary enough information for getting the key in
6403  *    most of the cases.
6404  *
6405  * Moreover getting a secure packet when we expect clear
6406  * implies that SA's were added without checking for
6407  * policy on both ends. This should not happen once ISAKMP
6408  * is used to negotiate SAs as SAs will be added only after
6409  * verifying the policy.
6410  *
6411  * NOTE : If the packet was tunneled and not multicast we only send
6412  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6413  * back to delivering packets to AF_INET6 raw sockets.
6414  *
6415  * IPQoS Notes:
6416  * Once we have determined the client, invoke IPPF processing.
6417  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6418  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6419  * ip_policy will be false.
6420  *
6421  * Zones notes:
6422  * Currently only applications in the global zone can create raw sockets for
6423  * protocols other than ICMP. So unlike the broadcast / multicast case of
6424  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6425  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6426  */
6427 static void
6428 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6429     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6430     zoneid_t zoneid)
6431 {
6432 	queue_t	*rq;
6433 	mblk_t	*mp1, *first_mp1;
6434 	uint_t	protocol = ipha->ipha_protocol;
6435 	ipaddr_t dst;
6436 	boolean_t one_only;
6437 	mblk_t *first_mp = mp;
6438 	boolean_t secure;
6439 	uint32_t ill_index;
6440 	conn_t	*connp, *first_connp, *next_connp;
6441 	connf_t	*connfp;
6442 	boolean_t shared_addr;
6443 	mib2_ipIfStatsEntry_t *mibptr;
6444 	ip_stack_t *ipst = recv_ill->ill_ipst;
6445 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6446 
6447 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6448 	if (mctl_present) {
6449 		mp = first_mp->b_cont;
6450 		secure = ipsec_in_is_secure(first_mp);
6451 		ASSERT(mp != NULL);
6452 	} else {
6453 		secure = B_FALSE;
6454 	}
6455 	dst = ipha->ipha_dst;
6456 	/*
6457 	 * If the packet was tunneled and not multicast we only send to it
6458 	 * the first match.
6459 	 */
6460 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6461 	    !CLASSD(dst));
6462 
6463 	shared_addr = (zoneid == ALL_ZONES);
6464 	if (shared_addr) {
6465 		/*
6466 		 * We don't allow multilevel ports for raw IP, so no need to
6467 		 * check for that here.
6468 		 */
6469 		zoneid = tsol_packet_to_zoneid(mp);
6470 	}
6471 
6472 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6473 	mutex_enter(&connfp->connf_lock);
6474 	connp = connfp->connf_head;
6475 	for (connp = connfp->connf_head; connp != NULL;
6476 	    connp = connp->conn_next) {
6477 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6478 		    zoneid) &&
6479 		    (!is_system_labeled() ||
6480 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6481 		    connp))) {
6482 			break;
6483 		}
6484 	}
6485 
6486 	if (connp == NULL) {
6487 		/*
6488 		 * No one bound to these addresses.  Is
6489 		 * there a client that wants all
6490 		 * unclaimed datagrams?
6491 		 */
6492 		mutex_exit(&connfp->connf_lock);
6493 		/*
6494 		 * Check for IPPROTO_ENCAP...
6495 		 */
6496 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6497 			/*
6498 			 * If an IPsec mblk is here on a multicast
6499 			 * tunnel (using ip_mroute stuff), check policy here,
6500 			 * THEN ship off to ip_mroute_decap().
6501 			 *
6502 			 * BTW,  If I match a configured IP-in-IP
6503 			 * tunnel, this path will not be reached, and
6504 			 * ip_mroute_decap will never be called.
6505 			 */
6506 			first_mp = ipsec_check_global_policy(first_mp, connp,
6507 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6508 			if (first_mp != NULL) {
6509 				if (mctl_present)
6510 					freeb(first_mp);
6511 				ip_mroute_decap(q, mp, ill);
6512 			} /* Else we already freed everything! */
6513 		} else {
6514 			/*
6515 			 * Otherwise send an ICMP protocol unreachable.
6516 			 */
6517 			if (ip_fanout_send_icmp(q, first_mp, flags,
6518 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6519 			    mctl_present, zoneid, ipst)) {
6520 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6521 			}
6522 		}
6523 		return;
6524 	}
6525 
6526 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6527 
6528 	CONN_INC_REF(connp);
6529 	first_connp = connp;
6530 
6531 	/*
6532 	 * Only send message to one tunnel driver by immediately
6533 	 * terminating the loop.
6534 	 */
6535 	connp = one_only ? NULL : connp->conn_next;
6536 
6537 	for (;;) {
6538 		while (connp != NULL) {
6539 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6540 			    flags, zoneid) &&
6541 			    (!is_system_labeled() ||
6542 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6543 			    shared_addr, connp)))
6544 				break;
6545 			connp = connp->conn_next;
6546 		}
6547 
6548 		/*
6549 		 * Copy the packet.
6550 		 */
6551 		if (connp == NULL ||
6552 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6553 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6554 			/*
6555 			 * No more interested clients or memory
6556 			 * allocation failed
6557 			 */
6558 			connp = first_connp;
6559 			break;
6560 		}
6561 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6562 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6563 		CONN_INC_REF(connp);
6564 		mutex_exit(&connfp->connf_lock);
6565 		rq = connp->conn_rq;
6566 
6567 		/*
6568 		 * Check flow control
6569 		 */
6570 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6571 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6572 			if (flags & IP_FF_RAWIP) {
6573 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6574 			} else {
6575 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6576 			}
6577 
6578 			freemsg(first_mp1);
6579 		} else {
6580 			/*
6581 			 * Don't enforce here if we're an actual tunnel -
6582 			 * let "tun" do it instead.
6583 			 */
6584 			if (!IPCL_IS_IPTUN(connp) &&
6585 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6586 			    secure)) {
6587 				first_mp1 = ipsec_check_inbound_policy
6588 				    (first_mp1, connp, ipha, NULL,
6589 				    mctl_present);
6590 			}
6591 			if (first_mp1 != NULL) {
6592 				int in_flags = 0;
6593 				/*
6594 				 * ip_fanout_proto also gets called from
6595 				 * icmp_inbound_error_fanout, in which case
6596 				 * the msg type is M_CTL.  Don't add info
6597 				 * in this case for the time being. In future
6598 				 * when there is a need for knowing the
6599 				 * inbound iface index for ICMP error msgs,
6600 				 * then this can be changed.
6601 				 */
6602 				if (connp->conn_recvif)
6603 					in_flags = IPF_RECVIF;
6604 				/*
6605 				 * The ULP may support IP_RECVPKTINFO for both
6606 				 * IP v4 and v6 so pass the appropriate argument
6607 				 * based on conn IP version.
6608 				 */
6609 				if (connp->conn_ip_recvpktinfo) {
6610 					if (connp->conn_af_isv6) {
6611 						/*
6612 						 * V6 only needs index
6613 						 */
6614 						in_flags |= IPF_RECVIF;
6615 					} else {
6616 						/*
6617 						 * V4 needs index +
6618 						 * matching address.
6619 						 */
6620 						in_flags |= IPF_RECVADDR;
6621 					}
6622 				}
6623 				if ((in_flags != 0) &&
6624 				    (mp->b_datap->db_type != M_CTL)) {
6625 					/*
6626 					 * the actual data will be
6627 					 * contained in b_cont upon
6628 					 * successful return of the
6629 					 * following call else
6630 					 * original mblk is returned
6631 					 */
6632 					ASSERT(recv_ill != NULL);
6633 					mp1 = ip_add_info(mp1, recv_ill,
6634 					    in_flags, IPCL_ZONEID(connp), ipst);
6635 				}
6636 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6637 				if (mctl_present)
6638 					freeb(first_mp1);
6639 				(connp->conn_recv)(connp, mp1, NULL);
6640 			}
6641 		}
6642 		mutex_enter(&connfp->connf_lock);
6643 		/* Follow the next pointer before releasing the conn. */
6644 		next_connp = connp->conn_next;
6645 		CONN_DEC_REF(connp);
6646 		connp = next_connp;
6647 	}
6648 
6649 	/* Last one.  Send it upstream. */
6650 	mutex_exit(&connfp->connf_lock);
6651 
6652 	/*
6653 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6654 	 * will be set to false.
6655 	 */
6656 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6657 		ill_index = ill->ill_phyint->phyint_ifindex;
6658 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6659 		if (mp == NULL) {
6660 			CONN_DEC_REF(connp);
6661 			if (mctl_present) {
6662 				freeb(first_mp);
6663 			}
6664 			return;
6665 		}
6666 	}
6667 
6668 	rq = connp->conn_rq;
6669 	/*
6670 	 * Check flow control
6671 	 */
6672 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6673 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6674 		if (flags & IP_FF_RAWIP) {
6675 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6676 		} else {
6677 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6678 		}
6679 
6680 		freemsg(first_mp);
6681 	} else {
6682 		if (IPCL_IS_IPTUN(connp)) {
6683 			/*
6684 			 * Tunneled packet.  We enforce policy in the tunnel
6685 			 * module itself.
6686 			 *
6687 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6688 			 * a policy check.
6689 			 * FIXME to use conn_recv for tun later.
6690 			 */
6691 			putnext(rq, first_mp);
6692 			CONN_DEC_REF(connp);
6693 			return;
6694 		}
6695 
6696 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6697 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6698 			    ipha, NULL, mctl_present);
6699 		}
6700 
6701 		if (first_mp != NULL) {
6702 			int in_flags = 0;
6703 
6704 			/*
6705 			 * ip_fanout_proto also gets called
6706 			 * from icmp_inbound_error_fanout, in
6707 			 * which case the msg type is M_CTL.
6708 			 * Don't add info in this case for time
6709 			 * being. In future when there is a
6710 			 * need for knowing the inbound iface
6711 			 * index for ICMP error msgs, then this
6712 			 * can be changed
6713 			 */
6714 			if (connp->conn_recvif)
6715 				in_flags = IPF_RECVIF;
6716 			if (connp->conn_ip_recvpktinfo) {
6717 				if (connp->conn_af_isv6) {
6718 					/*
6719 					 * V6 only needs index
6720 					 */
6721 					in_flags |= IPF_RECVIF;
6722 				} else {
6723 					/*
6724 					 * V4 needs index +
6725 					 * matching address.
6726 					 */
6727 					in_flags |= IPF_RECVADDR;
6728 				}
6729 			}
6730 			if ((in_flags != 0) &&
6731 			    (mp->b_datap->db_type != M_CTL)) {
6732 
6733 				/*
6734 				 * the actual data will be contained in
6735 				 * b_cont upon successful return
6736 				 * of the following call else original
6737 				 * mblk is returned
6738 				 */
6739 				ASSERT(recv_ill != NULL);
6740 				mp = ip_add_info(mp, recv_ill,
6741 				    in_flags, IPCL_ZONEID(connp), ipst);
6742 			}
6743 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6744 			(connp->conn_recv)(connp, mp, NULL);
6745 			if (mctl_present)
6746 				freeb(first_mp);
6747 		}
6748 	}
6749 	CONN_DEC_REF(connp);
6750 }
6751 
6752 /*
6753  * Fanout for TCP packets
6754  * The caller puts <fport, lport> in the ports parameter.
6755  *
6756  * IPQoS Notes
6757  * Before sending it to the client, invoke IPPF processing.
6758  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6759  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6760  * ip_policy is false.
6761  */
6762 static void
6763 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6764     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6765 {
6766 	mblk_t  *first_mp;
6767 	boolean_t secure;
6768 	uint32_t ill_index;
6769 	int	ip_hdr_len;
6770 	tcph_t	*tcph;
6771 	boolean_t syn_present = B_FALSE;
6772 	conn_t	*connp;
6773 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6774 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6775 
6776 	ASSERT(recv_ill != NULL);
6777 
6778 	first_mp = mp;
6779 	if (mctl_present) {
6780 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6781 		mp = first_mp->b_cont;
6782 		secure = ipsec_in_is_secure(first_mp);
6783 		ASSERT(mp != NULL);
6784 	} else {
6785 		secure = B_FALSE;
6786 	}
6787 
6788 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6789 
6790 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6791 	    zoneid, ipst)) == NULL) {
6792 		/*
6793 		 * No connected connection or listener. Send a
6794 		 * TH_RST via tcp_xmit_listeners_reset.
6795 		 */
6796 
6797 		/* Initiate IPPf processing, if needed. */
6798 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6799 			uint32_t ill_index;
6800 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6801 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6802 			if (first_mp == NULL)
6803 				return;
6804 		}
6805 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6806 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6807 		    zoneid));
6808 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6809 		    ipst->ips_netstack->netstack_tcp, NULL);
6810 		return;
6811 	}
6812 
6813 	/*
6814 	 * Allocate the SYN for the TCP connection here itself
6815 	 */
6816 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6817 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6818 		if (IPCL_IS_TCP(connp)) {
6819 			squeue_t *sqp;
6820 
6821 			/*
6822 			 * For fused tcp loopback, assign the eager's
6823 			 * squeue to be that of the active connect's.
6824 			 * Note that we don't check for IP_FF_LOOPBACK
6825 			 * here since this routine gets called only
6826 			 * for loopback (unlike the IPv6 counterpart).
6827 			 */
6828 			ASSERT(Q_TO_CONN(q) != NULL);
6829 			if (do_tcp_fusion &&
6830 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6831 			    !secure &&
6832 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6833 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6834 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6835 				sqp = Q_TO_CONN(q)->conn_sqp;
6836 			} else {
6837 				sqp = IP_SQUEUE_GET(lbolt);
6838 			}
6839 
6840 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6841 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6842 			syn_present = B_TRUE;
6843 		}
6844 	}
6845 
6846 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6847 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6848 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6849 		if ((flags & TH_RST) || (flags & TH_URG)) {
6850 			CONN_DEC_REF(connp);
6851 			freemsg(first_mp);
6852 			return;
6853 		}
6854 		if (flags & TH_ACK) {
6855 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6856 			    ipst->ips_netstack->netstack_tcp, connp);
6857 			CONN_DEC_REF(connp);
6858 			return;
6859 		}
6860 
6861 		CONN_DEC_REF(connp);
6862 		freemsg(first_mp);
6863 		return;
6864 	}
6865 
6866 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6867 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6868 		    NULL, mctl_present);
6869 		if (first_mp == NULL) {
6870 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6871 			CONN_DEC_REF(connp);
6872 			return;
6873 		}
6874 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6875 			ASSERT(syn_present);
6876 			if (mctl_present) {
6877 				ASSERT(first_mp != mp);
6878 				first_mp->b_datap->db_struioflag |=
6879 				    STRUIO_POLICY;
6880 			} else {
6881 				ASSERT(first_mp == mp);
6882 				mp->b_datap->db_struioflag &=
6883 				    ~STRUIO_EAGER;
6884 				mp->b_datap->db_struioflag |=
6885 				    STRUIO_POLICY;
6886 			}
6887 		} else {
6888 			/*
6889 			 * Discard first_mp early since we're dealing with a
6890 			 * fully-connected conn_t and tcp doesn't do policy in
6891 			 * this case.
6892 			 */
6893 			if (mctl_present) {
6894 				freeb(first_mp);
6895 				mctl_present = B_FALSE;
6896 			}
6897 			first_mp = mp;
6898 		}
6899 	}
6900 
6901 	/*
6902 	 * Initiate policy processing here if needed. If we get here from
6903 	 * icmp_inbound_error_fanout, ip_policy is false.
6904 	 */
6905 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6906 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6907 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6908 		if (mp == NULL) {
6909 			CONN_DEC_REF(connp);
6910 			if (mctl_present)
6911 				freeb(first_mp);
6912 			return;
6913 		} else if (mctl_present) {
6914 			ASSERT(first_mp != mp);
6915 			first_mp->b_cont = mp;
6916 		} else {
6917 			first_mp = mp;
6918 		}
6919 	}
6920 
6921 	/* Handle socket options. */
6922 	if (!syn_present &&
6923 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6924 		/* Add header */
6925 		ASSERT(recv_ill != NULL);
6926 		/*
6927 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6928 		 * IPF_RECVIF.
6929 		 */
6930 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6931 		    ipst);
6932 		if (mp == NULL) {
6933 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6934 			CONN_DEC_REF(connp);
6935 			if (mctl_present)
6936 				freeb(first_mp);
6937 			return;
6938 		} else if (mctl_present) {
6939 			/*
6940 			 * ip_add_info might return a new mp.
6941 			 */
6942 			ASSERT(first_mp != mp);
6943 			first_mp->b_cont = mp;
6944 		} else {
6945 			first_mp = mp;
6946 		}
6947 	}
6948 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6949 	if (IPCL_IS_TCP(connp)) {
6950 		/* do not drain, certain use cases can blow the stack */
6951 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6952 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6953 	} else {
6954 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6955 		(connp->conn_recv)(connp, first_mp, NULL);
6956 		CONN_DEC_REF(connp);
6957 	}
6958 }
6959 
6960 /*
6961  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6962  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6963  * is not consumed.
6964  *
6965  * One of four things can happen, all of which affect the passed-in mblk:
6966  *
6967  * 1.) ICMP messages that go through here just get returned TRUE.
6968  *
6969  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6970  *
6971  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6972  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6973  *
6974  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6975  */
6976 static boolean_t
6977 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6978     ipsec_stack_t *ipss)
6979 {
6980 	int shift, plen, iph_len;
6981 	ipha_t *ipha;
6982 	udpha_t *udpha;
6983 	uint32_t *spi;
6984 	uint32_t esp_ports;
6985 	uint8_t *orptr;
6986 	boolean_t free_ire;
6987 
6988 	if (DB_TYPE(mp) == M_CTL) {
6989 		/*
6990 		 * ICMP message with UDP inside.  Don't bother stripping, just
6991 		 * send it up.
6992 		 *
6993 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6994 		 * to ignore errors set by ICMP anyway ('cause they might be
6995 		 * forged), but that's the app's decision, not ours.
6996 		 */
6997 
6998 		/* Bunch of reality checks for DEBUG kernels... */
6999 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7000 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7001 
7002 		return (B_TRUE);
7003 	}
7004 
7005 	ipha = (ipha_t *)mp->b_rptr;
7006 	iph_len = IPH_HDR_LENGTH(ipha);
7007 	plen = ntohs(ipha->ipha_length);
7008 
7009 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7010 		/*
7011 		 * Most likely a keepalive for the benefit of an intervening
7012 		 * NAT.  These aren't for us, per se, so drop it.
7013 		 *
7014 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7015 		 * byte packets (keepalives are 1-byte), but we'll drop them
7016 		 * also.
7017 		 */
7018 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7019 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7020 		return (B_FALSE);
7021 	}
7022 
7023 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7024 		/* might as well pull it all up - it might be ESP. */
7025 		if (!pullupmsg(mp, -1)) {
7026 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7027 			    DROPPER(ipss, ipds_esp_nomem),
7028 			    &ipss->ipsec_dropper);
7029 			return (B_FALSE);
7030 		}
7031 
7032 		ipha = (ipha_t *)mp->b_rptr;
7033 	}
7034 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7035 	if (*spi == 0) {
7036 		/* UDP packet - remove 0-spi. */
7037 		shift = sizeof (uint32_t);
7038 	} else {
7039 		/* ESP-in-UDP packet - reduce to ESP. */
7040 		ipha->ipha_protocol = IPPROTO_ESP;
7041 		shift = sizeof (udpha_t);
7042 	}
7043 
7044 	/* Fix IP header */
7045 	ipha->ipha_length = htons(plen - shift);
7046 	ipha->ipha_hdr_checksum = 0;
7047 
7048 	orptr = mp->b_rptr;
7049 	mp->b_rptr += shift;
7050 
7051 	udpha = (udpha_t *)(orptr + iph_len);
7052 	if (*spi == 0) {
7053 		ASSERT((uint8_t *)ipha == orptr);
7054 		udpha->uha_length = htons(plen - shift - iph_len);
7055 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7056 		esp_ports = 0;
7057 	} else {
7058 		esp_ports = *((uint32_t *)udpha);
7059 		ASSERT(esp_ports != 0);
7060 	}
7061 	ovbcopy(orptr, orptr + shift, iph_len);
7062 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7063 		ipha = (ipha_t *)(orptr + shift);
7064 
7065 		free_ire = (ire == NULL);
7066 		if (free_ire) {
7067 			/* Re-acquire ire. */
7068 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7069 			    ipss->ipsec_netstack->netstack_ip);
7070 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7071 				if (ire != NULL)
7072 					ire_refrele(ire);
7073 				/*
7074 				 * Do a regular freemsg(), as this is an IP
7075 				 * error (no local route) not an IPsec one.
7076 				 */
7077 				freemsg(mp);
7078 			}
7079 		}
7080 
7081 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7082 		if (free_ire)
7083 			ire_refrele(ire);
7084 	}
7085 
7086 	return (esp_ports == 0);
7087 }
7088 
7089 /*
7090  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7091  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7092  * Caller is responsible for dropping references to the conn, and freeing
7093  * first_mp.
7094  *
7095  * IPQoS Notes
7096  * Before sending it to the client, invoke IPPF processing. Policy processing
7097  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7098  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7099  * ip_wput_local, ip_policy is false.
7100  */
7101 static void
7102 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7103     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7104     boolean_t ip_policy)
7105 {
7106 	boolean_t	mctl_present = (first_mp != NULL);
7107 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7108 	uint32_t	ill_index;
7109 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7110 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7111 
7112 	ASSERT(ill != NULL);
7113 
7114 	if (mctl_present)
7115 		first_mp->b_cont = mp;
7116 	else
7117 		first_mp = mp;
7118 
7119 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7120 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7121 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7122 		freemsg(first_mp);
7123 		return;
7124 	}
7125 
7126 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7127 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7128 		    NULL, mctl_present);
7129 		/* Freed by ipsec_check_inbound_policy(). */
7130 		if (first_mp == NULL) {
7131 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7132 			return;
7133 		}
7134 	}
7135 	if (mctl_present)
7136 		freeb(first_mp);
7137 
7138 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7139 	if (connp->conn_udp->udp_nat_t_endpoint) {
7140 		if (mctl_present) {
7141 			/* mctl_present *shouldn't* happen. */
7142 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7143 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7144 			    &ipss->ipsec_dropper);
7145 			return;
7146 		}
7147 
7148 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7149 			return;
7150 	}
7151 
7152 	/* Handle options. */
7153 	if (connp->conn_recvif)
7154 		in_flags = IPF_RECVIF;
7155 	/*
7156 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7157 	 * passed to ip_add_info is based on IP version of connp.
7158 	 */
7159 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7160 		if (connp->conn_af_isv6) {
7161 			/*
7162 			 * V6 only needs index
7163 			 */
7164 			in_flags |= IPF_RECVIF;
7165 		} else {
7166 			/*
7167 			 * V4 needs index + matching address.
7168 			 */
7169 			in_flags |= IPF_RECVADDR;
7170 		}
7171 	}
7172 
7173 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7174 		in_flags |= IPF_RECVSLLA;
7175 
7176 	/*
7177 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7178 	 * freed if the packet is dropped. The caller will do so.
7179 	 */
7180 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7181 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7182 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7183 		if (mp == NULL) {
7184 			return;
7185 		}
7186 	}
7187 	if ((in_flags != 0) &&
7188 	    (mp->b_datap->db_type != M_CTL)) {
7189 		/*
7190 		 * The actual data will be contained in b_cont
7191 		 * upon successful return of the following call
7192 		 * else original mblk is returned
7193 		 */
7194 		ASSERT(recv_ill != NULL);
7195 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7196 		    ipst);
7197 	}
7198 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7199 	/* Send it upstream */
7200 	(connp->conn_recv)(connp, mp, NULL);
7201 }
7202 
7203 /*
7204  * Fanout for UDP packets.
7205  * The caller puts <fport, lport> in the ports parameter.
7206  *
7207  * If SO_REUSEADDR is set all multicast and broadcast packets
7208  * will be delivered to all streams bound to the same port.
7209  *
7210  * Zones notes:
7211  * Multicast and broadcast packets will be distributed to streams in all zones.
7212  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7213  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7214  * packets. To maintain this behavior with multiple zones, the conns are grouped
7215  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7216  * each zone. If unset, all the following conns in the same zone are skipped.
7217  */
7218 static void
7219 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7220     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7221     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7222 {
7223 	uint32_t	dstport, srcport;
7224 	ipaddr_t	dst;
7225 	mblk_t		*first_mp;
7226 	boolean_t	secure;
7227 	in6_addr_t	v6src;
7228 	conn_t		*connp;
7229 	connf_t		*connfp;
7230 	conn_t		*first_connp;
7231 	conn_t		*next_connp;
7232 	mblk_t		*mp1, *first_mp1;
7233 	ipaddr_t	src;
7234 	zoneid_t	last_zoneid;
7235 	boolean_t	reuseaddr;
7236 	boolean_t	shared_addr;
7237 	boolean_t	unlabeled;
7238 	ip_stack_t	*ipst;
7239 
7240 	ASSERT(recv_ill != NULL);
7241 	ipst = recv_ill->ill_ipst;
7242 
7243 	first_mp = mp;
7244 	if (mctl_present) {
7245 		mp = first_mp->b_cont;
7246 		first_mp->b_cont = NULL;
7247 		secure = ipsec_in_is_secure(first_mp);
7248 		ASSERT(mp != NULL);
7249 	} else {
7250 		first_mp = NULL;
7251 		secure = B_FALSE;
7252 	}
7253 
7254 	/* Extract ports in net byte order */
7255 	dstport = htons(ntohl(ports) & 0xFFFF);
7256 	srcport = htons(ntohl(ports) >> 16);
7257 	dst = ipha->ipha_dst;
7258 	src = ipha->ipha_src;
7259 
7260 	unlabeled = B_FALSE;
7261 	if (is_system_labeled())
7262 		/* Cred cannot be null on IPv4 */
7263 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7264 		    TSLF_UNLABELED) != 0;
7265 	shared_addr = (zoneid == ALL_ZONES);
7266 	if (shared_addr) {
7267 		/*
7268 		 * No need to handle exclusive-stack zones since ALL_ZONES
7269 		 * only applies to the shared stack.
7270 		 */
7271 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7272 		/*
7273 		 * If no shared MLP is found, tsol_mlp_findzone returns
7274 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7275 		 * search for the zone based on the packet label.
7276 		 *
7277 		 * If there is such a zone, we prefer to find a
7278 		 * connection in it.  Otherwise, we look for a
7279 		 * MAC-exempt connection in any zone whose label
7280 		 * dominates the default label on the packet.
7281 		 */
7282 		if (zoneid == ALL_ZONES)
7283 			zoneid = tsol_packet_to_zoneid(mp);
7284 		else
7285 			unlabeled = B_FALSE;
7286 	}
7287 
7288 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7289 	mutex_enter(&connfp->connf_lock);
7290 	connp = connfp->connf_head;
7291 	if (!broadcast && !CLASSD(dst)) {
7292 		/*
7293 		 * Not broadcast or multicast. Send to the one (first)
7294 		 * client we find. No need to check conn_wantpacket()
7295 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7296 		 * IPv4 unicast packets.
7297 		 */
7298 		while ((connp != NULL) &&
7299 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7300 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7301 		    !(unlabeled && connp->conn_mac_exempt)))) {
7302 			/*
7303 			 * We keep searching since the conn did not match,
7304 			 * or its zone did not match and it is not either
7305 			 * an allzones conn or a mac exempt conn (if the
7306 			 * sender is unlabeled.)
7307 			 */
7308 			connp = connp->conn_next;
7309 		}
7310 
7311 		if (connp == NULL ||
7312 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7313 			goto notfound;
7314 
7315 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7316 
7317 		if (is_system_labeled() &&
7318 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7319 		    connp))
7320 			goto notfound;
7321 
7322 		CONN_INC_REF(connp);
7323 		mutex_exit(&connfp->connf_lock);
7324 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7325 		    flags, recv_ill, ip_policy);
7326 		IP_STAT(ipst, ip_udp_fannorm);
7327 		CONN_DEC_REF(connp);
7328 		return;
7329 	}
7330 
7331 	/*
7332 	 * Broadcast and multicast case
7333 	 *
7334 	 * Need to check conn_wantpacket().
7335 	 * If SO_REUSEADDR has been set on the first we send the
7336 	 * packet to all clients that have joined the group and
7337 	 * match the port.
7338 	 */
7339 
7340 	while (connp != NULL) {
7341 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7342 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7343 		    (!is_system_labeled() ||
7344 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7345 		    connp)))
7346 			break;
7347 		connp = connp->conn_next;
7348 	}
7349 
7350 	if (connp == NULL ||
7351 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7352 		goto notfound;
7353 
7354 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7355 
7356 	first_connp = connp;
7357 	/*
7358 	 * When SO_REUSEADDR is not set, send the packet only to the first
7359 	 * matching connection in its zone by keeping track of the zoneid.
7360 	 */
7361 	reuseaddr = first_connp->conn_reuseaddr;
7362 	last_zoneid = first_connp->conn_zoneid;
7363 
7364 	CONN_INC_REF(connp);
7365 	connp = connp->conn_next;
7366 	for (;;) {
7367 		while (connp != NULL) {
7368 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7369 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7370 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7371 			    (!is_system_labeled() ||
7372 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7373 			    shared_addr, connp)))
7374 				break;
7375 			connp = connp->conn_next;
7376 		}
7377 		/*
7378 		 * Just copy the data part alone. The mctl part is
7379 		 * needed just for verifying policy and it is never
7380 		 * sent up.
7381 		 */
7382 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7383 		    ((mp1 = copymsg(mp)) == NULL))) {
7384 			/*
7385 			 * No more interested clients or memory
7386 			 * allocation failed
7387 			 */
7388 			connp = first_connp;
7389 			break;
7390 		}
7391 		if (connp->conn_zoneid != last_zoneid) {
7392 			/*
7393 			 * Update the zoneid so that the packet isn't sent to
7394 			 * any more conns in the same zone unless SO_REUSEADDR
7395 			 * is set.
7396 			 */
7397 			reuseaddr = connp->conn_reuseaddr;
7398 			last_zoneid = connp->conn_zoneid;
7399 		}
7400 		if (first_mp != NULL) {
7401 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7402 			    ipsec_info_type == IPSEC_IN);
7403 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7404 			    ipst->ips_netstack);
7405 			if (first_mp1 == NULL) {
7406 				freemsg(mp1);
7407 				connp = first_connp;
7408 				break;
7409 			}
7410 		} else {
7411 			first_mp1 = NULL;
7412 		}
7413 		CONN_INC_REF(connp);
7414 		mutex_exit(&connfp->connf_lock);
7415 		/*
7416 		 * IPQoS notes: We don't send the packet for policy
7417 		 * processing here, will do it for the last one (below).
7418 		 * i.e. we do it per-packet now, but if we do policy
7419 		 * processing per-conn, then we would need to do it
7420 		 * here too.
7421 		 */
7422 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7423 		    ipha, flags, recv_ill, B_FALSE);
7424 		mutex_enter(&connfp->connf_lock);
7425 		/* Follow the next pointer before releasing the conn. */
7426 		next_connp = connp->conn_next;
7427 		IP_STAT(ipst, ip_udp_fanmb);
7428 		CONN_DEC_REF(connp);
7429 		connp = next_connp;
7430 	}
7431 
7432 	/* Last one.  Send it upstream. */
7433 	mutex_exit(&connfp->connf_lock);
7434 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7435 	    recv_ill, ip_policy);
7436 	IP_STAT(ipst, ip_udp_fanmb);
7437 	CONN_DEC_REF(connp);
7438 	return;
7439 
7440 notfound:
7441 
7442 	mutex_exit(&connfp->connf_lock);
7443 	IP_STAT(ipst, ip_udp_fanothers);
7444 	/*
7445 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7446 	 * have already been matched above, since they live in the IPv4
7447 	 * fanout tables. This implies we only need to
7448 	 * check for IPv6 in6addr_any endpoints here.
7449 	 * Thus we compare using ipv6_all_zeros instead of the destination
7450 	 * address, except for the multicast group membership lookup which
7451 	 * uses the IPv4 destination.
7452 	 */
7453 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7454 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7455 	mutex_enter(&connfp->connf_lock);
7456 	connp = connfp->connf_head;
7457 	if (!broadcast && !CLASSD(dst)) {
7458 		while (connp != NULL) {
7459 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7460 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7461 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7462 			    !connp->conn_ipv6_v6only)
7463 				break;
7464 			connp = connp->conn_next;
7465 		}
7466 
7467 		if (connp != NULL && is_system_labeled() &&
7468 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7469 		    connp))
7470 			connp = NULL;
7471 
7472 		if (connp == NULL ||
7473 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7474 			/*
7475 			 * No one bound to this port.  Is
7476 			 * there a client that wants all
7477 			 * unclaimed datagrams?
7478 			 */
7479 			mutex_exit(&connfp->connf_lock);
7480 
7481 			if (mctl_present)
7482 				first_mp->b_cont = mp;
7483 			else
7484 				first_mp = mp;
7485 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7486 			    connf_head != NULL) {
7487 				ip_fanout_proto(q, first_mp, ill, ipha,
7488 				    flags | IP_FF_RAWIP, mctl_present,
7489 				    ip_policy, recv_ill, zoneid);
7490 			} else {
7491 				if (ip_fanout_send_icmp(q, first_mp, flags,
7492 				    ICMP_DEST_UNREACHABLE,
7493 				    ICMP_PORT_UNREACHABLE,
7494 				    mctl_present, zoneid, ipst)) {
7495 					BUMP_MIB(ill->ill_ip_mib,
7496 					    udpIfStatsNoPorts);
7497 				}
7498 			}
7499 			return;
7500 		}
7501 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7502 
7503 		CONN_INC_REF(connp);
7504 		mutex_exit(&connfp->connf_lock);
7505 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7506 		    flags, recv_ill, ip_policy);
7507 		CONN_DEC_REF(connp);
7508 		return;
7509 	}
7510 	/*
7511 	 * IPv4 multicast packet being delivered to an AF_INET6
7512 	 * in6addr_any endpoint.
7513 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7514 	 * and not conn_wantpacket_v6() since any multicast membership is
7515 	 * for an IPv4-mapped multicast address.
7516 	 * The packet is sent to all clients in all zones that have joined the
7517 	 * group and match the port.
7518 	 */
7519 	while (connp != NULL) {
7520 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7521 		    srcport, v6src) &&
7522 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7523 		    (!is_system_labeled() ||
7524 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7525 		    connp)))
7526 			break;
7527 		connp = connp->conn_next;
7528 	}
7529 
7530 	if (connp == NULL ||
7531 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7532 		/*
7533 		 * No one bound to this port.  Is
7534 		 * there a client that wants all
7535 		 * unclaimed datagrams?
7536 		 */
7537 		mutex_exit(&connfp->connf_lock);
7538 
7539 		if (mctl_present)
7540 			first_mp->b_cont = mp;
7541 		else
7542 			first_mp = mp;
7543 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7544 		    NULL) {
7545 			ip_fanout_proto(q, first_mp, ill, ipha,
7546 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7547 			    recv_ill, zoneid);
7548 		} else {
7549 			/*
7550 			 * We used to attempt to send an icmp error here, but
7551 			 * since this is known to be a multicast packet
7552 			 * and we don't send icmp errors in response to
7553 			 * multicast, just drop the packet and give up sooner.
7554 			 */
7555 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7556 			freemsg(first_mp);
7557 		}
7558 		return;
7559 	}
7560 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7561 
7562 	first_connp = connp;
7563 
7564 	CONN_INC_REF(connp);
7565 	connp = connp->conn_next;
7566 	for (;;) {
7567 		while (connp != NULL) {
7568 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7569 			    ipv6_all_zeros, srcport, v6src) &&
7570 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7571 			    (!is_system_labeled() ||
7572 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7573 			    shared_addr, connp)))
7574 				break;
7575 			connp = connp->conn_next;
7576 		}
7577 		/*
7578 		 * Just copy the data part alone. The mctl part is
7579 		 * needed just for verifying policy and it is never
7580 		 * sent up.
7581 		 */
7582 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7583 		    ((mp1 = copymsg(mp)) == NULL))) {
7584 			/*
7585 			 * No more intested clients or memory
7586 			 * allocation failed
7587 			 */
7588 			connp = first_connp;
7589 			break;
7590 		}
7591 		if (first_mp != NULL) {
7592 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7593 			    ipsec_info_type == IPSEC_IN);
7594 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7595 			    ipst->ips_netstack);
7596 			if (first_mp1 == NULL) {
7597 				freemsg(mp1);
7598 				connp = first_connp;
7599 				break;
7600 			}
7601 		} else {
7602 			first_mp1 = NULL;
7603 		}
7604 		CONN_INC_REF(connp);
7605 		mutex_exit(&connfp->connf_lock);
7606 		/*
7607 		 * IPQoS notes: We don't send the packet for policy
7608 		 * processing here, will do it for the last one (below).
7609 		 * i.e. we do it per-packet now, but if we do policy
7610 		 * processing per-conn, then we would need to do it
7611 		 * here too.
7612 		 */
7613 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7614 		    ipha, flags, recv_ill, B_FALSE);
7615 		mutex_enter(&connfp->connf_lock);
7616 		/* Follow the next pointer before releasing the conn. */
7617 		next_connp = connp->conn_next;
7618 		CONN_DEC_REF(connp);
7619 		connp = next_connp;
7620 	}
7621 
7622 	/* Last one.  Send it upstream. */
7623 	mutex_exit(&connfp->connf_lock);
7624 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7625 	    recv_ill, ip_policy);
7626 	CONN_DEC_REF(connp);
7627 }
7628 
7629 /*
7630  * Complete the ip_wput header so that it
7631  * is possible to generate ICMP
7632  * errors.
7633  */
7634 int
7635 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7636 {
7637 	ire_t *ire;
7638 
7639 	if (ipha->ipha_src == INADDR_ANY) {
7640 		ire = ire_lookup_local(zoneid, ipst);
7641 		if (ire == NULL) {
7642 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7643 			return (1);
7644 		}
7645 		ipha->ipha_src = ire->ire_addr;
7646 		ire_refrele(ire);
7647 	}
7648 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7649 	ipha->ipha_hdr_checksum = 0;
7650 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7651 	return (0);
7652 }
7653 
7654 /*
7655  * Nobody should be sending
7656  * packets up this stream
7657  */
7658 static void
7659 ip_lrput(queue_t *q, mblk_t *mp)
7660 {
7661 	mblk_t *mp1;
7662 
7663 	switch (mp->b_datap->db_type) {
7664 	case M_FLUSH:
7665 		/* Turn around */
7666 		if (*mp->b_rptr & FLUSHW) {
7667 			*mp->b_rptr &= ~FLUSHR;
7668 			qreply(q, mp);
7669 			return;
7670 		}
7671 		break;
7672 	}
7673 	/* Could receive messages that passed through ar_rput */
7674 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7675 		mp1->b_prev = mp1->b_next = NULL;
7676 	freemsg(mp);
7677 }
7678 
7679 /* Nobody should be sending packets down this stream */
7680 /* ARGSUSED */
7681 void
7682 ip_lwput(queue_t *q, mblk_t *mp)
7683 {
7684 	freemsg(mp);
7685 }
7686 
7687 /*
7688  * Move the first hop in any source route to ipha_dst and remove that part of
7689  * the source route.  Called by other protocols.  Errors in option formatting
7690  * are ignored - will be handled by ip_wput_options Return the final
7691  * destination (either ipha_dst or the last entry in a source route.)
7692  */
7693 ipaddr_t
7694 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7695 {
7696 	ipoptp_t	opts;
7697 	uchar_t		*opt;
7698 	uint8_t		optval;
7699 	uint8_t		optlen;
7700 	ipaddr_t	dst;
7701 	int		i;
7702 	ire_t		*ire;
7703 	ip_stack_t	*ipst = ns->netstack_ip;
7704 
7705 	ip2dbg(("ip_massage_options\n"));
7706 	dst = ipha->ipha_dst;
7707 	for (optval = ipoptp_first(&opts, ipha);
7708 	    optval != IPOPT_EOL;
7709 	    optval = ipoptp_next(&opts)) {
7710 		opt = opts.ipoptp_cur;
7711 		switch (optval) {
7712 			uint8_t off;
7713 		case IPOPT_SSRR:
7714 		case IPOPT_LSRR:
7715 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7716 				ip1dbg(("ip_massage_options: bad src route\n"));
7717 				break;
7718 			}
7719 			optlen = opts.ipoptp_len;
7720 			off = opt[IPOPT_OFFSET];
7721 			off--;
7722 		redo_srr:
7723 			if (optlen < IP_ADDR_LEN ||
7724 			    off > optlen - IP_ADDR_LEN) {
7725 				/* End of source route */
7726 				ip1dbg(("ip_massage_options: end of SR\n"));
7727 				break;
7728 			}
7729 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7730 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7731 			    ntohl(dst)));
7732 			/*
7733 			 * Check if our address is present more than
7734 			 * once as consecutive hops in source route.
7735 			 * XXX verify per-interface ip_forwarding
7736 			 * for source route?
7737 			 */
7738 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7739 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7740 			if (ire != NULL) {
7741 				ire_refrele(ire);
7742 				off += IP_ADDR_LEN;
7743 				goto redo_srr;
7744 			}
7745 			if (dst == htonl(INADDR_LOOPBACK)) {
7746 				ip1dbg(("ip_massage_options: loopback addr in "
7747 				    "source route!\n"));
7748 				break;
7749 			}
7750 			/*
7751 			 * Update ipha_dst to be the first hop and remove the
7752 			 * first hop from the source route (by overwriting
7753 			 * part of the option with NOP options).
7754 			 */
7755 			ipha->ipha_dst = dst;
7756 			/* Put the last entry in dst */
7757 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7758 			    3;
7759 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7760 
7761 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7762 			    ntohl(dst)));
7763 			/* Move down and overwrite */
7764 			opt[IP_ADDR_LEN] = opt[0];
7765 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7766 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7767 			for (i = 0; i < IP_ADDR_LEN; i++)
7768 				opt[i] = IPOPT_NOP;
7769 			break;
7770 		}
7771 	}
7772 	return (dst);
7773 }
7774 
7775 /*
7776  * Return the network mask
7777  * associated with the specified address.
7778  */
7779 ipaddr_t
7780 ip_net_mask(ipaddr_t addr)
7781 {
7782 	uchar_t	*up = (uchar_t *)&addr;
7783 	ipaddr_t mask = 0;
7784 	uchar_t	*maskp = (uchar_t *)&mask;
7785 
7786 #if defined(__i386) || defined(__amd64)
7787 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7788 #endif
7789 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7790 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7791 #endif
7792 	if (CLASSD(addr)) {
7793 		maskp[0] = 0xF0;
7794 		return (mask);
7795 	}
7796 
7797 	/* We assume Class E default netmask to be 32 */
7798 	if (CLASSE(addr))
7799 		return (0xffffffffU);
7800 
7801 	if (addr == 0)
7802 		return (0);
7803 	maskp[0] = 0xFF;
7804 	if ((up[0] & 0x80) == 0)
7805 		return (mask);
7806 
7807 	maskp[1] = 0xFF;
7808 	if ((up[0] & 0xC0) == 0x80)
7809 		return (mask);
7810 
7811 	maskp[2] = 0xFF;
7812 	if ((up[0] & 0xE0) == 0xC0)
7813 		return (mask);
7814 
7815 	/* Otherwise return no mask */
7816 	return ((ipaddr_t)0);
7817 }
7818 
7819 /*
7820  * Helper ill lookup function used by IPsec.
7821  */
7822 ill_t *
7823 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7824 {
7825 	ill_t *ret_ill;
7826 
7827 	ASSERT(ifindex != 0);
7828 
7829 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7830 	    ipst);
7831 	if (ret_ill == NULL) {
7832 		if (isv6) {
7833 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7834 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7835 			    ifindex));
7836 		} else {
7837 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7838 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7839 			    ifindex));
7840 		}
7841 		freemsg(first_mp);
7842 		return (NULL);
7843 	}
7844 	return (ret_ill);
7845 }
7846 
7847 /*
7848  * IPv4 -
7849  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7850  * out a packet to a destination address for which we do not have specific
7851  * (or sufficient) routing information.
7852  *
7853  * NOTE : These are the scopes of some of the variables that point at IRE,
7854  *	  which needs to be followed while making any future modifications
7855  *	  to avoid memory leaks.
7856  *
7857  *	- ire and sire are the entries looked up initially by
7858  *	  ire_ftable_lookup.
7859  *	- ipif_ire is used to hold the interface ire associated with
7860  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7861  *	  it before branching out to error paths.
7862  *	- save_ire is initialized before ire_create, so that ire returned
7863  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7864  *	  before breaking out of the switch.
7865  *
7866  *	Thus on failures, we have to REFRELE only ire and sire, if they
7867  *	are not NULL.
7868  */
7869 void
7870 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7871     zoneid_t zoneid, ip_stack_t *ipst)
7872 {
7873 	areq_t	*areq;
7874 	ipaddr_t gw = 0;
7875 	ire_t	*ire = NULL;
7876 	mblk_t	*res_mp;
7877 	ipaddr_t *addrp;
7878 	ipaddr_t nexthop_addr;
7879 	ipif_t  *src_ipif = NULL;
7880 	ill_t	*dst_ill = NULL;
7881 	ipha_t  *ipha;
7882 	ire_t	*sire = NULL;
7883 	mblk_t	*first_mp;
7884 	ire_t	*save_ire;
7885 	ushort_t ire_marks = 0;
7886 	boolean_t mctl_present;
7887 	ipsec_out_t *io;
7888 	mblk_t	*saved_mp;
7889 	ire_t	*first_sire = NULL;
7890 	mblk_t	*copy_mp = NULL;
7891 	mblk_t	*xmit_mp = NULL;
7892 	ipaddr_t save_dst;
7893 	uint32_t multirt_flags =
7894 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7895 	boolean_t multirt_is_resolvable;
7896 	boolean_t multirt_resolve_next;
7897 	boolean_t unspec_src;
7898 	boolean_t ip_nexthop = B_FALSE;
7899 	tsol_ire_gw_secattr_t *attrp = NULL;
7900 	tsol_gcgrp_t *gcgrp = NULL;
7901 	tsol_gcgrp_addr_t ga;
7902 
7903 	if (ip_debug > 2) {
7904 		/* ip1dbg */
7905 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7906 	}
7907 
7908 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7909 	if (mctl_present) {
7910 		io = (ipsec_out_t *)first_mp->b_rptr;
7911 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7912 		ASSERT(zoneid == io->ipsec_out_zoneid);
7913 		ASSERT(zoneid != ALL_ZONES);
7914 	}
7915 
7916 	ipha = (ipha_t *)mp->b_rptr;
7917 
7918 	/* All multicast lookups come through ip_newroute_ipif() */
7919 	if (CLASSD(dst)) {
7920 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7921 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7922 		freemsg(first_mp);
7923 		return;
7924 	}
7925 
7926 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7927 		ip_nexthop = B_TRUE;
7928 		nexthop_addr = io->ipsec_out_nexthop_addr;
7929 	}
7930 	/*
7931 	 * If this IRE is created for forwarding or it is not for
7932 	 * traffic for congestion controlled protocols, mark it as temporary.
7933 	 */
7934 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7935 		ire_marks |= IRE_MARK_TEMPORARY;
7936 
7937 	/*
7938 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7939 	 * chain until it gets the most specific information available.
7940 	 * For example, we know that there is no IRE_CACHE for this dest,
7941 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7942 	 * ire_ftable_lookup will look up the gateway, etc.
7943 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7944 	 * to the destination, of equal netmask length in the forward table,
7945 	 * will be recursively explored. If no information is available
7946 	 * for the final gateway of that route, we force the returned ire
7947 	 * to be equal to sire using MATCH_IRE_PARENT.
7948 	 * At least, in this case we have a starting point (in the buckets)
7949 	 * to look for other routes to the destination in the forward table.
7950 	 * This is actually used only for multirouting, where a list
7951 	 * of routes has to be processed in sequence.
7952 	 *
7953 	 * In the process of coming up with the most specific information,
7954 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7955 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7956 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7957 	 * Two caveats when handling incomplete ire's in ip_newroute:
7958 	 * - we should be careful when accessing its ire_nce (specifically
7959 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7960 	 * - not all legacy code path callers are prepared to handle
7961 	 *   incomplete ire's, so we should not create/add incomplete
7962 	 *   ire_cache entries here. (See discussion about temporary solution
7963 	 *   further below).
7964 	 *
7965 	 * In order to minimize packet dropping, and to preserve existing
7966 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7967 	 * gateway, and instead use the IF_RESOLVER ire to send out
7968 	 * another request to ARP (this is achieved by passing the
7969 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7970 	 * arp response comes back in ip_wput_nondata, we will create
7971 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7972 	 *
7973 	 * Note that this is a temporary solution; the correct solution is
7974 	 * to create an incomplete  per-dst ire_cache entry, and send the
7975 	 * packet out when the gw's nce is resolved. In order to achieve this,
7976 	 * all packet processing must have been completed prior to calling
7977 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7978 	 * to be modified to accomodate this solution.
7979 	 */
7980 	if (ip_nexthop) {
7981 		/*
7982 		 * The first time we come here, we look for an IRE_INTERFACE
7983 		 * entry for the specified nexthop, set the dst to be the
7984 		 * nexthop address and create an IRE_CACHE entry for the
7985 		 * nexthop. The next time around, we are able to find an
7986 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7987 		 * nexthop address and create an IRE_CACHE entry for the
7988 		 * destination address via the specified nexthop.
7989 		 */
7990 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7991 		    msg_getlabel(mp), ipst);
7992 		if (ire != NULL) {
7993 			gw = nexthop_addr;
7994 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7995 		} else {
7996 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7997 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7998 			    msg_getlabel(mp),
7999 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8000 			    ipst);
8001 			if (ire != NULL) {
8002 				dst = nexthop_addr;
8003 			}
8004 		}
8005 	} else {
8006 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8007 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8008 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8009 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8010 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8011 		    ipst);
8012 	}
8013 
8014 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8015 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8016 
8017 	/*
8018 	 * This loop is run only once in most cases.
8019 	 * We loop to resolve further routes only when the destination
8020 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8021 	 */
8022 	do {
8023 		/* Clear the previous iteration's values */
8024 		if (src_ipif != NULL) {
8025 			ipif_refrele(src_ipif);
8026 			src_ipif = NULL;
8027 		}
8028 		if (dst_ill != NULL) {
8029 			ill_refrele(dst_ill);
8030 			dst_ill = NULL;
8031 		}
8032 
8033 		multirt_resolve_next = B_FALSE;
8034 		/*
8035 		 * We check if packets have to be multirouted.
8036 		 * In this case, given the current <ire, sire> couple,
8037 		 * we look for the next suitable <ire, sire>.
8038 		 * This check is done in ire_multirt_lookup(),
8039 		 * which applies various criteria to find the next route
8040 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8041 		 * unchanged if it detects it has not been tried yet.
8042 		 */
8043 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8044 			ip3dbg(("ip_newroute: starting next_resolution "
8045 			    "with first_mp %p, tag %d\n",
8046 			    (void *)first_mp,
8047 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8048 
8049 			ASSERT(sire != NULL);
8050 			multirt_is_resolvable =
8051 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8052 			    msg_getlabel(mp), ipst);
8053 
8054 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8055 			    "ire %p, sire %p\n",
8056 			    multirt_is_resolvable,
8057 			    (void *)ire, (void *)sire));
8058 
8059 			if (!multirt_is_resolvable) {
8060 				/*
8061 				 * No more multirt route to resolve; give up
8062 				 * (all routes resolved or no more
8063 				 * resolvable routes).
8064 				 */
8065 				if (ire != NULL) {
8066 					ire_refrele(ire);
8067 					ire = NULL;
8068 				}
8069 			} else {
8070 				ASSERT(sire != NULL);
8071 				ASSERT(ire != NULL);
8072 				/*
8073 				 * We simply use first_sire as a flag that
8074 				 * indicates if a resolvable multirt route
8075 				 * has already been found.
8076 				 * If it is not the case, we may have to send
8077 				 * an ICMP error to report that the
8078 				 * destination is unreachable.
8079 				 * We do not IRE_REFHOLD first_sire.
8080 				 */
8081 				if (first_sire == NULL) {
8082 					first_sire = sire;
8083 				}
8084 			}
8085 		}
8086 		if (ire == NULL) {
8087 			if (ip_debug > 3) {
8088 				/* ip2dbg */
8089 				pr_addr_dbg("ip_newroute: "
8090 				    "can't resolve %s\n", AF_INET, &dst);
8091 			}
8092 			ip3dbg(("ip_newroute: "
8093 			    "ire %p, sire %p, first_sire %p\n",
8094 			    (void *)ire, (void *)sire, (void *)first_sire));
8095 
8096 			if (sire != NULL) {
8097 				ire_refrele(sire);
8098 				sire = NULL;
8099 			}
8100 
8101 			if (first_sire != NULL) {
8102 				/*
8103 				 * At least one multirt route has been found
8104 				 * in the same call to ip_newroute();
8105 				 * there is no need to report an ICMP error.
8106 				 * first_sire was not IRE_REFHOLDed.
8107 				 */
8108 				MULTIRT_DEBUG_UNTAG(first_mp);
8109 				freemsg(first_mp);
8110 				return;
8111 			}
8112 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8113 			    RTA_DST, ipst);
8114 			goto icmp_err_ret;
8115 		}
8116 
8117 		/*
8118 		 * Verify that the returned IRE does not have either
8119 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8120 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8121 		 */
8122 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8123 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8124 			goto icmp_err_ret;
8125 		}
8126 		/*
8127 		 * Increment the ire_ob_pkt_count field for ire if it is an
8128 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8129 		 * increment the same for the parent IRE, sire, if it is some
8130 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8131 		 */
8132 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8133 			UPDATE_OB_PKT_COUNT(ire);
8134 			ire->ire_last_used_time = lbolt;
8135 		}
8136 
8137 		if (sire != NULL) {
8138 			gw = sire->ire_gateway_addr;
8139 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8140 			    IRE_INTERFACE)) == 0);
8141 			UPDATE_OB_PKT_COUNT(sire);
8142 			sire->ire_last_used_time = lbolt;
8143 		}
8144 		/*
8145 		 * We have a route to reach the destination.  Find the
8146 		 * appropriate ill, then get a source address using
8147 		 * ipif_select_source().
8148 		 *
8149 		 * If we are here trying to create an IRE_CACHE for an offlink
8150 		 * destination and have an IRE_CACHE entry for VNI, then use
8151 		 * ire_stq instead since VNI's queue is a black hole.
8152 		 */
8153 		if ((ire->ire_type == IRE_CACHE) &&
8154 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8155 			dst_ill = ire->ire_stq->q_ptr;
8156 			ill_refhold(dst_ill);
8157 		} else {
8158 			ill_t *ill = ire->ire_ipif->ipif_ill;
8159 
8160 			if (IS_IPMP(ill)) {
8161 				dst_ill =
8162 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8163 			} else {
8164 				dst_ill = ill;
8165 				ill_refhold(dst_ill);
8166 			}
8167 		}
8168 
8169 		if (dst_ill == NULL) {
8170 			if (ip_debug > 2) {
8171 				pr_addr_dbg("ip_newroute: no dst "
8172 				    "ill for dst %s\n", AF_INET, &dst);
8173 			}
8174 			goto icmp_err_ret;
8175 		}
8176 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8177 
8178 		/*
8179 		 * Pick the best source address from dst_ill.
8180 		 *
8181 		 * 1) Try to pick the source address from the destination
8182 		 *    route. Clustering assumes that when we have multiple
8183 		 *    prefixes hosted on an interface, the prefix of the
8184 		 *    source address matches the prefix of the destination
8185 		 *    route. We do this only if the address is not
8186 		 *    DEPRECATED.
8187 		 *
8188 		 * 2) If the conn is in a different zone than the ire, we
8189 		 *    need to pick a source address from the right zone.
8190 		 */
8191 		ASSERT(src_ipif == NULL);
8192 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8193 			/*
8194 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8195 			 * Check that the ipif matching the requested source
8196 			 * address still exists.
8197 			 */
8198 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8199 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8200 		}
8201 
8202 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8203 
8204 		if (src_ipif == NULL &&
8205 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8206 			ire_marks |= IRE_MARK_USESRC_CHECK;
8207 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8208 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8209 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8210 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8211 			    ire->ire_zoneid != ALL_ZONES) ||
8212 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8213 				/*
8214 				 * If the destination is reachable via a
8215 				 * given gateway, the selected source address
8216 				 * should be in the same subnet as the gateway.
8217 				 * Otherwise, the destination is not reachable.
8218 				 *
8219 				 * If there are no interfaces on the same subnet
8220 				 * as the destination, ipif_select_source gives
8221 				 * first non-deprecated interface which might be
8222 				 * on a different subnet than the gateway.
8223 				 * This is not desirable. Hence pass the dst_ire
8224 				 * source address to ipif_select_source.
8225 				 * It is sure that the destination is reachable
8226 				 * with the dst_ire source address subnet.
8227 				 * So passing dst_ire source address to
8228 				 * ipif_select_source will make sure that the
8229 				 * selected source will be on the same subnet
8230 				 * as dst_ire source address.
8231 				 */
8232 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8233 
8234 				src_ipif = ipif_select_source(dst_ill, saddr,
8235 				    zoneid);
8236 				if (src_ipif == NULL) {
8237 					if (ip_debug > 2) {
8238 						pr_addr_dbg("ip_newroute: "
8239 						    "no src for dst %s ",
8240 						    AF_INET, &dst);
8241 						printf("on interface %s\n",
8242 						    dst_ill->ill_name);
8243 					}
8244 					goto icmp_err_ret;
8245 				}
8246 			} else {
8247 				src_ipif = ire->ire_ipif;
8248 				ASSERT(src_ipif != NULL);
8249 				/* hold src_ipif for uniformity */
8250 				ipif_refhold(src_ipif);
8251 			}
8252 		}
8253 
8254 		/*
8255 		 * Assign a source address while we have the conn.
8256 		 * We can't have ip_wput_ire pick a source address when the
8257 		 * packet returns from arp since we need to look at
8258 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8259 		 * going through arp.
8260 		 *
8261 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8262 		 *	  it uses ip6i to store this information.
8263 		 */
8264 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8265 			ipha->ipha_src = src_ipif->ipif_src_addr;
8266 
8267 		if (ip_debug > 3) {
8268 			/* ip2dbg */
8269 			pr_addr_dbg("ip_newroute: first hop %s\n",
8270 			    AF_INET, &gw);
8271 		}
8272 		ip2dbg(("\tire type %s (%d)\n",
8273 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8274 
8275 		/*
8276 		 * The TTL of multirouted packets is bounded by the
8277 		 * ip_multirt_ttl ndd variable.
8278 		 */
8279 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8280 			/* Force TTL of multirouted packets */
8281 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8282 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8283 				ip2dbg(("ip_newroute: forcing multirt TTL "
8284 				    "to %d (was %d), dst 0x%08x\n",
8285 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8286 				    ntohl(sire->ire_addr)));
8287 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8288 			}
8289 		}
8290 		/*
8291 		 * At this point in ip_newroute(), ire is either the
8292 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8293 		 * destination or an IRE_INTERFACE type that should be used
8294 		 * to resolve an on-subnet destination or an on-subnet
8295 		 * next-hop gateway.
8296 		 *
8297 		 * In the IRE_CACHE case, we have the following :
8298 		 *
8299 		 * 1) src_ipif - used for getting a source address.
8300 		 *
8301 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8302 		 *    means packets using this IRE_CACHE will go out on
8303 		 *    dst_ill.
8304 		 *
8305 		 * 3) The IRE sire will point to the prefix that is the
8306 		 *    longest  matching route for the destination. These
8307 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8308 		 *
8309 		 *    The newly created IRE_CACHE entry for the off-subnet
8310 		 *    destination is tied to both the prefix route and the
8311 		 *    interface route used to resolve the next-hop gateway
8312 		 *    via the ire_phandle and ire_ihandle fields,
8313 		 *    respectively.
8314 		 *
8315 		 * In the IRE_INTERFACE case, we have the following :
8316 		 *
8317 		 * 1) src_ipif - used for getting a source address.
8318 		 *
8319 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8320 		 *    means packets using the IRE_CACHE that we will build
8321 		 *    here will go out on dst_ill.
8322 		 *
8323 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8324 		 *    to be created will only be tied to the IRE_INTERFACE
8325 		 *    that was derived from the ire_ihandle field.
8326 		 *
8327 		 *    If sire is non-NULL, it means the destination is
8328 		 *    off-link and we will first create the IRE_CACHE for the
8329 		 *    gateway. Next time through ip_newroute, we will create
8330 		 *    the IRE_CACHE for the final destination as described
8331 		 *    above.
8332 		 *
8333 		 * In both cases, after the current resolution has been
8334 		 * completed (or possibly initialised, in the IRE_INTERFACE
8335 		 * case), the loop may be re-entered to attempt the resolution
8336 		 * of another RTF_MULTIRT route.
8337 		 *
8338 		 * When an IRE_CACHE entry for the off-subnet destination is
8339 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8340 		 * for further processing in emission loops.
8341 		 */
8342 		save_ire = ire;
8343 		switch (ire->ire_type) {
8344 		case IRE_CACHE: {
8345 			ire_t	*ipif_ire;
8346 
8347 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8348 			if (gw == 0)
8349 				gw = ire->ire_gateway_addr;
8350 			/*
8351 			 * We need 3 ire's to create a new cache ire for an
8352 			 * off-link destination from the cache ire of the
8353 			 * gateway.
8354 			 *
8355 			 *	1. The prefix ire 'sire' (Note that this does
8356 			 *	   not apply to the conn_nexthop_set case)
8357 			 *	2. The cache ire of the gateway 'ire'
8358 			 *	3. The interface ire 'ipif_ire'
8359 			 *
8360 			 * We have (1) and (2). We lookup (3) below.
8361 			 *
8362 			 * If there is no interface route to the gateway,
8363 			 * it is a race condition, where we found the cache
8364 			 * but the interface route has been deleted.
8365 			 */
8366 			if (ip_nexthop) {
8367 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8368 			} else {
8369 				ipif_ire =
8370 				    ire_ihandle_lookup_offlink(ire, sire);
8371 			}
8372 			if (ipif_ire == NULL) {
8373 				ip1dbg(("ip_newroute: "
8374 				    "ire_ihandle_lookup_offlink failed\n"));
8375 				goto icmp_err_ret;
8376 			}
8377 
8378 			/*
8379 			 * Check cached gateway IRE for any security
8380 			 * attributes; if found, associate the gateway
8381 			 * credentials group to the destination IRE.
8382 			 */
8383 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8384 				mutex_enter(&attrp->igsa_lock);
8385 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8386 					GCGRP_REFHOLD(gcgrp);
8387 				mutex_exit(&attrp->igsa_lock);
8388 			}
8389 
8390 			/*
8391 			 * XXX For the source of the resolver mp,
8392 			 * we are using the same DL_UNITDATA_REQ
8393 			 * (from save_ire->ire_nce->nce_res_mp)
8394 			 * though the save_ire is not pointing at the same ill.
8395 			 * This is incorrect. We need to send it up to the
8396 			 * resolver to get the right res_mp. For ethernets
8397 			 * this may be okay (ill_type == DL_ETHER).
8398 			 */
8399 
8400 			ire = ire_create(
8401 			    (uchar_t *)&dst,		/* dest address */
8402 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8403 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8404 			    (uchar_t *)&gw,		/* gateway address */
8405 			    &save_ire->ire_max_frag,
8406 			    save_ire->ire_nce,		/* src nce */
8407 			    dst_ill->ill_rq,		/* recv-from queue */
8408 			    dst_ill->ill_wq,		/* send-to queue */
8409 			    IRE_CACHE,			/* IRE type */
8410 			    src_ipif,
8411 			    (sire != NULL) ?
8412 			    sire->ire_mask : 0, 	/* Parent mask */
8413 			    (sire != NULL) ?
8414 			    sire->ire_phandle : 0,	/* Parent handle */
8415 			    ipif_ire->ire_ihandle,	/* Interface handle */
8416 			    (sire != NULL) ? (sire->ire_flags &
8417 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8418 			    (sire != NULL) ?
8419 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8420 			    NULL,
8421 			    gcgrp,
8422 			    ipst);
8423 
8424 			if (ire == NULL) {
8425 				if (gcgrp != NULL) {
8426 					GCGRP_REFRELE(gcgrp);
8427 					gcgrp = NULL;
8428 				}
8429 				ire_refrele(ipif_ire);
8430 				ire_refrele(save_ire);
8431 				break;
8432 			}
8433 
8434 			/* reference now held by IRE */
8435 			gcgrp = NULL;
8436 
8437 			ire->ire_marks |= ire_marks;
8438 
8439 			/*
8440 			 * Prevent sire and ipif_ire from getting deleted.
8441 			 * The newly created ire is tied to both of them via
8442 			 * the phandle and ihandle respectively.
8443 			 */
8444 			if (sire != NULL) {
8445 				IRB_REFHOLD(sire->ire_bucket);
8446 				/* Has it been removed already ? */
8447 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8448 					IRB_REFRELE(sire->ire_bucket);
8449 					ire_refrele(ipif_ire);
8450 					ire_refrele(save_ire);
8451 					break;
8452 				}
8453 			}
8454 
8455 			IRB_REFHOLD(ipif_ire->ire_bucket);
8456 			/* Has it been removed already ? */
8457 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8458 				IRB_REFRELE(ipif_ire->ire_bucket);
8459 				if (sire != NULL)
8460 					IRB_REFRELE(sire->ire_bucket);
8461 				ire_refrele(ipif_ire);
8462 				ire_refrele(save_ire);
8463 				break;
8464 			}
8465 
8466 			xmit_mp = first_mp;
8467 			/*
8468 			 * In the case of multirouting, a copy
8469 			 * of the packet is done before its sending.
8470 			 * The copy is used to attempt another
8471 			 * route resolution, in a next loop.
8472 			 */
8473 			if (ire->ire_flags & RTF_MULTIRT) {
8474 				copy_mp = copymsg(first_mp);
8475 				if (copy_mp != NULL) {
8476 					xmit_mp = copy_mp;
8477 					MULTIRT_DEBUG_TAG(first_mp);
8478 				}
8479 			}
8480 
8481 			ire_add_then_send(q, ire, xmit_mp);
8482 			ire_refrele(save_ire);
8483 
8484 			/* Assert that sire is not deleted yet. */
8485 			if (sire != NULL) {
8486 				ASSERT(sire->ire_ptpn != NULL);
8487 				IRB_REFRELE(sire->ire_bucket);
8488 			}
8489 
8490 			/* Assert that ipif_ire is not deleted yet. */
8491 			ASSERT(ipif_ire->ire_ptpn != NULL);
8492 			IRB_REFRELE(ipif_ire->ire_bucket);
8493 			ire_refrele(ipif_ire);
8494 
8495 			/*
8496 			 * If copy_mp is not NULL, multirouting was
8497 			 * requested. We loop to initiate a next
8498 			 * route resolution attempt, starting from sire.
8499 			 */
8500 			if (copy_mp != NULL) {
8501 				/*
8502 				 * Search for the next unresolved
8503 				 * multirt route.
8504 				 */
8505 				copy_mp = NULL;
8506 				ipif_ire = NULL;
8507 				ire = NULL;
8508 				multirt_resolve_next = B_TRUE;
8509 				continue;
8510 			}
8511 			if (sire != NULL)
8512 				ire_refrele(sire);
8513 			ipif_refrele(src_ipif);
8514 			ill_refrele(dst_ill);
8515 			return;
8516 		}
8517 		case IRE_IF_NORESOLVER: {
8518 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8519 			    dst_ill->ill_resolver_mp == NULL) {
8520 				ip1dbg(("ip_newroute: dst_ill %p "
8521 				    "for IRE_IF_NORESOLVER ire %p has "
8522 				    "no ill_resolver_mp\n",
8523 				    (void *)dst_ill, (void *)ire));
8524 				break;
8525 			}
8526 
8527 			/*
8528 			 * TSol note: We are creating the ire cache for the
8529 			 * destination 'dst'. If 'dst' is offlink, going
8530 			 * through the first hop 'gw', the security attributes
8531 			 * of 'dst' must be set to point to the gateway
8532 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8533 			 * is possible that 'dst' is a potential gateway that is
8534 			 * referenced by some route that has some security
8535 			 * attributes. Thus in the former case, we need to do a
8536 			 * gcgrp_lookup of 'gw' while in the latter case we
8537 			 * need to do gcgrp_lookup of 'dst' itself.
8538 			 */
8539 			ga.ga_af = AF_INET;
8540 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8541 			    &ga.ga_addr);
8542 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8543 
8544 			ire = ire_create(
8545 			    (uchar_t *)&dst,		/* dest address */
8546 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8547 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8548 			    (uchar_t *)&gw,		/* gateway address */
8549 			    &save_ire->ire_max_frag,
8550 			    NULL,			/* no src nce */
8551 			    dst_ill->ill_rq,		/* recv-from queue */
8552 			    dst_ill->ill_wq,		/* send-to queue */
8553 			    IRE_CACHE,
8554 			    src_ipif,
8555 			    save_ire->ire_mask,		/* Parent mask */
8556 			    (sire != NULL) ?		/* Parent handle */
8557 			    sire->ire_phandle : 0,
8558 			    save_ire->ire_ihandle,	/* Interface handle */
8559 			    (sire != NULL) ? sire->ire_flags &
8560 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8561 			    &(save_ire->ire_uinfo),
8562 			    NULL,
8563 			    gcgrp,
8564 			    ipst);
8565 
8566 			if (ire == NULL) {
8567 				if (gcgrp != NULL) {
8568 					GCGRP_REFRELE(gcgrp);
8569 					gcgrp = NULL;
8570 				}
8571 				ire_refrele(save_ire);
8572 				break;
8573 			}
8574 
8575 			/* reference now held by IRE */
8576 			gcgrp = NULL;
8577 
8578 			ire->ire_marks |= ire_marks;
8579 
8580 			/* Prevent save_ire from getting deleted */
8581 			IRB_REFHOLD(save_ire->ire_bucket);
8582 			/* Has it been removed already ? */
8583 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8584 				IRB_REFRELE(save_ire->ire_bucket);
8585 				ire_refrele(save_ire);
8586 				break;
8587 			}
8588 
8589 			/*
8590 			 * In the case of multirouting, a copy
8591 			 * of the packet is made before it is sent.
8592 			 * The copy is used in the next
8593 			 * loop to attempt another resolution.
8594 			 */
8595 			xmit_mp = first_mp;
8596 			if ((sire != NULL) &&
8597 			    (sire->ire_flags & RTF_MULTIRT)) {
8598 				copy_mp = copymsg(first_mp);
8599 				if (copy_mp != NULL) {
8600 					xmit_mp = copy_mp;
8601 					MULTIRT_DEBUG_TAG(first_mp);
8602 				}
8603 			}
8604 			ire_add_then_send(q, ire, xmit_mp);
8605 
8606 			/* Assert that it is not deleted yet. */
8607 			ASSERT(save_ire->ire_ptpn != NULL);
8608 			IRB_REFRELE(save_ire->ire_bucket);
8609 			ire_refrele(save_ire);
8610 
8611 			if (copy_mp != NULL) {
8612 				/*
8613 				 * If we found a (no)resolver, we ignore any
8614 				 * trailing top priority IRE_CACHE in further
8615 				 * loops. This ensures that we do not omit any
8616 				 * (no)resolver.
8617 				 * This IRE_CACHE, if any, will be processed
8618 				 * by another thread entering ip_newroute().
8619 				 * IRE_CACHE entries, if any, will be processed
8620 				 * by another thread entering ip_newroute(),
8621 				 * (upon resolver response, for instance).
8622 				 * This aims to force parallel multirt
8623 				 * resolutions as soon as a packet must be sent.
8624 				 * In the best case, after the tx of only one
8625 				 * packet, all reachable routes are resolved.
8626 				 * Otherwise, the resolution of all RTF_MULTIRT
8627 				 * routes would require several emissions.
8628 				 */
8629 				multirt_flags &= ~MULTIRT_CACHEGW;
8630 
8631 				/*
8632 				 * Search for the next unresolved multirt
8633 				 * route.
8634 				 */
8635 				copy_mp = NULL;
8636 				save_ire = NULL;
8637 				ire = NULL;
8638 				multirt_resolve_next = B_TRUE;
8639 				continue;
8640 			}
8641 
8642 			/*
8643 			 * Don't need sire anymore
8644 			 */
8645 			if (sire != NULL)
8646 				ire_refrele(sire);
8647 
8648 			ipif_refrele(src_ipif);
8649 			ill_refrele(dst_ill);
8650 			return;
8651 		}
8652 		case IRE_IF_RESOLVER:
8653 			/*
8654 			 * We can't build an IRE_CACHE yet, but at least we
8655 			 * found a resolver that can help.
8656 			 */
8657 			res_mp = dst_ill->ill_resolver_mp;
8658 			if (!OK_RESOLVER_MP(res_mp))
8659 				break;
8660 
8661 			/*
8662 			 * To be at this point in the code with a non-zero gw
8663 			 * means that dst is reachable through a gateway that
8664 			 * we have never resolved.  By changing dst to the gw
8665 			 * addr we resolve the gateway first.
8666 			 * When ire_add_then_send() tries to put the IP dg
8667 			 * to dst, it will reenter ip_newroute() at which
8668 			 * time we will find the IRE_CACHE for the gw and
8669 			 * create another IRE_CACHE in case IRE_CACHE above.
8670 			 */
8671 			if (gw != INADDR_ANY) {
8672 				/*
8673 				 * The source ipif that was determined above was
8674 				 * relative to the destination address, not the
8675 				 * gateway's. If src_ipif was not taken out of
8676 				 * the IRE_IF_RESOLVER entry, we'll need to call
8677 				 * ipif_select_source() again.
8678 				 */
8679 				if (src_ipif != ire->ire_ipif) {
8680 					ipif_refrele(src_ipif);
8681 					src_ipif = ipif_select_source(dst_ill,
8682 					    gw, zoneid);
8683 					if (src_ipif == NULL) {
8684 						if (ip_debug > 2) {
8685 							pr_addr_dbg(
8686 							    "ip_newroute: no "
8687 							    "src for gw %s ",
8688 							    AF_INET, &gw);
8689 							printf("on "
8690 							    "interface %s\n",
8691 							    dst_ill->ill_name);
8692 						}
8693 						goto icmp_err_ret;
8694 					}
8695 				}
8696 				save_dst = dst;
8697 				dst = gw;
8698 				gw = INADDR_ANY;
8699 			}
8700 
8701 			/*
8702 			 * We obtain a partial IRE_CACHE which we will pass
8703 			 * along with the resolver query.  When the response
8704 			 * comes back it will be there ready for us to add.
8705 			 * The ire_max_frag is atomically set under the
8706 			 * irebucket lock in ire_add_v[46].
8707 			 */
8708 
8709 			ire = ire_create_mp(
8710 			    (uchar_t *)&dst,		/* dest address */
8711 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8712 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8713 			    (uchar_t *)&gw,		/* gateway address */
8714 			    NULL,			/* ire_max_frag */
8715 			    NULL,			/* no src nce */
8716 			    dst_ill->ill_rq,		/* recv-from queue */
8717 			    dst_ill->ill_wq,		/* send-to queue */
8718 			    IRE_CACHE,
8719 			    src_ipif,			/* Interface ipif */
8720 			    save_ire->ire_mask,		/* Parent mask */
8721 			    0,
8722 			    save_ire->ire_ihandle,	/* Interface handle */
8723 			    0,				/* flags if any */
8724 			    &(save_ire->ire_uinfo),
8725 			    NULL,
8726 			    NULL,
8727 			    ipst);
8728 
8729 			if (ire == NULL) {
8730 				ire_refrele(save_ire);
8731 				break;
8732 			}
8733 
8734 			if ((sire != NULL) &&
8735 			    (sire->ire_flags & RTF_MULTIRT)) {
8736 				copy_mp = copymsg(first_mp);
8737 				if (copy_mp != NULL)
8738 					MULTIRT_DEBUG_TAG(copy_mp);
8739 			}
8740 
8741 			ire->ire_marks |= ire_marks;
8742 
8743 			/*
8744 			 * Construct message chain for the resolver
8745 			 * of the form:
8746 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8747 			 * Packet could contain a IPSEC_OUT mp.
8748 			 *
8749 			 * NOTE : ire will be added later when the response
8750 			 * comes back from ARP. If the response does not
8751 			 * come back, ARP frees the packet. For this reason,
8752 			 * we can't REFHOLD the bucket of save_ire to prevent
8753 			 * deletions. We may not be able to REFRELE the bucket
8754 			 * if the response never comes back. Thus, before
8755 			 * adding the ire, ire_add_v4 will make sure that the
8756 			 * interface route does not get deleted. This is the
8757 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8758 			 * where we can always prevent deletions because of
8759 			 * the synchronous nature of adding IRES i.e
8760 			 * ire_add_then_send is called after creating the IRE.
8761 			 */
8762 			ASSERT(ire->ire_mp != NULL);
8763 			ire->ire_mp->b_cont = first_mp;
8764 			/* Have saved_mp handy, for cleanup if canput fails */
8765 			saved_mp = mp;
8766 			mp = copyb(res_mp);
8767 			if (mp == NULL) {
8768 				/* Prepare for cleanup */
8769 				mp = saved_mp; /* pkt */
8770 				ire_delete(ire); /* ire_mp */
8771 				ire = NULL;
8772 				ire_refrele(save_ire);
8773 				if (copy_mp != NULL) {
8774 					MULTIRT_DEBUG_UNTAG(copy_mp);
8775 					freemsg(copy_mp);
8776 					copy_mp = NULL;
8777 				}
8778 				break;
8779 			}
8780 			linkb(mp, ire->ire_mp);
8781 
8782 			/*
8783 			 * Fill in the source and dest addrs for the resolver.
8784 			 * NOTE: this depends on memory layouts imposed by
8785 			 * ill_init().
8786 			 */
8787 			areq = (areq_t *)mp->b_rptr;
8788 			addrp = (ipaddr_t *)((char *)areq +
8789 			    areq->areq_sender_addr_offset);
8790 			*addrp = save_ire->ire_src_addr;
8791 
8792 			ire_refrele(save_ire);
8793 			addrp = (ipaddr_t *)((char *)areq +
8794 			    areq->areq_target_addr_offset);
8795 			*addrp = dst;
8796 			/* Up to the resolver. */
8797 			if (canputnext(dst_ill->ill_rq) &&
8798 			    !(dst_ill->ill_arp_closing)) {
8799 				putnext(dst_ill->ill_rq, mp);
8800 				ire = NULL;
8801 				if (copy_mp != NULL) {
8802 					/*
8803 					 * If we found a resolver, we ignore
8804 					 * any trailing top priority IRE_CACHE
8805 					 * in the further loops. This ensures
8806 					 * that we do not omit any resolver.
8807 					 * IRE_CACHE entries, if any, will be
8808 					 * processed next time we enter
8809 					 * ip_newroute().
8810 					 */
8811 					multirt_flags &= ~MULTIRT_CACHEGW;
8812 					/*
8813 					 * Search for the next unresolved
8814 					 * multirt route.
8815 					 */
8816 					first_mp = copy_mp;
8817 					copy_mp = NULL;
8818 					/* Prepare the next resolution loop. */
8819 					mp = first_mp;
8820 					EXTRACT_PKT_MP(mp, first_mp,
8821 					    mctl_present);
8822 					if (mctl_present)
8823 						io = (ipsec_out_t *)
8824 						    first_mp->b_rptr;
8825 					ipha = (ipha_t *)mp->b_rptr;
8826 
8827 					ASSERT(sire != NULL);
8828 
8829 					dst = save_dst;
8830 					multirt_resolve_next = B_TRUE;
8831 					continue;
8832 				}
8833 
8834 				if (sire != NULL)
8835 					ire_refrele(sire);
8836 
8837 				/*
8838 				 * The response will come back in ip_wput
8839 				 * with db_type IRE_DB_TYPE.
8840 				 */
8841 				ipif_refrele(src_ipif);
8842 				ill_refrele(dst_ill);
8843 				return;
8844 			} else {
8845 				/* Prepare for cleanup */
8846 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8847 				    mp);
8848 				mp->b_cont = NULL;
8849 				freeb(mp); /* areq */
8850 				/*
8851 				 * this is an ire that is not added to the
8852 				 * cache. ire_freemblk will handle the release
8853 				 * of any resources associated with the ire.
8854 				 */
8855 				ire_delete(ire); /* ire_mp */
8856 				mp = saved_mp; /* pkt */
8857 				ire = NULL;
8858 				if (copy_mp != NULL) {
8859 					MULTIRT_DEBUG_UNTAG(copy_mp);
8860 					freemsg(copy_mp);
8861 					copy_mp = NULL;
8862 				}
8863 				break;
8864 			}
8865 		default:
8866 			break;
8867 		}
8868 	} while (multirt_resolve_next);
8869 
8870 	ip1dbg(("ip_newroute: dropped\n"));
8871 	/* Did this packet originate externally? */
8872 	if (mp->b_prev) {
8873 		mp->b_next = NULL;
8874 		mp->b_prev = NULL;
8875 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8876 	} else {
8877 		if (dst_ill != NULL) {
8878 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8879 		} else {
8880 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8881 		}
8882 	}
8883 	ASSERT(copy_mp == NULL);
8884 	MULTIRT_DEBUG_UNTAG(first_mp);
8885 	freemsg(first_mp);
8886 	if (ire != NULL)
8887 		ire_refrele(ire);
8888 	if (sire != NULL)
8889 		ire_refrele(sire);
8890 	if (src_ipif != NULL)
8891 		ipif_refrele(src_ipif);
8892 	if (dst_ill != NULL)
8893 		ill_refrele(dst_ill);
8894 	return;
8895 
8896 icmp_err_ret:
8897 	ip1dbg(("ip_newroute: no route\n"));
8898 	if (src_ipif != NULL)
8899 		ipif_refrele(src_ipif);
8900 	if (dst_ill != NULL)
8901 		ill_refrele(dst_ill);
8902 	if (sire != NULL)
8903 		ire_refrele(sire);
8904 	/* Did this packet originate externally? */
8905 	if (mp->b_prev) {
8906 		mp->b_next = NULL;
8907 		mp->b_prev = NULL;
8908 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8909 		q = WR(q);
8910 	} else {
8911 		/*
8912 		 * There is no outgoing ill, so just increment the
8913 		 * system MIB.
8914 		 */
8915 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8916 		/*
8917 		 * Since ip_wput() isn't close to finished, we fill
8918 		 * in enough of the header for credible error reporting.
8919 		 */
8920 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8921 			/* Failed */
8922 			MULTIRT_DEBUG_UNTAG(first_mp);
8923 			freemsg(first_mp);
8924 			if (ire != NULL)
8925 				ire_refrele(ire);
8926 			return;
8927 		}
8928 	}
8929 
8930 	/*
8931 	 * At this point we will have ire only if RTF_BLACKHOLE
8932 	 * or RTF_REJECT flags are set on the IRE. It will not
8933 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8934 	 */
8935 	if (ire != NULL) {
8936 		if (ire->ire_flags & RTF_BLACKHOLE) {
8937 			ire_refrele(ire);
8938 			MULTIRT_DEBUG_UNTAG(first_mp);
8939 			freemsg(first_mp);
8940 			return;
8941 		}
8942 		ire_refrele(ire);
8943 	}
8944 	if (ip_source_routed(ipha, ipst)) {
8945 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8946 		    zoneid, ipst);
8947 		return;
8948 	}
8949 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8950 }
8951 
8952 ip_opt_info_t zero_info;
8953 
8954 /*
8955  * IPv4 -
8956  * ip_newroute_ipif is called by ip_wput_multicast and
8957  * ip_rput_forward_multicast whenever we need to send
8958  * out a packet to a destination address for which we do not have specific
8959  * routing information. It is used when the packet will be sent out
8960  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8961  * socket option is set or icmp error message wants to go out on a particular
8962  * interface for a unicast packet.
8963  *
8964  * In most cases, the destination address is resolved thanks to the ipif
8965  * intrinsic resolver. However, there are some cases where the call to
8966  * ip_newroute_ipif must take into account the potential presence of
8967  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8968  * that uses the interface. This is specified through flags,
8969  * which can be a combination of:
8970  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8971  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8972  *   and flags. Additionally, the packet source address has to be set to
8973  *   the specified address. The caller is thus expected to set this flag
8974  *   if the packet has no specific source address yet.
8975  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8976  *   flag, the resulting ire will inherit the flag. All unresolved routes
8977  *   to the destination must be explored in the same call to
8978  *   ip_newroute_ipif().
8979  */
8980 static void
8981 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8982     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8983 {
8984 	areq_t	*areq;
8985 	ire_t	*ire = NULL;
8986 	mblk_t	*res_mp;
8987 	ipaddr_t *addrp;
8988 	mblk_t *first_mp;
8989 	ire_t	*save_ire = NULL;
8990 	ipif_t	*src_ipif = NULL;
8991 	ushort_t ire_marks = 0;
8992 	ill_t	*dst_ill = NULL;
8993 	ipha_t *ipha;
8994 	mblk_t	*saved_mp;
8995 	ire_t   *fire = NULL;
8996 	mblk_t  *copy_mp = NULL;
8997 	boolean_t multirt_resolve_next;
8998 	boolean_t unspec_src;
8999 	ipaddr_t ipha_dst;
9000 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9001 
9002 	/*
9003 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9004 	 * here for uniformity
9005 	 */
9006 	ipif_refhold(ipif);
9007 
9008 	/*
9009 	 * This loop is run only once in most cases.
9010 	 * We loop to resolve further routes only when the destination
9011 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9012 	 */
9013 	do {
9014 		if (dst_ill != NULL) {
9015 			ill_refrele(dst_ill);
9016 			dst_ill = NULL;
9017 		}
9018 		if (src_ipif != NULL) {
9019 			ipif_refrele(src_ipif);
9020 			src_ipif = NULL;
9021 		}
9022 		multirt_resolve_next = B_FALSE;
9023 
9024 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9025 		    ipif->ipif_ill->ill_name));
9026 
9027 		first_mp = mp;
9028 		if (DB_TYPE(mp) == M_CTL)
9029 			mp = mp->b_cont;
9030 		ipha = (ipha_t *)mp->b_rptr;
9031 
9032 		/*
9033 		 * Save the packet destination address, we may need it after
9034 		 * the packet has been consumed.
9035 		 */
9036 		ipha_dst = ipha->ipha_dst;
9037 
9038 		/*
9039 		 * If the interface is a pt-pt interface we look for an
9040 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9041 		 * local_address and the pt-pt destination address. Otherwise
9042 		 * we just match the local address.
9043 		 * NOTE: dst could be different than ipha->ipha_dst in case
9044 		 * of sending igmp multicast packets over a point-to-point
9045 		 * connection.
9046 		 * Thus we must be careful enough to check ipha_dst to be a
9047 		 * multicast address, otherwise it will take xmit_if path for
9048 		 * multicast packets resulting into kernel stack overflow by
9049 		 * repeated calls to ip_newroute_ipif from ire_send().
9050 		 */
9051 		if (CLASSD(ipha_dst) &&
9052 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9053 			goto err_ret;
9054 		}
9055 
9056 		/*
9057 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9058 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9059 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9060 		 * propagate its flags to the new ire.
9061 		 */
9062 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9063 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9064 			ip2dbg(("ip_newroute_ipif: "
9065 			    "ipif_lookup_multi_ire("
9066 			    "ipif %p, dst %08x) = fire %p\n",
9067 			    (void *)ipif, ntohl(dst), (void *)fire));
9068 		}
9069 
9070 		/*
9071 		 * Note: While we pick a dst_ill we are really only
9072 		 * interested in the ill for load spreading. The source
9073 		 * ipif is determined by source address selection below.
9074 		 */
9075 		if (IS_IPMP(ipif->ipif_ill)) {
9076 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9077 
9078 			if (CLASSD(ipha_dst))
9079 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9080 			else
9081 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9082 		} else {
9083 			dst_ill = ipif->ipif_ill;
9084 			ill_refhold(dst_ill);
9085 		}
9086 
9087 		if (dst_ill == NULL) {
9088 			if (ip_debug > 2) {
9089 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9090 				    "for dst %s\n", AF_INET, &dst);
9091 			}
9092 			goto err_ret;
9093 		}
9094 
9095 		/*
9096 		 * Pick a source address preferring non-deprecated ones.
9097 		 * Unlike ip_newroute, we don't do any source address
9098 		 * selection here since for multicast it really does not help
9099 		 * in inbound load spreading as in the unicast case.
9100 		 */
9101 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9102 		    (fire->ire_flags & RTF_SETSRC)) {
9103 			/*
9104 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9105 			 * on that interface. This ire has RTF_SETSRC flag, so
9106 			 * the source address of the packet must be changed.
9107 			 * Check that the ipif matching the requested source
9108 			 * address still exists.
9109 			 */
9110 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9111 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9112 		}
9113 
9114 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9115 
9116 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9117 		    (IS_IPMP(ipif->ipif_ill) ||
9118 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9119 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9120 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9121 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9122 		    (src_ipif == NULL) &&
9123 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9124 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9125 			if (src_ipif == NULL) {
9126 				if (ip_debug > 2) {
9127 					/* ip1dbg */
9128 					pr_addr_dbg("ip_newroute_ipif: "
9129 					    "no src for dst %s",
9130 					    AF_INET, &dst);
9131 				}
9132 				ip1dbg((" on interface %s\n",
9133 				    dst_ill->ill_name));
9134 				goto err_ret;
9135 			}
9136 			ipif_refrele(ipif);
9137 			ipif = src_ipif;
9138 			ipif_refhold(ipif);
9139 		}
9140 		if (src_ipif == NULL) {
9141 			src_ipif = ipif;
9142 			ipif_refhold(src_ipif);
9143 		}
9144 
9145 		/*
9146 		 * Assign a source address while we have the conn.
9147 		 * We can't have ip_wput_ire pick a source address when the
9148 		 * packet returns from arp since conn_unspec_src might be set
9149 		 * and we lose the conn when going through arp.
9150 		 */
9151 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9152 			ipha->ipha_src = src_ipif->ipif_src_addr;
9153 
9154 		/*
9155 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9156 		 * that the outgoing interface does not have an interface ire.
9157 		 */
9158 		if (CLASSD(ipha_dst) && (connp == NULL ||
9159 		    connp->conn_outgoing_ill == NULL) &&
9160 		    infop->ip_opt_ill_index == 0) {
9161 			/* ipif_to_ire returns an held ire */
9162 			ire = ipif_to_ire(ipif);
9163 			if (ire == NULL)
9164 				goto err_ret;
9165 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9166 				goto err_ret;
9167 			save_ire = ire;
9168 
9169 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9170 			    "flags %04x\n",
9171 			    (void *)ire, (void *)ipif, flags));
9172 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9173 			    (fire->ire_flags & RTF_MULTIRT)) {
9174 				/*
9175 				 * As requested by flags, an IRE_OFFSUBNET was
9176 				 * looked up on that interface. This ire has
9177 				 * RTF_MULTIRT flag, so the resolution loop will
9178 				 * be re-entered to resolve additional routes on
9179 				 * other interfaces. For that purpose, a copy of
9180 				 * the packet is performed at this point.
9181 				 */
9182 				fire->ire_last_used_time = lbolt;
9183 				copy_mp = copymsg(first_mp);
9184 				if (copy_mp) {
9185 					MULTIRT_DEBUG_TAG(copy_mp);
9186 				}
9187 			}
9188 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9189 			    (fire->ire_flags & RTF_SETSRC)) {
9190 				/*
9191 				 * As requested by flags, an IRE_OFFSUBET was
9192 				 * looked up on that interface. This ire has
9193 				 * RTF_SETSRC flag, so the source address of the
9194 				 * packet must be changed.
9195 				 */
9196 				ipha->ipha_src = fire->ire_src_addr;
9197 			}
9198 		} else {
9199 			/*
9200 			 * The only ways we can come here are:
9201 			 * 1) IP_BOUND_IF socket option is set
9202 			 * 2) SO_DONTROUTE socket option is set
9203 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9204 			 * In all cases, the new ire will not be added
9205 			 * into cache table.
9206 			 */
9207 			ASSERT(connp == NULL || connp->conn_dontroute ||
9208 			    connp->conn_outgoing_ill != NULL ||
9209 			    infop->ip_opt_ill_index != 0);
9210 			ire_marks |= IRE_MARK_NOADD;
9211 		}
9212 
9213 		switch (ipif->ipif_net_type) {
9214 		case IRE_IF_NORESOLVER: {
9215 			/* We have what we need to build an IRE_CACHE. */
9216 
9217 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9218 			    (dst_ill->ill_resolver_mp == NULL)) {
9219 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9220 				    "for IRE_IF_NORESOLVER ire %p has "
9221 				    "no ill_resolver_mp\n",
9222 				    (void *)dst_ill, (void *)ire));
9223 				break;
9224 			}
9225 
9226 			/*
9227 			 * The new ire inherits the IRE_OFFSUBNET flags
9228 			 * and source address, if this was requested.
9229 			 */
9230 			ire = ire_create(
9231 			    (uchar_t *)&dst,		/* dest address */
9232 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9233 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9234 			    NULL,			/* gateway address */
9235 			    &ipif->ipif_mtu,
9236 			    NULL,			/* no src nce */
9237 			    dst_ill->ill_rq,		/* recv-from queue */
9238 			    dst_ill->ill_wq,		/* send-to queue */
9239 			    IRE_CACHE,
9240 			    src_ipif,
9241 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9242 			    (fire != NULL) ?		/* Parent handle */
9243 			    fire->ire_phandle : 0,
9244 			    (save_ire != NULL) ?	/* Interface handle */
9245 			    save_ire->ire_ihandle : 0,
9246 			    (fire != NULL) ?
9247 			    (fire->ire_flags &
9248 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9249 			    (save_ire == NULL ? &ire_uinfo_null :
9250 			    &save_ire->ire_uinfo),
9251 			    NULL,
9252 			    NULL,
9253 			    ipst);
9254 
9255 			if (ire == NULL) {
9256 				if (save_ire != NULL)
9257 					ire_refrele(save_ire);
9258 				break;
9259 			}
9260 
9261 			ire->ire_marks |= ire_marks;
9262 
9263 			/*
9264 			 * If IRE_MARK_NOADD is set then we need to convert
9265 			 * the max_fragp to a useable value now. This is
9266 			 * normally done in ire_add_v[46]. We also need to
9267 			 * associate the ire with an nce (normally would be
9268 			 * done in ip_wput_nondata()).
9269 			 *
9270 			 * Note that IRE_MARK_NOADD packets created here
9271 			 * do not have a non-null ire_mp pointer. The null
9272 			 * value of ire_bucket indicates that they were
9273 			 * never added.
9274 			 */
9275 			if (ire->ire_marks & IRE_MARK_NOADD) {
9276 				uint_t  max_frag;
9277 
9278 				max_frag = *ire->ire_max_fragp;
9279 				ire->ire_max_fragp = NULL;
9280 				ire->ire_max_frag = max_frag;
9281 
9282 				if ((ire->ire_nce = ndp_lookup_v4(
9283 				    ire_to_ill(ire),
9284 				    (ire->ire_gateway_addr != INADDR_ANY ?
9285 				    &ire->ire_gateway_addr : &ire->ire_addr),
9286 				    B_FALSE)) == NULL) {
9287 					if (save_ire != NULL)
9288 						ire_refrele(save_ire);
9289 					break;
9290 				}
9291 				ASSERT(ire->ire_nce->nce_state ==
9292 				    ND_REACHABLE);
9293 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9294 			}
9295 
9296 			/* Prevent save_ire from getting deleted */
9297 			if (save_ire != NULL) {
9298 				IRB_REFHOLD(save_ire->ire_bucket);
9299 				/* Has it been removed already ? */
9300 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9301 					IRB_REFRELE(save_ire->ire_bucket);
9302 					ire_refrele(save_ire);
9303 					break;
9304 				}
9305 			}
9306 
9307 			ire_add_then_send(q, ire, first_mp);
9308 
9309 			/* Assert that save_ire is not deleted yet. */
9310 			if (save_ire != NULL) {
9311 				ASSERT(save_ire->ire_ptpn != NULL);
9312 				IRB_REFRELE(save_ire->ire_bucket);
9313 				ire_refrele(save_ire);
9314 				save_ire = NULL;
9315 			}
9316 			if (fire != NULL) {
9317 				ire_refrele(fire);
9318 				fire = NULL;
9319 			}
9320 
9321 			/*
9322 			 * the resolution loop is re-entered if this
9323 			 * was requested through flags and if we
9324 			 * actually are in a multirouting case.
9325 			 */
9326 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9327 				boolean_t need_resolve =
9328 				    ire_multirt_need_resolve(ipha_dst,
9329 				    msg_getlabel(copy_mp), ipst);
9330 				if (!need_resolve) {
9331 					MULTIRT_DEBUG_UNTAG(copy_mp);
9332 					freemsg(copy_mp);
9333 					copy_mp = NULL;
9334 				} else {
9335 					/*
9336 					 * ipif_lookup_group() calls
9337 					 * ire_lookup_multi() that uses
9338 					 * ire_ftable_lookup() to find
9339 					 * an IRE_INTERFACE for the group.
9340 					 * In the multirt case,
9341 					 * ire_lookup_multi() then invokes
9342 					 * ire_multirt_lookup() to find
9343 					 * the next resolvable ire.
9344 					 * As a result, we obtain an new
9345 					 * interface, derived from the
9346 					 * next ire.
9347 					 */
9348 					ipif_refrele(ipif);
9349 					ipif = ipif_lookup_group(ipha_dst,
9350 					    zoneid, ipst);
9351 					ip2dbg(("ip_newroute_ipif: "
9352 					    "multirt dst %08x, ipif %p\n",
9353 					    htonl(dst), (void *)ipif));
9354 					if (ipif != NULL) {
9355 						mp = copy_mp;
9356 						copy_mp = NULL;
9357 						multirt_resolve_next = B_TRUE;
9358 						continue;
9359 					} else {
9360 						freemsg(copy_mp);
9361 					}
9362 				}
9363 			}
9364 			if (ipif != NULL)
9365 				ipif_refrele(ipif);
9366 			ill_refrele(dst_ill);
9367 			ipif_refrele(src_ipif);
9368 			return;
9369 		}
9370 		case IRE_IF_RESOLVER:
9371 			/*
9372 			 * We can't build an IRE_CACHE yet, but at least
9373 			 * we found a resolver that can help.
9374 			 */
9375 			res_mp = dst_ill->ill_resolver_mp;
9376 			if (!OK_RESOLVER_MP(res_mp))
9377 				break;
9378 
9379 			/*
9380 			 * We obtain a partial IRE_CACHE which we will pass
9381 			 * along with the resolver query.  When the response
9382 			 * comes back it will be there ready for us to add.
9383 			 * The new ire inherits the IRE_OFFSUBNET flags
9384 			 * and source address, if this was requested.
9385 			 * The ire_max_frag is atomically set under the
9386 			 * irebucket lock in ire_add_v[46]. Only in the
9387 			 * case of IRE_MARK_NOADD, we set it here itself.
9388 			 */
9389 			ire = ire_create_mp(
9390 			    (uchar_t *)&dst,		/* dest address */
9391 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9392 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9393 			    NULL,			/* gateway address */
9394 			    (ire_marks & IRE_MARK_NOADD) ?
9395 			    ipif->ipif_mtu : 0,		/* max_frag */
9396 			    NULL,			/* no src nce */
9397 			    dst_ill->ill_rq,		/* recv-from queue */
9398 			    dst_ill->ill_wq,		/* send-to queue */
9399 			    IRE_CACHE,
9400 			    src_ipif,
9401 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9402 			    (fire != NULL) ?		/* Parent handle */
9403 			    fire->ire_phandle : 0,
9404 			    (save_ire != NULL) ?	/* Interface handle */
9405 			    save_ire->ire_ihandle : 0,
9406 			    (fire != NULL) ?		/* flags if any */
9407 			    (fire->ire_flags &
9408 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9409 			    (save_ire == NULL ? &ire_uinfo_null :
9410 			    &save_ire->ire_uinfo),
9411 			    NULL,
9412 			    NULL,
9413 			    ipst);
9414 
9415 			if (save_ire != NULL) {
9416 				ire_refrele(save_ire);
9417 				save_ire = NULL;
9418 			}
9419 			if (ire == NULL)
9420 				break;
9421 
9422 			ire->ire_marks |= ire_marks;
9423 			/*
9424 			 * Construct message chain for the resolver of the
9425 			 * form:
9426 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9427 			 *
9428 			 * NOTE : ire will be added later when the response
9429 			 * comes back from ARP. If the response does not
9430 			 * come back, ARP frees the packet. For this reason,
9431 			 * we can't REFHOLD the bucket of save_ire to prevent
9432 			 * deletions. We may not be able to REFRELE the
9433 			 * bucket if the response never comes back.
9434 			 * Thus, before adding the ire, ire_add_v4 will make
9435 			 * sure that the interface route does not get deleted.
9436 			 * This is the only case unlike ip_newroute_v6,
9437 			 * ip_newroute_ipif_v6 where we can always prevent
9438 			 * deletions because ire_add_then_send is called after
9439 			 * creating the IRE.
9440 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9441 			 * does not add this IRE into the IRE CACHE.
9442 			 */
9443 			ASSERT(ire->ire_mp != NULL);
9444 			ire->ire_mp->b_cont = first_mp;
9445 			/* Have saved_mp handy, for cleanup if canput fails */
9446 			saved_mp = mp;
9447 			mp = copyb(res_mp);
9448 			if (mp == NULL) {
9449 				/* Prepare for cleanup */
9450 				mp = saved_mp; /* pkt */
9451 				ire_delete(ire); /* ire_mp */
9452 				ire = NULL;
9453 				if (copy_mp != NULL) {
9454 					MULTIRT_DEBUG_UNTAG(copy_mp);
9455 					freemsg(copy_mp);
9456 					copy_mp = NULL;
9457 				}
9458 				break;
9459 			}
9460 			linkb(mp, ire->ire_mp);
9461 
9462 			/*
9463 			 * Fill in the source and dest addrs for the resolver.
9464 			 * NOTE: this depends on memory layouts imposed by
9465 			 * ill_init().  There are corner cases above where we
9466 			 * might've created the IRE with an INADDR_ANY source
9467 			 * address (e.g., if the zeroth ipif on an underlying
9468 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9469 			 * on the ill has a usable test address).  If so, tell
9470 			 * ARP to use ipha_src as its sender address.
9471 			 */
9472 			areq = (areq_t *)mp->b_rptr;
9473 			addrp = (ipaddr_t *)((char *)areq +
9474 			    areq->areq_sender_addr_offset);
9475 			if (ire->ire_src_addr != INADDR_ANY)
9476 				*addrp = ire->ire_src_addr;
9477 			else
9478 				*addrp = ipha->ipha_src;
9479 			addrp = (ipaddr_t *)((char *)areq +
9480 			    areq->areq_target_addr_offset);
9481 			*addrp = dst;
9482 			/* Up to the resolver. */
9483 			if (canputnext(dst_ill->ill_rq) &&
9484 			    !(dst_ill->ill_arp_closing)) {
9485 				putnext(dst_ill->ill_rq, mp);
9486 				/*
9487 				 * The response will come back in ip_wput
9488 				 * with db_type IRE_DB_TYPE.
9489 				 */
9490 			} else {
9491 				mp->b_cont = NULL;
9492 				freeb(mp); /* areq */
9493 				ire_delete(ire); /* ire_mp */
9494 				saved_mp->b_next = NULL;
9495 				saved_mp->b_prev = NULL;
9496 				freemsg(first_mp); /* pkt */
9497 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9498 			}
9499 
9500 			if (fire != NULL) {
9501 				ire_refrele(fire);
9502 				fire = NULL;
9503 			}
9504 
9505 			/*
9506 			 * The resolution loop is re-entered if this was
9507 			 * requested through flags and we actually are
9508 			 * in a multirouting case.
9509 			 */
9510 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9511 				boolean_t need_resolve =
9512 				    ire_multirt_need_resolve(ipha_dst,
9513 				    msg_getlabel(copy_mp), ipst);
9514 				if (!need_resolve) {
9515 					MULTIRT_DEBUG_UNTAG(copy_mp);
9516 					freemsg(copy_mp);
9517 					copy_mp = NULL;
9518 				} else {
9519 					/*
9520 					 * ipif_lookup_group() calls
9521 					 * ire_lookup_multi() that uses
9522 					 * ire_ftable_lookup() to find
9523 					 * an IRE_INTERFACE for the group.
9524 					 * In the multirt case,
9525 					 * ire_lookup_multi() then invokes
9526 					 * ire_multirt_lookup() to find
9527 					 * the next resolvable ire.
9528 					 * As a result, we obtain an new
9529 					 * interface, derived from the
9530 					 * next ire.
9531 					 */
9532 					ipif_refrele(ipif);
9533 					ipif = ipif_lookup_group(ipha_dst,
9534 					    zoneid, ipst);
9535 					if (ipif != NULL) {
9536 						mp = copy_mp;
9537 						copy_mp = NULL;
9538 						multirt_resolve_next = B_TRUE;
9539 						continue;
9540 					} else {
9541 						freemsg(copy_mp);
9542 					}
9543 				}
9544 			}
9545 			if (ipif != NULL)
9546 				ipif_refrele(ipif);
9547 			ill_refrele(dst_ill);
9548 			ipif_refrele(src_ipif);
9549 			return;
9550 		default:
9551 			break;
9552 		}
9553 	} while (multirt_resolve_next);
9554 
9555 err_ret:
9556 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9557 	if (fire != NULL)
9558 		ire_refrele(fire);
9559 	ipif_refrele(ipif);
9560 	/* Did this packet originate externally? */
9561 	if (dst_ill != NULL)
9562 		ill_refrele(dst_ill);
9563 	if (src_ipif != NULL)
9564 		ipif_refrele(src_ipif);
9565 	if (mp->b_prev || mp->b_next) {
9566 		mp->b_next = NULL;
9567 		mp->b_prev = NULL;
9568 	} else {
9569 		/*
9570 		 * Since ip_wput() isn't close to finished, we fill
9571 		 * in enough of the header for credible error reporting.
9572 		 */
9573 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9574 			/* Failed */
9575 			freemsg(first_mp);
9576 			if (ire != NULL)
9577 				ire_refrele(ire);
9578 			return;
9579 		}
9580 	}
9581 	/*
9582 	 * At this point we will have ire only if RTF_BLACKHOLE
9583 	 * or RTF_REJECT flags are set on the IRE. It will not
9584 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9585 	 */
9586 	if (ire != NULL) {
9587 		if (ire->ire_flags & RTF_BLACKHOLE) {
9588 			ire_refrele(ire);
9589 			freemsg(first_mp);
9590 			return;
9591 		}
9592 		ire_refrele(ire);
9593 	}
9594 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9595 }
9596 
9597 /* Name/Value Table Lookup Routine */
9598 char *
9599 ip_nv_lookup(nv_t *nv, int value)
9600 {
9601 	if (!nv)
9602 		return (NULL);
9603 	for (; nv->nv_name; nv++) {
9604 		if (nv->nv_value == value)
9605 			return (nv->nv_name);
9606 	}
9607 	return ("unknown");
9608 }
9609 
9610 /*
9611  * This is a module open, i.e. this is a control stream for access
9612  * to a DLPI device.  We allocate an ill_t as the instance data in
9613  * this case.
9614  */
9615 int
9616 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9617 {
9618 	ill_t	*ill;
9619 	int	err;
9620 	zoneid_t zoneid;
9621 	netstack_t *ns;
9622 	ip_stack_t *ipst;
9623 
9624 	/*
9625 	 * Prevent unprivileged processes from pushing IP so that
9626 	 * they can't send raw IP.
9627 	 */
9628 	if (secpolicy_net_rawaccess(credp) != 0)
9629 		return (EPERM);
9630 
9631 	ns = netstack_find_by_cred(credp);
9632 	ASSERT(ns != NULL);
9633 	ipst = ns->netstack_ip;
9634 	ASSERT(ipst != NULL);
9635 
9636 	/*
9637 	 * For exclusive stacks we set the zoneid to zero
9638 	 * to make IP operate as if in the global zone.
9639 	 */
9640 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9641 		zoneid = GLOBAL_ZONEID;
9642 	else
9643 		zoneid = crgetzoneid(credp);
9644 
9645 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9646 	q->q_ptr = WR(q)->q_ptr = ill;
9647 	ill->ill_ipst = ipst;
9648 	ill->ill_zoneid = zoneid;
9649 
9650 	/*
9651 	 * ill_init initializes the ill fields and then sends down
9652 	 * down a DL_INFO_REQ after calling qprocson.
9653 	 */
9654 	err = ill_init(q, ill);
9655 	if (err != 0) {
9656 		mi_free(ill);
9657 		netstack_rele(ipst->ips_netstack);
9658 		q->q_ptr = NULL;
9659 		WR(q)->q_ptr = NULL;
9660 		return (err);
9661 	}
9662 
9663 	/* ill_init initializes the ipsq marking this thread as writer */
9664 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9665 	/* Wait for the DL_INFO_ACK */
9666 	mutex_enter(&ill->ill_lock);
9667 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9668 		/*
9669 		 * Return value of 0 indicates a pending signal.
9670 		 */
9671 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9672 		if (err == 0) {
9673 			mutex_exit(&ill->ill_lock);
9674 			(void) ip_close(q, 0);
9675 			return (EINTR);
9676 		}
9677 	}
9678 	mutex_exit(&ill->ill_lock);
9679 
9680 	/*
9681 	 * ip_rput_other could have set an error  in ill_error on
9682 	 * receipt of M_ERROR.
9683 	 */
9684 
9685 	err = ill->ill_error;
9686 	if (err != 0) {
9687 		(void) ip_close(q, 0);
9688 		return (err);
9689 	}
9690 
9691 	ill->ill_credp = credp;
9692 	crhold(credp);
9693 
9694 	mutex_enter(&ipst->ips_ip_mi_lock);
9695 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9696 	    credp);
9697 	mutex_exit(&ipst->ips_ip_mi_lock);
9698 	if (err) {
9699 		(void) ip_close(q, 0);
9700 		return (err);
9701 	}
9702 	return (0);
9703 }
9704 
9705 /* For /dev/ip aka AF_INET open */
9706 int
9707 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9708 {
9709 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9710 }
9711 
9712 /* For /dev/ip6 aka AF_INET6 open */
9713 int
9714 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9715 {
9716 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9717 }
9718 
9719 /* IP open routine. */
9720 int
9721 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9722     boolean_t isv6)
9723 {
9724 	conn_t 		*connp;
9725 	major_t		maj;
9726 	zoneid_t	zoneid;
9727 	netstack_t	*ns;
9728 	ip_stack_t	*ipst;
9729 
9730 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9731 
9732 	/* Allow reopen. */
9733 	if (q->q_ptr != NULL)
9734 		return (0);
9735 
9736 	if (sflag & MODOPEN) {
9737 		/* This is a module open */
9738 		return (ip_modopen(q, devp, flag, sflag, credp));
9739 	}
9740 
9741 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9742 		/*
9743 		 * Non streams based socket looking for a stream
9744 		 * to access IP
9745 		 */
9746 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9747 		    credp, isv6));
9748 	}
9749 
9750 	ns = netstack_find_by_cred(credp);
9751 	ASSERT(ns != NULL);
9752 	ipst = ns->netstack_ip;
9753 	ASSERT(ipst != NULL);
9754 
9755 	/*
9756 	 * For exclusive stacks we set the zoneid to zero
9757 	 * to make IP operate as if in the global zone.
9758 	 */
9759 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9760 		zoneid = GLOBAL_ZONEID;
9761 	else
9762 		zoneid = crgetzoneid(credp);
9763 
9764 	/*
9765 	 * We are opening as a device. This is an IP client stream, and we
9766 	 * allocate an conn_t as the instance data.
9767 	 */
9768 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9769 
9770 	/*
9771 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9772 	 * done by netstack_find_by_cred()
9773 	 */
9774 	netstack_rele(ipst->ips_netstack);
9775 
9776 	connp->conn_zoneid = zoneid;
9777 	connp->conn_sqp = NULL;
9778 	connp->conn_initial_sqp = NULL;
9779 	connp->conn_final_sqp = NULL;
9780 
9781 	connp->conn_upq = q;
9782 	q->q_ptr = WR(q)->q_ptr = connp;
9783 
9784 	if (flag & SO_SOCKSTR)
9785 		connp->conn_flags |= IPCL_SOCKET;
9786 
9787 	/* Minor tells us which /dev entry was opened */
9788 	if (isv6) {
9789 		connp->conn_flags |= IPCL_ISV6;
9790 		connp->conn_af_isv6 = B_TRUE;
9791 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9792 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9793 	} else {
9794 		connp->conn_af_isv6 = B_FALSE;
9795 		connp->conn_pkt_isv6 = B_FALSE;
9796 	}
9797 
9798 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9799 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9800 		connp->conn_minor_arena = ip_minor_arena_la;
9801 	} else {
9802 		/*
9803 		 * Either minor numbers in the large arena were exhausted
9804 		 * or a non socket application is doing the open.
9805 		 * Try to allocate from the small arena.
9806 		 */
9807 		if ((connp->conn_dev =
9808 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9809 			/* CONN_DEC_REF takes care of netstack_rele() */
9810 			q->q_ptr = WR(q)->q_ptr = NULL;
9811 			CONN_DEC_REF(connp);
9812 			return (EBUSY);
9813 		}
9814 		connp->conn_minor_arena = ip_minor_arena_sa;
9815 	}
9816 
9817 	maj = getemajor(*devp);
9818 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9819 
9820 	/*
9821 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9822 	 */
9823 	connp->conn_cred = credp;
9824 
9825 	/*
9826 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9827 	 */
9828 	connp->conn_recv = ip_conn_input;
9829 
9830 	crhold(connp->conn_cred);
9831 
9832 	/*
9833 	 * If the caller has the process-wide flag set, then default to MAC
9834 	 * exempt mode.  This allows read-down to unlabeled hosts.
9835 	 */
9836 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9837 		connp->conn_mac_exempt = B_TRUE;
9838 
9839 	connp->conn_rq = q;
9840 	connp->conn_wq = WR(q);
9841 
9842 	/* Non-zero default values */
9843 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9844 
9845 	/*
9846 	 * Make the conn globally visible to walkers
9847 	 */
9848 	ASSERT(connp->conn_ref == 1);
9849 	mutex_enter(&connp->conn_lock);
9850 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9851 	mutex_exit(&connp->conn_lock);
9852 
9853 	qprocson(q);
9854 
9855 	return (0);
9856 }
9857 
9858 /*
9859  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9860  * Note that there is no race since either ip_output function works - it
9861  * is just an optimization to enter the best ip_output routine directly.
9862  */
9863 void
9864 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9865     ip_stack_t *ipst)
9866 {
9867 	if (isv6)  {
9868 		if (bump_mib) {
9869 			BUMP_MIB(&ipst->ips_ip6_mib,
9870 			    ipIfStatsOutSwitchIPVersion);
9871 		}
9872 		connp->conn_send = ip_output_v6;
9873 		connp->conn_pkt_isv6 = B_TRUE;
9874 	} else {
9875 		if (bump_mib) {
9876 			BUMP_MIB(&ipst->ips_ip_mib,
9877 			    ipIfStatsOutSwitchIPVersion);
9878 		}
9879 		connp->conn_send = ip_output;
9880 		connp->conn_pkt_isv6 = B_FALSE;
9881 	}
9882 
9883 }
9884 
9885 /*
9886  * See if IPsec needs loading because of the options in mp.
9887  */
9888 static boolean_t
9889 ipsec_opt_present(mblk_t *mp)
9890 {
9891 	uint8_t *optcp, *next_optcp, *opt_endcp;
9892 	struct opthdr *opt;
9893 	struct T_opthdr *topt;
9894 	int opthdr_len;
9895 	t_uscalar_t optname, optlevel;
9896 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9897 	ipsec_req_t *ipsr;
9898 
9899 	/*
9900 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9901 	 * return TRUE.
9902 	 */
9903 
9904 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9905 	opt_endcp = optcp + tor->OPT_length;
9906 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9907 		opthdr_len = sizeof (struct T_opthdr);
9908 	} else {		/* O_OPTMGMT_REQ */
9909 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9910 		opthdr_len = sizeof (struct opthdr);
9911 	}
9912 	for (; optcp < opt_endcp; optcp = next_optcp) {
9913 		if (optcp + opthdr_len > opt_endcp)
9914 			return (B_FALSE);	/* Not enough option header. */
9915 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9916 			topt = (struct T_opthdr *)optcp;
9917 			optlevel = topt->level;
9918 			optname = topt->name;
9919 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9920 		} else {
9921 			opt = (struct opthdr *)optcp;
9922 			optlevel = opt->level;
9923 			optname = opt->name;
9924 			next_optcp = optcp + opthdr_len +
9925 			    _TPI_ALIGN_OPT(opt->len);
9926 		}
9927 		if ((next_optcp < optcp) || /* wraparound pointer space */
9928 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9929 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9930 			return (B_FALSE); /* bad option buffer */
9931 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9932 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9933 			/*
9934 			 * Check to see if it's an all-bypass or all-zeroes
9935 			 * IPsec request.  Don't bother loading IPsec if
9936 			 * the socket doesn't want to use it.  (A good example
9937 			 * is a bypass request.)
9938 			 *
9939 			 * Basically, if any of the non-NEVER bits are set,
9940 			 * load IPsec.
9941 			 */
9942 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9943 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9944 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9945 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9946 			    != 0)
9947 				return (B_TRUE);
9948 		}
9949 	}
9950 	return (B_FALSE);
9951 }
9952 
9953 /*
9954  * If conn is is waiting for ipsec to finish loading, kick it.
9955  */
9956 /* ARGSUSED */
9957 static void
9958 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9959 {
9960 	t_scalar_t	optreq_prim;
9961 	mblk_t		*mp;
9962 	cred_t		*cr;
9963 	int		err = 0;
9964 
9965 	/*
9966 	 * This function is called, after ipsec loading is complete.
9967 	 * Since IP checks exclusively and atomically (i.e it prevents
9968 	 * ipsec load from completing until ip_optcom_req completes)
9969 	 * whether ipsec load is complete, there cannot be a race with IP
9970 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9971 	 */
9972 	mutex_enter(&connp->conn_lock);
9973 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9974 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9975 		mp = connp->conn_ipsec_opt_mp;
9976 		connp->conn_ipsec_opt_mp = NULL;
9977 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9978 		mutex_exit(&connp->conn_lock);
9979 
9980 		/*
9981 		 * All Solaris components should pass a db_credp
9982 		 * for this TPI message, hence we ASSERT.
9983 		 * But in case there is some other M_PROTO that looks
9984 		 * like a TPI message sent by some other kernel
9985 		 * component, we check and return an error.
9986 		 */
9987 		cr = msg_getcred(mp, NULL);
9988 		ASSERT(cr != NULL);
9989 		if (cr == NULL) {
9990 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
9991 			if (mp != NULL)
9992 				qreply(connp->conn_wq, mp);
9993 			return;
9994 		}
9995 
9996 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9997 
9998 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9999 		if (optreq_prim == T_OPTMGMT_REQ) {
10000 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10001 			    &ip_opt_obj, B_FALSE);
10002 		} else {
10003 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10004 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10005 			    &ip_opt_obj, B_FALSE);
10006 		}
10007 		if (err != EINPROGRESS)
10008 			CONN_OPER_PENDING_DONE(connp);
10009 		return;
10010 	}
10011 	mutex_exit(&connp->conn_lock);
10012 }
10013 
10014 /*
10015  * Called from the ipsec_loader thread, outside any perimeter, to tell
10016  * ip qenable any of the queues waiting for the ipsec loader to
10017  * complete.
10018  */
10019 void
10020 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10021 {
10022 	netstack_t *ns = ipss->ipsec_netstack;
10023 
10024 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10025 }
10026 
10027 /*
10028  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10029  * determines the grp on which it has to become exclusive, queues the mp
10030  * and IPSQ draining restarts the optmgmt
10031  */
10032 static boolean_t
10033 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10034 {
10035 	conn_t *connp = Q_TO_CONN(q);
10036 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10037 
10038 	/*
10039 	 * Take IPsec requests and treat them special.
10040 	 */
10041 	if (ipsec_opt_present(mp)) {
10042 		/* First check if IPsec is loaded. */
10043 		mutex_enter(&ipss->ipsec_loader_lock);
10044 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10045 			mutex_exit(&ipss->ipsec_loader_lock);
10046 			return (B_FALSE);
10047 		}
10048 		mutex_enter(&connp->conn_lock);
10049 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10050 
10051 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10052 		connp->conn_ipsec_opt_mp = mp;
10053 		mutex_exit(&connp->conn_lock);
10054 		mutex_exit(&ipss->ipsec_loader_lock);
10055 
10056 		ipsec_loader_loadnow(ipss);
10057 		return (B_TRUE);
10058 	}
10059 	return (B_FALSE);
10060 }
10061 
10062 /*
10063  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10064  * all of them are copied to the conn_t. If the req is "zero", the policy is
10065  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10066  * fields.
10067  * We keep only the latest setting of the policy and thus policy setting
10068  * is not incremental/cumulative.
10069  *
10070  * Requests to set policies with multiple alternative actions will
10071  * go through a different API.
10072  */
10073 int
10074 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10075 {
10076 	uint_t ah_req = 0;
10077 	uint_t esp_req = 0;
10078 	uint_t se_req = 0;
10079 	ipsec_selkey_t sel;
10080 	ipsec_act_t *actp = NULL;
10081 	uint_t nact;
10082 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10083 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10084 	ipsec_policy_root_t *pr;
10085 	ipsec_policy_head_t *ph;
10086 	int fam;
10087 	boolean_t is_pol_reset;
10088 	int error = 0;
10089 	netstack_t	*ns = connp->conn_netstack;
10090 	ip_stack_t	*ipst = ns->netstack_ip;
10091 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10092 
10093 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10094 
10095 	/*
10096 	 * The IP_SEC_OPT option does not allow variable length parameters,
10097 	 * hence a request cannot be NULL.
10098 	 */
10099 	if (req == NULL)
10100 		return (EINVAL);
10101 
10102 	ah_req = req->ipsr_ah_req;
10103 	esp_req = req->ipsr_esp_req;
10104 	se_req = req->ipsr_self_encap_req;
10105 
10106 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10107 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10108 		return (EINVAL);
10109 
10110 	/*
10111 	 * Are we dealing with a request to reset the policy (i.e.
10112 	 * zero requests).
10113 	 */
10114 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10115 	    (esp_req & REQ_MASK) == 0 &&
10116 	    (se_req & REQ_MASK) == 0);
10117 
10118 	if (!is_pol_reset) {
10119 		/*
10120 		 * If we couldn't load IPsec, fail with "protocol
10121 		 * not supported".
10122 		 * IPsec may not have been loaded for a request with zero
10123 		 * policies, so we don't fail in this case.
10124 		 */
10125 		mutex_enter(&ipss->ipsec_loader_lock);
10126 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10127 			mutex_exit(&ipss->ipsec_loader_lock);
10128 			return (EPROTONOSUPPORT);
10129 		}
10130 		mutex_exit(&ipss->ipsec_loader_lock);
10131 
10132 		/*
10133 		 * Test for valid requests. Invalid algorithms
10134 		 * need to be tested by IPsec code because new
10135 		 * algorithms can be added dynamically.
10136 		 */
10137 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10138 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10139 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10140 			return (EINVAL);
10141 		}
10142 
10143 		/*
10144 		 * Only privileged users can issue these
10145 		 * requests.
10146 		 */
10147 		if (((ah_req & IPSEC_PREF_NEVER) ||
10148 		    (esp_req & IPSEC_PREF_NEVER) ||
10149 		    (se_req & IPSEC_PREF_NEVER)) &&
10150 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10151 			return (EPERM);
10152 		}
10153 
10154 		/*
10155 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10156 		 * are mutually exclusive.
10157 		 */
10158 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10159 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10160 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10161 			/* Both of them are set */
10162 			return (EINVAL);
10163 		}
10164 	}
10165 
10166 	mutex_enter(&connp->conn_lock);
10167 
10168 	/*
10169 	 * If we have already cached policies in ip_bind_connected*(), don't
10170 	 * let them change now. We cache policies for connections
10171 	 * whose src,dst [addr, port] is known.
10172 	 */
10173 	if (connp->conn_policy_cached) {
10174 		mutex_exit(&connp->conn_lock);
10175 		return (EINVAL);
10176 	}
10177 
10178 	/*
10179 	 * We have a zero policies, reset the connection policy if already
10180 	 * set. This will cause the connection to inherit the
10181 	 * global policy, if any.
10182 	 */
10183 	if (is_pol_reset) {
10184 		if (connp->conn_policy != NULL) {
10185 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10186 			connp->conn_policy = NULL;
10187 		}
10188 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10189 		connp->conn_in_enforce_policy = B_FALSE;
10190 		connp->conn_out_enforce_policy = B_FALSE;
10191 		mutex_exit(&connp->conn_lock);
10192 		return (0);
10193 	}
10194 
10195 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10196 	    ipst->ips_netstack);
10197 	if (ph == NULL)
10198 		goto enomem;
10199 
10200 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10201 	if (actp == NULL)
10202 		goto enomem;
10203 
10204 	/*
10205 	 * Always allocate IPv4 policy entries, since they can also
10206 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10207 	 */
10208 	bzero(&sel, sizeof (sel));
10209 	sel.ipsl_valid = IPSL_IPV4;
10210 
10211 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10212 	    ipst->ips_netstack);
10213 	if (pin4 == NULL)
10214 		goto enomem;
10215 
10216 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10217 	    ipst->ips_netstack);
10218 	if (pout4 == NULL)
10219 		goto enomem;
10220 
10221 	if (connp->conn_af_isv6) {
10222 		/*
10223 		 * We're looking at a v6 socket, also allocate the
10224 		 * v6-specific entries...
10225 		 */
10226 		sel.ipsl_valid = IPSL_IPV6;
10227 		pin6 = ipsec_policy_create(&sel, actp, nact,
10228 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10229 		if (pin6 == NULL)
10230 			goto enomem;
10231 
10232 		pout6 = ipsec_policy_create(&sel, actp, nact,
10233 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10234 		if (pout6 == NULL)
10235 			goto enomem;
10236 
10237 		/*
10238 		 * .. and file them away in the right place.
10239 		 */
10240 		fam = IPSEC_AF_V6;
10241 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10242 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10243 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10244 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10245 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10246 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10247 	}
10248 
10249 	ipsec_actvec_free(actp, nact);
10250 
10251 	/*
10252 	 * File the v4 policies.
10253 	 */
10254 	fam = IPSEC_AF_V4;
10255 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10256 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10257 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10258 
10259 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10260 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10261 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10262 
10263 	/*
10264 	 * If the requests need security, set enforce_policy.
10265 	 * If the requests are IPSEC_PREF_NEVER, one should
10266 	 * still set conn_out_enforce_policy so that an ipsec_out
10267 	 * gets attached in ip_wput. This is needed so that
10268 	 * for connections that we don't cache policy in ip_bind,
10269 	 * if global policy matches in ip_wput_attach_policy, we
10270 	 * don't wrongly inherit global policy. Similarly, we need
10271 	 * to set conn_in_enforce_policy also so that we don't verify
10272 	 * policy wrongly.
10273 	 */
10274 	if ((ah_req & REQ_MASK) != 0 ||
10275 	    (esp_req & REQ_MASK) != 0 ||
10276 	    (se_req & REQ_MASK) != 0) {
10277 		connp->conn_in_enforce_policy = B_TRUE;
10278 		connp->conn_out_enforce_policy = B_TRUE;
10279 		connp->conn_flags |= IPCL_CHECK_POLICY;
10280 	}
10281 
10282 	mutex_exit(&connp->conn_lock);
10283 	return (error);
10284 #undef REQ_MASK
10285 
10286 	/*
10287 	 * Common memory-allocation-failure exit path.
10288 	 */
10289 enomem:
10290 	mutex_exit(&connp->conn_lock);
10291 	if (actp != NULL)
10292 		ipsec_actvec_free(actp, nact);
10293 	if (pin4 != NULL)
10294 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10295 	if (pout4 != NULL)
10296 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10297 	if (pin6 != NULL)
10298 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10299 	if (pout6 != NULL)
10300 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10301 	return (ENOMEM);
10302 }
10303 
10304 /*
10305  * Only for options that pass in an IP addr. Currently only V4 options
10306  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10307  * So this function assumes level is IPPROTO_IP
10308  */
10309 int
10310 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10311     mblk_t *first_mp)
10312 {
10313 	ipif_t *ipif = NULL;
10314 	int error;
10315 	ill_t *ill;
10316 	int zoneid;
10317 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10318 
10319 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10320 
10321 	if (addr != INADDR_ANY || checkonly) {
10322 		ASSERT(connp != NULL);
10323 		zoneid = IPCL_ZONEID(connp);
10324 		if (option == IP_NEXTHOP) {
10325 			ipif = ipif_lookup_onlink_addr(addr,
10326 			    connp->conn_zoneid, ipst);
10327 		} else {
10328 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10329 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10330 			    &error, ipst);
10331 		}
10332 		if (ipif == NULL) {
10333 			if (error == EINPROGRESS)
10334 				return (error);
10335 			if ((option == IP_MULTICAST_IF) ||
10336 			    (option == IP_NEXTHOP))
10337 				return (EHOSTUNREACH);
10338 			else
10339 				return (EINVAL);
10340 		} else if (checkonly) {
10341 			if (option == IP_MULTICAST_IF) {
10342 				ill = ipif->ipif_ill;
10343 				/* not supported by the virtual network iface */
10344 				if (IS_VNI(ill)) {
10345 					ipif_refrele(ipif);
10346 					return (EINVAL);
10347 				}
10348 			}
10349 			ipif_refrele(ipif);
10350 			return (0);
10351 		}
10352 		ill = ipif->ipif_ill;
10353 		mutex_enter(&connp->conn_lock);
10354 		mutex_enter(&ill->ill_lock);
10355 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10356 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10357 			mutex_exit(&ill->ill_lock);
10358 			mutex_exit(&connp->conn_lock);
10359 			ipif_refrele(ipif);
10360 			return (option == IP_MULTICAST_IF ?
10361 			    EHOSTUNREACH : EINVAL);
10362 		}
10363 	} else {
10364 		mutex_enter(&connp->conn_lock);
10365 	}
10366 
10367 	/* None of the options below are supported on the VNI */
10368 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10369 		mutex_exit(&ill->ill_lock);
10370 		mutex_exit(&connp->conn_lock);
10371 		ipif_refrele(ipif);
10372 		return (EINVAL);
10373 	}
10374 
10375 	switch (option) {
10376 	case IP_MULTICAST_IF:
10377 		connp->conn_multicast_ipif = ipif;
10378 		break;
10379 	case IP_NEXTHOP:
10380 		connp->conn_nexthop_v4 = addr;
10381 		connp->conn_nexthop_set = B_TRUE;
10382 		break;
10383 	}
10384 
10385 	if (ipif != NULL) {
10386 		mutex_exit(&ill->ill_lock);
10387 		mutex_exit(&connp->conn_lock);
10388 		ipif_refrele(ipif);
10389 		return (0);
10390 	}
10391 	mutex_exit(&connp->conn_lock);
10392 	/* We succeded in cleared the option */
10393 	return (0);
10394 }
10395 
10396 /*
10397  * For options that pass in an ifindex specifying the ill. V6 options always
10398  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10399  */
10400 int
10401 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10402     int level, int option, mblk_t *first_mp)
10403 {
10404 	ill_t *ill = NULL;
10405 	int error = 0;
10406 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10407 
10408 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10409 	if (ifindex != 0) {
10410 		ASSERT(connp != NULL);
10411 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10412 		    first_mp, ip_restart_optmgmt, &error, ipst);
10413 		if (ill != NULL) {
10414 			if (checkonly) {
10415 				/* not supported by the virtual network iface */
10416 				if (IS_VNI(ill)) {
10417 					ill_refrele(ill);
10418 					return (EINVAL);
10419 				}
10420 				ill_refrele(ill);
10421 				return (0);
10422 			}
10423 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10424 			    0, NULL)) {
10425 				ill_refrele(ill);
10426 				ill = NULL;
10427 				mutex_enter(&connp->conn_lock);
10428 				goto setit;
10429 			}
10430 			mutex_enter(&connp->conn_lock);
10431 			mutex_enter(&ill->ill_lock);
10432 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10433 				mutex_exit(&ill->ill_lock);
10434 				mutex_exit(&connp->conn_lock);
10435 				ill_refrele(ill);
10436 				ill = NULL;
10437 				mutex_enter(&connp->conn_lock);
10438 			}
10439 			goto setit;
10440 		} else if (error == EINPROGRESS) {
10441 			return (error);
10442 		} else {
10443 			error = 0;
10444 		}
10445 	}
10446 	mutex_enter(&connp->conn_lock);
10447 setit:
10448 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10449 
10450 	/*
10451 	 * The options below assume that the ILL (if any) transmits and/or
10452 	 * receives traffic. Neither of which is true for the virtual network
10453 	 * interface, so fail setting these on a VNI.
10454 	 */
10455 	if (IS_VNI(ill)) {
10456 		ASSERT(ill != NULL);
10457 		mutex_exit(&ill->ill_lock);
10458 		mutex_exit(&connp->conn_lock);
10459 		ill_refrele(ill);
10460 		return (EINVAL);
10461 	}
10462 
10463 	if (level == IPPROTO_IP) {
10464 		switch (option) {
10465 		case IP_BOUND_IF:
10466 			connp->conn_incoming_ill = ill;
10467 			connp->conn_outgoing_ill = ill;
10468 			break;
10469 
10470 		case IP_MULTICAST_IF:
10471 			/*
10472 			 * This option is an internal special. The socket
10473 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10474 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10475 			 * specifies an ifindex and we try first on V6 ill's.
10476 			 * If we don't find one, we they try using on v4 ill's
10477 			 * intenally and we come here.
10478 			 */
10479 			if (!checkonly && ill != NULL) {
10480 				ipif_t	*ipif;
10481 				ipif = ill->ill_ipif;
10482 
10483 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10484 					mutex_exit(&ill->ill_lock);
10485 					mutex_exit(&connp->conn_lock);
10486 					ill_refrele(ill);
10487 					ill = NULL;
10488 					mutex_enter(&connp->conn_lock);
10489 				} else {
10490 					connp->conn_multicast_ipif = ipif;
10491 				}
10492 			}
10493 			break;
10494 
10495 		case IP_DHCPINIT_IF:
10496 			if (connp->conn_dhcpinit_ill != NULL) {
10497 				/*
10498 				 * We've locked the conn so conn_cleanup_ill()
10499 				 * cannot clear conn_dhcpinit_ill -- so it's
10500 				 * safe to access the ill.
10501 				 */
10502 				ill_t *oill = connp->conn_dhcpinit_ill;
10503 
10504 				ASSERT(oill->ill_dhcpinit != 0);
10505 				atomic_dec_32(&oill->ill_dhcpinit);
10506 				connp->conn_dhcpinit_ill = NULL;
10507 			}
10508 
10509 			if (ill != NULL) {
10510 				connp->conn_dhcpinit_ill = ill;
10511 				atomic_inc_32(&ill->ill_dhcpinit);
10512 			}
10513 			break;
10514 		}
10515 	} else {
10516 		switch (option) {
10517 		case IPV6_BOUND_IF:
10518 			connp->conn_incoming_ill = ill;
10519 			connp->conn_outgoing_ill = ill;
10520 			break;
10521 
10522 		case IPV6_MULTICAST_IF:
10523 			/*
10524 			 * Set conn_multicast_ill to be the IPv6 ill.
10525 			 * Set conn_multicast_ipif to be an IPv4 ipif
10526 			 * for ifindex to make IPv4 mapped addresses
10527 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10528 			 * Even if no IPv6 ill exists for the ifindex
10529 			 * we need to check for an IPv4 ifindex in order
10530 			 * for this to work with mapped addresses. In that
10531 			 * case only set conn_multicast_ipif.
10532 			 */
10533 			if (!checkonly) {
10534 				if (ifindex == 0) {
10535 					connp->conn_multicast_ill = NULL;
10536 					connp->conn_multicast_ipif = NULL;
10537 				} else if (ill != NULL) {
10538 					connp->conn_multicast_ill = ill;
10539 				}
10540 			}
10541 			break;
10542 		}
10543 	}
10544 
10545 	if (ill != NULL) {
10546 		mutex_exit(&ill->ill_lock);
10547 		mutex_exit(&connp->conn_lock);
10548 		ill_refrele(ill);
10549 		return (0);
10550 	}
10551 	mutex_exit(&connp->conn_lock);
10552 	/*
10553 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10554 	 * locate the ill and could not set the option (ifindex != 0)
10555 	 */
10556 	return (ifindex == 0 ? 0 : EINVAL);
10557 }
10558 
10559 /* This routine sets socket options. */
10560 /* ARGSUSED */
10561 int
10562 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10563     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10564     void *dummy, cred_t *cr, mblk_t *first_mp)
10565 {
10566 	int		*i1 = (int *)invalp;
10567 	conn_t		*connp = Q_TO_CONN(q);
10568 	int		error = 0;
10569 	boolean_t	checkonly;
10570 	ire_t		*ire;
10571 	boolean_t	found;
10572 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10573 
10574 	switch (optset_context) {
10575 
10576 	case SETFN_OPTCOM_CHECKONLY:
10577 		checkonly = B_TRUE;
10578 		/*
10579 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10580 		 * inlen != 0 implies value supplied and
10581 		 * 	we have to "pretend" to set it.
10582 		 * inlen == 0 implies that there is no
10583 		 * 	value part in T_CHECK request and just validation
10584 		 * done elsewhere should be enough, we just return here.
10585 		 */
10586 		if (inlen == 0) {
10587 			*outlenp = 0;
10588 			return (0);
10589 		}
10590 		break;
10591 	case SETFN_OPTCOM_NEGOTIATE:
10592 	case SETFN_UD_NEGOTIATE:
10593 	case SETFN_CONN_NEGOTIATE:
10594 		checkonly = B_FALSE;
10595 		break;
10596 	default:
10597 		/*
10598 		 * We should never get here
10599 		 */
10600 		*outlenp = 0;
10601 		return (EINVAL);
10602 	}
10603 
10604 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10605 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10606 
10607 	/*
10608 	 * For fixed length options, no sanity check
10609 	 * of passed in length is done. It is assumed *_optcom_req()
10610 	 * routines do the right thing.
10611 	 */
10612 
10613 	switch (level) {
10614 	case SOL_SOCKET:
10615 		/*
10616 		 * conn_lock protects the bitfields, and is used to
10617 		 * set the fields atomically.
10618 		 */
10619 		switch (name) {
10620 		case SO_BROADCAST:
10621 			if (!checkonly) {
10622 				/* TODO: use value someplace? */
10623 				mutex_enter(&connp->conn_lock);
10624 				connp->conn_broadcast = *i1 ? 1 : 0;
10625 				mutex_exit(&connp->conn_lock);
10626 			}
10627 			break;	/* goto sizeof (int) option return */
10628 		case SO_USELOOPBACK:
10629 			if (!checkonly) {
10630 				/* TODO: use value someplace? */
10631 				mutex_enter(&connp->conn_lock);
10632 				connp->conn_loopback = *i1 ? 1 : 0;
10633 				mutex_exit(&connp->conn_lock);
10634 			}
10635 			break;	/* goto sizeof (int) option return */
10636 		case SO_DONTROUTE:
10637 			if (!checkonly) {
10638 				mutex_enter(&connp->conn_lock);
10639 				connp->conn_dontroute = *i1 ? 1 : 0;
10640 				mutex_exit(&connp->conn_lock);
10641 			}
10642 			break;	/* goto sizeof (int) option return */
10643 		case SO_REUSEADDR:
10644 			if (!checkonly) {
10645 				mutex_enter(&connp->conn_lock);
10646 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10647 				mutex_exit(&connp->conn_lock);
10648 			}
10649 			break;	/* goto sizeof (int) option return */
10650 		case SO_PROTOTYPE:
10651 			if (!checkonly) {
10652 				mutex_enter(&connp->conn_lock);
10653 				connp->conn_proto = *i1;
10654 				mutex_exit(&connp->conn_lock);
10655 			}
10656 			break;	/* goto sizeof (int) option return */
10657 		case SO_ALLZONES:
10658 			if (!checkonly) {
10659 				mutex_enter(&connp->conn_lock);
10660 				if (IPCL_IS_BOUND(connp)) {
10661 					mutex_exit(&connp->conn_lock);
10662 					return (EINVAL);
10663 				}
10664 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10665 				mutex_exit(&connp->conn_lock);
10666 			}
10667 			break;	/* goto sizeof (int) option return */
10668 		case SO_ANON_MLP:
10669 			if (!checkonly) {
10670 				mutex_enter(&connp->conn_lock);
10671 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10672 				mutex_exit(&connp->conn_lock);
10673 			}
10674 			break;	/* goto sizeof (int) option return */
10675 		case SO_MAC_EXEMPT:
10676 			if (secpolicy_net_mac_aware(cr) != 0 ||
10677 			    IPCL_IS_BOUND(connp))
10678 				return (EACCES);
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			break;	/* goto sizeof (int) option return */
10685 		default:
10686 			/*
10687 			 * "soft" error (negative)
10688 			 * option not handled at this level
10689 			 * Note: Do not modify *outlenp
10690 			 */
10691 			return (-EINVAL);
10692 		}
10693 		break;
10694 	case IPPROTO_IP:
10695 		switch (name) {
10696 		case IP_NEXTHOP:
10697 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10698 				return (EPERM);
10699 			/* FALLTHRU */
10700 		case IP_MULTICAST_IF: {
10701 			ipaddr_t addr = *i1;
10702 
10703 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10704 			    first_mp);
10705 			if (error != 0)
10706 				return (error);
10707 			break;	/* goto sizeof (int) option return */
10708 		}
10709 
10710 		case IP_MULTICAST_TTL:
10711 			/* Recorded in transport above IP */
10712 			*outvalp = *invalp;
10713 			*outlenp = sizeof (uchar_t);
10714 			return (0);
10715 		case IP_MULTICAST_LOOP:
10716 			if (!checkonly) {
10717 				mutex_enter(&connp->conn_lock);
10718 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10719 				mutex_exit(&connp->conn_lock);
10720 			}
10721 			*outvalp = *invalp;
10722 			*outlenp = sizeof (uchar_t);
10723 			return (0);
10724 		case IP_ADD_MEMBERSHIP:
10725 		case MCAST_JOIN_GROUP:
10726 		case IP_DROP_MEMBERSHIP:
10727 		case MCAST_LEAVE_GROUP: {
10728 			struct ip_mreq *mreqp;
10729 			struct group_req *greqp;
10730 			ire_t *ire;
10731 			boolean_t done = B_FALSE;
10732 			ipaddr_t group, ifaddr;
10733 			struct sockaddr_in *sin;
10734 			uint32_t *ifindexp;
10735 			boolean_t mcast_opt = B_TRUE;
10736 			mcast_record_t fmode;
10737 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10738 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10739 
10740 			switch (name) {
10741 			case IP_ADD_MEMBERSHIP:
10742 				mcast_opt = B_FALSE;
10743 				/* FALLTHRU */
10744 			case MCAST_JOIN_GROUP:
10745 				fmode = MODE_IS_EXCLUDE;
10746 				optfn = ip_opt_add_group;
10747 				break;
10748 
10749 			case IP_DROP_MEMBERSHIP:
10750 				mcast_opt = B_FALSE;
10751 				/* FALLTHRU */
10752 			case MCAST_LEAVE_GROUP:
10753 				fmode = MODE_IS_INCLUDE;
10754 				optfn = ip_opt_delete_group;
10755 				break;
10756 			}
10757 
10758 			if (mcast_opt) {
10759 				greqp = (struct group_req *)i1;
10760 				sin = (struct sockaddr_in *)&greqp->gr_group;
10761 				if (sin->sin_family != AF_INET) {
10762 					*outlenp = 0;
10763 					return (ENOPROTOOPT);
10764 				}
10765 				group = (ipaddr_t)sin->sin_addr.s_addr;
10766 				ifaddr = INADDR_ANY;
10767 				ifindexp = &greqp->gr_interface;
10768 			} else {
10769 				mreqp = (struct ip_mreq *)i1;
10770 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10771 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10772 				ifindexp = NULL;
10773 			}
10774 
10775 			/*
10776 			 * In the multirouting case, we need to replicate
10777 			 * the request on all interfaces that will take part
10778 			 * in replication.  We do so because multirouting is
10779 			 * reflective, thus we will probably receive multi-
10780 			 * casts on those interfaces.
10781 			 * The ip_multirt_apply_membership() succeeds if the
10782 			 * operation succeeds on at least one interface.
10783 			 */
10784 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10785 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10786 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10787 			if (ire != NULL) {
10788 				if (ire->ire_flags & RTF_MULTIRT) {
10789 					error = ip_multirt_apply_membership(
10790 					    optfn, ire, connp, checkonly, group,
10791 					    fmode, INADDR_ANY, first_mp);
10792 					done = B_TRUE;
10793 				}
10794 				ire_refrele(ire);
10795 			}
10796 			if (!done) {
10797 				error = optfn(connp, checkonly, group, ifaddr,
10798 				    ifindexp, fmode, INADDR_ANY, first_mp);
10799 			}
10800 			if (error) {
10801 				/*
10802 				 * EINPROGRESS is a soft error, needs retry
10803 				 * so don't make *outlenp zero.
10804 				 */
10805 				if (error != EINPROGRESS)
10806 					*outlenp = 0;
10807 				return (error);
10808 			}
10809 			/* OK return - copy input buffer into output buffer */
10810 			if (invalp != outvalp) {
10811 				/* don't trust bcopy for identical src/dst */
10812 				bcopy(invalp, outvalp, inlen);
10813 			}
10814 			*outlenp = inlen;
10815 			return (0);
10816 		}
10817 		case IP_BLOCK_SOURCE:
10818 		case IP_UNBLOCK_SOURCE:
10819 		case IP_ADD_SOURCE_MEMBERSHIP:
10820 		case IP_DROP_SOURCE_MEMBERSHIP:
10821 		case MCAST_BLOCK_SOURCE:
10822 		case MCAST_UNBLOCK_SOURCE:
10823 		case MCAST_JOIN_SOURCE_GROUP:
10824 		case MCAST_LEAVE_SOURCE_GROUP: {
10825 			struct ip_mreq_source *imreqp;
10826 			struct group_source_req *gsreqp;
10827 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10828 			uint32_t ifindex = 0;
10829 			mcast_record_t fmode;
10830 			struct sockaddr_in *sin;
10831 			ire_t *ire;
10832 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10833 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10834 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10835 
10836 			switch (name) {
10837 			case IP_BLOCK_SOURCE:
10838 				mcast_opt = B_FALSE;
10839 				/* FALLTHRU */
10840 			case MCAST_BLOCK_SOURCE:
10841 				fmode = MODE_IS_EXCLUDE;
10842 				optfn = ip_opt_add_group;
10843 				break;
10844 
10845 			case IP_UNBLOCK_SOURCE:
10846 				mcast_opt = B_FALSE;
10847 				/* FALLTHRU */
10848 			case MCAST_UNBLOCK_SOURCE:
10849 				fmode = MODE_IS_EXCLUDE;
10850 				optfn = ip_opt_delete_group;
10851 				break;
10852 
10853 			case IP_ADD_SOURCE_MEMBERSHIP:
10854 				mcast_opt = B_FALSE;
10855 				/* FALLTHRU */
10856 			case MCAST_JOIN_SOURCE_GROUP:
10857 				fmode = MODE_IS_INCLUDE;
10858 				optfn = ip_opt_add_group;
10859 				break;
10860 
10861 			case IP_DROP_SOURCE_MEMBERSHIP:
10862 				mcast_opt = B_FALSE;
10863 				/* FALLTHRU */
10864 			case MCAST_LEAVE_SOURCE_GROUP:
10865 				fmode = MODE_IS_INCLUDE;
10866 				optfn = ip_opt_delete_group;
10867 				break;
10868 			}
10869 
10870 			if (mcast_opt) {
10871 				gsreqp = (struct group_source_req *)i1;
10872 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10873 					*outlenp = 0;
10874 					return (ENOPROTOOPT);
10875 				}
10876 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10877 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10878 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10879 				src = (ipaddr_t)sin->sin_addr.s_addr;
10880 				ifindex = gsreqp->gsr_interface;
10881 			} else {
10882 				imreqp = (struct ip_mreq_source *)i1;
10883 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10884 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10885 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10886 			}
10887 
10888 			/*
10889 			 * In the multirouting case, we need to replicate
10890 			 * the request as noted in the mcast cases above.
10891 			 */
10892 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10893 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10894 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10895 			if (ire != NULL) {
10896 				if (ire->ire_flags & RTF_MULTIRT) {
10897 					error = ip_multirt_apply_membership(
10898 					    optfn, ire, connp, checkonly, grp,
10899 					    fmode, src, first_mp);
10900 					done = B_TRUE;
10901 				}
10902 				ire_refrele(ire);
10903 			}
10904 			if (!done) {
10905 				error = optfn(connp, checkonly, grp, ifaddr,
10906 				    &ifindex, fmode, src, first_mp);
10907 			}
10908 			if (error != 0) {
10909 				/*
10910 				 * EINPROGRESS is a soft error, needs retry
10911 				 * so don't make *outlenp zero.
10912 				 */
10913 				if (error != EINPROGRESS)
10914 					*outlenp = 0;
10915 				return (error);
10916 			}
10917 			/* OK return - copy input buffer into output buffer */
10918 			if (invalp != outvalp) {
10919 				bcopy(invalp, outvalp, inlen);
10920 			}
10921 			*outlenp = inlen;
10922 			return (0);
10923 		}
10924 		case IP_SEC_OPT:
10925 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10926 			if (error != 0) {
10927 				*outlenp = 0;
10928 				return (error);
10929 			}
10930 			break;
10931 		case IP_HDRINCL:
10932 		case IP_OPTIONS:
10933 		case T_IP_OPTIONS:
10934 		case IP_TOS:
10935 		case T_IP_TOS:
10936 		case IP_TTL:
10937 		case IP_RECVDSTADDR:
10938 		case IP_RECVOPTS:
10939 			/* OK return - copy input buffer into output buffer */
10940 			if (invalp != outvalp) {
10941 				/* don't trust bcopy for identical src/dst */
10942 				bcopy(invalp, outvalp, inlen);
10943 			}
10944 			*outlenp = inlen;
10945 			return (0);
10946 		case IP_RECVIF:
10947 			/* Retrieve the inbound interface index */
10948 			if (!checkonly) {
10949 				mutex_enter(&connp->conn_lock);
10950 				connp->conn_recvif = *i1 ? 1 : 0;
10951 				mutex_exit(&connp->conn_lock);
10952 			}
10953 			break;	/* goto sizeof (int) option return */
10954 		case IP_RECVPKTINFO:
10955 			if (!checkonly) {
10956 				mutex_enter(&connp->conn_lock);
10957 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10958 				mutex_exit(&connp->conn_lock);
10959 			}
10960 			break;	/* goto sizeof (int) option return */
10961 		case IP_RECVSLLA:
10962 			/* Retrieve the source link layer address */
10963 			if (!checkonly) {
10964 				mutex_enter(&connp->conn_lock);
10965 				connp->conn_recvslla = *i1 ? 1 : 0;
10966 				mutex_exit(&connp->conn_lock);
10967 			}
10968 			break;	/* goto sizeof (int) option return */
10969 		case MRT_INIT:
10970 		case MRT_DONE:
10971 		case MRT_ADD_VIF:
10972 		case MRT_DEL_VIF:
10973 		case MRT_ADD_MFC:
10974 		case MRT_DEL_MFC:
10975 		case MRT_ASSERT:
10976 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10977 				*outlenp = 0;
10978 				return (error);
10979 			}
10980 			error = ip_mrouter_set((int)name, q, checkonly,
10981 			    (uchar_t *)invalp, inlen, first_mp);
10982 			if (error) {
10983 				*outlenp = 0;
10984 				return (error);
10985 			}
10986 			/* OK return - copy input buffer into output buffer */
10987 			if (invalp != outvalp) {
10988 				/* don't trust bcopy for identical src/dst */
10989 				bcopy(invalp, outvalp, inlen);
10990 			}
10991 			*outlenp = inlen;
10992 			return (0);
10993 		case IP_BOUND_IF:
10994 		case IP_DHCPINIT_IF:
10995 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10996 			    level, name, first_mp);
10997 			if (error != 0)
10998 				return (error);
10999 			break; 		/* goto sizeof (int) option return */
11000 
11001 		case IP_UNSPEC_SRC:
11002 			/* Allow sending with a zero source address */
11003 			if (!checkonly) {
11004 				mutex_enter(&connp->conn_lock);
11005 				connp->conn_unspec_src = *i1 ? 1 : 0;
11006 				mutex_exit(&connp->conn_lock);
11007 			}
11008 			break;	/* goto sizeof (int) option return */
11009 		default:
11010 			/*
11011 			 * "soft" error (negative)
11012 			 * option not handled at this level
11013 			 * Note: Do not modify *outlenp
11014 			 */
11015 			return (-EINVAL);
11016 		}
11017 		break;
11018 	case IPPROTO_IPV6:
11019 		switch (name) {
11020 		case IPV6_BOUND_IF:
11021 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11022 			    level, name, first_mp);
11023 			if (error != 0)
11024 				return (error);
11025 			break; 		/* goto sizeof (int) option return */
11026 
11027 		case IPV6_MULTICAST_IF:
11028 			/*
11029 			 * The only possible errors are EINPROGRESS and
11030 			 * EINVAL. EINPROGRESS will be restarted and is not
11031 			 * a hard error. We call this option on both V4 and V6
11032 			 * If both return EINVAL, then this call returns
11033 			 * EINVAL. If at least one of them succeeds we
11034 			 * return success.
11035 			 */
11036 			found = B_FALSE;
11037 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11038 			    level, name, first_mp);
11039 			if (error == EINPROGRESS)
11040 				return (error);
11041 			if (error == 0)
11042 				found = B_TRUE;
11043 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11044 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11045 			if (error == 0)
11046 				found = B_TRUE;
11047 			if (!found)
11048 				return (error);
11049 			break; 		/* goto sizeof (int) option return */
11050 
11051 		case IPV6_MULTICAST_HOPS:
11052 			/* Recorded in transport above IP */
11053 			break;	/* goto sizeof (int) option return */
11054 		case IPV6_MULTICAST_LOOP:
11055 			if (!checkonly) {
11056 				mutex_enter(&connp->conn_lock);
11057 				connp->conn_multicast_loop = *i1;
11058 				mutex_exit(&connp->conn_lock);
11059 			}
11060 			break;	/* goto sizeof (int) option return */
11061 		case IPV6_JOIN_GROUP:
11062 		case MCAST_JOIN_GROUP:
11063 		case IPV6_LEAVE_GROUP:
11064 		case MCAST_LEAVE_GROUP: {
11065 			struct ipv6_mreq *ip_mreqp;
11066 			struct group_req *greqp;
11067 			ire_t *ire;
11068 			boolean_t done = B_FALSE;
11069 			in6_addr_t groupv6;
11070 			uint32_t ifindex;
11071 			boolean_t mcast_opt = B_TRUE;
11072 			mcast_record_t fmode;
11073 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11074 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11075 
11076 			switch (name) {
11077 			case IPV6_JOIN_GROUP:
11078 				mcast_opt = B_FALSE;
11079 				/* FALLTHRU */
11080 			case MCAST_JOIN_GROUP:
11081 				fmode = MODE_IS_EXCLUDE;
11082 				optfn = ip_opt_add_group_v6;
11083 				break;
11084 
11085 			case IPV6_LEAVE_GROUP:
11086 				mcast_opt = B_FALSE;
11087 				/* FALLTHRU */
11088 			case MCAST_LEAVE_GROUP:
11089 				fmode = MODE_IS_INCLUDE;
11090 				optfn = ip_opt_delete_group_v6;
11091 				break;
11092 			}
11093 
11094 			if (mcast_opt) {
11095 				struct sockaddr_in *sin;
11096 				struct sockaddr_in6 *sin6;
11097 				greqp = (struct group_req *)i1;
11098 				if (greqp->gr_group.ss_family == AF_INET) {
11099 					sin = (struct sockaddr_in *)
11100 					    &(greqp->gr_group);
11101 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11102 					    &groupv6);
11103 				} else {
11104 					sin6 = (struct sockaddr_in6 *)
11105 					    &(greqp->gr_group);
11106 					groupv6 = sin6->sin6_addr;
11107 				}
11108 				ifindex = greqp->gr_interface;
11109 			} else {
11110 				ip_mreqp = (struct ipv6_mreq *)i1;
11111 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11112 				ifindex = ip_mreqp->ipv6mr_interface;
11113 			}
11114 			/*
11115 			 * In the multirouting case, we need to replicate
11116 			 * the request on all interfaces that will take part
11117 			 * in replication.  We do so because multirouting is
11118 			 * reflective, thus we will probably receive multi-
11119 			 * casts on those interfaces.
11120 			 * The ip_multirt_apply_membership_v6() succeeds if
11121 			 * the operation succeeds on at least one interface.
11122 			 */
11123 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11124 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11125 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11126 			if (ire != NULL) {
11127 				if (ire->ire_flags & RTF_MULTIRT) {
11128 					error = ip_multirt_apply_membership_v6(
11129 					    optfn, ire, connp, checkonly,
11130 					    &groupv6, fmode, &ipv6_all_zeros,
11131 					    first_mp);
11132 					done = B_TRUE;
11133 				}
11134 				ire_refrele(ire);
11135 			}
11136 			if (!done) {
11137 				error = optfn(connp, checkonly, &groupv6,
11138 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11139 			}
11140 			if (error) {
11141 				/*
11142 				 * EINPROGRESS is a soft error, needs retry
11143 				 * so don't make *outlenp zero.
11144 				 */
11145 				if (error != EINPROGRESS)
11146 					*outlenp = 0;
11147 				return (error);
11148 			}
11149 			/* OK return - copy input buffer into output buffer */
11150 			if (invalp != outvalp) {
11151 				/* don't trust bcopy for identical src/dst */
11152 				bcopy(invalp, outvalp, inlen);
11153 			}
11154 			*outlenp = inlen;
11155 			return (0);
11156 		}
11157 		case MCAST_BLOCK_SOURCE:
11158 		case MCAST_UNBLOCK_SOURCE:
11159 		case MCAST_JOIN_SOURCE_GROUP:
11160 		case MCAST_LEAVE_SOURCE_GROUP: {
11161 			struct group_source_req *gsreqp;
11162 			in6_addr_t v6grp, v6src;
11163 			uint32_t ifindex;
11164 			mcast_record_t fmode;
11165 			ire_t *ire;
11166 			boolean_t done = B_FALSE;
11167 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11168 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11169 
11170 			switch (name) {
11171 			case MCAST_BLOCK_SOURCE:
11172 				fmode = MODE_IS_EXCLUDE;
11173 				optfn = ip_opt_add_group_v6;
11174 				break;
11175 			case MCAST_UNBLOCK_SOURCE:
11176 				fmode = MODE_IS_EXCLUDE;
11177 				optfn = ip_opt_delete_group_v6;
11178 				break;
11179 			case MCAST_JOIN_SOURCE_GROUP:
11180 				fmode = MODE_IS_INCLUDE;
11181 				optfn = ip_opt_add_group_v6;
11182 				break;
11183 			case MCAST_LEAVE_SOURCE_GROUP:
11184 				fmode = MODE_IS_INCLUDE;
11185 				optfn = ip_opt_delete_group_v6;
11186 				break;
11187 			}
11188 
11189 			gsreqp = (struct group_source_req *)i1;
11190 			ifindex = gsreqp->gsr_interface;
11191 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11192 				struct sockaddr_in *s;
11193 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11194 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11195 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11196 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11197 			} else {
11198 				struct sockaddr_in6 *s6;
11199 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11200 				v6grp = s6->sin6_addr;
11201 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11202 				v6src = s6->sin6_addr;
11203 			}
11204 
11205 			/*
11206 			 * In the multirouting case, we need to replicate
11207 			 * the request as noted in the mcast cases above.
11208 			 */
11209 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11210 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11211 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11212 			if (ire != NULL) {
11213 				if (ire->ire_flags & RTF_MULTIRT) {
11214 					error = ip_multirt_apply_membership_v6(
11215 					    optfn, ire, connp, checkonly,
11216 					    &v6grp, fmode, &v6src, first_mp);
11217 					done = B_TRUE;
11218 				}
11219 				ire_refrele(ire);
11220 			}
11221 			if (!done) {
11222 				error = optfn(connp, checkonly, &v6grp,
11223 				    ifindex, fmode, &v6src, first_mp);
11224 			}
11225 			if (error != 0) {
11226 				/*
11227 				 * EINPROGRESS is a soft error, needs retry
11228 				 * so don't make *outlenp zero.
11229 				 */
11230 				if (error != EINPROGRESS)
11231 					*outlenp = 0;
11232 				return (error);
11233 			}
11234 			/* OK return - copy input buffer into output buffer */
11235 			if (invalp != outvalp) {
11236 				bcopy(invalp, outvalp, inlen);
11237 			}
11238 			*outlenp = inlen;
11239 			return (0);
11240 		}
11241 		case IPV6_UNICAST_HOPS:
11242 			/* Recorded in transport above IP */
11243 			break;	/* goto sizeof (int) option return */
11244 		case IPV6_UNSPEC_SRC:
11245 			/* Allow sending with a zero source address */
11246 			if (!checkonly) {
11247 				mutex_enter(&connp->conn_lock);
11248 				connp->conn_unspec_src = *i1 ? 1 : 0;
11249 				mutex_exit(&connp->conn_lock);
11250 			}
11251 			break;	/* goto sizeof (int) option return */
11252 		case IPV6_RECVPKTINFO:
11253 			if (!checkonly) {
11254 				mutex_enter(&connp->conn_lock);
11255 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11256 				mutex_exit(&connp->conn_lock);
11257 			}
11258 			break;	/* goto sizeof (int) option return */
11259 		case IPV6_RECVTCLASS:
11260 			if (!checkonly) {
11261 				if (*i1 < 0 || *i1 > 1) {
11262 					return (EINVAL);
11263 				}
11264 				mutex_enter(&connp->conn_lock);
11265 				connp->conn_ipv6_recvtclass = *i1;
11266 				mutex_exit(&connp->conn_lock);
11267 			}
11268 			break;
11269 		case IPV6_RECVPATHMTU:
11270 			if (!checkonly) {
11271 				if (*i1 < 0 || *i1 > 1) {
11272 					return (EINVAL);
11273 				}
11274 				mutex_enter(&connp->conn_lock);
11275 				connp->conn_ipv6_recvpathmtu = *i1;
11276 				mutex_exit(&connp->conn_lock);
11277 			}
11278 			break;
11279 		case IPV6_RECVHOPLIMIT:
11280 			if (!checkonly) {
11281 				mutex_enter(&connp->conn_lock);
11282 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11283 				mutex_exit(&connp->conn_lock);
11284 			}
11285 			break;	/* goto sizeof (int) option return */
11286 		case IPV6_RECVHOPOPTS:
11287 			if (!checkonly) {
11288 				mutex_enter(&connp->conn_lock);
11289 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11290 				mutex_exit(&connp->conn_lock);
11291 			}
11292 			break;	/* goto sizeof (int) option return */
11293 		case IPV6_RECVDSTOPTS:
11294 			if (!checkonly) {
11295 				mutex_enter(&connp->conn_lock);
11296 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11297 				mutex_exit(&connp->conn_lock);
11298 			}
11299 			break;	/* goto sizeof (int) option return */
11300 		case IPV6_RECVRTHDR:
11301 			if (!checkonly) {
11302 				mutex_enter(&connp->conn_lock);
11303 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11304 				mutex_exit(&connp->conn_lock);
11305 			}
11306 			break;	/* goto sizeof (int) option return */
11307 		case IPV6_RECVRTHDRDSTOPTS:
11308 			if (!checkonly) {
11309 				mutex_enter(&connp->conn_lock);
11310 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11311 				mutex_exit(&connp->conn_lock);
11312 			}
11313 			break;	/* goto sizeof (int) option return */
11314 		case IPV6_PKTINFO:
11315 			if (inlen == 0)
11316 				return (-EINVAL);	/* clearing option */
11317 			error = ip6_set_pktinfo(cr, connp,
11318 			    (struct in6_pktinfo *)invalp);
11319 			if (error != 0)
11320 				*outlenp = 0;
11321 			else
11322 				*outlenp = inlen;
11323 			return (error);
11324 		case IPV6_NEXTHOP: {
11325 			struct sockaddr_in6 *sin6;
11326 
11327 			/* Verify that the nexthop is reachable */
11328 			if (inlen == 0)
11329 				return (-EINVAL);	/* clearing option */
11330 
11331 			sin6 = (struct sockaddr_in6 *)invalp;
11332 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11333 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11334 			    NULL, MATCH_IRE_DEFAULT, ipst);
11335 
11336 			if (ire == NULL) {
11337 				*outlenp = 0;
11338 				return (EHOSTUNREACH);
11339 			}
11340 			ire_refrele(ire);
11341 			return (-EINVAL);
11342 		}
11343 		case IPV6_SEC_OPT:
11344 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11345 			if (error != 0) {
11346 				*outlenp = 0;
11347 				return (error);
11348 			}
11349 			break;
11350 		case IPV6_SRC_PREFERENCES: {
11351 			/*
11352 			 * This is implemented strictly in the ip module
11353 			 * (here and in tcp_opt_*() to accomodate tcp
11354 			 * sockets).  Modules above ip pass this option
11355 			 * down here since ip is the only one that needs to
11356 			 * be aware of source address preferences.
11357 			 *
11358 			 * This socket option only affects connected
11359 			 * sockets that haven't already bound to a specific
11360 			 * IPv6 address.  In other words, sockets that
11361 			 * don't call bind() with an address other than the
11362 			 * unspecified address and that call connect().
11363 			 * ip_bind_connected_v6() passes these preferences
11364 			 * to the ipif_select_source_v6() function.
11365 			 */
11366 			if (inlen != sizeof (uint32_t))
11367 				return (EINVAL);
11368 			error = ip6_set_src_preferences(connp,
11369 			    *(uint32_t *)invalp);
11370 			if (error != 0) {
11371 				*outlenp = 0;
11372 				return (error);
11373 			} else {
11374 				*outlenp = sizeof (uint32_t);
11375 			}
11376 			break;
11377 		}
11378 		case IPV6_V6ONLY:
11379 			if (*i1 < 0 || *i1 > 1) {
11380 				return (EINVAL);
11381 			}
11382 			mutex_enter(&connp->conn_lock);
11383 			connp->conn_ipv6_v6only = *i1;
11384 			mutex_exit(&connp->conn_lock);
11385 			break;
11386 		default:
11387 			return (-EINVAL);
11388 		}
11389 		break;
11390 	default:
11391 		/*
11392 		 * "soft" error (negative)
11393 		 * option not handled at this level
11394 		 * Note: Do not modify *outlenp
11395 		 */
11396 		return (-EINVAL);
11397 	}
11398 	/*
11399 	 * Common case of return from an option that is sizeof (int)
11400 	 */
11401 	*(int *)outvalp = *i1;
11402 	*outlenp = sizeof (int);
11403 	return (0);
11404 }
11405 
11406 /*
11407  * This routine gets default values of certain options whose default
11408  * values are maintained by protocol specific code
11409  */
11410 /* ARGSUSED */
11411 int
11412 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11413 {
11414 	int *i1 = (int *)ptr;
11415 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11416 
11417 	switch (level) {
11418 	case IPPROTO_IP:
11419 		switch (name) {
11420 		case IP_MULTICAST_TTL:
11421 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11422 			return (sizeof (uchar_t));
11423 		case IP_MULTICAST_LOOP:
11424 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11425 			return (sizeof (uchar_t));
11426 		default:
11427 			return (-1);
11428 		}
11429 	case IPPROTO_IPV6:
11430 		switch (name) {
11431 		case IPV6_UNICAST_HOPS:
11432 			*i1 = ipst->ips_ipv6_def_hops;
11433 			return (sizeof (int));
11434 		case IPV6_MULTICAST_HOPS:
11435 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11436 			return (sizeof (int));
11437 		case IPV6_MULTICAST_LOOP:
11438 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11439 			return (sizeof (int));
11440 		case IPV6_V6ONLY:
11441 			*i1 = 1;
11442 			return (sizeof (int));
11443 		default:
11444 			return (-1);
11445 		}
11446 	default:
11447 		return (-1);
11448 	}
11449 	/* NOTREACHED */
11450 }
11451 
11452 /*
11453  * Given a destination address and a pointer to where to put the information
11454  * this routine fills in the mtuinfo.
11455  */
11456 int
11457 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11458     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11459 {
11460 	ire_t *ire;
11461 	ip_stack_t	*ipst = ns->netstack_ip;
11462 
11463 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11464 		return (-1);
11465 
11466 	bzero(mtuinfo, sizeof (*mtuinfo));
11467 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11468 	mtuinfo->ip6m_addr.sin6_port = port;
11469 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11470 
11471 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11472 	if (ire != NULL) {
11473 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11474 		ire_refrele(ire);
11475 	} else {
11476 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11477 	}
11478 	return (sizeof (struct ip6_mtuinfo));
11479 }
11480 
11481 /*
11482  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11483  * checking of cred and that ip_g_mrouter is set should be done and
11484  * isn't.  This doesn't matter as the error checking is done properly for the
11485  * other MRT options coming in through ip_opt_set.
11486  */
11487 int
11488 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11489 {
11490 	conn_t		*connp = Q_TO_CONN(q);
11491 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11492 
11493 	switch (level) {
11494 	case IPPROTO_IP:
11495 		switch (name) {
11496 		case MRT_VERSION:
11497 		case MRT_ASSERT:
11498 			(void) ip_mrouter_get(name, q, ptr);
11499 			return (sizeof (int));
11500 		case IP_SEC_OPT:
11501 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11502 		case IP_NEXTHOP:
11503 			if (connp->conn_nexthop_set) {
11504 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11505 				return (sizeof (ipaddr_t));
11506 			} else
11507 				return (0);
11508 		case IP_RECVPKTINFO:
11509 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11510 			return (sizeof (int));
11511 		default:
11512 			break;
11513 		}
11514 		break;
11515 	case IPPROTO_IPV6:
11516 		switch (name) {
11517 		case IPV6_SEC_OPT:
11518 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11519 		case IPV6_SRC_PREFERENCES: {
11520 			return (ip6_get_src_preferences(connp,
11521 			    (uint32_t *)ptr));
11522 		}
11523 		case IPV6_V6ONLY:
11524 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11525 			return (sizeof (int));
11526 		case IPV6_PATHMTU:
11527 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11528 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11529 		default:
11530 			break;
11531 		}
11532 		break;
11533 	default:
11534 		break;
11535 	}
11536 	return (-1);
11537 }
11538 /* Named Dispatch routine to get a current value out of our parameter table. */
11539 /* ARGSUSED */
11540 static int
11541 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11542 {
11543 	ipparam_t *ippa = (ipparam_t *)cp;
11544 
11545 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11546 	return (0);
11547 }
11548 
11549 /* ARGSUSED */
11550 static int
11551 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11552 {
11553 
11554 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11555 	return (0);
11556 }
11557 
11558 /*
11559  * Set ip{,6}_forwarding values.  This means walking through all of the
11560  * ill's and toggling their forwarding values.
11561  */
11562 /* ARGSUSED */
11563 static int
11564 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11565 {
11566 	long new_value;
11567 	int *forwarding_value = (int *)cp;
11568 	ill_t *ill;
11569 	boolean_t isv6;
11570 	ill_walk_context_t ctx;
11571 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11572 
11573 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11574 
11575 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11576 	    new_value < 0 || new_value > 1) {
11577 		return (EINVAL);
11578 	}
11579 
11580 	*forwarding_value = new_value;
11581 
11582 	/*
11583 	 * Regardless of the current value of ip_forwarding, set all per-ill
11584 	 * values of ip_forwarding to the value being set.
11585 	 *
11586 	 * Bring all the ill's up to date with the new global value.
11587 	 */
11588 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11589 
11590 	if (isv6)
11591 		ill = ILL_START_WALK_V6(&ctx, ipst);
11592 	else
11593 		ill = ILL_START_WALK_V4(&ctx, ipst);
11594 
11595 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11596 		(void) ill_forward_set(ill, new_value != 0);
11597 
11598 	rw_exit(&ipst->ips_ill_g_lock);
11599 	return (0);
11600 }
11601 
11602 /*
11603  * Walk through the param array specified registering each element with the
11604  * Named Dispatch handler. This is called only during init. So it is ok
11605  * not to acquire any locks
11606  */
11607 static boolean_t
11608 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11609     ipndp_t *ipnd, size_t ipnd_cnt)
11610 {
11611 	for (; ippa_cnt-- > 0; ippa++) {
11612 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11613 			if (!nd_load(ndp, ippa->ip_param_name,
11614 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11615 				nd_free(ndp);
11616 				return (B_FALSE);
11617 			}
11618 		}
11619 	}
11620 
11621 	for (; ipnd_cnt-- > 0; ipnd++) {
11622 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11623 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11624 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11625 			    ipnd->ip_ndp_data)) {
11626 				nd_free(ndp);
11627 				return (B_FALSE);
11628 			}
11629 		}
11630 	}
11631 
11632 	return (B_TRUE);
11633 }
11634 
11635 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11636 /* ARGSUSED */
11637 static int
11638 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11639 {
11640 	long		new_value;
11641 	ipparam_t	*ippa = (ipparam_t *)cp;
11642 
11643 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11644 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11645 		return (EINVAL);
11646 	}
11647 	ippa->ip_param_value = new_value;
11648 	return (0);
11649 }
11650 
11651 /*
11652  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11653  * When an ipf is passed here for the first time, if
11654  * we already have in-order fragments on the queue, we convert from the fast-
11655  * path reassembly scheme to the hard-case scheme.  From then on, additional
11656  * fragments are reassembled here.  We keep track of the start and end offsets
11657  * of each piece, and the number of holes in the chain.  When the hole count
11658  * goes to zero, we are done!
11659  *
11660  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11661  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11662  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11663  * after the call to ip_reassemble().
11664  */
11665 int
11666 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11667     size_t msg_len)
11668 {
11669 	uint_t	end;
11670 	mblk_t	*next_mp;
11671 	mblk_t	*mp1;
11672 	uint_t	offset;
11673 	boolean_t incr_dups = B_TRUE;
11674 	boolean_t offset_zero_seen = B_FALSE;
11675 	boolean_t pkt_boundary_checked = B_FALSE;
11676 
11677 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11678 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11679 
11680 	/* Add in byte count */
11681 	ipf->ipf_count += msg_len;
11682 	if (ipf->ipf_end) {
11683 		/*
11684 		 * We were part way through in-order reassembly, but now there
11685 		 * is a hole.  We walk through messages already queued, and
11686 		 * mark them for hard case reassembly.  We know that up till
11687 		 * now they were in order starting from offset zero.
11688 		 */
11689 		offset = 0;
11690 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11691 			IP_REASS_SET_START(mp1, offset);
11692 			if (offset == 0) {
11693 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11694 				offset = -ipf->ipf_nf_hdr_len;
11695 			}
11696 			offset += mp1->b_wptr - mp1->b_rptr;
11697 			IP_REASS_SET_END(mp1, offset);
11698 		}
11699 		/* One hole at the end. */
11700 		ipf->ipf_hole_cnt = 1;
11701 		/* Brand it as a hard case, forever. */
11702 		ipf->ipf_end = 0;
11703 	}
11704 	/* Walk through all the new pieces. */
11705 	do {
11706 		end = start + (mp->b_wptr - mp->b_rptr);
11707 		/*
11708 		 * If start is 0, decrease 'end' only for the first mblk of
11709 		 * the fragment. Otherwise 'end' can get wrong value in the
11710 		 * second pass of the loop if first mblk is exactly the
11711 		 * size of ipf_nf_hdr_len.
11712 		 */
11713 		if (start == 0 && !offset_zero_seen) {
11714 			/* First segment */
11715 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11716 			end -= ipf->ipf_nf_hdr_len;
11717 			offset_zero_seen = B_TRUE;
11718 		}
11719 		next_mp = mp->b_cont;
11720 		/*
11721 		 * We are checking to see if there is any interesing data
11722 		 * to process.  If there isn't and the mblk isn't the
11723 		 * one which carries the unfragmentable header then we
11724 		 * drop it.  It's possible to have just the unfragmentable
11725 		 * header come through without any data.  That needs to be
11726 		 * saved.
11727 		 *
11728 		 * If the assert at the top of this function holds then the
11729 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11730 		 * is infrequently traveled enough that the test is left in
11731 		 * to protect against future code changes which break that
11732 		 * invariant.
11733 		 */
11734 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11735 			/* Empty.  Blast it. */
11736 			IP_REASS_SET_START(mp, 0);
11737 			IP_REASS_SET_END(mp, 0);
11738 			/*
11739 			 * If the ipf points to the mblk we are about to free,
11740 			 * update ipf to point to the next mblk (or NULL
11741 			 * if none).
11742 			 */
11743 			if (ipf->ipf_mp->b_cont == mp)
11744 				ipf->ipf_mp->b_cont = next_mp;
11745 			freeb(mp);
11746 			continue;
11747 		}
11748 		mp->b_cont = NULL;
11749 		IP_REASS_SET_START(mp, start);
11750 		IP_REASS_SET_END(mp, end);
11751 		if (!ipf->ipf_tail_mp) {
11752 			ipf->ipf_tail_mp = mp;
11753 			ipf->ipf_mp->b_cont = mp;
11754 			if (start == 0 || !more) {
11755 				ipf->ipf_hole_cnt = 1;
11756 				/*
11757 				 * if the first fragment comes in more than one
11758 				 * mblk, this loop will be executed for each
11759 				 * mblk. Need to adjust hole count so exiting
11760 				 * this routine will leave hole count at 1.
11761 				 */
11762 				if (next_mp)
11763 					ipf->ipf_hole_cnt++;
11764 			} else
11765 				ipf->ipf_hole_cnt = 2;
11766 			continue;
11767 		} else if (ipf->ipf_last_frag_seen && !more &&
11768 		    !pkt_boundary_checked) {
11769 			/*
11770 			 * We check datagram boundary only if this fragment
11771 			 * claims to be the last fragment and we have seen a
11772 			 * last fragment in the past too. We do this only
11773 			 * once for a given fragment.
11774 			 *
11775 			 * start cannot be 0 here as fragments with start=0
11776 			 * and MF=0 gets handled as a complete packet. These
11777 			 * fragments should not reach here.
11778 			 */
11779 
11780 			if (start + msgdsize(mp) !=
11781 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11782 				/*
11783 				 * We have two fragments both of which claim
11784 				 * to be the last fragment but gives conflicting
11785 				 * information about the whole datagram size.
11786 				 * Something fishy is going on. Drop the
11787 				 * fragment and free up the reassembly list.
11788 				 */
11789 				return (IP_REASS_FAILED);
11790 			}
11791 
11792 			/*
11793 			 * We shouldn't come to this code block again for this
11794 			 * particular fragment.
11795 			 */
11796 			pkt_boundary_checked = B_TRUE;
11797 		}
11798 
11799 		/* New stuff at or beyond tail? */
11800 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11801 		if (start >= offset) {
11802 			if (ipf->ipf_last_frag_seen) {
11803 				/* current fragment is beyond last fragment */
11804 				return (IP_REASS_FAILED);
11805 			}
11806 			/* Link it on end. */
11807 			ipf->ipf_tail_mp->b_cont = mp;
11808 			ipf->ipf_tail_mp = mp;
11809 			if (more) {
11810 				if (start != offset)
11811 					ipf->ipf_hole_cnt++;
11812 			} else if (start == offset && next_mp == NULL)
11813 					ipf->ipf_hole_cnt--;
11814 			continue;
11815 		}
11816 		mp1 = ipf->ipf_mp->b_cont;
11817 		offset = IP_REASS_START(mp1);
11818 		/* New stuff at the front? */
11819 		if (start < offset) {
11820 			if (start == 0) {
11821 				if (end >= offset) {
11822 					/* Nailed the hole at the begining. */
11823 					ipf->ipf_hole_cnt--;
11824 				}
11825 			} else if (end < offset) {
11826 				/*
11827 				 * A hole, stuff, and a hole where there used
11828 				 * to be just a hole.
11829 				 */
11830 				ipf->ipf_hole_cnt++;
11831 			}
11832 			mp->b_cont = mp1;
11833 			/* Check for overlap. */
11834 			while (end > offset) {
11835 				if (end < IP_REASS_END(mp1)) {
11836 					mp->b_wptr -= end - offset;
11837 					IP_REASS_SET_END(mp, offset);
11838 					BUMP_MIB(ill->ill_ip_mib,
11839 					    ipIfStatsReasmPartDups);
11840 					break;
11841 				}
11842 				/* Did we cover another hole? */
11843 				if ((mp1->b_cont &&
11844 				    IP_REASS_END(mp1) !=
11845 				    IP_REASS_START(mp1->b_cont) &&
11846 				    end >= IP_REASS_START(mp1->b_cont)) ||
11847 				    (!ipf->ipf_last_frag_seen && !more)) {
11848 					ipf->ipf_hole_cnt--;
11849 				}
11850 				/* Clip out mp1. */
11851 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11852 					/*
11853 					 * After clipping out mp1, this guy
11854 					 * is now hanging off the end.
11855 					 */
11856 					ipf->ipf_tail_mp = mp;
11857 				}
11858 				IP_REASS_SET_START(mp1, 0);
11859 				IP_REASS_SET_END(mp1, 0);
11860 				/* Subtract byte count */
11861 				ipf->ipf_count -= mp1->b_datap->db_lim -
11862 				    mp1->b_datap->db_base;
11863 				freeb(mp1);
11864 				BUMP_MIB(ill->ill_ip_mib,
11865 				    ipIfStatsReasmPartDups);
11866 				mp1 = mp->b_cont;
11867 				if (!mp1)
11868 					break;
11869 				offset = IP_REASS_START(mp1);
11870 			}
11871 			ipf->ipf_mp->b_cont = mp;
11872 			continue;
11873 		}
11874 		/*
11875 		 * The new piece starts somewhere between the start of the head
11876 		 * and before the end of the tail.
11877 		 */
11878 		for (; mp1; mp1 = mp1->b_cont) {
11879 			offset = IP_REASS_END(mp1);
11880 			if (start < offset) {
11881 				if (end <= offset) {
11882 					/* Nothing new. */
11883 					IP_REASS_SET_START(mp, 0);
11884 					IP_REASS_SET_END(mp, 0);
11885 					/* Subtract byte count */
11886 					ipf->ipf_count -= mp->b_datap->db_lim -
11887 					    mp->b_datap->db_base;
11888 					if (incr_dups) {
11889 						ipf->ipf_num_dups++;
11890 						incr_dups = B_FALSE;
11891 					}
11892 					freeb(mp);
11893 					BUMP_MIB(ill->ill_ip_mib,
11894 					    ipIfStatsReasmDuplicates);
11895 					break;
11896 				}
11897 				/*
11898 				 * Trim redundant stuff off beginning of new
11899 				 * piece.
11900 				 */
11901 				IP_REASS_SET_START(mp, offset);
11902 				mp->b_rptr += offset - start;
11903 				BUMP_MIB(ill->ill_ip_mib,
11904 				    ipIfStatsReasmPartDups);
11905 				start = offset;
11906 				if (!mp1->b_cont) {
11907 					/*
11908 					 * After trimming, this guy is now
11909 					 * hanging off the end.
11910 					 */
11911 					mp1->b_cont = mp;
11912 					ipf->ipf_tail_mp = mp;
11913 					if (!more) {
11914 						ipf->ipf_hole_cnt--;
11915 					}
11916 					break;
11917 				}
11918 			}
11919 			if (start >= IP_REASS_START(mp1->b_cont))
11920 				continue;
11921 			/* Fill a hole */
11922 			if (start > offset)
11923 				ipf->ipf_hole_cnt++;
11924 			mp->b_cont = mp1->b_cont;
11925 			mp1->b_cont = mp;
11926 			mp1 = mp->b_cont;
11927 			offset = IP_REASS_START(mp1);
11928 			if (end >= offset) {
11929 				ipf->ipf_hole_cnt--;
11930 				/* Check for overlap. */
11931 				while (end > offset) {
11932 					if (end < IP_REASS_END(mp1)) {
11933 						mp->b_wptr -= end - offset;
11934 						IP_REASS_SET_END(mp, offset);
11935 						/*
11936 						 * TODO we might bump
11937 						 * this up twice if there is
11938 						 * overlap at both ends.
11939 						 */
11940 						BUMP_MIB(ill->ill_ip_mib,
11941 						    ipIfStatsReasmPartDups);
11942 						break;
11943 					}
11944 					/* Did we cover another hole? */
11945 					if ((mp1->b_cont &&
11946 					    IP_REASS_END(mp1)
11947 					    != IP_REASS_START(mp1->b_cont) &&
11948 					    end >=
11949 					    IP_REASS_START(mp1->b_cont)) ||
11950 					    (!ipf->ipf_last_frag_seen &&
11951 					    !more)) {
11952 						ipf->ipf_hole_cnt--;
11953 					}
11954 					/* Clip out mp1. */
11955 					if ((mp->b_cont = mp1->b_cont) ==
11956 					    NULL) {
11957 						/*
11958 						 * After clipping out mp1,
11959 						 * this guy is now hanging
11960 						 * off the end.
11961 						 */
11962 						ipf->ipf_tail_mp = mp;
11963 					}
11964 					IP_REASS_SET_START(mp1, 0);
11965 					IP_REASS_SET_END(mp1, 0);
11966 					/* Subtract byte count */
11967 					ipf->ipf_count -=
11968 					    mp1->b_datap->db_lim -
11969 					    mp1->b_datap->db_base;
11970 					freeb(mp1);
11971 					BUMP_MIB(ill->ill_ip_mib,
11972 					    ipIfStatsReasmPartDups);
11973 					mp1 = mp->b_cont;
11974 					if (!mp1)
11975 						break;
11976 					offset = IP_REASS_START(mp1);
11977 				}
11978 			}
11979 			break;
11980 		}
11981 	} while (start = end, mp = next_mp);
11982 
11983 	/* Fragment just processed could be the last one. Remember this fact */
11984 	if (!more)
11985 		ipf->ipf_last_frag_seen = B_TRUE;
11986 
11987 	/* Still got holes? */
11988 	if (ipf->ipf_hole_cnt)
11989 		return (IP_REASS_PARTIAL);
11990 	/* Clean up overloaded fields to avoid upstream disasters. */
11991 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11992 		IP_REASS_SET_START(mp1, 0);
11993 		IP_REASS_SET_END(mp1, 0);
11994 	}
11995 	return (IP_REASS_COMPLETE);
11996 }
11997 
11998 /*
11999  * ipsec processing for the fast path, used for input UDP Packets
12000  * Returns true if ready for passup to UDP.
12001  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12002  * was an ESP-in-UDP packet, etc.).
12003  */
12004 static boolean_t
12005 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12006     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12007 {
12008 	uint32_t	ill_index;
12009 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12010 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12011 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12012 	udp_t		*udp = connp->conn_udp;
12013 
12014 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12015 	/* The ill_index of the incoming ILL */
12016 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12017 
12018 	/* pass packet up to the transport */
12019 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12020 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12021 		    NULL, mctl_present);
12022 		if (*first_mpp == NULL) {
12023 			return (B_FALSE);
12024 		}
12025 	}
12026 
12027 	/* Initiate IPPF processing for fastpath UDP */
12028 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12029 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12030 		if (*mpp == NULL) {
12031 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12032 			    "deferred/dropped during IPPF processing\n"));
12033 			return (B_FALSE);
12034 		}
12035 	}
12036 	/*
12037 	 * Remove 0-spi if it's 0, or move everything behind
12038 	 * the UDP header over it and forward to ESP via
12039 	 * ip_proto_input().
12040 	 */
12041 	if (udp->udp_nat_t_endpoint) {
12042 		if (mctl_present) {
12043 			/* mctl_present *shouldn't* happen. */
12044 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12045 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12046 			    &ipss->ipsec_dropper);
12047 			*first_mpp = NULL;
12048 			return (B_FALSE);
12049 		}
12050 
12051 		/* "ill" is "recv_ill" in actuality. */
12052 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12053 			return (B_FALSE);
12054 
12055 		/* Else continue like a normal UDP packet. */
12056 	}
12057 
12058 	/*
12059 	 * We make the checks as below since we are in the fast path
12060 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12061 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12062 	 */
12063 	if (connp->conn_recvif || connp->conn_recvslla ||
12064 	    connp->conn_ip_recvpktinfo) {
12065 		if (connp->conn_recvif) {
12066 			in_flags = IPF_RECVIF;
12067 		}
12068 		/*
12069 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12070 		 * so the flag passed to ip_add_info is based on IP version
12071 		 * of connp.
12072 		 */
12073 		if (connp->conn_ip_recvpktinfo) {
12074 			if (connp->conn_af_isv6) {
12075 				/*
12076 				 * V6 only needs index
12077 				 */
12078 				in_flags |= IPF_RECVIF;
12079 			} else {
12080 				/*
12081 				 * V4 needs index + matching address.
12082 				 */
12083 				in_flags |= IPF_RECVADDR;
12084 			}
12085 		}
12086 		if (connp->conn_recvslla) {
12087 			in_flags |= IPF_RECVSLLA;
12088 		}
12089 		/*
12090 		 * since in_flags are being set ill will be
12091 		 * referenced in ip_add_info, so it better not
12092 		 * be NULL.
12093 		 */
12094 		/*
12095 		 * the actual data will be contained in b_cont
12096 		 * upon successful return of the following call.
12097 		 * If the call fails then the original mblk is
12098 		 * returned.
12099 		 */
12100 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12101 		    ipst);
12102 	}
12103 
12104 	return (B_TRUE);
12105 }
12106 
12107 /*
12108  * Fragmentation reassembly.  Each ILL has a hash table for
12109  * queuing packets undergoing reassembly for all IPIFs
12110  * associated with the ILL.  The hash is based on the packet
12111  * IP ident field.  The ILL frag hash table was allocated
12112  * as a timer block at the time the ILL was created.  Whenever
12113  * there is anything on the reassembly queue, the timer will
12114  * be running.  Returns B_TRUE if successful else B_FALSE;
12115  * frees mp on failure.
12116  */
12117 static boolean_t
12118 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12119     uint32_t *cksum_val, uint16_t *cksum_flags)
12120 {
12121 	uint32_t	frag_offset_flags;
12122 	mblk_t		*mp = *mpp;
12123 	mblk_t		*t_mp;
12124 	ipaddr_t	dst;
12125 	uint8_t		proto = ipha->ipha_protocol;
12126 	uint32_t	sum_val;
12127 	uint16_t	sum_flags;
12128 	ipf_t		*ipf;
12129 	ipf_t		**ipfp;
12130 	ipfb_t		*ipfb;
12131 	uint16_t	ident;
12132 	uint32_t	offset;
12133 	ipaddr_t	src;
12134 	uint_t		hdr_length;
12135 	uint32_t	end;
12136 	mblk_t		*mp1;
12137 	mblk_t		*tail_mp;
12138 	size_t		count;
12139 	size_t		msg_len;
12140 	uint8_t		ecn_info = 0;
12141 	uint32_t	packet_size;
12142 	boolean_t	pruned = B_FALSE;
12143 	ip_stack_t *ipst = ill->ill_ipst;
12144 
12145 	if (cksum_val != NULL)
12146 		*cksum_val = 0;
12147 	if (cksum_flags != NULL)
12148 		*cksum_flags = 0;
12149 
12150 	/*
12151 	 * Drop the fragmented as early as possible, if
12152 	 * we don't have resource(s) to re-assemble.
12153 	 */
12154 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12155 		freemsg(mp);
12156 		return (B_FALSE);
12157 	}
12158 
12159 	/* Check for fragmentation offset; return if there's none */
12160 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12161 	    (IPH_MF | IPH_OFFSET)) == 0)
12162 		return (B_TRUE);
12163 
12164 	/*
12165 	 * We utilize hardware computed checksum info only for UDP since
12166 	 * IP fragmentation is a normal occurrence for the protocol.  In
12167 	 * addition, checksum offload support for IP fragments carrying
12168 	 * UDP payload is commonly implemented across network adapters.
12169 	 */
12170 	ASSERT(recv_ill != NULL);
12171 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12172 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12173 		mblk_t *mp1 = mp->b_cont;
12174 		int32_t len;
12175 
12176 		/* Record checksum information from the packet */
12177 		sum_val = (uint32_t)DB_CKSUM16(mp);
12178 		sum_flags = DB_CKSUMFLAGS(mp);
12179 
12180 		/* IP payload offset from beginning of mblk */
12181 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12182 
12183 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12184 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12185 		    offset >= DB_CKSUMSTART(mp) &&
12186 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12187 			uint32_t adj;
12188 			/*
12189 			 * Partial checksum has been calculated by hardware
12190 			 * and attached to the packet; in addition, any
12191 			 * prepended extraneous data is even byte aligned.
12192 			 * If any such data exists, we adjust the checksum;
12193 			 * this would also handle any postpended data.
12194 			 */
12195 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12196 			    mp, mp1, len, adj);
12197 
12198 			/* One's complement subtract extraneous checksum */
12199 			if (adj >= sum_val)
12200 				sum_val = ~(adj - sum_val) & 0xFFFF;
12201 			else
12202 				sum_val -= adj;
12203 		}
12204 	} else {
12205 		sum_val = 0;
12206 		sum_flags = 0;
12207 	}
12208 
12209 	/* Clear hardware checksumming flag */
12210 	DB_CKSUMFLAGS(mp) = 0;
12211 
12212 	ident = ipha->ipha_ident;
12213 	offset = (frag_offset_flags << 3) & 0xFFFF;
12214 	src = ipha->ipha_src;
12215 	dst = ipha->ipha_dst;
12216 	hdr_length = IPH_HDR_LENGTH(ipha);
12217 	end = ntohs(ipha->ipha_length) - hdr_length;
12218 
12219 	/* If end == 0 then we have a packet with no data, so just free it */
12220 	if (end == 0) {
12221 		freemsg(mp);
12222 		return (B_FALSE);
12223 	}
12224 
12225 	/* Record the ECN field info. */
12226 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12227 	if (offset != 0) {
12228 		/*
12229 		 * If this isn't the first piece, strip the header, and
12230 		 * add the offset to the end value.
12231 		 */
12232 		mp->b_rptr += hdr_length;
12233 		end += offset;
12234 	}
12235 
12236 	msg_len = MBLKSIZE(mp);
12237 	tail_mp = mp;
12238 	while (tail_mp->b_cont != NULL) {
12239 		tail_mp = tail_mp->b_cont;
12240 		msg_len += MBLKSIZE(tail_mp);
12241 	}
12242 
12243 	/* If the reassembly list for this ILL will get too big, prune it */
12244 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12245 	    ipst->ips_ip_reass_queue_bytes) {
12246 		ill_frag_prune(ill,
12247 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12248 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12249 		pruned = B_TRUE;
12250 	}
12251 
12252 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12253 	mutex_enter(&ipfb->ipfb_lock);
12254 
12255 	ipfp = &ipfb->ipfb_ipf;
12256 	/* Try to find an existing fragment queue for this packet. */
12257 	for (;;) {
12258 		ipf = ipfp[0];
12259 		if (ipf != NULL) {
12260 			/*
12261 			 * It has to match on ident and src/dst address.
12262 			 */
12263 			if (ipf->ipf_ident == ident &&
12264 			    ipf->ipf_src == src &&
12265 			    ipf->ipf_dst == dst &&
12266 			    ipf->ipf_protocol == proto) {
12267 				/*
12268 				 * If we have received too many
12269 				 * duplicate fragments for this packet
12270 				 * free it.
12271 				 */
12272 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12273 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12274 					freemsg(mp);
12275 					mutex_exit(&ipfb->ipfb_lock);
12276 					return (B_FALSE);
12277 				}
12278 				/* Found it. */
12279 				break;
12280 			}
12281 			ipfp = &ipf->ipf_hash_next;
12282 			continue;
12283 		}
12284 
12285 		/*
12286 		 * If we pruned the list, do we want to store this new
12287 		 * fragment?. We apply an optimization here based on the
12288 		 * fact that most fragments will be received in order.
12289 		 * So if the offset of this incoming fragment is zero,
12290 		 * it is the first fragment of a new packet. We will
12291 		 * keep it.  Otherwise drop the fragment, as we have
12292 		 * probably pruned the packet already (since the
12293 		 * packet cannot be found).
12294 		 */
12295 		if (pruned && offset != 0) {
12296 			mutex_exit(&ipfb->ipfb_lock);
12297 			freemsg(mp);
12298 			return (B_FALSE);
12299 		}
12300 
12301 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12302 			/*
12303 			 * Too many fragmented packets in this hash
12304 			 * bucket. Free the oldest.
12305 			 */
12306 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12307 		}
12308 
12309 		/* New guy.  Allocate a frag message. */
12310 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12311 		if (mp1 == NULL) {
12312 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12313 			freemsg(mp);
12314 reass_done:
12315 			mutex_exit(&ipfb->ipfb_lock);
12316 			return (B_FALSE);
12317 		}
12318 
12319 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12320 		mp1->b_cont = mp;
12321 
12322 		/* Initialize the fragment header. */
12323 		ipf = (ipf_t *)mp1->b_rptr;
12324 		ipf->ipf_mp = mp1;
12325 		ipf->ipf_ptphn = ipfp;
12326 		ipfp[0] = ipf;
12327 		ipf->ipf_hash_next = NULL;
12328 		ipf->ipf_ident = ident;
12329 		ipf->ipf_protocol = proto;
12330 		ipf->ipf_src = src;
12331 		ipf->ipf_dst = dst;
12332 		ipf->ipf_nf_hdr_len = 0;
12333 		/* Record reassembly start time. */
12334 		ipf->ipf_timestamp = gethrestime_sec();
12335 		/* Record ipf generation and account for frag header */
12336 		ipf->ipf_gen = ill->ill_ipf_gen++;
12337 		ipf->ipf_count = MBLKSIZE(mp1);
12338 		ipf->ipf_last_frag_seen = B_FALSE;
12339 		ipf->ipf_ecn = ecn_info;
12340 		ipf->ipf_num_dups = 0;
12341 		ipfb->ipfb_frag_pkts++;
12342 		ipf->ipf_checksum = 0;
12343 		ipf->ipf_checksum_flags = 0;
12344 
12345 		/* Store checksum value in fragment header */
12346 		if (sum_flags != 0) {
12347 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12348 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12349 			ipf->ipf_checksum = sum_val;
12350 			ipf->ipf_checksum_flags = sum_flags;
12351 		}
12352 
12353 		/*
12354 		 * We handle reassembly two ways.  In the easy case,
12355 		 * where all the fragments show up in order, we do
12356 		 * minimal bookkeeping, and just clip new pieces on
12357 		 * the end.  If we ever see a hole, then we go off
12358 		 * to ip_reassemble which has to mark the pieces and
12359 		 * keep track of the number of holes, etc.  Obviously,
12360 		 * the point of having both mechanisms is so we can
12361 		 * handle the easy case as efficiently as possible.
12362 		 */
12363 		if (offset == 0) {
12364 			/* Easy case, in-order reassembly so far. */
12365 			ipf->ipf_count += msg_len;
12366 			ipf->ipf_tail_mp = tail_mp;
12367 			/*
12368 			 * Keep track of next expected offset in
12369 			 * ipf_end.
12370 			 */
12371 			ipf->ipf_end = end;
12372 			ipf->ipf_nf_hdr_len = hdr_length;
12373 		} else {
12374 			/* Hard case, hole at the beginning. */
12375 			ipf->ipf_tail_mp = NULL;
12376 			/*
12377 			 * ipf_end == 0 means that we have given up
12378 			 * on easy reassembly.
12379 			 */
12380 			ipf->ipf_end = 0;
12381 
12382 			/* Forget checksum offload from now on */
12383 			ipf->ipf_checksum_flags = 0;
12384 
12385 			/*
12386 			 * ipf_hole_cnt is set by ip_reassemble.
12387 			 * ipf_count is updated by ip_reassemble.
12388 			 * No need to check for return value here
12389 			 * as we don't expect reassembly to complete
12390 			 * or fail for the first fragment itself.
12391 			 */
12392 			(void) ip_reassemble(mp, ipf,
12393 			    (frag_offset_flags & IPH_OFFSET) << 3,
12394 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12395 		}
12396 		/* Update per ipfb and ill byte counts */
12397 		ipfb->ipfb_count += ipf->ipf_count;
12398 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12399 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12400 		/* If the frag timer wasn't already going, start it. */
12401 		mutex_enter(&ill->ill_lock);
12402 		ill_frag_timer_start(ill);
12403 		mutex_exit(&ill->ill_lock);
12404 		goto reass_done;
12405 	}
12406 
12407 	/*
12408 	 * If the packet's flag has changed (it could be coming up
12409 	 * from an interface different than the previous, therefore
12410 	 * possibly different checksum capability), then forget about
12411 	 * any stored checksum states.  Otherwise add the value to
12412 	 * the existing one stored in the fragment header.
12413 	 */
12414 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12415 		sum_val += ipf->ipf_checksum;
12416 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12417 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12418 		ipf->ipf_checksum = sum_val;
12419 	} else if (ipf->ipf_checksum_flags != 0) {
12420 		/* Forget checksum offload from now on */
12421 		ipf->ipf_checksum_flags = 0;
12422 	}
12423 
12424 	/*
12425 	 * We have a new piece of a datagram which is already being
12426 	 * reassembled.  Update the ECN info if all IP fragments
12427 	 * are ECN capable.  If there is one which is not, clear
12428 	 * all the info.  If there is at least one which has CE
12429 	 * code point, IP needs to report that up to transport.
12430 	 */
12431 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12432 		if (ecn_info == IPH_ECN_CE)
12433 			ipf->ipf_ecn = IPH_ECN_CE;
12434 	} else {
12435 		ipf->ipf_ecn = IPH_ECN_NECT;
12436 	}
12437 	if (offset && ipf->ipf_end == offset) {
12438 		/* The new fragment fits at the end */
12439 		ipf->ipf_tail_mp->b_cont = mp;
12440 		/* Update the byte count */
12441 		ipf->ipf_count += msg_len;
12442 		/* Update per ipfb and ill byte counts */
12443 		ipfb->ipfb_count += msg_len;
12444 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12445 		atomic_add_32(&ill->ill_frag_count, msg_len);
12446 		if (frag_offset_flags & IPH_MF) {
12447 			/* More to come. */
12448 			ipf->ipf_end = end;
12449 			ipf->ipf_tail_mp = tail_mp;
12450 			goto reass_done;
12451 		}
12452 	} else {
12453 		/* Go do the hard cases. */
12454 		int ret;
12455 
12456 		if (offset == 0)
12457 			ipf->ipf_nf_hdr_len = hdr_length;
12458 
12459 		/* Save current byte count */
12460 		count = ipf->ipf_count;
12461 		ret = ip_reassemble(mp, ipf,
12462 		    (frag_offset_flags & IPH_OFFSET) << 3,
12463 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12464 		/* Count of bytes added and subtracted (freeb()ed) */
12465 		count = ipf->ipf_count - count;
12466 		if (count) {
12467 			/* Update per ipfb and ill byte counts */
12468 			ipfb->ipfb_count += count;
12469 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12470 			atomic_add_32(&ill->ill_frag_count, count);
12471 		}
12472 		if (ret == IP_REASS_PARTIAL) {
12473 			goto reass_done;
12474 		} else if (ret == IP_REASS_FAILED) {
12475 			/* Reassembly failed. Free up all resources */
12476 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12477 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12478 				IP_REASS_SET_START(t_mp, 0);
12479 				IP_REASS_SET_END(t_mp, 0);
12480 			}
12481 			freemsg(mp);
12482 			goto reass_done;
12483 		}
12484 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12485 	}
12486 	/*
12487 	 * We have completed reassembly.  Unhook the frag header from
12488 	 * the reassembly list.
12489 	 *
12490 	 * Before we free the frag header, record the ECN info
12491 	 * to report back to the transport.
12492 	 */
12493 	ecn_info = ipf->ipf_ecn;
12494 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12495 	ipfp = ipf->ipf_ptphn;
12496 
12497 	/* We need to supply these to caller */
12498 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12499 		sum_val = ipf->ipf_checksum;
12500 	else
12501 		sum_val = 0;
12502 
12503 	mp1 = ipf->ipf_mp;
12504 	count = ipf->ipf_count;
12505 	ipf = ipf->ipf_hash_next;
12506 	if (ipf != NULL)
12507 		ipf->ipf_ptphn = ipfp;
12508 	ipfp[0] = ipf;
12509 	atomic_add_32(&ill->ill_frag_count, -count);
12510 	ASSERT(ipfb->ipfb_count >= count);
12511 	ipfb->ipfb_count -= count;
12512 	ipfb->ipfb_frag_pkts--;
12513 	mutex_exit(&ipfb->ipfb_lock);
12514 	/* Ditch the frag header. */
12515 	mp = mp1->b_cont;
12516 
12517 	freeb(mp1);
12518 
12519 	/* Restore original IP length in header. */
12520 	packet_size = (uint32_t)msgdsize(mp);
12521 	if (packet_size > IP_MAXPACKET) {
12522 		freemsg(mp);
12523 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12524 		return (B_FALSE);
12525 	}
12526 
12527 	if (DB_REF(mp) > 1) {
12528 		mblk_t *mp2 = copymsg(mp);
12529 
12530 		freemsg(mp);
12531 		if (mp2 == NULL) {
12532 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12533 			return (B_FALSE);
12534 		}
12535 		mp = mp2;
12536 	}
12537 	ipha = (ipha_t *)mp->b_rptr;
12538 
12539 	ipha->ipha_length = htons((uint16_t)packet_size);
12540 	/* We're now complete, zip the frag state */
12541 	ipha->ipha_fragment_offset_and_flags = 0;
12542 	/* Record the ECN info. */
12543 	ipha->ipha_type_of_service &= 0xFC;
12544 	ipha->ipha_type_of_service |= ecn_info;
12545 	*mpp = mp;
12546 
12547 	/* Reassembly is successful; return checksum information if needed */
12548 	if (cksum_val != NULL)
12549 		*cksum_val = sum_val;
12550 	if (cksum_flags != NULL)
12551 		*cksum_flags = sum_flags;
12552 
12553 	return (B_TRUE);
12554 }
12555 
12556 /*
12557  * Perform ip header check sum update local options.
12558  * return B_TRUE if all is well, else return B_FALSE and release
12559  * the mp. caller is responsible for decrementing ire ref cnt.
12560  */
12561 static boolean_t
12562 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12563     ip_stack_t *ipst)
12564 {
12565 	mblk_t		*first_mp;
12566 	boolean_t	mctl_present;
12567 	uint16_t	sum;
12568 
12569 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12570 	/*
12571 	 * Don't do the checksum if it has gone through AH/ESP
12572 	 * processing.
12573 	 */
12574 	if (!mctl_present) {
12575 		sum = ip_csum_hdr(ipha);
12576 		if (sum != 0) {
12577 			if (ill != NULL) {
12578 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12579 			} else {
12580 				BUMP_MIB(&ipst->ips_ip_mib,
12581 				    ipIfStatsInCksumErrs);
12582 			}
12583 			freemsg(first_mp);
12584 			return (B_FALSE);
12585 		}
12586 	}
12587 
12588 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12589 		if (mctl_present)
12590 			freeb(first_mp);
12591 		return (B_FALSE);
12592 	}
12593 
12594 	return (B_TRUE);
12595 }
12596 
12597 /*
12598  * All udp packet are delivered to the local host via this routine.
12599  */
12600 void
12601 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12602     ill_t *recv_ill)
12603 {
12604 	uint32_t	sum;
12605 	uint32_t	u1;
12606 	boolean_t	mctl_present;
12607 	conn_t		*connp;
12608 	mblk_t		*first_mp;
12609 	uint16_t	*up;
12610 	ill_t		*ill = (ill_t *)q->q_ptr;
12611 	uint16_t	reass_hck_flags = 0;
12612 	ip_stack_t	*ipst;
12613 
12614 	ASSERT(recv_ill != NULL);
12615 	ipst = recv_ill->ill_ipst;
12616 
12617 #define	rptr    ((uchar_t *)ipha)
12618 
12619 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12620 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12621 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12622 	ASSERT(ill != NULL);
12623 
12624 	/*
12625 	 * FAST PATH for udp packets
12626 	 */
12627 
12628 	/* u1 is # words of IP options */
12629 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12630 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12631 
12632 	/* IP options present */
12633 	if (u1 != 0)
12634 		goto ipoptions;
12635 
12636 	/* Check the IP header checksum.  */
12637 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12638 		/* Clear the IP header h/w cksum flag */
12639 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12640 	} else if (!mctl_present) {
12641 		/*
12642 		 * Don't verify header checksum if this packet is coming
12643 		 * back from AH/ESP as we already did it.
12644 		 */
12645 #define	uph	((uint16_t *)ipha)
12646 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12647 		    uph[6] + uph[7] + uph[8] + uph[9];
12648 #undef	uph
12649 		/* finish doing IP checksum */
12650 		sum = (sum & 0xFFFF) + (sum >> 16);
12651 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12652 		if (sum != 0 && sum != 0xFFFF) {
12653 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12654 			freemsg(first_mp);
12655 			return;
12656 		}
12657 	}
12658 
12659 	/*
12660 	 * Count for SNMP of inbound packets for ire.
12661 	 * if mctl is present this might be a secure packet and
12662 	 * has already been counted for in ip_proto_input().
12663 	 */
12664 	if (!mctl_present) {
12665 		UPDATE_IB_PKT_COUNT(ire);
12666 		ire->ire_last_used_time = lbolt;
12667 	}
12668 
12669 	/* packet part of fragmented IP packet? */
12670 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12671 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12672 		goto fragmented;
12673 	}
12674 
12675 	/* u1 = IP header length (20 bytes) */
12676 	u1 = IP_SIMPLE_HDR_LENGTH;
12677 
12678 	/* packet does not contain complete IP & UDP headers */
12679 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12680 		goto udppullup;
12681 
12682 	/* up points to UDP header */
12683 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12684 #define	iphs    ((uint16_t *)ipha)
12685 
12686 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12687 	if (up[3] != 0) {
12688 		mblk_t *mp1 = mp->b_cont;
12689 		boolean_t cksum_err;
12690 		uint16_t hck_flags = 0;
12691 
12692 		/* Pseudo-header checksum */
12693 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12694 		    iphs[9] + up[2];
12695 
12696 		/*
12697 		 * Revert to software checksum calculation if the interface
12698 		 * isn't capable of checksum offload or if IPsec is present.
12699 		 */
12700 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12701 			hck_flags = DB_CKSUMFLAGS(mp);
12702 
12703 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12704 			IP_STAT(ipst, ip_in_sw_cksum);
12705 
12706 		IP_CKSUM_RECV(hck_flags, u1,
12707 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12708 		    (int32_t)((uchar_t *)up - rptr),
12709 		    mp, mp1, cksum_err);
12710 
12711 		if (cksum_err) {
12712 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12713 			if (hck_flags & HCK_FULLCKSUM)
12714 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12715 			else if (hck_flags & HCK_PARTIALCKSUM)
12716 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12717 			else
12718 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12719 
12720 			freemsg(first_mp);
12721 			return;
12722 		}
12723 	}
12724 
12725 	/* Non-fragmented broadcast or multicast packet? */
12726 	if (ire->ire_type == IRE_BROADCAST)
12727 		goto udpslowpath;
12728 
12729 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12730 	    ire->ire_zoneid, ipst)) != NULL) {
12731 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12732 		IP_STAT(ipst, ip_udp_fast_path);
12733 
12734 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12735 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12736 			freemsg(mp);
12737 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12738 		} else {
12739 			if (!mctl_present) {
12740 				BUMP_MIB(ill->ill_ip_mib,
12741 				    ipIfStatsHCInDelivers);
12742 			}
12743 			/*
12744 			 * mp and first_mp can change.
12745 			 */
12746 			if (ip_udp_check(q, connp, recv_ill,
12747 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12748 				/* Send it upstream */
12749 				(connp->conn_recv)(connp, mp, NULL);
12750 			}
12751 		}
12752 		/*
12753 		 * freeb() cannot deal with null mblk being passed
12754 		 * in and first_mp can be set to null in the call
12755 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12756 		 */
12757 		if (mctl_present && first_mp != NULL) {
12758 			freeb(first_mp);
12759 		}
12760 		CONN_DEC_REF(connp);
12761 		return;
12762 	}
12763 
12764 	/*
12765 	 * if we got here we know the packet is not fragmented and
12766 	 * has no options. The classifier could not find a conn_t and
12767 	 * most likely its an icmp packet so send it through slow path.
12768 	 */
12769 
12770 	goto udpslowpath;
12771 
12772 ipoptions:
12773 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12774 		goto slow_done;
12775 	}
12776 
12777 	UPDATE_IB_PKT_COUNT(ire);
12778 	ire->ire_last_used_time = lbolt;
12779 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12780 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12781 fragmented:
12782 		/*
12783 		 * "sum" and "reass_hck_flags" are non-zero if the
12784 		 * reassembled packet has a valid hardware computed
12785 		 * checksum information associated with it.
12786 		 */
12787 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12788 		    &reass_hck_flags)) {
12789 			goto slow_done;
12790 		}
12791 
12792 		/*
12793 		 * Make sure that first_mp points back to mp as
12794 		 * the mp we came in with could have changed in
12795 		 * ip_rput_fragment().
12796 		 */
12797 		ASSERT(!mctl_present);
12798 		ipha = (ipha_t *)mp->b_rptr;
12799 		first_mp = mp;
12800 	}
12801 
12802 	/* Now we have a complete datagram, destined for this machine. */
12803 	u1 = IPH_HDR_LENGTH(ipha);
12804 	/* Pull up the UDP header, if necessary. */
12805 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12806 udppullup:
12807 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12808 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12809 			freemsg(first_mp);
12810 			goto slow_done;
12811 		}
12812 		ipha = (ipha_t *)mp->b_rptr;
12813 	}
12814 
12815 	/*
12816 	 * Validate the checksum for the reassembled packet; for the
12817 	 * pullup case we calculate the payload checksum in software.
12818 	 */
12819 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12820 	if (up[3] != 0) {
12821 		boolean_t cksum_err;
12822 
12823 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12824 			IP_STAT(ipst, ip_in_sw_cksum);
12825 
12826 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12827 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12828 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12829 		    iphs[9] + up[2], sum, cksum_err);
12830 
12831 		if (cksum_err) {
12832 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12833 
12834 			if (reass_hck_flags & HCK_FULLCKSUM)
12835 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12836 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12837 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12838 			else
12839 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12840 
12841 			freemsg(first_mp);
12842 			goto slow_done;
12843 		}
12844 	}
12845 udpslowpath:
12846 
12847 	/* Clear hardware checksum flag to be safe */
12848 	DB_CKSUMFLAGS(mp) = 0;
12849 
12850 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12851 	    (ire->ire_type == IRE_BROADCAST),
12852 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12853 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12854 
12855 slow_done:
12856 	IP_STAT(ipst, ip_udp_slow_path);
12857 	return;
12858 
12859 #undef  iphs
12860 #undef  rptr
12861 }
12862 
12863 /* ARGSUSED */
12864 static mblk_t *
12865 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12866     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12867     ill_rx_ring_t *ill_ring)
12868 {
12869 	conn_t		*connp;
12870 	uint32_t	sum;
12871 	uint32_t	u1;
12872 	uint16_t	*up;
12873 	int		offset;
12874 	ssize_t		len;
12875 	mblk_t		*mp1;
12876 	boolean_t	syn_present = B_FALSE;
12877 	tcph_t		*tcph;
12878 	uint_t		tcph_flags;
12879 	uint_t		ip_hdr_len;
12880 	ill_t		*ill = (ill_t *)q->q_ptr;
12881 	zoneid_t	zoneid = ire->ire_zoneid;
12882 	boolean_t	cksum_err;
12883 	uint16_t	hck_flags = 0;
12884 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12885 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12886 
12887 #define	rptr	((uchar_t *)ipha)
12888 
12889 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12890 	ASSERT(ill != NULL);
12891 
12892 	/*
12893 	 * FAST PATH for tcp packets
12894 	 */
12895 
12896 	/* u1 is # words of IP options */
12897 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12898 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12899 
12900 	/* IP options present */
12901 	if (u1) {
12902 		goto ipoptions;
12903 	} else if (!mctl_present) {
12904 		/* Check the IP header checksum.  */
12905 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12906 			/* Clear the IP header h/w cksum flag */
12907 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12908 		} else if (!mctl_present) {
12909 			/*
12910 			 * Don't verify header checksum if this packet
12911 			 * is coming back from AH/ESP as we already did it.
12912 			 */
12913 #define	uph	((uint16_t *)ipha)
12914 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12915 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12916 #undef	uph
12917 			/* finish doing IP checksum */
12918 			sum = (sum & 0xFFFF) + (sum >> 16);
12919 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12920 			if (sum != 0 && sum != 0xFFFF) {
12921 				BUMP_MIB(ill->ill_ip_mib,
12922 				    ipIfStatsInCksumErrs);
12923 				goto error;
12924 			}
12925 		}
12926 	}
12927 
12928 	if (!mctl_present) {
12929 		UPDATE_IB_PKT_COUNT(ire);
12930 		ire->ire_last_used_time = lbolt;
12931 	}
12932 
12933 	/* packet part of fragmented IP packet? */
12934 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12935 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12936 		goto fragmented;
12937 	}
12938 
12939 	/* u1 = IP header length (20 bytes) */
12940 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12941 
12942 	/* does packet contain IP+TCP headers? */
12943 	len = mp->b_wptr - rptr;
12944 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12945 		IP_STAT(ipst, ip_tcppullup);
12946 		goto tcppullup;
12947 	}
12948 
12949 	/* TCP options present? */
12950 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12951 
12952 	/*
12953 	 * If options need to be pulled up, then goto tcpoptions.
12954 	 * otherwise we are still in the fast path
12955 	 */
12956 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12957 		IP_STAT(ipst, ip_tcpoptions);
12958 		goto tcpoptions;
12959 	}
12960 
12961 	/* multiple mblks of tcp data? */
12962 	if ((mp1 = mp->b_cont) != NULL) {
12963 		/* more then two? */
12964 		if (mp1->b_cont != NULL) {
12965 			IP_STAT(ipst, ip_multipkttcp);
12966 			goto multipkttcp;
12967 		}
12968 		len += mp1->b_wptr - mp1->b_rptr;
12969 	}
12970 
12971 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12972 
12973 	/* part of pseudo checksum */
12974 
12975 	/* TCP datagram length */
12976 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12977 
12978 #define	iphs    ((uint16_t *)ipha)
12979 
12980 #ifdef	_BIG_ENDIAN
12981 	u1 += IPPROTO_TCP;
12982 #else
12983 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12984 #endif
12985 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12986 
12987 	/*
12988 	 * Revert to software checksum calculation if the interface
12989 	 * isn't capable of checksum offload or if IPsec is present.
12990 	 */
12991 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12992 		hck_flags = DB_CKSUMFLAGS(mp);
12993 
12994 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12995 		IP_STAT(ipst, ip_in_sw_cksum);
12996 
12997 	IP_CKSUM_RECV(hck_flags, u1,
12998 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12999 	    (int32_t)((uchar_t *)up - rptr),
13000 	    mp, mp1, cksum_err);
13001 
13002 	if (cksum_err) {
13003 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13004 
13005 		if (hck_flags & HCK_FULLCKSUM)
13006 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13007 		else if (hck_flags & HCK_PARTIALCKSUM)
13008 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13009 		else
13010 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13011 
13012 		goto error;
13013 	}
13014 
13015 try_again:
13016 
13017 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13018 	    zoneid, ipst)) == NULL) {
13019 		/* Send the TH_RST */
13020 		goto no_conn;
13021 	}
13022 
13023 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13024 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13025 
13026 	/*
13027 	 * TCP FAST PATH for AF_INET socket.
13028 	 *
13029 	 * TCP fast path to avoid extra work. An AF_INET socket type
13030 	 * does not have facility to receive extra information via
13031 	 * ip_process or ip_add_info. Also, when the connection was
13032 	 * established, we made a check if this connection is impacted
13033 	 * by any global IPsec policy or per connection policy (a
13034 	 * policy that comes in effect later will not apply to this
13035 	 * connection). Since all this can be determined at the
13036 	 * connection establishment time, a quick check of flags
13037 	 * can avoid extra work.
13038 	 */
13039 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13040 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13041 		ASSERT(first_mp == mp);
13042 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13043 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13044 			SET_SQUEUE(mp, tcp_rput_data, connp);
13045 			return (mp);
13046 		}
13047 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13048 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13049 		SET_SQUEUE(mp, tcp_input, connp);
13050 		return (mp);
13051 	}
13052 
13053 	if (tcph_flags == TH_SYN) {
13054 		if (IPCL_IS_TCP(connp)) {
13055 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13056 			DB_CKSUMSTART(mp) =
13057 			    (intptr_t)ip_squeue_get(ill_ring);
13058 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13059 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13060 				BUMP_MIB(ill->ill_ip_mib,
13061 				    ipIfStatsHCInDelivers);
13062 				SET_SQUEUE(mp, connp->conn_recv, connp);
13063 				return (mp);
13064 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13065 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13066 				BUMP_MIB(ill->ill_ip_mib,
13067 				    ipIfStatsHCInDelivers);
13068 				ip_squeue_enter_unbound++;
13069 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13070 				    connp);
13071 				return (mp);
13072 			}
13073 			syn_present = B_TRUE;
13074 		}
13075 	}
13076 
13077 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13078 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13079 
13080 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13081 		/* No need to send this packet to TCP */
13082 		if ((flags & TH_RST) || (flags & TH_URG)) {
13083 			CONN_DEC_REF(connp);
13084 			freemsg(first_mp);
13085 			return (NULL);
13086 		}
13087 		if (flags & TH_ACK) {
13088 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13089 			    ipst->ips_netstack->netstack_tcp, connp);
13090 			CONN_DEC_REF(connp);
13091 			return (NULL);
13092 		}
13093 
13094 		CONN_DEC_REF(connp);
13095 		freemsg(first_mp);
13096 		return (NULL);
13097 	}
13098 
13099 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13100 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13101 		    ipha, NULL, mctl_present);
13102 		if (first_mp == NULL) {
13103 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13104 			CONN_DEC_REF(connp);
13105 			return (NULL);
13106 		}
13107 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13108 			ASSERT(syn_present);
13109 			if (mctl_present) {
13110 				ASSERT(first_mp != mp);
13111 				first_mp->b_datap->db_struioflag |=
13112 				    STRUIO_POLICY;
13113 			} else {
13114 				ASSERT(first_mp == mp);
13115 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13116 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13117 			}
13118 		} else {
13119 			/*
13120 			 * Discard first_mp early since we're dealing with a
13121 			 * fully-connected conn_t and tcp doesn't do policy in
13122 			 * this case.
13123 			 */
13124 			if (mctl_present) {
13125 				freeb(first_mp);
13126 				mctl_present = B_FALSE;
13127 			}
13128 			first_mp = mp;
13129 		}
13130 	}
13131 
13132 	/* Initiate IPPF processing for fastpath */
13133 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13134 		uint32_t	ill_index;
13135 
13136 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13137 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13138 		if (mp == NULL) {
13139 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13140 			    "deferred/dropped during IPPF processing\n"));
13141 			CONN_DEC_REF(connp);
13142 			if (mctl_present)
13143 				freeb(first_mp);
13144 			return (NULL);
13145 		} else if (mctl_present) {
13146 			/*
13147 			 * ip_process might return a new mp.
13148 			 */
13149 			ASSERT(first_mp != mp);
13150 			first_mp->b_cont = mp;
13151 		} else {
13152 			first_mp = mp;
13153 		}
13154 
13155 	}
13156 
13157 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13158 		/*
13159 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13160 		 * make sure IPF_RECVIF is passed to ip_add_info.
13161 		 */
13162 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13163 		    IPCL_ZONEID(connp), ipst);
13164 		if (mp == NULL) {
13165 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13166 			CONN_DEC_REF(connp);
13167 			if (mctl_present)
13168 				freeb(first_mp);
13169 			return (NULL);
13170 		} else if (mctl_present) {
13171 			/*
13172 			 * ip_add_info might return a new mp.
13173 			 */
13174 			ASSERT(first_mp != mp);
13175 			first_mp->b_cont = mp;
13176 		} else {
13177 			first_mp = mp;
13178 		}
13179 	}
13180 
13181 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13182 	if (IPCL_IS_TCP(connp)) {
13183 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13184 		return (first_mp);
13185 	} else {
13186 		/* SOCK_RAW, IPPROTO_TCP case */
13187 		(connp->conn_recv)(connp, first_mp, NULL);
13188 		CONN_DEC_REF(connp);
13189 		return (NULL);
13190 	}
13191 
13192 no_conn:
13193 	/* Initiate IPPf processing, if needed. */
13194 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13195 		uint32_t ill_index;
13196 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13197 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13198 		if (first_mp == NULL) {
13199 			return (NULL);
13200 		}
13201 	}
13202 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13203 
13204 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13205 	    ipst->ips_netstack->netstack_tcp, NULL);
13206 	return (NULL);
13207 ipoptions:
13208 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13209 		goto slow_done;
13210 	}
13211 
13212 	UPDATE_IB_PKT_COUNT(ire);
13213 	ire->ire_last_used_time = lbolt;
13214 
13215 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13216 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13217 fragmented:
13218 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13219 			if (mctl_present)
13220 				freeb(first_mp);
13221 			goto slow_done;
13222 		}
13223 		/*
13224 		 * Make sure that first_mp points back to mp as
13225 		 * the mp we came in with could have changed in
13226 		 * ip_rput_fragment().
13227 		 */
13228 		ASSERT(!mctl_present);
13229 		ipha = (ipha_t *)mp->b_rptr;
13230 		first_mp = mp;
13231 	}
13232 
13233 	/* Now we have a complete datagram, destined for this machine. */
13234 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13235 
13236 	len = mp->b_wptr - mp->b_rptr;
13237 	/* Pull up a minimal TCP header, if necessary. */
13238 	if (len < (u1 + 20)) {
13239 tcppullup:
13240 		if (!pullupmsg(mp, u1 + 20)) {
13241 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13242 			goto error;
13243 		}
13244 		ipha = (ipha_t *)mp->b_rptr;
13245 		len = mp->b_wptr - mp->b_rptr;
13246 	}
13247 
13248 	/*
13249 	 * Extract the offset field from the TCP header.  As usual, we
13250 	 * try to help the compiler more than the reader.
13251 	 */
13252 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13253 	if (offset != 5) {
13254 tcpoptions:
13255 		if (offset < 5) {
13256 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13257 			goto error;
13258 		}
13259 		/*
13260 		 * There must be TCP options.
13261 		 * Make sure we can grab them.
13262 		 */
13263 		offset <<= 2;
13264 		offset += u1;
13265 		if (len < offset) {
13266 			if (!pullupmsg(mp, offset)) {
13267 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13268 				goto error;
13269 			}
13270 			ipha = (ipha_t *)mp->b_rptr;
13271 			len = mp->b_wptr - rptr;
13272 		}
13273 	}
13274 
13275 	/* Get the total packet length in len, including headers. */
13276 	if (mp->b_cont) {
13277 multipkttcp:
13278 		len = msgdsize(mp);
13279 	}
13280 
13281 	/*
13282 	 * Check the TCP checksum by pulling together the pseudo-
13283 	 * header checksum, and passing it to ip_csum to be added in
13284 	 * with the TCP datagram.
13285 	 *
13286 	 * Since we are not using the hwcksum if available we must
13287 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13288 	 * If either of these fails along the way the mblk is freed.
13289 	 * If this logic ever changes and mblk is reused to say send
13290 	 * ICMP's back, then this flag may need to be cleared in
13291 	 * other places as well.
13292 	 */
13293 	DB_CKSUMFLAGS(mp) = 0;
13294 
13295 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13296 
13297 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13298 #ifdef	_BIG_ENDIAN
13299 	u1 += IPPROTO_TCP;
13300 #else
13301 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13302 #endif
13303 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13304 	/*
13305 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13306 	 */
13307 	IP_STAT(ipst, ip_in_sw_cksum);
13308 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13309 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13310 		goto error;
13311 	}
13312 
13313 	IP_STAT(ipst, ip_tcp_slow_path);
13314 	goto try_again;
13315 #undef  iphs
13316 #undef  rptr
13317 
13318 error:
13319 	freemsg(first_mp);
13320 slow_done:
13321 	return (NULL);
13322 }
13323 
13324 /* ARGSUSED */
13325 static void
13326 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13327     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13328 {
13329 	conn_t		*connp;
13330 	uint32_t	sum;
13331 	uint32_t	u1;
13332 	ssize_t		len;
13333 	sctp_hdr_t	*sctph;
13334 	zoneid_t	zoneid = ire->ire_zoneid;
13335 	uint32_t	pktsum;
13336 	uint32_t	calcsum;
13337 	uint32_t	ports;
13338 	in6_addr_t	map_src, map_dst;
13339 	ill_t		*ill = (ill_t *)q->q_ptr;
13340 	ip_stack_t	*ipst;
13341 	sctp_stack_t	*sctps;
13342 	boolean_t	sctp_csum_err = B_FALSE;
13343 
13344 	ASSERT(recv_ill != NULL);
13345 	ipst = recv_ill->ill_ipst;
13346 	sctps = ipst->ips_netstack->netstack_sctp;
13347 
13348 #define	rptr	((uchar_t *)ipha)
13349 
13350 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13351 	ASSERT(ill != NULL);
13352 
13353 	/* u1 is # words of IP options */
13354 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13355 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13356 
13357 	/* IP options present */
13358 	if (u1 > 0) {
13359 		goto ipoptions;
13360 	} else {
13361 		/* Check the IP header checksum.  */
13362 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13363 		    !mctl_present) {
13364 #define	uph	((uint16_t *)ipha)
13365 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13366 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13367 #undef	uph
13368 			/* finish doing IP checksum */
13369 			sum = (sum & 0xFFFF) + (sum >> 16);
13370 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13371 			/*
13372 			 * Don't verify header checksum if this packet
13373 			 * is coming back from AH/ESP as we already did it.
13374 			 */
13375 			if (sum != 0 && sum != 0xFFFF) {
13376 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13377 				goto error;
13378 			}
13379 		}
13380 		/*
13381 		 * Since there is no SCTP h/w cksum support yet, just
13382 		 * clear the flag.
13383 		 */
13384 		DB_CKSUMFLAGS(mp) = 0;
13385 	}
13386 
13387 	/*
13388 	 * Don't verify header checksum if this packet is coming
13389 	 * back from AH/ESP as we already did it.
13390 	 */
13391 	if (!mctl_present) {
13392 		UPDATE_IB_PKT_COUNT(ire);
13393 		ire->ire_last_used_time = lbolt;
13394 	}
13395 
13396 	/* packet part of fragmented IP packet? */
13397 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13398 	if (u1 & (IPH_MF | IPH_OFFSET))
13399 		goto fragmented;
13400 
13401 	/* u1 = IP header length (20 bytes) */
13402 	u1 = IP_SIMPLE_HDR_LENGTH;
13403 
13404 find_sctp_client:
13405 	/* Pullup if we don't have the sctp common header. */
13406 	len = MBLKL(mp);
13407 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13408 		if (mp->b_cont == NULL ||
13409 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13410 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13411 			goto error;
13412 		}
13413 		ipha = (ipha_t *)mp->b_rptr;
13414 		len = MBLKL(mp);
13415 	}
13416 
13417 	sctph = (sctp_hdr_t *)(rptr + u1);
13418 #ifdef	DEBUG
13419 	if (!skip_sctp_cksum) {
13420 #endif
13421 		pktsum = sctph->sh_chksum;
13422 		sctph->sh_chksum = 0;
13423 		calcsum = sctp_cksum(mp, u1);
13424 		sctph->sh_chksum = pktsum;
13425 		if (calcsum != pktsum)
13426 			sctp_csum_err = B_TRUE;
13427 #ifdef	DEBUG	/* skip_sctp_cksum */
13428 	}
13429 #endif
13430 	/* get the ports */
13431 	ports = *(uint32_t *)&sctph->sh_sport;
13432 
13433 	IRE_REFRELE(ire);
13434 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13435 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13436 	if (sctp_csum_err) {
13437 		/*
13438 		 * No potential sctp checksum errors go to the Sun
13439 		 * sctp stack however they might be Adler-32 summed
13440 		 * packets a userland stack bound to a raw IP socket
13441 		 * could reasonably use. Note though that Adler-32 is
13442 		 * a long deprecated algorithm and customer sctp
13443 		 * networks should eventually migrate to CRC-32 at
13444 		 * which time this facility should be removed.
13445 		 */
13446 		flags |= IP_FF_SCTP_CSUM_ERR;
13447 		goto no_conn;
13448 	}
13449 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13450 	    sctps)) == NULL) {
13451 		/* Check for raw socket or OOTB handling */
13452 		goto no_conn;
13453 	}
13454 
13455 	/* Found a client; up it goes */
13456 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13457 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13458 	return;
13459 
13460 no_conn:
13461 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13462 	    ports, mctl_present, flags, B_TRUE, zoneid);
13463 	return;
13464 
13465 ipoptions:
13466 	DB_CKSUMFLAGS(mp) = 0;
13467 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13468 		goto slow_done;
13469 
13470 	UPDATE_IB_PKT_COUNT(ire);
13471 	ire->ire_last_used_time = lbolt;
13472 
13473 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13474 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13475 fragmented:
13476 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13477 			goto slow_done;
13478 		/*
13479 		 * Make sure that first_mp points back to mp as
13480 		 * the mp we came in with could have changed in
13481 		 * ip_rput_fragment().
13482 		 */
13483 		ASSERT(!mctl_present);
13484 		ipha = (ipha_t *)mp->b_rptr;
13485 		first_mp = mp;
13486 	}
13487 
13488 	/* Now we have a complete datagram, destined for this machine. */
13489 	u1 = IPH_HDR_LENGTH(ipha);
13490 	goto find_sctp_client;
13491 #undef  iphs
13492 #undef  rptr
13493 
13494 error:
13495 	freemsg(first_mp);
13496 slow_done:
13497 	IRE_REFRELE(ire);
13498 }
13499 
13500 #define	VER_BITS	0xF0
13501 #define	VERSION_6	0x60
13502 
13503 static boolean_t
13504 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13505     ipaddr_t *dstp, ip_stack_t *ipst)
13506 {
13507 	uint_t	opt_len;
13508 	ipha_t *ipha;
13509 	ssize_t len;
13510 	uint_t	pkt_len;
13511 
13512 	ASSERT(ill != NULL);
13513 	IP_STAT(ipst, ip_ipoptions);
13514 	ipha = *iphapp;
13515 
13516 #define	rptr    ((uchar_t *)ipha)
13517 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13518 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13519 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13520 		freemsg(mp);
13521 		return (B_FALSE);
13522 	}
13523 
13524 	/* multiple mblk or too short */
13525 	pkt_len = ntohs(ipha->ipha_length);
13526 
13527 	/* Get the number of words of IP options in the IP header. */
13528 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13529 	if (opt_len) {
13530 		/* IP Options present!  Validate and process. */
13531 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13532 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13533 			goto done;
13534 		}
13535 		/*
13536 		 * Recompute complete header length and make sure we
13537 		 * have access to all of it.
13538 		 */
13539 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13540 		if (len > (mp->b_wptr - rptr)) {
13541 			if (len > pkt_len) {
13542 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13543 				goto done;
13544 			}
13545 			if (!pullupmsg(mp, len)) {
13546 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13547 				goto done;
13548 			}
13549 			ipha = (ipha_t *)mp->b_rptr;
13550 		}
13551 		/*
13552 		 * Go off to ip_rput_options which returns the next hop
13553 		 * destination address, which may have been affected
13554 		 * by source routing.
13555 		 */
13556 		IP_STAT(ipst, ip_opt);
13557 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13558 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13559 			return (B_FALSE);
13560 		}
13561 	}
13562 	*iphapp = ipha;
13563 	return (B_TRUE);
13564 done:
13565 	/* clear b_prev - used by ip_mroute_decap */
13566 	mp->b_prev = NULL;
13567 	freemsg(mp);
13568 	return (B_FALSE);
13569 #undef  rptr
13570 }
13571 
13572 /*
13573  * Deal with the fact that there is no ire for the destination.
13574  */
13575 static ire_t *
13576 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13577 {
13578 	ipha_t	*ipha;
13579 	ill_t	*ill;
13580 	ire_t	*ire;
13581 	ip_stack_t *ipst;
13582 	enum	ire_forward_action ret_action;
13583 
13584 	ipha = (ipha_t *)mp->b_rptr;
13585 	ill = (ill_t *)q->q_ptr;
13586 
13587 	ASSERT(ill != NULL);
13588 	ipst = ill->ill_ipst;
13589 
13590 	/*
13591 	 * No IRE for this destination, so it can't be for us.
13592 	 * Unless we are forwarding, drop the packet.
13593 	 * We have to let source routed packets through
13594 	 * since we don't yet know if they are 'ping -l'
13595 	 * packets i.e. if they will go out over the
13596 	 * same interface as they came in on.
13597 	 */
13598 	if (ll_multicast) {
13599 		freemsg(mp);
13600 		return (NULL);
13601 	}
13602 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13603 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13604 		freemsg(mp);
13605 		return (NULL);
13606 	}
13607 
13608 	/*
13609 	 * Mark this packet as having originated externally.
13610 	 *
13611 	 * For non-forwarding code path, ire_send later double
13612 	 * checks this interface to see if it is still exists
13613 	 * post-ARP resolution.
13614 	 *
13615 	 * Also, IPQOS uses this to differentiate between
13616 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13617 	 * QOS packet processing in ip_wput_attach_llhdr().
13618 	 * The QoS module can mark the b_band for a fastpath message
13619 	 * or the dl_priority field in a unitdata_req header for
13620 	 * CoS marking. This info can only be found in
13621 	 * ip_wput_attach_llhdr().
13622 	 */
13623 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13624 	/*
13625 	 * Clear the indication that this may have a hardware checksum
13626 	 * as we are not using it
13627 	 */
13628 	DB_CKSUMFLAGS(mp) = 0;
13629 
13630 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13631 	    msg_getlabel(mp), ipst);
13632 
13633 	if (ire == NULL && ret_action == Forward_check_multirt) {
13634 		/* Let ip_newroute handle CGTP  */
13635 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13636 		return (NULL);
13637 	}
13638 
13639 	if (ire != NULL)
13640 		return (ire);
13641 
13642 	mp->b_prev = mp->b_next = 0;
13643 
13644 	if (ret_action == Forward_blackhole) {
13645 		freemsg(mp);
13646 		return (NULL);
13647 	}
13648 	/* send icmp unreachable */
13649 	q = WR(q);
13650 	/* Sent by forwarding path, and router is global zone */
13651 	if (ip_source_routed(ipha, ipst)) {
13652 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13653 		    GLOBAL_ZONEID, ipst);
13654 	} else {
13655 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13656 		    ipst);
13657 	}
13658 
13659 	return (NULL);
13660 
13661 }
13662 
13663 /*
13664  * check ip header length and align it.
13665  */
13666 static boolean_t
13667 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13668 {
13669 	ssize_t len;
13670 	ill_t *ill;
13671 	ipha_t	*ipha;
13672 
13673 	len = MBLKL(mp);
13674 
13675 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13676 		ill = (ill_t *)q->q_ptr;
13677 
13678 		if (!OK_32PTR(mp->b_rptr))
13679 			IP_STAT(ipst, ip_notaligned1);
13680 		else
13681 			IP_STAT(ipst, ip_notaligned2);
13682 		/* Guard against bogus device drivers */
13683 		if (len < 0) {
13684 			/* clear b_prev - used by ip_mroute_decap */
13685 			mp->b_prev = NULL;
13686 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13687 			freemsg(mp);
13688 			return (B_FALSE);
13689 		}
13690 
13691 		if (ip_rput_pullups++ == 0) {
13692 			ipha = (ipha_t *)mp->b_rptr;
13693 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13694 			    "ip_check_and_align_header: %s forced us to "
13695 			    " pullup pkt, hdr len %ld, hdr addr %p",
13696 			    ill->ill_name, len, (void *)ipha);
13697 		}
13698 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13699 			/* clear b_prev - used by ip_mroute_decap */
13700 			mp->b_prev = NULL;
13701 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13702 			freemsg(mp);
13703 			return (B_FALSE);
13704 		}
13705 	}
13706 	return (B_TRUE);
13707 }
13708 
13709 /*
13710  * Handle the situation where a packet came in on `ill' but matched an IRE
13711  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13712  * for interface statistics.
13713  */
13714 ire_t *
13715 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13716 {
13717 	ire_t		*new_ire;
13718 	ill_t		*ire_ill;
13719 	uint_t		ifindex;
13720 	ip_stack_t	*ipst = ill->ill_ipst;
13721 	boolean_t	strict_check = B_FALSE;
13722 
13723 	/*
13724 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13725 	 * issue (e.g. packet received on an underlying interface matched an
13726 	 * IRE_LOCAL on its associated group interface).
13727 	 */
13728 	if (ire->ire_rfq != NULL &&
13729 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13730 		return (ire);
13731 	}
13732 
13733 	/*
13734 	 * Do another ire lookup here, using the ingress ill, to see if the
13735 	 * interface is in a usesrc group.
13736 	 * As long as the ills belong to the same group, we don't consider
13737 	 * them to be arriving on the wrong interface. Thus, if the switch
13738 	 * is doing inbound load spreading, we won't drop packets when the
13739 	 * ip*_strict_dst_multihoming switch is on.
13740 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13741 	 * where the local address may not be unique. In this case we were
13742 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13743 	 * actually returned. The new lookup, which is more specific, should
13744 	 * only find the IRE_LOCAL associated with the ingress ill if one
13745 	 * exists.
13746 	 */
13747 
13748 	if (ire->ire_ipversion == IPV4_VERSION) {
13749 		if (ipst->ips_ip_strict_dst_multihoming)
13750 			strict_check = B_TRUE;
13751 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13752 		    ill->ill_ipif, ALL_ZONES, NULL,
13753 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13754 	} else {
13755 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13756 		if (ipst->ips_ipv6_strict_dst_multihoming)
13757 			strict_check = B_TRUE;
13758 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13759 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13760 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13761 	}
13762 	/*
13763 	 * If the same ire that was returned in ip_input() is found then this
13764 	 * is an indication that usesrc groups are in use. The packet
13765 	 * arrived on a different ill in the group than the one associated with
13766 	 * the destination address.  If a different ire was found then the same
13767 	 * IP address must be hosted on multiple ills. This is possible with
13768 	 * unnumbered point2point interfaces. We switch to use this new ire in
13769 	 * order to have accurate interface statistics.
13770 	 */
13771 	if (new_ire != NULL) {
13772 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13773 			ire_refrele(ire);
13774 			ire = new_ire;
13775 		} else {
13776 			ire_refrele(new_ire);
13777 		}
13778 		return (ire);
13779 	} else if ((ire->ire_rfq == NULL) &&
13780 	    (ire->ire_ipversion == IPV4_VERSION)) {
13781 		/*
13782 		 * The best match could have been the original ire which
13783 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13784 		 * the strict multihoming checks are irrelevant as we consider
13785 		 * local addresses hosted on lo0 to be interface agnostic. We
13786 		 * only expect a null ire_rfq on IREs which are associated with
13787 		 * lo0 hence we can return now.
13788 		 */
13789 		return (ire);
13790 	}
13791 
13792 	/*
13793 	 * Chase pointers once and store locally.
13794 	 */
13795 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13796 	    (ill_t *)(ire->ire_rfq->q_ptr);
13797 	ifindex = ill->ill_usesrc_ifindex;
13798 
13799 	/*
13800 	 * Check if it's a legal address on the 'usesrc' interface.
13801 	 */
13802 	if ((ifindex != 0) && (ire_ill != NULL) &&
13803 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13804 		return (ire);
13805 	}
13806 
13807 	/*
13808 	 * If the ip*_strict_dst_multihoming switch is on then we can
13809 	 * only accept this packet if the interface is marked as routing.
13810 	 */
13811 	if (!(strict_check))
13812 		return (ire);
13813 
13814 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13815 	    ILLF_ROUTER) != 0) {
13816 		return (ire);
13817 	}
13818 
13819 	ire_refrele(ire);
13820 	return (NULL);
13821 }
13822 
13823 /*
13824  *
13825  * This is the fast forward path. If we are here, we dont need to
13826  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13827  * needed to find the nexthop in this case is much simpler
13828  */
13829 ire_t *
13830 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13831 {
13832 	ipha_t	*ipha;
13833 	ire_t	*src_ire;
13834 	ill_t	*stq_ill;
13835 	uint_t	hlen;
13836 	uint_t	pkt_len;
13837 	uint32_t sum;
13838 	queue_t	*dev_q;
13839 	ip_stack_t *ipst = ill->ill_ipst;
13840 	mblk_t *fpmp;
13841 	enum	ire_forward_action ret_action;
13842 
13843 	ipha = (ipha_t *)mp->b_rptr;
13844 
13845 	if (ire != NULL &&
13846 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13847 	    ire->ire_zoneid != ALL_ZONES) {
13848 		/*
13849 		 * Should only use IREs that are visible to the global
13850 		 * zone for forwarding.
13851 		 */
13852 		ire_refrele(ire);
13853 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13854 		/*
13855 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13856 		 * transient cases. In such case, just drop the packet
13857 		 */
13858 		if (ire->ire_type != IRE_CACHE)
13859 			goto drop;
13860 	}
13861 
13862 	/*
13863 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13864 	 * The loopback address check for both src and dst has already
13865 	 * been checked in ip_input
13866 	 */
13867 
13868 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13869 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13870 		goto drop;
13871 	}
13872 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13873 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13874 
13875 	if (src_ire != NULL) {
13876 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13877 		ire_refrele(src_ire);
13878 		goto drop;
13879 	}
13880 
13881 	/* No ire cache of nexthop. So first create one  */
13882 	if (ire == NULL) {
13883 
13884 		ire = ire_forward_simple(dst, &ret_action, ipst);
13885 
13886 		/*
13887 		 * We only come to ip_fast_forward if ip_cgtp_filter
13888 		 * is not set. So ire_forward() should not return with
13889 		 * Forward_check_multirt as the next action.
13890 		 */
13891 		ASSERT(ret_action != Forward_check_multirt);
13892 		if (ire == NULL) {
13893 			/* An attempt was made to forward the packet */
13894 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13895 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13896 			mp->b_prev = mp->b_next = 0;
13897 			/* send icmp unreachable */
13898 			/* Sent by forwarding path, and router is global zone */
13899 			if (ret_action == Forward_ret_icmp_err) {
13900 				if (ip_source_routed(ipha, ipst)) {
13901 					icmp_unreachable(ill->ill_wq, mp,
13902 					    ICMP_SOURCE_ROUTE_FAILED,
13903 					    GLOBAL_ZONEID, ipst);
13904 				} else {
13905 					icmp_unreachable(ill->ill_wq, mp,
13906 					    ICMP_HOST_UNREACHABLE,
13907 					    GLOBAL_ZONEID, ipst);
13908 				}
13909 			} else {
13910 				freemsg(mp);
13911 			}
13912 			return (NULL);
13913 		}
13914 	}
13915 
13916 	/*
13917 	 * Forwarding fastpath exception case:
13918 	 * If any of the following are true, we take the slowpath:
13919 	 *	o forwarding is not enabled
13920 	 *	o incoming and outgoing interface are the same, or in the same
13921 	 *	  IPMP group.
13922 	 *	o corresponding ire is in incomplete state
13923 	 *	o packet needs fragmentation
13924 	 *	o ARP cache is not resolved
13925 	 *
13926 	 * The codeflow from here on is thus:
13927 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13928 	 */
13929 	pkt_len = ntohs(ipha->ipha_length);
13930 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13931 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13932 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13933 	    (ire->ire_nce == NULL) ||
13934 	    (pkt_len > ire->ire_max_frag) ||
13935 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13936 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13937 	    ipha->ipha_ttl <= 1) {
13938 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13939 		    ipha, ill, B_FALSE, B_TRUE);
13940 		return (ire);
13941 	}
13942 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13943 
13944 	DTRACE_PROBE4(ip4__forwarding__start,
13945 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13946 
13947 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13948 	    ipst->ips_ipv4firewall_forwarding,
13949 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13950 
13951 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13952 
13953 	if (mp == NULL)
13954 		goto drop;
13955 
13956 	mp->b_datap->db_struioun.cksum.flags = 0;
13957 	/* Adjust the checksum to reflect the ttl decrement. */
13958 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13959 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13960 	ipha->ipha_ttl--;
13961 
13962 	/*
13963 	 * Write the link layer header.  We can do this safely here,
13964 	 * because we have already tested to make sure that the IP
13965 	 * policy is not set, and that we have a fast path destination
13966 	 * header.
13967 	 */
13968 	mp->b_rptr -= hlen;
13969 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13970 
13971 	UPDATE_IB_PKT_COUNT(ire);
13972 	ire->ire_last_used_time = lbolt;
13973 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13974 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13975 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13976 
13977 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
13978 		dev_q = ire->ire_stq->q_next;
13979 		if (DEV_Q_FLOW_BLOCKED(dev_q))
13980 			goto indiscard;
13981 	}
13982 
13983 	DTRACE_PROBE4(ip4__physical__out__start,
13984 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13985 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
13986 	    ipst->ips_ipv4firewall_physical_out,
13987 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13988 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13989 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
13990 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
13991 	    ip6_t *, NULL, int, 0);
13992 
13993 	if (mp != NULL) {
13994 		if (ipst->ips_ipobs_enabled) {
13995 			zoneid_t szone;
13996 
13997 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
13998 			    ipst, ALL_ZONES);
13999 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14000 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14001 		}
14002 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14003 	}
14004 	return (ire);
14005 
14006 indiscard:
14007 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14008 drop:
14009 	if (mp != NULL)
14010 		freemsg(mp);
14011 	return (ire);
14012 
14013 }
14014 
14015 /*
14016  * This function is called in the forwarding slowpath, when
14017  * either the ire lacks the link-layer address, or the packet needs
14018  * further processing(eg. fragmentation), before transmission.
14019  */
14020 
14021 static void
14022 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14023     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14024 {
14025 	queue_t		*dev_q;
14026 	ire_t		*src_ire;
14027 	ip_stack_t	*ipst = ill->ill_ipst;
14028 	boolean_t	same_illgrp = B_FALSE;
14029 
14030 	ASSERT(ire->ire_stq != NULL);
14031 
14032 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14033 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14034 
14035 	/*
14036 	 * If the caller of this function is ip_fast_forward() skip the
14037 	 * next three checks as it does not apply.
14038 	 */
14039 	if (from_ip_fast_forward)
14040 		goto skip;
14041 
14042 	if (ll_multicast != 0) {
14043 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14044 		goto drop_pkt;
14045 	}
14046 
14047 	/*
14048 	 * check if ipha_src is a broadcast address. Note that this
14049 	 * check is redundant when we get here from ip_fast_forward()
14050 	 * which has already done this check. However, since we can
14051 	 * also get here from ip_rput_process_broadcast() or, for
14052 	 * for the slow path through ip_fast_forward(), we perform
14053 	 * the check again for code-reusability
14054 	 */
14055 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14056 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14057 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14058 		if (src_ire != NULL)
14059 			ire_refrele(src_ire);
14060 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14061 		ip2dbg(("ip_rput_process_forward: Received packet with"
14062 		    " bad src/dst address on %s\n", ill->ill_name));
14063 		goto drop_pkt;
14064 	}
14065 
14066 	/*
14067 	 * Check if we want to forward this one at this time.
14068 	 * We allow source routed packets on a host provided that
14069 	 * they go out the same ill or illgrp as they came in on.
14070 	 *
14071 	 * XXX To be quicker, we may wish to not chase pointers to
14072 	 * get the ILLF_ROUTER flag and instead store the
14073 	 * forwarding policy in the ire.  An unfortunate
14074 	 * side-effect of that would be requiring an ire flush
14075 	 * whenever the ILLF_ROUTER flag changes.
14076 	 */
14077 skip:
14078 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14079 
14080 	if (((ill->ill_flags &
14081 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14082 	    !(ip_source_routed(ipha, ipst) &&
14083 	    (ire->ire_rfq == q || same_illgrp))) {
14084 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14085 		if (ip_source_routed(ipha, ipst)) {
14086 			q = WR(q);
14087 			/*
14088 			 * Clear the indication that this may have
14089 			 * hardware checksum as we are not using it.
14090 			 */
14091 			DB_CKSUMFLAGS(mp) = 0;
14092 			/* Sent by forwarding path, and router is global zone */
14093 			icmp_unreachable(q, mp,
14094 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14095 			return;
14096 		}
14097 		goto drop_pkt;
14098 	}
14099 
14100 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14101 
14102 	/* Packet is being forwarded. Turning off hwcksum flag. */
14103 	DB_CKSUMFLAGS(mp) = 0;
14104 	if (ipst->ips_ip_g_send_redirects) {
14105 		/*
14106 		 * Check whether the incoming interface and outgoing
14107 		 * interface is part of the same group. If so,
14108 		 * send redirects.
14109 		 *
14110 		 * Check the source address to see if it originated
14111 		 * on the same logical subnet it is going back out on.
14112 		 * If so, we should be able to send it a redirect.
14113 		 * Avoid sending a redirect if the destination
14114 		 * is directly connected (i.e., ipha_dst is the same
14115 		 * as ire_gateway_addr or the ire_addr of the
14116 		 * nexthop IRE_CACHE ), or if the packet was source
14117 		 * routed out this interface.
14118 		 */
14119 		ipaddr_t src, nhop;
14120 		mblk_t	*mp1;
14121 		ire_t	*nhop_ire = NULL;
14122 
14123 		/*
14124 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14125 		 * If so, send redirects.
14126 		 */
14127 		if ((ire->ire_rfq == q || same_illgrp) &&
14128 		    !ip_source_routed(ipha, ipst)) {
14129 
14130 			nhop = (ire->ire_gateway_addr != 0 ?
14131 			    ire->ire_gateway_addr : ire->ire_addr);
14132 
14133 			if (ipha->ipha_dst == nhop) {
14134 				/*
14135 				 * We avoid sending a redirect if the
14136 				 * destination is directly connected
14137 				 * because it is possible that multiple
14138 				 * IP subnets may have been configured on
14139 				 * the link, and the source may not
14140 				 * be on the same subnet as ip destination,
14141 				 * even though they are on the same
14142 				 * physical link.
14143 				 */
14144 				goto sendit;
14145 			}
14146 
14147 			src = ipha->ipha_src;
14148 
14149 			/*
14150 			 * We look up the interface ire for the nexthop,
14151 			 * to see if ipha_src is in the same subnet
14152 			 * as the nexthop.
14153 			 *
14154 			 * Note that, if, in the future, IRE_CACHE entries
14155 			 * are obsoleted,  this lookup will not be needed,
14156 			 * as the ire passed to this function will be the
14157 			 * same as the nhop_ire computed below.
14158 			 */
14159 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14160 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14161 			    0, NULL, MATCH_IRE_TYPE, ipst);
14162 
14163 			if (nhop_ire != NULL) {
14164 				if ((src & nhop_ire->ire_mask) ==
14165 				    (nhop & nhop_ire->ire_mask)) {
14166 					/*
14167 					 * The source is directly connected.
14168 					 * Just copy the ip header (which is
14169 					 * in the first mblk)
14170 					 */
14171 					mp1 = copyb(mp);
14172 					if (mp1 != NULL) {
14173 						icmp_send_redirect(WR(q), mp1,
14174 						    nhop, ipst);
14175 					}
14176 				}
14177 				ire_refrele(nhop_ire);
14178 			}
14179 		}
14180 	}
14181 sendit:
14182 	dev_q = ire->ire_stq->q_next;
14183 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14184 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14185 		freemsg(mp);
14186 		return;
14187 	}
14188 
14189 	ip_rput_forward(ire, ipha, mp, ill);
14190 	return;
14191 
14192 drop_pkt:
14193 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14194 	freemsg(mp);
14195 }
14196 
14197 ire_t *
14198 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14199     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14200 {
14201 	queue_t		*q;
14202 	uint16_t	hcksumflags;
14203 	ip_stack_t	*ipst = ill->ill_ipst;
14204 
14205 	q = *qp;
14206 
14207 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14208 
14209 	/*
14210 	 * Clear the indication that this may have hardware
14211 	 * checksum as we are not using it for forwarding.
14212 	 */
14213 	hcksumflags = DB_CKSUMFLAGS(mp);
14214 	DB_CKSUMFLAGS(mp) = 0;
14215 
14216 	/*
14217 	 * Directed broadcast forwarding: if the packet came in over a
14218 	 * different interface then it is routed out over we can forward it.
14219 	 */
14220 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14221 		ire_refrele(ire);
14222 		freemsg(mp);
14223 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14224 		return (NULL);
14225 	}
14226 	/*
14227 	 * For multicast we have set dst to be INADDR_BROADCAST
14228 	 * for delivering to all STREAMS.
14229 	 */
14230 	if (!CLASSD(ipha->ipha_dst)) {
14231 		ire_t *new_ire;
14232 		ipif_t *ipif;
14233 
14234 		ipif = ipif_get_next_ipif(NULL, ill);
14235 		if (ipif == NULL) {
14236 discard:		ire_refrele(ire);
14237 			freemsg(mp);
14238 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14239 			return (NULL);
14240 		}
14241 		new_ire = ire_ctable_lookup(dst, 0, 0,
14242 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14243 		ipif_refrele(ipif);
14244 
14245 		if (new_ire != NULL) {
14246 			/*
14247 			 * If the matching IRE_BROADCAST is part of an IPMP
14248 			 * group, then drop the packet unless our ill has been
14249 			 * nominated to receive for the group.
14250 			 */
14251 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14252 			    new_ire->ire_rfq != q) {
14253 				ire_refrele(new_ire);
14254 				goto discard;
14255 			}
14256 
14257 			/*
14258 			 * In the special case of multirouted broadcast
14259 			 * packets, we unconditionally need to "gateway"
14260 			 * them to the appropriate interface here.
14261 			 * In the normal case, this cannot happen, because
14262 			 * there is no broadcast IRE tagged with the
14263 			 * RTF_MULTIRT flag.
14264 			 */
14265 			if (new_ire->ire_flags & RTF_MULTIRT) {
14266 				ire_refrele(new_ire);
14267 				if (ire->ire_rfq != NULL) {
14268 					q = ire->ire_rfq;
14269 					*qp = q;
14270 				}
14271 			} else {
14272 				ire_refrele(ire);
14273 				ire = new_ire;
14274 			}
14275 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14276 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14277 				/*
14278 				 * Free the message if
14279 				 * ip_g_forward_directed_bcast is turned
14280 				 * off for non-local broadcast.
14281 				 */
14282 				ire_refrele(ire);
14283 				freemsg(mp);
14284 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14285 				return (NULL);
14286 			}
14287 		} else {
14288 			/*
14289 			 * This CGTP packet successfully passed the
14290 			 * CGTP filter, but the related CGTP
14291 			 * broadcast IRE has not been found,
14292 			 * meaning that the redundant ipif is
14293 			 * probably down. However, if we discarded
14294 			 * this packet, its duplicate would be
14295 			 * filtered out by the CGTP filter so none
14296 			 * of them would get through. So we keep
14297 			 * going with this one.
14298 			 */
14299 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14300 			if (ire->ire_rfq != NULL) {
14301 				q = ire->ire_rfq;
14302 				*qp = q;
14303 			}
14304 		}
14305 	}
14306 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14307 		/*
14308 		 * Verify that there are not more then one
14309 		 * IRE_BROADCAST with this broadcast address which
14310 		 * has ire_stq set.
14311 		 * TODO: simplify, loop over all IRE's
14312 		 */
14313 		ire_t	*ire1;
14314 		int	num_stq = 0;
14315 		mblk_t	*mp1;
14316 
14317 		/* Find the first one with ire_stq set */
14318 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14319 		for (ire1 = ire; ire1 &&
14320 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14321 		    ire1 = ire1->ire_next)
14322 			;
14323 		if (ire1) {
14324 			ire_refrele(ire);
14325 			ire = ire1;
14326 			IRE_REFHOLD(ire);
14327 		}
14328 
14329 		/* Check if there are additional ones with stq set */
14330 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14331 			if (ire->ire_addr != ire1->ire_addr)
14332 				break;
14333 			if (ire1->ire_stq) {
14334 				num_stq++;
14335 				break;
14336 			}
14337 		}
14338 		rw_exit(&ire->ire_bucket->irb_lock);
14339 		if (num_stq == 1 && ire->ire_stq != NULL) {
14340 			ip1dbg(("ip_rput_process_broadcast: directed "
14341 			    "broadcast to 0x%x\n",
14342 			    ntohl(ire->ire_addr)));
14343 			mp1 = copymsg(mp);
14344 			if (mp1) {
14345 				switch (ipha->ipha_protocol) {
14346 				case IPPROTO_UDP:
14347 					ip_udp_input(q, mp1, ipha, ire, ill);
14348 					break;
14349 				default:
14350 					ip_proto_input(q, mp1, ipha, ire, ill,
14351 					    0);
14352 					break;
14353 				}
14354 			}
14355 			/*
14356 			 * Adjust ttl to 2 (1+1 - the forward engine
14357 			 * will decrement it by one.
14358 			 */
14359 			if (ip_csum_hdr(ipha)) {
14360 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14361 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14362 				freemsg(mp);
14363 				ire_refrele(ire);
14364 				return (NULL);
14365 			}
14366 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14367 			ipha->ipha_hdr_checksum = 0;
14368 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14369 			ip_rput_process_forward(q, mp, ire, ipha,
14370 			    ill, ll_multicast, B_FALSE);
14371 			ire_refrele(ire);
14372 			return (NULL);
14373 		}
14374 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14375 		    ntohl(ire->ire_addr)));
14376 	}
14377 
14378 	/* Restore any hardware checksum flags */
14379 	DB_CKSUMFLAGS(mp) = hcksumflags;
14380 	return (ire);
14381 }
14382 
14383 /* ARGSUSED */
14384 static boolean_t
14385 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14386     int *ll_multicast, ipaddr_t *dstp)
14387 {
14388 	ip_stack_t	*ipst = ill->ill_ipst;
14389 
14390 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14391 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14392 	    ntohs(ipha->ipha_length));
14393 
14394 	/*
14395 	 * So that we don't end up with dups, only one ill in an IPMP group is
14396 	 * nominated to receive multicast traffic.
14397 	 */
14398 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14399 		goto drop_pkt;
14400 
14401 	/*
14402 	 * Forward packets only if we have joined the allmulti
14403 	 * group on this interface.
14404 	 */
14405 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14406 		int retval;
14407 
14408 		/*
14409 		 * Clear the indication that this may have hardware
14410 		 * checksum as we are not using it.
14411 		 */
14412 		DB_CKSUMFLAGS(mp) = 0;
14413 		retval = ip_mforward(ill, ipha, mp);
14414 		/* ip_mforward updates mib variables if needed */
14415 		/* clear b_prev - used by ip_mroute_decap */
14416 		mp->b_prev = NULL;
14417 
14418 		switch (retval) {
14419 		case 0:
14420 			/*
14421 			 * pkt is okay and arrived on phyint.
14422 			 *
14423 			 * If we are running as a multicast router
14424 			 * we need to see all IGMP and/or PIM packets.
14425 			 */
14426 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14427 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14428 				goto done;
14429 			}
14430 			break;
14431 		case -1:
14432 			/* pkt is mal-formed, toss it */
14433 			goto drop_pkt;
14434 		case 1:
14435 			/* pkt is okay and arrived on a tunnel */
14436 			/*
14437 			 * If we are running a multicast router
14438 			 *  we need to see all igmp packets.
14439 			 */
14440 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14441 				*dstp = INADDR_BROADCAST;
14442 				*ll_multicast = 1;
14443 				return (B_FALSE);
14444 			}
14445 
14446 			goto drop_pkt;
14447 		}
14448 	}
14449 
14450 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14451 		/*
14452 		 * This might just be caused by the fact that
14453 		 * multiple IP Multicast addresses map to the same
14454 		 * link layer multicast - no need to increment counter!
14455 		 */
14456 		freemsg(mp);
14457 		return (B_TRUE);
14458 	}
14459 done:
14460 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14461 	/*
14462 	 * This assumes the we deliver to all streams for multicast
14463 	 * and broadcast packets.
14464 	 */
14465 	*dstp = INADDR_BROADCAST;
14466 	*ll_multicast = 1;
14467 	return (B_FALSE);
14468 drop_pkt:
14469 	ip2dbg(("ip_rput: drop pkt\n"));
14470 	freemsg(mp);
14471 	return (B_TRUE);
14472 }
14473 
14474 /*
14475  * This function is used to both return an indication of whether or not
14476  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14477  * and in doing so, determine whether or not it is broadcast vs multicast.
14478  * For it to be a broadcast packet, we must have the appropriate mblk_t
14479  * hanging off the ill_t.  If this is either not present or doesn't match
14480  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14481  * to be multicast.  Thus NICs that have no broadcast address (or no
14482  * capability for one, such as point to point links) cannot return as
14483  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14484  * the return values simplifies the current use of the return value of this
14485  * function, which is to pass through the multicast/broadcast characteristic
14486  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14487  * changing the return value to some other symbol demands the appropriate
14488  * "translation" when hpe_flags is set prior to calling hook_run() for
14489  * packet events.
14490  */
14491 int
14492 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14493 {
14494 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14495 	mblk_t *bmp;
14496 
14497 	if (ind->dl_group_address) {
14498 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14499 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14500 		    MBLKL(mb) &&
14501 		    (bmp = ill->ill_bcast_mp) != NULL) {
14502 			dl_unitdata_req_t *dlur;
14503 			uint8_t *bphys_addr;
14504 
14505 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14506 			if (ill->ill_sap_length < 0)
14507 				bphys_addr = (uchar_t *)dlur +
14508 				    dlur->dl_dest_addr_offset;
14509 			else
14510 				bphys_addr = (uchar_t *)dlur +
14511 				    dlur->dl_dest_addr_offset +
14512 				    ill->ill_sap_length;
14513 
14514 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14515 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14516 				return (HPE_BROADCAST);
14517 			}
14518 			return (HPE_MULTICAST);
14519 		}
14520 		return (HPE_MULTICAST);
14521 	}
14522 	return (0);
14523 }
14524 
14525 static boolean_t
14526 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14527     int *ll_multicast, mblk_t **mpp)
14528 {
14529 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14530 	boolean_t must_copy = B_FALSE;
14531 	struct iocblk   *iocp;
14532 	ipha_t		*ipha;
14533 	ip_stack_t	*ipst = ill->ill_ipst;
14534 
14535 #define	rptr    ((uchar_t *)ipha)
14536 
14537 	first_mp = *first_mpp;
14538 	mp = *mpp;
14539 
14540 	ASSERT(first_mp == mp);
14541 
14542 	/*
14543 	 * if db_ref > 1 then copymsg and free original. Packet may be
14544 	 * changed and do not want other entity who has a reference to this
14545 	 * message to trip over the changes. This is a blind change because
14546 	 * trying to catch all places that might change packet is too
14547 	 * difficult (since it may be a module above this one)
14548 	 *
14549 	 * This corresponds to the non-fast path case. We walk down the full
14550 	 * chain in this case, and check the db_ref count of all the dblks,
14551 	 * and do a copymsg if required. It is possible that the db_ref counts
14552 	 * of the data blocks in the mblk chain can be different.
14553 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14554 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14555 	 * 'snoop' is running.
14556 	 */
14557 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14558 		if (mp1->b_datap->db_ref > 1) {
14559 			must_copy = B_TRUE;
14560 			break;
14561 		}
14562 	}
14563 
14564 	if (must_copy) {
14565 		mp1 = copymsg(mp);
14566 		if (mp1 == NULL) {
14567 			for (mp1 = mp; mp1 != NULL;
14568 			    mp1 = mp1->b_cont) {
14569 				mp1->b_next = NULL;
14570 				mp1->b_prev = NULL;
14571 			}
14572 			freemsg(mp);
14573 			if (ill != NULL) {
14574 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14575 			} else {
14576 				BUMP_MIB(&ipst->ips_ip_mib,
14577 				    ipIfStatsInDiscards);
14578 			}
14579 			return (B_TRUE);
14580 		}
14581 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14582 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14583 			/* Copy b_prev - used by ip_mroute_decap */
14584 			to_mp->b_prev = from_mp->b_prev;
14585 			from_mp->b_prev = NULL;
14586 		}
14587 		*first_mpp = first_mp = mp1;
14588 		freemsg(mp);
14589 		mp = mp1;
14590 		*mpp = mp1;
14591 	}
14592 
14593 	ipha = (ipha_t *)mp->b_rptr;
14594 
14595 	/*
14596 	 * previous code has a case for M_DATA.
14597 	 * We want to check how that happens.
14598 	 */
14599 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14600 	switch (first_mp->b_datap->db_type) {
14601 	case M_PROTO:
14602 	case M_PCPROTO:
14603 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14604 		    DL_UNITDATA_IND) {
14605 			/* Go handle anything other than data elsewhere. */
14606 			ip_rput_dlpi(q, mp);
14607 			return (B_TRUE);
14608 		}
14609 
14610 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14611 		/* Ditch the DLPI header. */
14612 		mp1 = mp->b_cont;
14613 		ASSERT(first_mp == mp);
14614 		*first_mpp = mp1;
14615 		freeb(mp);
14616 		*mpp = mp1;
14617 		return (B_FALSE);
14618 	case M_IOCACK:
14619 		ip1dbg(("got iocack "));
14620 		iocp = (struct iocblk *)mp->b_rptr;
14621 		switch (iocp->ioc_cmd) {
14622 		case DL_IOC_HDR_INFO:
14623 			ill = (ill_t *)q->q_ptr;
14624 			ill_fastpath_ack(ill, mp);
14625 			return (B_TRUE);
14626 		case SIOCSTUNPARAM:
14627 		case OSIOCSTUNPARAM:
14628 			/* Go through qwriter_ip */
14629 			break;
14630 		case SIOCGTUNPARAM:
14631 		case OSIOCGTUNPARAM:
14632 			ip_rput_other(NULL, q, mp, NULL);
14633 			return (B_TRUE);
14634 		default:
14635 			putnext(q, mp);
14636 			return (B_TRUE);
14637 		}
14638 		/* FALLTHRU */
14639 	case M_ERROR:
14640 	case M_HANGUP:
14641 		/*
14642 		 * Since this is on the ill stream we unconditionally
14643 		 * bump up the refcount
14644 		 */
14645 		ill_refhold(ill);
14646 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14647 		return (B_TRUE);
14648 	case M_CTL:
14649 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14650 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14651 		    IPHADA_M_CTL)) {
14652 			/*
14653 			 * It's an IPsec accelerated packet.
14654 			 * Make sure that the ill from which we received the
14655 			 * packet has enabled IPsec hardware acceleration.
14656 			 */
14657 			if (!(ill->ill_capabilities &
14658 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14659 				/* IPsec kstats: bean counter */
14660 				freemsg(mp);
14661 				return (B_TRUE);
14662 			}
14663 
14664 			/*
14665 			 * Make mp point to the mblk following the M_CTL,
14666 			 * then process according to type of mp.
14667 			 * After this processing, first_mp will point to
14668 			 * the data-attributes and mp to the pkt following
14669 			 * the M_CTL.
14670 			 */
14671 			mp = first_mp->b_cont;
14672 			if (mp == NULL) {
14673 				freemsg(first_mp);
14674 				return (B_TRUE);
14675 			}
14676 			/*
14677 			 * A Hardware Accelerated packet can only be M_DATA
14678 			 * ESP or AH packet.
14679 			 */
14680 			if (mp->b_datap->db_type != M_DATA) {
14681 				/* non-M_DATA IPsec accelerated packet */
14682 				IPSECHW_DEBUG(IPSECHW_PKT,
14683 				    ("non-M_DATA IPsec accelerated pkt\n"));
14684 				freemsg(first_mp);
14685 				return (B_TRUE);
14686 			}
14687 			ipha = (ipha_t *)mp->b_rptr;
14688 			if (ipha->ipha_protocol != IPPROTO_AH &&
14689 			    ipha->ipha_protocol != IPPROTO_ESP) {
14690 				IPSECHW_DEBUG(IPSECHW_PKT,
14691 				    ("non-M_DATA IPsec accelerated pkt\n"));
14692 				freemsg(first_mp);
14693 				return (B_TRUE);
14694 			}
14695 			*mpp = mp;
14696 			return (B_FALSE);
14697 		}
14698 		putnext(q, mp);
14699 		return (B_TRUE);
14700 	case M_IOCNAK:
14701 		ip1dbg(("got iocnak "));
14702 		iocp = (struct iocblk *)mp->b_rptr;
14703 		switch (iocp->ioc_cmd) {
14704 		case SIOCSTUNPARAM:
14705 		case OSIOCSTUNPARAM:
14706 			/*
14707 			 * Since this is on the ill stream we unconditionally
14708 			 * bump up the refcount
14709 			 */
14710 			ill_refhold(ill);
14711 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14712 			return (B_TRUE);
14713 		case DL_IOC_HDR_INFO:
14714 		case SIOCGTUNPARAM:
14715 		case OSIOCGTUNPARAM:
14716 			ip_rput_other(NULL, q, mp, NULL);
14717 			return (B_TRUE);
14718 		default:
14719 			break;
14720 		}
14721 		/* FALLTHRU */
14722 	default:
14723 		putnext(q, mp);
14724 		return (B_TRUE);
14725 	}
14726 }
14727 
14728 /* Read side put procedure.  Packets coming from the wire arrive here. */
14729 void
14730 ip_rput(queue_t *q, mblk_t *mp)
14731 {
14732 	ill_t	*ill;
14733 	union DL_primitives *dl;
14734 
14735 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14736 
14737 	ill = (ill_t *)q->q_ptr;
14738 
14739 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14740 		/*
14741 		 * If things are opening or closing, only accept high-priority
14742 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14743 		 * created; on close, things hanging off the ill may have been
14744 		 * freed already.)
14745 		 */
14746 		dl = (union DL_primitives *)mp->b_rptr;
14747 		if (DB_TYPE(mp) != M_PCPROTO ||
14748 		    dl->dl_primitive == DL_UNITDATA_IND) {
14749 			/*
14750 			 * SIOC[GS]TUNPARAM ioctls can come here.
14751 			 */
14752 			inet_freemsg(mp);
14753 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14754 			    "ip_rput_end: q %p (%S)", q, "uninit");
14755 			return;
14756 		}
14757 	}
14758 
14759 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14760 	    "ip_rput_end: q %p (%S)", q, "end");
14761 
14762 	ip_input(ill, NULL, mp, NULL);
14763 }
14764 
14765 static mblk_t *
14766 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14767 {
14768 	mblk_t *mp1;
14769 	boolean_t adjusted = B_FALSE;
14770 	ip_stack_t *ipst = ill->ill_ipst;
14771 
14772 	IP_STAT(ipst, ip_db_ref);
14773 	/*
14774 	 * The IP_RECVSLLA option depends on having the
14775 	 * link layer header. First check that:
14776 	 * a> the underlying device is of type ether,
14777 	 * since this option is currently supported only
14778 	 * over ethernet.
14779 	 * b> there is enough room to copy over the link
14780 	 * layer header.
14781 	 *
14782 	 * Once the checks are done, adjust rptr so that
14783 	 * the link layer header will be copied via
14784 	 * copymsg. Note that, IFT_ETHER may be returned
14785 	 * by some non-ethernet drivers but in this case
14786 	 * the second check will fail.
14787 	 */
14788 	if (ill->ill_type == IFT_ETHER &&
14789 	    (mp->b_rptr - mp->b_datap->db_base) >=
14790 	    sizeof (struct ether_header)) {
14791 		mp->b_rptr -= sizeof (struct ether_header);
14792 		adjusted = B_TRUE;
14793 	}
14794 	mp1 = copymsg(mp);
14795 
14796 	if (mp1 == NULL) {
14797 		mp->b_next = NULL;
14798 		/* clear b_prev - used by ip_mroute_decap */
14799 		mp->b_prev = NULL;
14800 		freemsg(mp);
14801 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14802 		return (NULL);
14803 	}
14804 
14805 	if (adjusted) {
14806 		/*
14807 		 * Copy is done. Restore the pointer in
14808 		 * the _new_ mblk
14809 		 */
14810 		mp1->b_rptr += sizeof (struct ether_header);
14811 	}
14812 
14813 	/* Copy b_prev - used by ip_mroute_decap */
14814 	mp1->b_prev = mp->b_prev;
14815 	mp->b_prev = NULL;
14816 
14817 	/* preserve the hardware checksum flags and data, if present */
14818 	if (DB_CKSUMFLAGS(mp) != 0) {
14819 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14820 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14821 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14822 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14823 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14824 	}
14825 
14826 	freemsg(mp);
14827 	return (mp1);
14828 }
14829 
14830 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14831 	if (tail != NULL)					\
14832 		tail->b_next = mp;				\
14833 	else							\
14834 		head = mp;					\
14835 	tail = mp;						\
14836 	cnt++;							\
14837 }
14838 
14839 /*
14840  * Direct read side procedure capable of dealing with chains. GLDv3 based
14841  * drivers call this function directly with mblk chains while STREAMS
14842  * read side procedure ip_rput() calls this for single packet with ip_ring
14843  * set to NULL to process one packet at a time.
14844  *
14845  * The ill will always be valid if this function is called directly from
14846  * the driver.
14847  *
14848  * If ip_input() is called from GLDv3:
14849  *
14850  *   - This must be a non-VLAN IP stream.
14851  *   - 'mp' is either an untagged or a special priority-tagged packet.
14852  *   - Any VLAN tag that was in the MAC header has been stripped.
14853  *
14854  * If the IP header in packet is not 32-bit aligned, every message in the
14855  * chain will be aligned before further operations. This is required on SPARC
14856  * platform.
14857  */
14858 /* ARGSUSED */
14859 void
14860 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14861     struct mac_header_info_s *mhip)
14862 {
14863 	ipaddr_t		dst = NULL;
14864 	ipaddr_t		prev_dst;
14865 	ire_t			*ire = NULL;
14866 	ipha_t			*ipha;
14867 	uint_t			pkt_len;
14868 	ssize_t			len;
14869 	uint_t			opt_len;
14870 	int			ll_multicast;
14871 	int			cgtp_flt_pkt;
14872 	queue_t			*q = ill->ill_rq;
14873 	squeue_t		*curr_sqp = NULL;
14874 	mblk_t 			*head = NULL;
14875 	mblk_t			*tail = NULL;
14876 	mblk_t			*first_mp;
14877 	int			cnt = 0;
14878 	ip_stack_t		*ipst = ill->ill_ipst;
14879 	mblk_t			*mp;
14880 	mblk_t			*dmp;
14881 	uint8_t			tag;
14882 
14883 	ASSERT(mp_chain != NULL);
14884 	ASSERT(ill != NULL);
14885 
14886 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14887 
14888 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14889 
14890 #define	rptr	((uchar_t *)ipha)
14891 
14892 	while (mp_chain != NULL) {
14893 		mp = mp_chain;
14894 		mp_chain = mp_chain->b_next;
14895 		mp->b_next = NULL;
14896 		ll_multicast = 0;
14897 
14898 		/*
14899 		 * We do ire caching from one iteration to
14900 		 * another. In the event the packet chain contains
14901 		 * all packets from the same dst, this caching saves
14902 		 * an ire_cache_lookup for each of the succeeding
14903 		 * packets in a packet chain.
14904 		 */
14905 		prev_dst = dst;
14906 
14907 		/*
14908 		 * if db_ref > 1 then copymsg and free original. Packet
14909 		 * may be changed and we do not want the other entity
14910 		 * who has a reference to this message to trip over the
14911 		 * changes. This is a blind change because trying to
14912 		 * catch all places that might change the packet is too
14913 		 * difficult.
14914 		 *
14915 		 * This corresponds to the fast path case, where we have
14916 		 * a chain of M_DATA mblks.  We check the db_ref count
14917 		 * of only the 1st data block in the mblk chain. There
14918 		 * doesn't seem to be a reason why a device driver would
14919 		 * send up data with varying db_ref counts in the mblk
14920 		 * chain. In any case the Fast path is a private
14921 		 * interface, and our drivers don't do such a thing.
14922 		 * Given the above assumption, there is no need to walk
14923 		 * down the entire mblk chain (which could have a
14924 		 * potential performance problem)
14925 		 *
14926 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14927 		 * to here because of exclusive ip stacks and vnics.
14928 		 * Packets transmitted from exclusive stack over vnic
14929 		 * can have db_ref > 1 and when it gets looped back to
14930 		 * another vnic in a different zone, you have ip_input()
14931 		 * getting dblks with db_ref > 1. So if someone
14932 		 * complains of TCP performance under this scenario,
14933 		 * take a serious look here on the impact of copymsg().
14934 		 */
14935 
14936 		if (DB_REF(mp) > 1) {
14937 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14938 				continue;
14939 		}
14940 
14941 		/*
14942 		 * Check and align the IP header.
14943 		 */
14944 		first_mp = mp;
14945 		if (DB_TYPE(mp) == M_DATA) {
14946 			dmp = mp;
14947 		} else if (DB_TYPE(mp) == M_PROTO &&
14948 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14949 			dmp = mp->b_cont;
14950 		} else {
14951 			dmp = NULL;
14952 		}
14953 		if (dmp != NULL) {
14954 			/*
14955 			 * IP header ptr not aligned?
14956 			 * OR IP header not complete in first mblk
14957 			 */
14958 			if (!OK_32PTR(dmp->b_rptr) ||
14959 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14960 				if (!ip_check_and_align_header(q, dmp, ipst))
14961 					continue;
14962 			}
14963 		}
14964 
14965 		/*
14966 		 * ip_input fast path
14967 		 */
14968 
14969 		/* mblk type is not M_DATA */
14970 		if (DB_TYPE(mp) != M_DATA) {
14971 			if (ip_rput_process_notdata(q, &first_mp, ill,
14972 			    &ll_multicast, &mp))
14973 				continue;
14974 
14975 			/*
14976 			 * The only way we can get here is if we had a
14977 			 * packet that was either a DL_UNITDATA_IND or
14978 			 * an M_CTL for an IPsec accelerated packet.
14979 			 *
14980 			 * In either case, the first_mp will point to
14981 			 * the leading M_PROTO or M_CTL.
14982 			 */
14983 			ASSERT(first_mp != NULL);
14984 		} else if (mhip != NULL) {
14985 			/*
14986 			 * ll_multicast is set here so that it is ready
14987 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14988 			 * manipulates ll_multicast in the same fashion when
14989 			 * called from ip_rput_process_notdata.
14990 			 */
14991 			switch (mhip->mhi_dsttype) {
14992 			case MAC_ADDRTYPE_MULTICAST :
14993 				ll_multicast = HPE_MULTICAST;
14994 				break;
14995 			case MAC_ADDRTYPE_BROADCAST :
14996 				ll_multicast = HPE_BROADCAST;
14997 				break;
14998 			default :
14999 				break;
15000 			}
15001 		}
15002 
15003 		/* Only M_DATA can come here and it is always aligned */
15004 		ASSERT(DB_TYPE(mp) == M_DATA);
15005 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15006 
15007 		ipha = (ipha_t *)mp->b_rptr;
15008 		len = mp->b_wptr - rptr;
15009 		pkt_len = ntohs(ipha->ipha_length);
15010 
15011 		/*
15012 		 * We must count all incoming packets, even if they end
15013 		 * up being dropped later on.
15014 		 */
15015 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15016 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15017 
15018 		/* multiple mblk or too short */
15019 		len -= pkt_len;
15020 		if (len != 0) {
15021 			/*
15022 			 * Make sure we have data length consistent
15023 			 * with the IP header.
15024 			 */
15025 			if (mp->b_cont == NULL) {
15026 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15027 					BUMP_MIB(ill->ill_ip_mib,
15028 					    ipIfStatsInHdrErrors);
15029 					ip2dbg(("ip_input: drop pkt\n"));
15030 					freemsg(mp);
15031 					continue;
15032 				}
15033 				mp->b_wptr = rptr + pkt_len;
15034 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15035 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15036 					BUMP_MIB(ill->ill_ip_mib,
15037 					    ipIfStatsInHdrErrors);
15038 					ip2dbg(("ip_input: drop pkt\n"));
15039 					freemsg(mp);
15040 					continue;
15041 				}
15042 				(void) adjmsg(mp, -len);
15043 				IP_STAT(ipst, ip_multimblk3);
15044 			}
15045 		}
15046 
15047 		/* Obtain the dst of the current packet */
15048 		dst = ipha->ipha_dst;
15049 
15050 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15051 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15052 		    ipha, ip6_t *, NULL, int, 0);
15053 
15054 		/*
15055 		 * The following test for loopback is faster than
15056 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15057 		 * operations.
15058 		 * Note that these addresses are always in network byte order
15059 		 */
15060 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15061 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15062 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15063 			freemsg(mp);
15064 			continue;
15065 		}
15066 
15067 		/*
15068 		 * The event for packets being received from a 'physical'
15069 		 * interface is placed after validation of the source and/or
15070 		 * destination address as being local so that packets can be
15071 		 * redirected to loopback addresses using ipnat.
15072 		 */
15073 		DTRACE_PROBE4(ip4__physical__in__start,
15074 		    ill_t *, ill, ill_t *, NULL,
15075 		    ipha_t *, ipha, mblk_t *, first_mp);
15076 
15077 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15078 		    ipst->ips_ipv4firewall_physical_in,
15079 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15080 
15081 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15082 
15083 		if (first_mp == NULL) {
15084 			continue;
15085 		}
15086 		dst = ipha->ipha_dst;
15087 		/*
15088 		 * Attach any necessary label information to
15089 		 * this packet
15090 		 */
15091 		if (is_system_labeled() &&
15092 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15093 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15094 			freemsg(mp);
15095 			continue;
15096 		}
15097 
15098 		if (ipst->ips_ipobs_enabled) {
15099 			zoneid_t dzone;
15100 
15101 			/*
15102 			 * On the inbound path the src zone will be unknown as
15103 			 * this packet has come from the wire.
15104 			 */
15105 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15106 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15107 			    ill, IPV4_VERSION, 0, ipst);
15108 		}
15109 
15110 		/*
15111 		 * Reuse the cached ire only if the ipha_dst of the previous
15112 		 * packet is the same as the current packet AND it is not
15113 		 * INADDR_ANY.
15114 		 */
15115 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15116 		    (ire != NULL)) {
15117 			ire_refrele(ire);
15118 			ire = NULL;
15119 		}
15120 
15121 		opt_len = ipha->ipha_version_and_hdr_length -
15122 		    IP_SIMPLE_HDR_VERSION;
15123 
15124 		/*
15125 		 * Check to see if we can take the fastpath.
15126 		 * That is possible if the following conditions are met
15127 		 *	o Tsol disabled
15128 		 *	o CGTP disabled
15129 		 *	o ipp_action_count is 0
15130 		 *	o no options in the packet
15131 		 *	o not a RSVP packet
15132 		 * 	o not a multicast packet
15133 		 *	o ill not in IP_DHCPINIT_IF mode
15134 		 */
15135 		if (!is_system_labeled() &&
15136 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15137 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15138 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15139 			if (ire == NULL)
15140 				ire = ire_cache_lookup_simple(dst, ipst);
15141 			/*
15142 			 * Unless forwarding is enabled, dont call
15143 			 * ip_fast_forward(). Incoming packet is for forwarding
15144 			 */
15145 			if ((ill->ill_flags & ILLF_ROUTER) &&
15146 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15147 				ire = ip_fast_forward(ire, dst, ill, mp);
15148 				continue;
15149 			}
15150 			/* incoming packet is for local consumption */
15151 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15152 				goto local;
15153 		}
15154 
15155 		/*
15156 		 * Disable ire caching for anything more complex
15157 		 * than the simple fast path case we checked for above.
15158 		 */
15159 		if (ire != NULL) {
15160 			ire_refrele(ire);
15161 			ire = NULL;
15162 		}
15163 
15164 		/*
15165 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15166 		 * server to unicast DHCP packets to a DHCP client using the
15167 		 * IP address it is offering to the client.  This can be
15168 		 * disabled through the "broadcast bit", but not all DHCP
15169 		 * servers honor that bit.  Therefore, to interoperate with as
15170 		 * many DHCP servers as possible, the DHCP client allows the
15171 		 * server to unicast, but we treat those packets as broadcast
15172 		 * here.  Note that we don't rewrite the packet itself since
15173 		 * (a) that would mess up the checksums and (b) the DHCP
15174 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15175 		 * hand it the packet regardless.
15176 		 */
15177 		if (ill->ill_dhcpinit != 0 &&
15178 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15179 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15180 			udpha_t *udpha;
15181 
15182 			/*
15183 			 * Reload ipha since pullupmsg() can change b_rptr.
15184 			 */
15185 			ipha = (ipha_t *)mp->b_rptr;
15186 			udpha = (udpha_t *)&ipha[1];
15187 
15188 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15189 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15190 				    mblk_t *, mp);
15191 				dst = INADDR_BROADCAST;
15192 			}
15193 		}
15194 
15195 		/* Full-blown slow path */
15196 		if (opt_len != 0) {
15197 			if (len != 0)
15198 				IP_STAT(ipst, ip_multimblk4);
15199 			else
15200 				IP_STAT(ipst, ip_ipoptions);
15201 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15202 			    &dst, ipst))
15203 				continue;
15204 		}
15205 
15206 		/*
15207 		 * Invoke the CGTP (multirouting) filtering module to process
15208 		 * the incoming packet. Packets identified as duplicates
15209 		 * must be discarded. Filtering is active only if the
15210 		 * the ip_cgtp_filter ndd variable is non-zero.
15211 		 */
15212 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15213 		if (ipst->ips_ip_cgtp_filter &&
15214 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15215 			netstackid_t stackid;
15216 
15217 			stackid = ipst->ips_netstack->netstack_stackid;
15218 			cgtp_flt_pkt =
15219 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15220 			    ill->ill_phyint->phyint_ifindex, mp);
15221 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15222 				freemsg(first_mp);
15223 				continue;
15224 			}
15225 		}
15226 
15227 		/*
15228 		 * If rsvpd is running, let RSVP daemon handle its processing
15229 		 * and forwarding of RSVP multicast/unicast packets.
15230 		 * If rsvpd is not running but mrouted is running, RSVP
15231 		 * multicast packets are forwarded as multicast traffic
15232 		 * and RSVP unicast packets are forwarded by unicast router.
15233 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15234 		 * packets are not forwarded, but the unicast packets are
15235 		 * forwarded like unicast traffic.
15236 		 */
15237 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15238 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15239 		    NULL) {
15240 			/* RSVP packet and rsvpd running. Treat as ours */
15241 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15242 			/*
15243 			 * This assumes that we deliver to all streams for
15244 			 * multicast and broadcast packets.
15245 			 * We have to force ll_multicast to 1 to handle the
15246 			 * M_DATA messages passed in from ip_mroute_decap.
15247 			 */
15248 			dst = INADDR_BROADCAST;
15249 			ll_multicast = 1;
15250 		} else if (CLASSD(dst)) {
15251 			/* packet is multicast */
15252 			mp->b_next = NULL;
15253 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15254 			    &ll_multicast, &dst))
15255 				continue;
15256 		}
15257 
15258 		if (ire == NULL) {
15259 			ire = ire_cache_lookup(dst, ALL_ZONES,
15260 			    msg_getlabel(mp), ipst);
15261 		}
15262 
15263 		if (ire != NULL && ire->ire_stq != NULL &&
15264 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15265 		    ire->ire_zoneid != ALL_ZONES) {
15266 			/*
15267 			 * Should only use IREs that are visible from the
15268 			 * global zone for forwarding.
15269 			 */
15270 			ire_refrele(ire);
15271 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15272 			    msg_getlabel(mp), ipst);
15273 		}
15274 
15275 		if (ire == NULL) {
15276 			/*
15277 			 * No IRE for this destination, so it can't be for us.
15278 			 * Unless we are forwarding, drop the packet.
15279 			 * We have to let source routed packets through
15280 			 * since we don't yet know if they are 'ping -l'
15281 			 * packets i.e. if they will go out over the
15282 			 * same interface as they came in on.
15283 			 */
15284 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15285 			if (ire == NULL)
15286 				continue;
15287 		}
15288 
15289 		/*
15290 		 * Broadcast IRE may indicate either broadcast or
15291 		 * multicast packet
15292 		 */
15293 		if (ire->ire_type == IRE_BROADCAST) {
15294 			/*
15295 			 * Skip broadcast checks if packet is UDP multicast;
15296 			 * we'd rather not enter ip_rput_process_broadcast()
15297 			 * unless the packet is broadcast for real, since
15298 			 * that routine is a no-op for multicast.
15299 			 */
15300 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15301 			    !CLASSD(ipha->ipha_dst)) {
15302 				ire = ip_rput_process_broadcast(&q, mp,
15303 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15304 				    ll_multicast);
15305 				if (ire == NULL)
15306 					continue;
15307 			}
15308 		} else if (ire->ire_stq != NULL) {
15309 			/* fowarding? */
15310 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15311 			    ll_multicast, B_FALSE);
15312 			/* ip_rput_process_forward consumed the packet */
15313 			continue;
15314 		}
15315 
15316 local:
15317 		/*
15318 		 * If the queue in the ire is different to the ingress queue
15319 		 * then we need to check to see if we can accept the packet.
15320 		 * Note that for multicast packets and broadcast packets sent
15321 		 * to a broadcast address which is shared between multiple
15322 		 * interfaces we should not do this since we just got a random
15323 		 * broadcast ire.
15324 		 */
15325 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15326 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15327 			if (ire == NULL) {
15328 				/* Drop packet */
15329 				BUMP_MIB(ill->ill_ip_mib,
15330 				    ipIfStatsForwProhibits);
15331 				freemsg(mp);
15332 				continue;
15333 			}
15334 			if (ire->ire_rfq != NULL)
15335 				q = ire->ire_rfq;
15336 		}
15337 
15338 		switch (ipha->ipha_protocol) {
15339 		case IPPROTO_TCP:
15340 			ASSERT(first_mp == mp);
15341 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15342 			    mp, 0, q, ip_ring)) != NULL) {
15343 				if (curr_sqp == NULL) {
15344 					curr_sqp = GET_SQUEUE(mp);
15345 					ASSERT(cnt == 0);
15346 					cnt++;
15347 					head = tail = mp;
15348 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15349 					ASSERT(tail != NULL);
15350 					cnt++;
15351 					tail->b_next = mp;
15352 					tail = mp;
15353 				} else {
15354 					/*
15355 					 * A different squeue. Send the
15356 					 * chain for the previous squeue on
15357 					 * its way. This shouldn't happen
15358 					 * often unless interrupt binding
15359 					 * changes.
15360 					 */
15361 					IP_STAT(ipst, ip_input_multi_squeue);
15362 					SQUEUE_ENTER(curr_sqp, head,
15363 					    tail, cnt, SQ_PROCESS, tag);
15364 					curr_sqp = GET_SQUEUE(mp);
15365 					head = mp;
15366 					tail = mp;
15367 					cnt = 1;
15368 				}
15369 			}
15370 			continue;
15371 		case IPPROTO_UDP:
15372 			ASSERT(first_mp == mp);
15373 			ip_udp_input(q, mp, ipha, ire, ill);
15374 			continue;
15375 		case IPPROTO_SCTP:
15376 			ASSERT(first_mp == mp);
15377 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15378 			    q, dst);
15379 			/* ire has been released by ip_sctp_input */
15380 			ire = NULL;
15381 			continue;
15382 		default:
15383 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15384 			continue;
15385 		}
15386 	}
15387 
15388 	if (ire != NULL)
15389 		ire_refrele(ire);
15390 
15391 	if (head != NULL)
15392 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15393 
15394 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15395 	    "ip_input_end: q %p (%S)", q, "end");
15396 #undef  rptr
15397 }
15398 
15399 /*
15400  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15401  * a chain of packets in the poll mode. The packets have gone through the
15402  * data link processing but not IP processing. For performance and latency
15403  * reasons, the squeue wants to process the chain in line instead of feeding
15404  * it back via ip_input path.
15405  *
15406  * So this is a light weight function which checks to see if the packets
15407  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15408  * but we still do the paranoid check) meant for local machine and we don't
15409  * have labels etc enabled. Packets that meet the criterion are returned to
15410  * the squeue and processed inline while the rest go via ip_input path.
15411  */
15412 /*ARGSUSED*/
15413 mblk_t *
15414 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15415     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15416 {
15417 	mblk_t 		*mp;
15418 	ipaddr_t	dst = NULL;
15419 	ipaddr_t	prev_dst;
15420 	ire_t		*ire = NULL;
15421 	ipha_t		*ipha;
15422 	uint_t		pkt_len;
15423 	ssize_t		len;
15424 	uint_t		opt_len;
15425 	queue_t		*q = ill->ill_rq;
15426 	squeue_t	*curr_sqp;
15427 	mblk_t 		*ahead = NULL;	/* Accepted head */
15428 	mblk_t		*atail = NULL;	/* Accepted tail */
15429 	uint_t		acnt = 0;	/* Accepted count */
15430 	mblk_t		*utail = NULL;	/* Unaccepted head */
15431 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15432 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15433 	ip_stack_t	*ipst = ill->ill_ipst;
15434 
15435 	*cnt = 0;
15436 
15437 	ASSERT(ill != NULL);
15438 	ASSERT(ip_ring != NULL);
15439 
15440 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15441 
15442 #define	rptr	((uchar_t *)ipha)
15443 
15444 	while (mp_chain != NULL) {
15445 		mp = mp_chain;
15446 		mp_chain = mp_chain->b_next;
15447 		mp->b_next = NULL;
15448 
15449 		/*
15450 		 * We do ire caching from one iteration to
15451 		 * another. In the event the packet chain contains
15452 		 * all packets from the same dst, this caching saves
15453 		 * an ire_cache_lookup for each of the succeeding
15454 		 * packets in a packet chain.
15455 		 */
15456 		prev_dst = dst;
15457 
15458 		ipha = (ipha_t *)mp->b_rptr;
15459 		len = mp->b_wptr - rptr;
15460 
15461 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15462 
15463 		/*
15464 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15465 		 * or doesn't have min len, reject.
15466 		 */
15467 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15468 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15469 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15470 			continue;
15471 		}
15472 
15473 		pkt_len = ntohs(ipha->ipha_length);
15474 		if (len != pkt_len) {
15475 			if (len > pkt_len) {
15476 				mp->b_wptr = rptr + pkt_len;
15477 			} else {
15478 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15479 				continue;
15480 			}
15481 		}
15482 
15483 		opt_len = ipha->ipha_version_and_hdr_length -
15484 		    IP_SIMPLE_HDR_VERSION;
15485 		dst = ipha->ipha_dst;
15486 
15487 		/* IP version bad or there are IP options */
15488 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15489 		    mp, &ipha, &dst, ipst)))
15490 			continue;
15491 
15492 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15493 		    (ipst->ips_ip_cgtp_filter &&
15494 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15495 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15496 			continue;
15497 		}
15498 
15499 		/*
15500 		 * Reuse the cached ire only if the ipha_dst of the previous
15501 		 * packet is the same as the current packet AND it is not
15502 		 * INADDR_ANY.
15503 		 */
15504 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15505 		    (ire != NULL)) {
15506 			ire_refrele(ire);
15507 			ire = NULL;
15508 		}
15509 
15510 		if (ire == NULL)
15511 			ire = ire_cache_lookup_simple(dst, ipst);
15512 
15513 		/*
15514 		 * Unless forwarding is enabled, dont call
15515 		 * ip_fast_forward(). Incoming packet is for forwarding
15516 		 */
15517 		if ((ill->ill_flags & ILLF_ROUTER) &&
15518 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15519 
15520 			DTRACE_PROBE4(ip4__physical__in__start,
15521 			    ill_t *, ill, ill_t *, NULL,
15522 			    ipha_t *, ipha, mblk_t *, mp);
15523 
15524 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15525 			    ipst->ips_ipv4firewall_physical_in,
15526 			    ill, NULL, ipha, mp, mp, 0, ipst);
15527 
15528 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15529 
15530 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15531 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15532 			    pkt_len);
15533 
15534 			ire = ip_fast_forward(ire, dst, ill, mp);
15535 			continue;
15536 		}
15537 
15538 		/* incoming packet is for local consumption */
15539 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15540 			goto local_accept;
15541 
15542 		/*
15543 		 * Disable ire caching for anything more complex
15544 		 * than the simple fast path case we checked for above.
15545 		 */
15546 		if (ire != NULL) {
15547 			ire_refrele(ire);
15548 			ire = NULL;
15549 		}
15550 
15551 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15552 		    ipst);
15553 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15554 		    ire->ire_stq != NULL) {
15555 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15556 			if (ire != NULL) {
15557 				ire_refrele(ire);
15558 				ire = NULL;
15559 			}
15560 			continue;
15561 		}
15562 
15563 local_accept:
15564 
15565 		if (ire->ire_rfq != q) {
15566 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15567 			if (ire != NULL) {
15568 				ire_refrele(ire);
15569 				ire = NULL;
15570 			}
15571 			continue;
15572 		}
15573 
15574 		/*
15575 		 * The event for packets being received from a 'physical'
15576 		 * interface is placed after validation of the source and/or
15577 		 * destination address as being local so that packets can be
15578 		 * redirected to loopback addresses using ipnat.
15579 		 */
15580 		DTRACE_PROBE4(ip4__physical__in__start,
15581 		    ill_t *, ill, ill_t *, NULL,
15582 		    ipha_t *, ipha, mblk_t *, mp);
15583 
15584 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15585 		    ipst->ips_ipv4firewall_physical_in,
15586 		    ill, NULL, ipha, mp, mp, 0, ipst);
15587 
15588 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15589 
15590 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15591 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15592 
15593 		if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15594 		    0, q, ip_ring)) != NULL) {
15595 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15596 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15597 			} else {
15598 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15599 				    SQ_FILL, SQTAG_IP_INPUT);
15600 			}
15601 		}
15602 	}
15603 
15604 	if (ire != NULL)
15605 		ire_refrele(ire);
15606 
15607 	if (uhead != NULL)
15608 		ip_input(ill, ip_ring, uhead, NULL);
15609 
15610 	if (ahead != NULL) {
15611 		*last = atail;
15612 		*cnt = acnt;
15613 		return (ahead);
15614 	}
15615 
15616 	return (NULL);
15617 #undef  rptr
15618 }
15619 
15620 static void
15621 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15622     t_uscalar_t err)
15623 {
15624 	if (dl_err == DL_SYSERR) {
15625 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15626 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15627 		    ill->ill_name, dl_primstr(prim), err);
15628 		return;
15629 	}
15630 
15631 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15632 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15633 	    dl_errstr(dl_err));
15634 }
15635 
15636 /*
15637  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15638  * than DL_UNITDATA_IND messages. If we need to process this message
15639  * exclusively, we call qwriter_ip, in which case we also need to call
15640  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15641  */
15642 void
15643 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15644 {
15645 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15646 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15647 	ill_t		*ill = q->q_ptr;
15648 	t_uscalar_t	prim = dloa->dl_primitive;
15649 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15650 
15651 	ip1dbg(("ip_rput_dlpi"));
15652 
15653 	/*
15654 	 * If we received an ACK but didn't send a request for it, then it
15655 	 * can't be part of any pending operation; discard up-front.
15656 	 */
15657 	switch (prim) {
15658 	case DL_ERROR_ACK:
15659 		reqprim = dlea->dl_error_primitive;
15660 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15661 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15662 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15663 		    dlea->dl_unix_errno));
15664 		break;
15665 	case DL_OK_ACK:
15666 		reqprim = dloa->dl_correct_primitive;
15667 		break;
15668 	case DL_INFO_ACK:
15669 		reqprim = DL_INFO_REQ;
15670 		break;
15671 	case DL_BIND_ACK:
15672 		reqprim = DL_BIND_REQ;
15673 		break;
15674 	case DL_PHYS_ADDR_ACK:
15675 		reqprim = DL_PHYS_ADDR_REQ;
15676 		break;
15677 	case DL_NOTIFY_ACK:
15678 		reqprim = DL_NOTIFY_REQ;
15679 		break;
15680 	case DL_CONTROL_ACK:
15681 		reqprim = DL_CONTROL_REQ;
15682 		break;
15683 	case DL_CAPABILITY_ACK:
15684 		reqprim = DL_CAPABILITY_REQ;
15685 		break;
15686 	}
15687 
15688 	if (prim != DL_NOTIFY_IND) {
15689 		if (reqprim == DL_PRIM_INVAL ||
15690 		    !ill_dlpi_pending(ill, reqprim)) {
15691 			/* Not a DLPI message we support or expected */
15692 			freemsg(mp);
15693 			return;
15694 		}
15695 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15696 		    dl_primstr(reqprim)));
15697 	}
15698 
15699 	switch (reqprim) {
15700 	case DL_UNBIND_REQ:
15701 		/*
15702 		 * NOTE: we mark the unbind as complete even if we got a
15703 		 * DL_ERROR_ACK, since there's not much else we can do.
15704 		 */
15705 		mutex_enter(&ill->ill_lock);
15706 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15707 		cv_signal(&ill->ill_cv);
15708 		mutex_exit(&ill->ill_lock);
15709 		break;
15710 
15711 	case DL_ENABMULTI_REQ:
15712 		if (prim == DL_OK_ACK) {
15713 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15714 				ill->ill_dlpi_multicast_state = IDS_OK;
15715 		}
15716 		break;
15717 	}
15718 
15719 	/*
15720 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15721 	 * need to become writer to continue to process it.  Because an
15722 	 * exclusive operation doesn't complete until replies to all queued
15723 	 * DLPI messages have been received, we know we're in the middle of an
15724 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15725 	 *
15726 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15727 	 * Since this is on the ill stream we unconditionally bump up the
15728 	 * refcount without doing ILL_CAN_LOOKUP().
15729 	 */
15730 	ill_refhold(ill);
15731 	if (prim == DL_NOTIFY_IND)
15732 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15733 	else
15734 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15735 }
15736 
15737 /*
15738  * Handling of DLPI messages that require exclusive access to the ipsq.
15739  *
15740  * Need to do ill_pending_mp_release on ioctl completion, which could
15741  * happen here. (along with mi_copy_done)
15742  */
15743 /* ARGSUSED */
15744 static void
15745 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15746 {
15747 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15748 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15749 	int		err = 0;
15750 	ill_t		*ill;
15751 	ipif_t		*ipif = NULL;
15752 	mblk_t		*mp1 = NULL;
15753 	conn_t		*connp = NULL;
15754 	t_uscalar_t	paddrreq;
15755 	mblk_t		*mp_hw;
15756 	boolean_t	success;
15757 	boolean_t	ioctl_aborted = B_FALSE;
15758 	boolean_t	log = B_TRUE;
15759 	ip_stack_t		*ipst;
15760 
15761 	ip1dbg(("ip_rput_dlpi_writer .."));
15762 	ill = (ill_t *)q->q_ptr;
15763 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15764 	ASSERT(IAM_WRITER_ILL(ill));
15765 
15766 	ipst = ill->ill_ipst;
15767 
15768 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15769 	/*
15770 	 * The current ioctl could have been aborted by the user and a new
15771 	 * ioctl to bring up another ill could have started. We could still
15772 	 * get a response from the driver later.
15773 	 */
15774 	if (ipif != NULL && ipif->ipif_ill != ill)
15775 		ioctl_aborted = B_TRUE;
15776 
15777 	switch (dloa->dl_primitive) {
15778 	case DL_ERROR_ACK:
15779 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15780 		    dl_primstr(dlea->dl_error_primitive)));
15781 
15782 		switch (dlea->dl_error_primitive) {
15783 		case DL_DISABMULTI_REQ:
15784 			if (!ill->ill_isv6)
15785 				ipsq_current_finish(ipsq);
15786 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15787 			break;
15788 		case DL_PROMISCON_REQ:
15789 		case DL_PROMISCOFF_REQ:
15790 		case DL_UNBIND_REQ:
15791 		case DL_ATTACH_REQ:
15792 		case DL_INFO_REQ:
15793 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15794 			break;
15795 		case DL_NOTIFY_REQ:
15796 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15797 			log = B_FALSE;
15798 			break;
15799 		case DL_PHYS_ADDR_REQ:
15800 			/*
15801 			 * For IPv6 only, there are two additional
15802 			 * phys_addr_req's sent to the driver to get the
15803 			 * IPv6 token and lla. This allows IP to acquire
15804 			 * the hardware address format for a given interface
15805 			 * without having built in knowledge of the hardware
15806 			 * address. ill_phys_addr_pend keeps track of the last
15807 			 * DL_PAR sent so we know which response we are
15808 			 * dealing with. ill_dlpi_done will update
15809 			 * ill_phys_addr_pend when it sends the next req.
15810 			 * We don't complete the IOCTL until all three DL_PARs
15811 			 * have been attempted, so set *_len to 0 and break.
15812 			 */
15813 			paddrreq = ill->ill_phys_addr_pend;
15814 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15815 			if (paddrreq == DL_IPV6_TOKEN) {
15816 				ill->ill_token_length = 0;
15817 				log = B_FALSE;
15818 				break;
15819 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15820 				ill->ill_nd_lla_len = 0;
15821 				log = B_FALSE;
15822 				break;
15823 			}
15824 			/*
15825 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15826 			 * We presumably have an IOCTL hanging out waiting
15827 			 * for completion. Find it and complete the IOCTL
15828 			 * with the error noted.
15829 			 * However, ill_dl_phys was called on an ill queue
15830 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15831 			 * set. But the ioctl is known to be pending on ill_wq.
15832 			 */
15833 			if (!ill->ill_ifname_pending)
15834 				break;
15835 			ill->ill_ifname_pending = 0;
15836 			if (!ioctl_aborted)
15837 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15838 			if (mp1 != NULL) {
15839 				/*
15840 				 * This operation (SIOCSLIFNAME) must have
15841 				 * happened on the ill. Assert there is no conn
15842 				 */
15843 				ASSERT(connp == NULL);
15844 				q = ill->ill_wq;
15845 			}
15846 			break;
15847 		case DL_BIND_REQ:
15848 			ill_dlpi_done(ill, DL_BIND_REQ);
15849 			if (ill->ill_ifname_pending)
15850 				break;
15851 			/*
15852 			 * Something went wrong with the bind.  We presumably
15853 			 * have an IOCTL hanging out waiting for completion.
15854 			 * Find it, take down the interface that was coming
15855 			 * up, and complete the IOCTL with the error noted.
15856 			 */
15857 			if (!ioctl_aborted)
15858 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15859 			if (mp1 != NULL) {
15860 				/*
15861 				 * This operation (SIOCSLIFFLAGS) must have
15862 				 * happened from a conn.
15863 				 */
15864 				ASSERT(connp != NULL);
15865 				q = CONNP_TO_WQ(connp);
15866 				(void) ipif_down(ipif, NULL, NULL);
15867 				/* error is set below the switch */
15868 			}
15869 			break;
15870 		case DL_ENABMULTI_REQ:
15871 			if (!ill->ill_isv6)
15872 				ipsq_current_finish(ipsq);
15873 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15874 
15875 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15876 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15877 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15878 				ipif_t *ipif;
15879 
15880 				printf("ip: joining multicasts failed (%d)"
15881 				    " on %s - will use link layer "
15882 				    "broadcasts for multicast\n",
15883 				    dlea->dl_errno, ill->ill_name);
15884 
15885 				/*
15886 				 * Set up the multicast mapping alone.
15887 				 * writer, so ok to access ill->ill_ipif
15888 				 * without any lock.
15889 				 */
15890 				ipif = ill->ill_ipif;
15891 				mutex_enter(&ill->ill_phyint->phyint_lock);
15892 				ill->ill_phyint->phyint_flags |=
15893 				    PHYI_MULTI_BCAST;
15894 				mutex_exit(&ill->ill_phyint->phyint_lock);
15895 
15896 				if (!ill->ill_isv6) {
15897 					(void) ipif_arp_setup_multicast(ipif,
15898 					    NULL);
15899 				} else {
15900 					(void) ipif_ndp_setup_multicast(ipif,
15901 					    NULL);
15902 				}
15903 			}
15904 			freemsg(mp);	/* Don't want to pass this up */
15905 			return;
15906 		case DL_CONTROL_REQ:
15907 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15908 			    "DL_CONTROL_REQ\n"));
15909 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15910 			freemsg(mp);
15911 			return;
15912 		case DL_CAPABILITY_REQ:
15913 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15914 			    "DL_CAPABILITY REQ\n"));
15915 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15916 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15917 			ill_capability_done(ill);
15918 			freemsg(mp);
15919 			return;
15920 		}
15921 		/*
15922 		 * Note the error for IOCTL completion (mp1 is set when
15923 		 * ready to complete ioctl). If ill_ifname_pending_err is
15924 		 * set, an error occured during plumbing (ill_ifname_pending),
15925 		 * so we want to report that error.
15926 		 *
15927 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15928 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15929 		 * expected to get errack'd if the driver doesn't support
15930 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15931 		 * if these error conditions are encountered.
15932 		 */
15933 		if (mp1 != NULL) {
15934 			if (ill->ill_ifname_pending_err != 0)  {
15935 				err = ill->ill_ifname_pending_err;
15936 				ill->ill_ifname_pending_err = 0;
15937 			} else {
15938 				err = dlea->dl_unix_errno ?
15939 				    dlea->dl_unix_errno : ENXIO;
15940 			}
15941 		/*
15942 		 * If we're plumbing an interface and an error hasn't already
15943 		 * been saved, set ill_ifname_pending_err to the error passed
15944 		 * up. Ignore the error if log is B_FALSE (see comment above).
15945 		 */
15946 		} else if (log && ill->ill_ifname_pending &&
15947 		    ill->ill_ifname_pending_err == 0) {
15948 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15949 			    dlea->dl_unix_errno : ENXIO;
15950 		}
15951 
15952 		if (log)
15953 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15954 			    dlea->dl_errno, dlea->dl_unix_errno);
15955 		break;
15956 	case DL_CAPABILITY_ACK:
15957 		ill_capability_ack(ill, mp);
15958 		/*
15959 		 * The message has been handed off to ill_capability_ack
15960 		 * and must not be freed below
15961 		 */
15962 		mp = NULL;
15963 		break;
15964 
15965 	case DL_CONTROL_ACK:
15966 		/* We treat all of these as "fire and forget" */
15967 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15968 		break;
15969 	case DL_INFO_ACK:
15970 		/* Call a routine to handle this one. */
15971 		ill_dlpi_done(ill, DL_INFO_REQ);
15972 		ip_ll_subnet_defaults(ill, mp);
15973 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15974 		return;
15975 	case DL_BIND_ACK:
15976 		/*
15977 		 * We should have an IOCTL waiting on this unless
15978 		 * sent by ill_dl_phys, in which case just return
15979 		 */
15980 		ill_dlpi_done(ill, DL_BIND_REQ);
15981 		if (ill->ill_ifname_pending)
15982 			break;
15983 
15984 		if (!ioctl_aborted)
15985 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15986 		if (mp1 == NULL)
15987 			break;
15988 		/*
15989 		 * Because mp1 was added by ill_dl_up(), and it always
15990 		 * passes a valid connp, connp must be valid here.
15991 		 */
15992 		ASSERT(connp != NULL);
15993 		q = CONNP_TO_WQ(connp);
15994 
15995 		/*
15996 		 * We are exclusive. So nothing can change even after
15997 		 * we get the pending mp. If need be we can put it back
15998 		 * and restart, as in calling ipif_arp_up()  below.
15999 		 */
16000 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16001 
16002 		mutex_enter(&ill->ill_lock);
16003 		ill->ill_dl_up = 1;
16004 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16005 		mutex_exit(&ill->ill_lock);
16006 
16007 		/*
16008 		 * Now bring up the resolver; when that is complete, we'll
16009 		 * create IREs.  Note that we intentionally mirror what
16010 		 * ipif_up() would have done, because we got here by way of
16011 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16012 		 */
16013 		if (ill->ill_isv6) {
16014 			if (ill->ill_flags & ILLF_XRESOLV) {
16015 				mutex_enter(&connp->conn_lock);
16016 				mutex_enter(&ill->ill_lock);
16017 				success = ipsq_pending_mp_add(connp, ipif, q,
16018 				    mp1, 0);
16019 				mutex_exit(&ill->ill_lock);
16020 				mutex_exit(&connp->conn_lock);
16021 				if (success) {
16022 					err = ipif_resolver_up(ipif,
16023 					    Res_act_initial);
16024 					if (err == EINPROGRESS) {
16025 						freemsg(mp);
16026 						return;
16027 					}
16028 					ASSERT(err != 0);
16029 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16030 					ASSERT(mp1 != NULL);
16031 				} else {
16032 					/* conn has started closing */
16033 					err = EINTR;
16034 				}
16035 			} else { /* Non XRESOLV interface */
16036 				(void) ipif_resolver_up(ipif, Res_act_initial);
16037 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16038 					err = ipif_up_done_v6(ipif);
16039 			}
16040 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16041 			/*
16042 			 * ARP and other v4 external resolvers.
16043 			 * Leave the pending mblk intact so that
16044 			 * the ioctl completes in ip_rput().
16045 			 */
16046 			mutex_enter(&connp->conn_lock);
16047 			mutex_enter(&ill->ill_lock);
16048 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16049 			mutex_exit(&ill->ill_lock);
16050 			mutex_exit(&connp->conn_lock);
16051 			if (success) {
16052 				err = ipif_resolver_up(ipif, Res_act_initial);
16053 				if (err == EINPROGRESS) {
16054 					freemsg(mp);
16055 					return;
16056 				}
16057 				ASSERT(err != 0);
16058 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16059 			} else {
16060 				/* The conn has started closing */
16061 				err = EINTR;
16062 			}
16063 		} else {
16064 			/*
16065 			 * This one is complete. Reply to pending ioctl.
16066 			 */
16067 			(void) ipif_resolver_up(ipif, Res_act_initial);
16068 			err = ipif_up_done(ipif);
16069 		}
16070 
16071 		if ((err == 0) && (ill->ill_up_ipifs)) {
16072 			err = ill_up_ipifs(ill, q, mp1);
16073 			if (err == EINPROGRESS) {
16074 				freemsg(mp);
16075 				return;
16076 			}
16077 		}
16078 
16079 		/*
16080 		 * If we have a moved ipif to bring up, and everything has
16081 		 * succeeded to this point, bring it up on the IPMP ill.
16082 		 * Otherwise, leave it down -- the admin can try to bring it
16083 		 * up by hand if need be.
16084 		 */
16085 		if (ill->ill_move_ipif != NULL) {
16086 			if (err != 0) {
16087 				ill->ill_move_ipif = NULL;
16088 			} else {
16089 				ipif = ill->ill_move_ipif;
16090 				ill->ill_move_ipif = NULL;
16091 				err = ipif_up(ipif, q, mp1);
16092 				if (err == EINPROGRESS) {
16093 					freemsg(mp);
16094 					return;
16095 				}
16096 			}
16097 		}
16098 		break;
16099 
16100 	case DL_NOTIFY_IND: {
16101 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16102 		ire_t *ire;
16103 		uint_t orig_mtu;
16104 		boolean_t need_ire_walk_v4 = B_FALSE;
16105 		boolean_t need_ire_walk_v6 = B_FALSE;
16106 
16107 		switch (notify->dl_notification) {
16108 		case DL_NOTE_PHYS_ADDR:
16109 			err = ill_set_phys_addr(ill, mp);
16110 			break;
16111 
16112 		case DL_NOTE_FASTPATH_FLUSH:
16113 			ill_fastpath_flush(ill);
16114 			break;
16115 
16116 		case DL_NOTE_SDU_SIZE:
16117 			/*
16118 			 * Change the MTU size of the interface, of all
16119 			 * attached ipif's, and of all relevant ire's.  The
16120 			 * new value's a uint32_t at notify->dl_data.
16121 			 * Mtu change Vs. new ire creation - protocol below.
16122 			 *
16123 			 * a Mark the ipif as IPIF_CHANGING.
16124 			 * b Set the new mtu in the ipif.
16125 			 * c Change the ire_max_frag on all affected ires
16126 			 * d Unmark the IPIF_CHANGING
16127 			 *
16128 			 * To see how the protocol works, assume an interface
16129 			 * route is also being added simultaneously by
16130 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16131 			 * the ire. If the ire is created before step a,
16132 			 * it will be cleaned up by step c. If the ire is
16133 			 * created after step d, it will see the new value of
16134 			 * ipif_mtu. Any attempt to create the ire between
16135 			 * steps a to d will fail because of the IPIF_CHANGING
16136 			 * flag. Note that ire_create() is passed a pointer to
16137 			 * the ipif_mtu, and not the value. During ire_add
16138 			 * under the bucket lock, the ire_max_frag of the
16139 			 * new ire being created is set from the ipif/ire from
16140 			 * which it is being derived.
16141 			 */
16142 			mutex_enter(&ill->ill_lock);
16143 
16144 			orig_mtu = ill->ill_max_mtu;
16145 			ill->ill_max_frag = (uint_t)notify->dl_data;
16146 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16147 
16148 			/*
16149 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16150 			 * clamp ill_max_mtu at it.
16151 			 */
16152 			if (ill->ill_user_mtu != 0 &&
16153 			    ill->ill_user_mtu < ill->ill_max_mtu)
16154 				ill->ill_max_mtu = ill->ill_user_mtu;
16155 
16156 			/*
16157 			 * If the MTU is unchanged, we're done.
16158 			 */
16159 			if (orig_mtu == ill->ill_max_mtu) {
16160 				mutex_exit(&ill->ill_lock);
16161 				break;
16162 			}
16163 
16164 			if (ill->ill_isv6) {
16165 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16166 					ill->ill_max_mtu = IPV6_MIN_MTU;
16167 			} else {
16168 				if (ill->ill_max_mtu < IP_MIN_MTU)
16169 					ill->ill_max_mtu = IP_MIN_MTU;
16170 			}
16171 			for (ipif = ill->ill_ipif; ipif != NULL;
16172 			    ipif = ipif->ipif_next) {
16173 				/*
16174 				 * Don't override the mtu if the user
16175 				 * has explicitly set it.
16176 				 */
16177 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16178 					continue;
16179 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16180 				if (ipif->ipif_isv6)
16181 					ire = ipif_to_ire_v6(ipif);
16182 				else
16183 					ire = ipif_to_ire(ipif);
16184 				if (ire != NULL) {
16185 					ire->ire_max_frag = ipif->ipif_mtu;
16186 					ire_refrele(ire);
16187 				}
16188 				if (ipif->ipif_flags & IPIF_UP) {
16189 					if (ill->ill_isv6)
16190 						need_ire_walk_v6 = B_TRUE;
16191 					else
16192 						need_ire_walk_v4 = B_TRUE;
16193 				}
16194 			}
16195 			mutex_exit(&ill->ill_lock);
16196 			if (need_ire_walk_v4)
16197 				ire_walk_v4(ill_mtu_change, (char *)ill,
16198 				    ALL_ZONES, ipst);
16199 			if (need_ire_walk_v6)
16200 				ire_walk_v6(ill_mtu_change, (char *)ill,
16201 				    ALL_ZONES, ipst);
16202 
16203 			/*
16204 			 * Refresh IPMP meta-interface MTU if necessary.
16205 			 */
16206 			if (IS_UNDER_IPMP(ill))
16207 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16208 			break;
16209 
16210 		case DL_NOTE_LINK_UP:
16211 		case DL_NOTE_LINK_DOWN: {
16212 			/*
16213 			 * We are writer. ill / phyint / ipsq assocs stable.
16214 			 * The RUNNING flag reflects the state of the link.
16215 			 */
16216 			phyint_t *phyint = ill->ill_phyint;
16217 			uint64_t new_phyint_flags;
16218 			boolean_t changed = B_FALSE;
16219 			boolean_t went_up;
16220 
16221 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16222 			mutex_enter(&phyint->phyint_lock);
16223 
16224 			new_phyint_flags = went_up ?
16225 			    phyint->phyint_flags | PHYI_RUNNING :
16226 			    phyint->phyint_flags & ~PHYI_RUNNING;
16227 
16228 			if (IS_IPMP(ill)) {
16229 				new_phyint_flags = went_up ?
16230 				    new_phyint_flags & ~PHYI_FAILED :
16231 				    new_phyint_flags | PHYI_FAILED;
16232 			}
16233 
16234 			if (new_phyint_flags != phyint->phyint_flags) {
16235 				phyint->phyint_flags = new_phyint_flags;
16236 				changed = B_TRUE;
16237 			}
16238 			mutex_exit(&phyint->phyint_lock);
16239 			/*
16240 			 * ill_restart_dad handles the DAD restart and routing
16241 			 * socket notification logic.
16242 			 */
16243 			if (changed) {
16244 				ill_restart_dad(phyint->phyint_illv4, went_up);
16245 				ill_restart_dad(phyint->phyint_illv6, went_up);
16246 			}
16247 			break;
16248 		}
16249 		case DL_NOTE_PROMISC_ON_PHYS:
16250 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16251 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16252 			mutex_enter(&ill->ill_lock);
16253 			ill->ill_promisc_on_phys = B_TRUE;
16254 			mutex_exit(&ill->ill_lock);
16255 			break;
16256 		case DL_NOTE_PROMISC_OFF_PHYS:
16257 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16258 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16259 			mutex_enter(&ill->ill_lock);
16260 			ill->ill_promisc_on_phys = B_FALSE;
16261 			mutex_exit(&ill->ill_lock);
16262 			break;
16263 		case DL_NOTE_CAPAB_RENEG:
16264 			/*
16265 			 * Something changed on the driver side.
16266 			 * It wants us to renegotiate the capabilities
16267 			 * on this ill. One possible cause is the aggregation
16268 			 * interface under us where a port got added or
16269 			 * went away.
16270 			 *
16271 			 * If the capability negotiation is already done
16272 			 * or is in progress, reset the capabilities and
16273 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16274 			 * so that when the ack comes back, we can start
16275 			 * the renegotiation process.
16276 			 *
16277 			 * Note that if ill_capab_reneg is already B_TRUE
16278 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16279 			 * the capability resetting request has been sent
16280 			 * and the renegotiation has not been started yet;
16281 			 * nothing needs to be done in this case.
16282 			 */
16283 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16284 			ill_capability_reset(ill, B_TRUE);
16285 			ipsq_current_finish(ipsq);
16286 			break;
16287 		default:
16288 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16289 			    "type 0x%x for DL_NOTIFY_IND\n",
16290 			    notify->dl_notification));
16291 			break;
16292 		}
16293 
16294 		/*
16295 		 * As this is an asynchronous operation, we
16296 		 * should not call ill_dlpi_done
16297 		 */
16298 		break;
16299 	}
16300 	case DL_NOTIFY_ACK: {
16301 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16302 
16303 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16304 			ill->ill_note_link = 1;
16305 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16306 		break;
16307 	}
16308 	case DL_PHYS_ADDR_ACK: {
16309 		/*
16310 		 * As part of plumbing the interface via SIOCSLIFNAME,
16311 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16312 		 * whose answers we receive here.  As each answer is received,
16313 		 * we call ill_dlpi_done() to dispatch the next request as
16314 		 * we're processing the current one.  Once all answers have
16315 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16316 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16317 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16318 		 * available, but we know the ioctl is pending on ill_wq.)
16319 		 */
16320 		uint_t	paddrlen, paddroff;
16321 
16322 		paddrreq = ill->ill_phys_addr_pend;
16323 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16324 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16325 
16326 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16327 		if (paddrreq == DL_IPV6_TOKEN) {
16328 			/*
16329 			 * bcopy to low-order bits of ill_token
16330 			 *
16331 			 * XXX Temporary hack - currently, all known tokens
16332 			 * are 64 bits, so I'll cheat for the moment.
16333 			 */
16334 			bcopy(mp->b_rptr + paddroff,
16335 			    &ill->ill_token.s6_addr32[2], paddrlen);
16336 			ill->ill_token_length = paddrlen;
16337 			break;
16338 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16339 			ASSERT(ill->ill_nd_lla_mp == NULL);
16340 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16341 			mp = NULL;
16342 			break;
16343 		}
16344 
16345 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16346 		ASSERT(ill->ill_phys_addr_mp == NULL);
16347 		if (!ill->ill_ifname_pending)
16348 			break;
16349 		ill->ill_ifname_pending = 0;
16350 		if (!ioctl_aborted)
16351 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16352 		if (mp1 != NULL) {
16353 			ASSERT(connp == NULL);
16354 			q = ill->ill_wq;
16355 		}
16356 		/*
16357 		 * If any error acks received during the plumbing sequence,
16358 		 * ill_ifname_pending_err will be set. Break out and send up
16359 		 * the error to the pending ioctl.
16360 		 */
16361 		if (ill->ill_ifname_pending_err != 0) {
16362 			err = ill->ill_ifname_pending_err;
16363 			ill->ill_ifname_pending_err = 0;
16364 			break;
16365 		}
16366 
16367 		ill->ill_phys_addr_mp = mp;
16368 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16369 		mp = NULL;
16370 
16371 		/*
16372 		 * If paddrlen is zero, the DLPI provider doesn't support
16373 		 * physical addresses.  The other two tests were historical
16374 		 * workarounds for bugs in our former PPP implementation, but
16375 		 * now other things have grown dependencies on them -- e.g.,
16376 		 * the tun module specifies a dl_addr_length of zero in its
16377 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16378 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16379 		 * but only after careful testing ensures that all dependent
16380 		 * broken DLPI providers have been fixed.
16381 		 */
16382 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16383 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16384 			ill->ill_phys_addr = NULL;
16385 		} else if (paddrlen != ill->ill_phys_addr_length) {
16386 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16387 			    paddrlen, ill->ill_phys_addr_length));
16388 			err = EINVAL;
16389 			break;
16390 		}
16391 
16392 		if (ill->ill_nd_lla_mp == NULL) {
16393 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16394 				err = ENOMEM;
16395 				break;
16396 			}
16397 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16398 		}
16399 
16400 		/*
16401 		 * Set the interface token.  If the zeroth interface address
16402 		 * is unspecified, then set it to the link local address.
16403 		 */
16404 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16405 			(void) ill_setdefaulttoken(ill);
16406 
16407 		ASSERT(ill->ill_ipif->ipif_id == 0);
16408 		if (ipif != NULL &&
16409 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16410 			(void) ipif_setlinklocal(ipif);
16411 		}
16412 		break;
16413 	}
16414 	case DL_OK_ACK:
16415 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16416 		    dl_primstr((int)dloa->dl_correct_primitive),
16417 		    dloa->dl_correct_primitive));
16418 		switch (dloa->dl_correct_primitive) {
16419 		case DL_ENABMULTI_REQ:
16420 		case DL_DISABMULTI_REQ:
16421 			if (!ill->ill_isv6)
16422 				ipsq_current_finish(ipsq);
16423 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16424 			break;
16425 		case DL_PROMISCON_REQ:
16426 		case DL_PROMISCOFF_REQ:
16427 		case DL_UNBIND_REQ:
16428 		case DL_ATTACH_REQ:
16429 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16430 			break;
16431 		}
16432 		break;
16433 	default:
16434 		break;
16435 	}
16436 
16437 	freemsg(mp);
16438 	if (mp1 == NULL)
16439 		return;
16440 
16441 	/*
16442 	 * The operation must complete without EINPROGRESS since
16443 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16444 	 * the operation will be stuck forever inside the IPSQ.
16445 	 */
16446 	ASSERT(err != EINPROGRESS);
16447 
16448 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16449 	case 0:
16450 		ipsq_current_finish(ipsq);
16451 		break;
16452 
16453 	case SIOCSLIFNAME:
16454 	case IF_UNITSEL: {
16455 		ill_t *ill_other = ILL_OTHER(ill);
16456 
16457 		/*
16458 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16459 		 * ill has a peer which is in an IPMP group, then place ill
16460 		 * into the same group.  One catch: although ifconfig plumbs
16461 		 * the appropriate IPMP meta-interface prior to plumbing this
16462 		 * ill, it is possible for multiple ifconfig applications to
16463 		 * race (or for another application to adjust plumbing), in
16464 		 * which case the IPMP meta-interface we need will be missing.
16465 		 * If so, kick the phyint out of the group.
16466 		 */
16467 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16468 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16469 			ipmp_illgrp_t	*illg;
16470 
16471 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16472 			if (illg == NULL)
16473 				ipmp_phyint_leave_grp(ill->ill_phyint);
16474 			else
16475 				ipmp_ill_join_illgrp(ill, illg);
16476 		}
16477 
16478 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16479 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16480 		else
16481 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16482 		break;
16483 	}
16484 	case SIOCLIFADDIF:
16485 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16486 		break;
16487 
16488 	default:
16489 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16490 		break;
16491 	}
16492 }
16493 
16494 /*
16495  * ip_rput_other is called by ip_rput to handle messages modifying the global
16496  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16497  */
16498 /* ARGSUSED */
16499 void
16500 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16501 {
16502 	ill_t		*ill = q->q_ptr;
16503 	struct iocblk	*iocp;
16504 	mblk_t		*mp1;
16505 	conn_t		*connp = NULL;
16506 
16507 	ip1dbg(("ip_rput_other "));
16508 	if (ipsq != NULL) {
16509 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16510 		ASSERT(ipsq->ipsq_xop ==
16511 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16512 	}
16513 
16514 	switch (mp->b_datap->db_type) {
16515 	case M_ERROR:
16516 	case M_HANGUP:
16517 		/*
16518 		 * The device has a problem.  We force the ILL down.  It can
16519 		 * be brought up again manually using SIOCSIFFLAGS (via
16520 		 * ifconfig or equivalent).
16521 		 */
16522 		ASSERT(ipsq != NULL);
16523 		if (mp->b_rptr < mp->b_wptr)
16524 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16525 		if (ill->ill_error == 0)
16526 			ill->ill_error = ENXIO;
16527 		if (!ill_down_start(q, mp))
16528 			return;
16529 		ipif_all_down_tail(ipsq, q, mp, NULL);
16530 		break;
16531 	case M_IOCACK:
16532 		iocp = (struct iocblk *)mp->b_rptr;
16533 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16534 		switch (iocp->ioc_cmd) {
16535 		case SIOCSTUNPARAM:
16536 		case OSIOCSTUNPARAM:
16537 			ASSERT(ipsq != NULL);
16538 			/*
16539 			 * Finish socket ioctl passed through to tun.
16540 			 * We should have an IOCTL waiting on this.
16541 			 */
16542 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16543 			if (ill->ill_isv6) {
16544 				struct iftun_req *ta;
16545 
16546 				/*
16547 				 * if a source or destination is
16548 				 * being set, try and set the link
16549 				 * local address for the tunnel
16550 				 */
16551 				ta = (struct iftun_req *)mp->b_cont->
16552 				    b_cont->b_rptr;
16553 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16554 					ipif_set_tun_llink(ill, ta);
16555 				}
16556 
16557 			}
16558 			if (mp1 != NULL) {
16559 				/*
16560 				 * Now copy back the b_next/b_prev used by
16561 				 * mi code for the mi_copy* functions.
16562 				 * See ip_sioctl_tunparam() for the reason.
16563 				 * Also protect against missing b_cont.
16564 				 */
16565 				if (mp->b_cont != NULL) {
16566 					mp->b_cont->b_next =
16567 					    mp1->b_cont->b_next;
16568 					mp->b_cont->b_prev =
16569 					    mp1->b_cont->b_prev;
16570 				}
16571 				inet_freemsg(mp1);
16572 				ASSERT(connp != NULL);
16573 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16574 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16575 			} else {
16576 				ASSERT(connp == NULL);
16577 				putnext(q, mp);
16578 			}
16579 			break;
16580 		case SIOCGTUNPARAM:
16581 		case OSIOCGTUNPARAM:
16582 			/*
16583 			 * This is really M_IOCDATA from the tunnel driver.
16584 			 * convert back and complete the ioctl.
16585 			 * We should have an IOCTL waiting on this.
16586 			 */
16587 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16588 			if (mp1) {
16589 				/*
16590 				 * Now copy back the b_next/b_prev used by
16591 				 * mi code for the mi_copy* functions.
16592 				 * See ip_sioctl_tunparam() for the reason.
16593 				 * Also protect against missing b_cont.
16594 				 */
16595 				if (mp->b_cont != NULL) {
16596 					mp->b_cont->b_next =
16597 					    mp1->b_cont->b_next;
16598 					mp->b_cont->b_prev =
16599 					    mp1->b_cont->b_prev;
16600 				}
16601 				inet_freemsg(mp1);
16602 				if (iocp->ioc_error == 0)
16603 					mp->b_datap->db_type = M_IOCDATA;
16604 				ASSERT(connp != NULL);
16605 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16606 				    iocp->ioc_error, COPYOUT, NULL);
16607 			} else {
16608 				ASSERT(connp == NULL);
16609 				putnext(q, mp);
16610 			}
16611 			break;
16612 		default:
16613 			break;
16614 		}
16615 		break;
16616 	case M_IOCNAK:
16617 		iocp = (struct iocblk *)mp->b_rptr;
16618 
16619 		switch (iocp->ioc_cmd) {
16620 			int mode;
16621 
16622 		case DL_IOC_HDR_INFO:
16623 			/*
16624 			 * If this was the first attempt, turn off the
16625 			 * fastpath probing.
16626 			 */
16627 			mutex_enter(&ill->ill_lock);
16628 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16629 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16630 				mutex_exit(&ill->ill_lock);
16631 				ill_fastpath_nack(ill);
16632 				ip1dbg(("ip_rput: DLPI fastpath off on "
16633 				    "interface %s\n",
16634 				    ill->ill_name));
16635 			} else {
16636 				mutex_exit(&ill->ill_lock);
16637 			}
16638 			freemsg(mp);
16639 			break;
16640 			case SIOCSTUNPARAM:
16641 		case OSIOCSTUNPARAM:
16642 			ASSERT(ipsq != NULL);
16643 			/*
16644 			 * Finish socket ioctl passed through to tun
16645 			 * We should have an IOCTL waiting on this.
16646 			 */
16647 			/* FALLTHRU */
16648 		case SIOCGTUNPARAM:
16649 		case OSIOCGTUNPARAM:
16650 			/*
16651 			 * This is really M_IOCDATA from the tunnel driver.
16652 			 * convert back and complete the ioctl.
16653 			 * We should have an IOCTL waiting on this.
16654 			 */
16655 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16656 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16657 				mp1 = ill_pending_mp_get(ill, &connp,
16658 				    iocp->ioc_id);
16659 				mode = COPYOUT;
16660 				ipsq = NULL;
16661 			} else {
16662 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16663 				mode = NO_COPYOUT;
16664 			}
16665 			if (mp1 != NULL) {
16666 				/*
16667 				 * Now copy back the b_next/b_prev used by
16668 				 * mi code for the mi_copy* functions.
16669 				 * See ip_sioctl_tunparam() for the reason.
16670 				 * Also protect against missing b_cont.
16671 				 */
16672 				if (mp->b_cont != NULL) {
16673 					mp->b_cont->b_next =
16674 					    mp1->b_cont->b_next;
16675 					mp->b_cont->b_prev =
16676 					    mp1->b_cont->b_prev;
16677 				}
16678 				inet_freemsg(mp1);
16679 				if (iocp->ioc_error == 0)
16680 					iocp->ioc_error = EINVAL;
16681 				ASSERT(connp != NULL);
16682 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16683 				    iocp->ioc_error, mode, ipsq);
16684 			} else {
16685 				ASSERT(connp == NULL);
16686 				putnext(q, mp);
16687 			}
16688 			break;
16689 		default:
16690 			break;
16691 		}
16692 	default:
16693 		break;
16694 	}
16695 }
16696 
16697 /*
16698  * NOTE : This function does not ire_refrele the ire argument passed in.
16699  *
16700  * IPQoS notes
16701  * IP policy is invoked twice for a forwarded packet, once on the read side
16702  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16703  * enabled. An additional parameter, in_ill, has been added for this purpose.
16704  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16705  * because ip_mroute drops this information.
16706  *
16707  */
16708 void
16709 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16710 {
16711 	uint32_t	old_pkt_len;
16712 	uint32_t	pkt_len;
16713 	queue_t	*q;
16714 	uint32_t	sum;
16715 #define	rptr	((uchar_t *)ipha)
16716 	uint32_t	max_frag;
16717 	uint32_t	ill_index;
16718 	ill_t		*out_ill;
16719 	mib2_ipIfStatsEntry_t *mibptr;
16720 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16721 
16722 	/* Get the ill_index of the incoming ILL */
16723 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16724 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16725 
16726 	/* Initiate Read side IPPF processing */
16727 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16728 		ip_process(IPP_FWD_IN, &mp, ill_index);
16729 		if (mp == NULL) {
16730 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16731 			    "during IPPF processing\n"));
16732 			return;
16733 		}
16734 	}
16735 
16736 	/* Adjust the checksum to reflect the ttl decrement. */
16737 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16738 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16739 
16740 	if (ipha->ipha_ttl-- <= 1) {
16741 		if (ip_csum_hdr(ipha)) {
16742 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16743 			goto drop_pkt;
16744 		}
16745 		/*
16746 		 * Note: ire_stq this will be NULL for multicast
16747 		 * datagrams using the long path through arp (the IRE
16748 		 * is not an IRE_CACHE). This should not cause
16749 		 * problems since we don't generate ICMP errors for
16750 		 * multicast packets.
16751 		 */
16752 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16753 		q = ire->ire_stq;
16754 		if (q != NULL) {
16755 			/* Sent by forwarding path, and router is global zone */
16756 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16757 			    GLOBAL_ZONEID, ipst);
16758 		} else
16759 			freemsg(mp);
16760 		return;
16761 	}
16762 
16763 	/*
16764 	 * Don't forward if the interface is down
16765 	 */
16766 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16767 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16768 		ip2dbg(("ip_rput_forward:interface is down\n"));
16769 		goto drop_pkt;
16770 	}
16771 
16772 	/* Get the ill_index of the outgoing ILL */
16773 	out_ill = ire_to_ill(ire);
16774 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16775 
16776 	DTRACE_PROBE4(ip4__forwarding__start,
16777 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16778 
16779 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16780 	    ipst->ips_ipv4firewall_forwarding,
16781 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16782 
16783 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16784 
16785 	if (mp == NULL)
16786 		return;
16787 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16788 
16789 	if (is_system_labeled()) {
16790 		mblk_t *mp1;
16791 
16792 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16793 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16794 			goto drop_pkt;
16795 		}
16796 		/* Size may have changed */
16797 		mp = mp1;
16798 		ipha = (ipha_t *)mp->b_rptr;
16799 		pkt_len = ntohs(ipha->ipha_length);
16800 	}
16801 
16802 	/* Check if there are options to update */
16803 	if (!IS_SIMPLE_IPH(ipha)) {
16804 		if (ip_csum_hdr(ipha)) {
16805 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16806 			goto drop_pkt;
16807 		}
16808 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16809 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16810 			return;
16811 		}
16812 
16813 		ipha->ipha_hdr_checksum = 0;
16814 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16815 	}
16816 	max_frag = ire->ire_max_frag;
16817 	if (pkt_len > max_frag) {
16818 		/*
16819 		 * It needs fragging on its way out.  We haven't
16820 		 * verified the header checksum yet.  Since we
16821 		 * are going to put a surely good checksum in the
16822 		 * outgoing header, we have to make sure that it
16823 		 * was good coming in.
16824 		 */
16825 		if (ip_csum_hdr(ipha)) {
16826 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16827 			goto drop_pkt;
16828 		}
16829 		/* Initiate Write side IPPF processing */
16830 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16831 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16832 			if (mp == NULL) {
16833 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16834 				    " during IPPF processing\n"));
16835 				return;
16836 			}
16837 		}
16838 		/*
16839 		 * Handle labeled packet resizing.
16840 		 *
16841 		 * If we have added a label, inform ip_wput_frag() of its
16842 		 * effect on the MTU for ICMP messages.
16843 		 */
16844 		if (pkt_len > old_pkt_len) {
16845 			uint32_t secopt_size;
16846 
16847 			secopt_size = pkt_len - old_pkt_len;
16848 			if (secopt_size < max_frag)
16849 				max_frag -= secopt_size;
16850 		}
16851 
16852 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16853 		    GLOBAL_ZONEID, ipst, NULL);
16854 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16855 		return;
16856 	}
16857 
16858 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16859 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16860 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16861 	    ipst->ips_ipv4firewall_physical_out,
16862 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16863 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16864 	if (mp == NULL)
16865 		return;
16866 
16867 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16868 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16869 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16870 	/* ip_xmit_v4 always consumes the packet */
16871 	return;
16872 
16873 drop_pkt:;
16874 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16875 	freemsg(mp);
16876 #undef	rptr
16877 }
16878 
16879 void
16880 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16881 {
16882 	ire_t	*ire;
16883 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16884 
16885 	ASSERT(!ipif->ipif_isv6);
16886 	/*
16887 	 * Find an IRE which matches the destination and the outgoing
16888 	 * queue in the cache table. All we need is an IRE_CACHE which
16889 	 * is pointing at ipif->ipif_ill.
16890 	 */
16891 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16892 		dst = ipif->ipif_pp_dst_addr;
16893 
16894 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16895 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16896 	if (ire == NULL) {
16897 		/*
16898 		 * Mark this packet to make it be delivered to
16899 		 * ip_rput_forward after the new ire has been
16900 		 * created.
16901 		 */
16902 		mp->b_prev = NULL;
16903 		mp->b_next = mp;
16904 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16905 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16906 	} else {
16907 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16908 		IRE_REFRELE(ire);
16909 	}
16910 }
16911 
16912 /* Update any source route, record route or timestamp options */
16913 static int
16914 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16915 {
16916 	ipoptp_t	opts;
16917 	uchar_t		*opt;
16918 	uint8_t		optval;
16919 	uint8_t		optlen;
16920 	ipaddr_t	dst;
16921 	uint32_t	ts;
16922 	ire_t		*dst_ire = NULL;
16923 	ire_t		*tmp_ire = NULL;
16924 	timestruc_t	now;
16925 
16926 	ip2dbg(("ip_rput_forward_options\n"));
16927 	dst = ipha->ipha_dst;
16928 	for (optval = ipoptp_first(&opts, ipha);
16929 	    optval != IPOPT_EOL;
16930 	    optval = ipoptp_next(&opts)) {
16931 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16932 		opt = opts.ipoptp_cur;
16933 		optlen = opts.ipoptp_len;
16934 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16935 		    optval, opts.ipoptp_len));
16936 		switch (optval) {
16937 			uint32_t off;
16938 		case IPOPT_SSRR:
16939 		case IPOPT_LSRR:
16940 			/* Check if adminstratively disabled */
16941 			if (!ipst->ips_ip_forward_src_routed) {
16942 				if (ire->ire_stq != NULL) {
16943 					/*
16944 					 * Sent by forwarding path, and router
16945 					 * is global zone
16946 					 */
16947 					icmp_unreachable(ire->ire_stq, mp,
16948 					    ICMP_SOURCE_ROUTE_FAILED,
16949 					    GLOBAL_ZONEID, ipst);
16950 				} else {
16951 					ip0dbg(("ip_rput_forward_options: "
16952 					    "unable to send unreach\n"));
16953 					freemsg(mp);
16954 				}
16955 				return (-1);
16956 			}
16957 
16958 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16959 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16960 			if (dst_ire == NULL) {
16961 				/*
16962 				 * Must be partial since ip_rput_options
16963 				 * checked for strict.
16964 				 */
16965 				break;
16966 			}
16967 			off = opt[IPOPT_OFFSET];
16968 			off--;
16969 		redo_srr:
16970 			if (optlen < IP_ADDR_LEN ||
16971 			    off > optlen - IP_ADDR_LEN) {
16972 				/* End of source route */
16973 				ip1dbg((
16974 				    "ip_rput_forward_options: end of SR\n"));
16975 				ire_refrele(dst_ire);
16976 				break;
16977 			}
16978 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16979 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16980 			    IP_ADDR_LEN);
16981 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16982 			    ntohl(dst)));
16983 
16984 			/*
16985 			 * Check if our address is present more than
16986 			 * once as consecutive hops in source route.
16987 			 */
16988 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16989 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16990 			if (tmp_ire != NULL) {
16991 				ire_refrele(tmp_ire);
16992 				off += IP_ADDR_LEN;
16993 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16994 				goto redo_srr;
16995 			}
16996 			ipha->ipha_dst = dst;
16997 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16998 			ire_refrele(dst_ire);
16999 			break;
17000 		case IPOPT_RR:
17001 			off = opt[IPOPT_OFFSET];
17002 			off--;
17003 			if (optlen < IP_ADDR_LEN ||
17004 			    off > optlen - IP_ADDR_LEN) {
17005 				/* No more room - ignore */
17006 				ip1dbg((
17007 				    "ip_rput_forward_options: end of RR\n"));
17008 				break;
17009 			}
17010 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17011 			    IP_ADDR_LEN);
17012 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17013 			break;
17014 		case IPOPT_TS:
17015 			/* Insert timestamp if there is room */
17016 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17017 			case IPOPT_TS_TSONLY:
17018 				off = IPOPT_TS_TIMELEN;
17019 				break;
17020 			case IPOPT_TS_PRESPEC:
17021 			case IPOPT_TS_PRESPEC_RFC791:
17022 				/* Verify that the address matched */
17023 				off = opt[IPOPT_OFFSET] - 1;
17024 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17025 				dst_ire = ire_ctable_lookup(dst, 0,
17026 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17027 				    MATCH_IRE_TYPE, ipst);
17028 				if (dst_ire == NULL) {
17029 					/* Not for us */
17030 					break;
17031 				}
17032 				ire_refrele(dst_ire);
17033 				/* FALLTHRU */
17034 			case IPOPT_TS_TSANDADDR:
17035 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17036 				break;
17037 			default:
17038 				/*
17039 				 * ip_*put_options should have already
17040 				 * dropped this packet.
17041 				 */
17042 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17043 				    "unknown IT - bug in ip_rput_options?\n");
17044 				return (0);	/* Keep "lint" happy */
17045 			}
17046 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17047 				/* Increase overflow counter */
17048 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17049 				opt[IPOPT_POS_OV_FLG] =
17050 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17051 				    (off << 4));
17052 				break;
17053 			}
17054 			off = opt[IPOPT_OFFSET] - 1;
17055 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17056 			case IPOPT_TS_PRESPEC:
17057 			case IPOPT_TS_PRESPEC_RFC791:
17058 			case IPOPT_TS_TSANDADDR:
17059 				bcopy(&ire->ire_src_addr,
17060 				    (char *)opt + off, IP_ADDR_LEN);
17061 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17062 				/* FALLTHRU */
17063 			case IPOPT_TS_TSONLY:
17064 				off = opt[IPOPT_OFFSET] - 1;
17065 				/* Compute # of milliseconds since midnight */
17066 				gethrestime(&now);
17067 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17068 				    now.tv_nsec / (NANOSEC / MILLISEC);
17069 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17070 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17071 				break;
17072 			}
17073 			break;
17074 		}
17075 	}
17076 	return (0);
17077 }
17078 
17079 /*
17080  * This is called after processing at least one of AH/ESP headers.
17081  *
17082  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17083  * the actual, physical interface on which the packet was received,
17084  * but, when ip_strict_dst_multihoming is set to 1, could be the
17085  * interface which had the ipha_dst configured when the packet went
17086  * through ip_rput. The ill_index corresponding to the recv_ill
17087  * is saved in ipsec_in_rill_index
17088  *
17089  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17090  * cannot assume "ire" points to valid data for any IPv6 cases.
17091  */
17092 void
17093 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17094 {
17095 	mblk_t *mp;
17096 	ipaddr_t dst;
17097 	in6_addr_t *v6dstp;
17098 	ipha_t *ipha;
17099 	ip6_t *ip6h;
17100 	ipsec_in_t *ii;
17101 	boolean_t ill_need_rele = B_FALSE;
17102 	boolean_t rill_need_rele = B_FALSE;
17103 	boolean_t ire_need_rele = B_FALSE;
17104 	netstack_t	*ns;
17105 	ip_stack_t	*ipst;
17106 
17107 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17108 	ASSERT(ii->ipsec_in_ill_index != 0);
17109 	ns = ii->ipsec_in_ns;
17110 	ASSERT(ii->ipsec_in_ns != NULL);
17111 	ipst = ns->netstack_ip;
17112 
17113 	mp = ipsec_mp->b_cont;
17114 	ASSERT(mp != NULL);
17115 
17116 	if (ill == NULL) {
17117 		ASSERT(recv_ill == NULL);
17118 		/*
17119 		 * We need to get the original queue on which ip_rput_local
17120 		 * or ip_rput_data_v6 was called.
17121 		 */
17122 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17123 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17124 		ill_need_rele = B_TRUE;
17125 
17126 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17127 			recv_ill = ill_lookup_on_ifindex(
17128 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17129 			    NULL, NULL, NULL, NULL, ipst);
17130 			rill_need_rele = B_TRUE;
17131 		} else {
17132 			recv_ill = ill;
17133 		}
17134 
17135 		if ((ill == NULL) || (recv_ill == NULL)) {
17136 			ip0dbg(("ip_fanout_proto_again: interface "
17137 			    "disappeared\n"));
17138 			if (ill != NULL)
17139 				ill_refrele(ill);
17140 			if (recv_ill != NULL)
17141 				ill_refrele(recv_ill);
17142 			freemsg(ipsec_mp);
17143 			return;
17144 		}
17145 	}
17146 
17147 	ASSERT(ill != NULL && recv_ill != NULL);
17148 
17149 	if (mp->b_datap->db_type == M_CTL) {
17150 		/*
17151 		 * AH/ESP is returning the ICMP message after
17152 		 * removing their headers. Fanout again till
17153 		 * it gets to the right protocol.
17154 		 */
17155 		if (ii->ipsec_in_v4) {
17156 			icmph_t *icmph;
17157 			int iph_hdr_length;
17158 			int hdr_length;
17159 
17160 			ipha = (ipha_t *)mp->b_rptr;
17161 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17162 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17163 			ipha = (ipha_t *)&icmph[1];
17164 			hdr_length = IPH_HDR_LENGTH(ipha);
17165 			/*
17166 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17167 			 * Reset the type to M_DATA.
17168 			 */
17169 			mp->b_datap->db_type = M_DATA;
17170 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17171 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17172 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17173 		} else {
17174 			icmp6_t *icmp6;
17175 			int hdr_length;
17176 
17177 			ip6h = (ip6_t *)mp->b_rptr;
17178 			/* Don't call hdr_length_v6() unless you have to. */
17179 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17180 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17181 			else
17182 				hdr_length = IPV6_HDR_LEN;
17183 
17184 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17185 			/*
17186 			 * icmp_inbound_error_fanout_v6 may need to do
17187 			 * pullupmsg.  Reset the type to M_DATA.
17188 			 */
17189 			mp->b_datap->db_type = M_DATA;
17190 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17191 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17192 			    ii->ipsec_in_zoneid);
17193 		}
17194 		if (ill_need_rele)
17195 			ill_refrele(ill);
17196 		if (rill_need_rele)
17197 			ill_refrele(recv_ill);
17198 		return;
17199 	}
17200 
17201 	if (ii->ipsec_in_v4) {
17202 		ipha = (ipha_t *)mp->b_rptr;
17203 		dst = ipha->ipha_dst;
17204 		if (CLASSD(dst)) {
17205 			/*
17206 			 * Multicast has to be delivered to all streams.
17207 			 */
17208 			dst = INADDR_BROADCAST;
17209 		}
17210 
17211 		if (ire == NULL) {
17212 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17213 			    msg_getlabel(mp), ipst);
17214 			if (ire == NULL) {
17215 				if (ill_need_rele)
17216 					ill_refrele(ill);
17217 				if (rill_need_rele)
17218 					ill_refrele(recv_ill);
17219 				ip1dbg(("ip_fanout_proto_again: "
17220 				    "IRE not found"));
17221 				freemsg(ipsec_mp);
17222 				return;
17223 			}
17224 			ire_need_rele = B_TRUE;
17225 		}
17226 
17227 		switch (ipha->ipha_protocol) {
17228 		case IPPROTO_UDP:
17229 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17230 			    recv_ill);
17231 			if (ire_need_rele)
17232 				ire_refrele(ire);
17233 			break;
17234 		case IPPROTO_TCP:
17235 			if (!ire_need_rele)
17236 				IRE_REFHOLD(ire);
17237 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17238 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17239 			IRE_REFRELE(ire);
17240 			if (mp != NULL) {
17241 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17242 				    mp, 1, SQ_PROCESS,
17243 				    SQTAG_IP_PROTO_AGAIN);
17244 			}
17245 			break;
17246 		case IPPROTO_SCTP:
17247 			if (!ire_need_rele)
17248 				IRE_REFHOLD(ire);
17249 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17250 			    ipsec_mp, 0, ill->ill_rq, dst);
17251 			break;
17252 		default:
17253 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17254 			    recv_ill, 0);
17255 			if (ire_need_rele)
17256 				ire_refrele(ire);
17257 			break;
17258 		}
17259 	} else {
17260 		uint32_t rput_flags = 0;
17261 
17262 		ip6h = (ip6_t *)mp->b_rptr;
17263 		v6dstp = &ip6h->ip6_dst;
17264 		/*
17265 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17266 		 * address.
17267 		 *
17268 		 * Currently, we don't store that state in the IPSEC_IN
17269 		 * message, and we may need to.
17270 		 */
17271 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17272 		    IP6_IN_LLMCAST : 0);
17273 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17274 		    NULL, NULL);
17275 	}
17276 	if (ill_need_rele)
17277 		ill_refrele(ill);
17278 	if (rill_need_rele)
17279 		ill_refrele(recv_ill);
17280 }
17281 
17282 /*
17283  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17284  * returns 'true' if there are still fragments left on the queue, in
17285  * which case we restart the timer.
17286  */
17287 void
17288 ill_frag_timer(void *arg)
17289 {
17290 	ill_t	*ill = (ill_t *)arg;
17291 	boolean_t frag_pending;
17292 	ip_stack_t	*ipst = ill->ill_ipst;
17293 
17294 	mutex_enter(&ill->ill_lock);
17295 	ASSERT(!ill->ill_fragtimer_executing);
17296 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17297 		ill->ill_frag_timer_id = 0;
17298 		mutex_exit(&ill->ill_lock);
17299 		return;
17300 	}
17301 	ill->ill_fragtimer_executing = 1;
17302 	mutex_exit(&ill->ill_lock);
17303 
17304 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17305 
17306 	/*
17307 	 * Restart the timer, if we have fragments pending or if someone
17308 	 * wanted us to be scheduled again.
17309 	 */
17310 	mutex_enter(&ill->ill_lock);
17311 	ill->ill_fragtimer_executing = 0;
17312 	ill->ill_frag_timer_id = 0;
17313 	if (frag_pending || ill->ill_fragtimer_needrestart)
17314 		ill_frag_timer_start(ill);
17315 	mutex_exit(&ill->ill_lock);
17316 }
17317 
17318 void
17319 ill_frag_timer_start(ill_t *ill)
17320 {
17321 	ip_stack_t	*ipst = ill->ill_ipst;
17322 
17323 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17324 
17325 	/* If the ill is closing or opening don't proceed */
17326 	if (ill->ill_state_flags & ILL_CONDEMNED)
17327 		return;
17328 
17329 	if (ill->ill_fragtimer_executing) {
17330 		/*
17331 		 * ill_frag_timer is currently executing. Just record the
17332 		 * the fact that we want the timer to be restarted.
17333 		 * ill_frag_timer will post a timeout before it returns,
17334 		 * ensuring it will be called again.
17335 		 */
17336 		ill->ill_fragtimer_needrestart = 1;
17337 		return;
17338 	}
17339 
17340 	if (ill->ill_frag_timer_id == 0) {
17341 		/*
17342 		 * The timer is neither running nor is the timeout handler
17343 		 * executing. Post a timeout so that ill_frag_timer will be
17344 		 * called
17345 		 */
17346 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17347 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17348 		ill->ill_fragtimer_needrestart = 0;
17349 	}
17350 }
17351 
17352 /*
17353  * This routine is needed for loopback when forwarding multicasts.
17354  *
17355  * IPQoS Notes:
17356  * IPPF processing is done in fanout routines.
17357  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17358  * processing for IPsec packets is done when it comes back in clear.
17359  * NOTE : The callers of this function need to do the ire_refrele for the
17360  *	  ire that is being passed in.
17361  */
17362 void
17363 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17364     ill_t *recv_ill, uint32_t esp_udp_ports)
17365 {
17366 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17367 	ill_t	*ill = (ill_t *)q->q_ptr;
17368 	uint32_t	sum;
17369 	uint32_t	u1;
17370 	uint32_t	u2;
17371 	int		hdr_length;
17372 	boolean_t	mctl_present;
17373 	mblk_t		*first_mp = mp;
17374 	mblk_t		*hada_mp = NULL;
17375 	ipha_t		*inner_ipha;
17376 	ip_stack_t	*ipst;
17377 
17378 	ASSERT(recv_ill != NULL);
17379 	ipst = recv_ill->ill_ipst;
17380 
17381 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17382 	    "ip_rput_locl_start: q %p", q);
17383 
17384 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17385 	ASSERT(ill != NULL);
17386 
17387 #define	rptr	((uchar_t *)ipha)
17388 #define	iphs	((uint16_t *)ipha)
17389 
17390 	/*
17391 	 * no UDP or TCP packet should come here anymore.
17392 	 */
17393 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17394 	    ipha->ipha_protocol != IPPROTO_UDP);
17395 
17396 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17397 	if (mctl_present &&
17398 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17399 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17400 
17401 		/*
17402 		 * It's an IPsec accelerated packet.
17403 		 * Keep a pointer to the data attributes around until
17404 		 * we allocate the ipsec_info_t.
17405 		 */
17406 		IPSECHW_DEBUG(IPSECHW_PKT,
17407 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17408 		hada_mp = first_mp;
17409 		hada_mp->b_cont = NULL;
17410 		/*
17411 		 * Since it is accelerated, it comes directly from
17412 		 * the ill and the data attributes is followed by
17413 		 * the packet data.
17414 		 */
17415 		ASSERT(mp->b_datap->db_type != M_CTL);
17416 		first_mp = mp;
17417 		mctl_present = B_FALSE;
17418 	}
17419 
17420 	/*
17421 	 * IF M_CTL is not present, then ipsec_in_is_secure
17422 	 * should return B_TRUE. There is a case where loopback
17423 	 * packets has an M_CTL in the front with all the
17424 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17425 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17426 	 * packets never comes here, it is safe to ASSERT the
17427 	 * following.
17428 	 */
17429 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17430 
17431 	/*
17432 	 * Also, we should never have an mctl_present if this is an
17433 	 * ESP-in-UDP packet.
17434 	 */
17435 	ASSERT(!mctl_present || !esp_in_udp_packet);
17436 
17437 	/* u1 is # words of IP options */
17438 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17439 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17440 
17441 	/*
17442 	 * Don't verify header checksum if we just removed UDP header or
17443 	 * packet is coming back from AH/ESP.
17444 	 */
17445 	if (!esp_in_udp_packet && !mctl_present) {
17446 		if (u1) {
17447 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17448 				if (hada_mp != NULL)
17449 					freemsg(hada_mp);
17450 				return;
17451 			}
17452 		} else {
17453 			/* Check the IP header checksum.  */
17454 #define	uph	((uint16_t *)ipha)
17455 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17456 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17457 #undef  uph
17458 			/* finish doing IP checksum */
17459 			sum = (sum & 0xFFFF) + (sum >> 16);
17460 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17461 			if (sum && sum != 0xFFFF) {
17462 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17463 				goto drop_pkt;
17464 			}
17465 		}
17466 	}
17467 
17468 	/*
17469 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17470 	 * might be called more than once for secure packets, count only
17471 	 * the first time.
17472 	 */
17473 	if (!mctl_present) {
17474 		UPDATE_IB_PKT_COUNT(ire);
17475 		ire->ire_last_used_time = lbolt;
17476 	}
17477 
17478 	/* Check for fragmentation offset. */
17479 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17480 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17481 	if (u1) {
17482 		/*
17483 		 * We re-assemble fragments before we do the AH/ESP
17484 		 * processing. Thus, M_CTL should not be present
17485 		 * while we are re-assembling.
17486 		 */
17487 		ASSERT(!mctl_present);
17488 		ASSERT(first_mp == mp);
17489 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17490 			return;
17491 
17492 		/*
17493 		 * Make sure that first_mp points back to mp as
17494 		 * the mp we came in with could have changed in
17495 		 * ip_rput_fragment().
17496 		 */
17497 		ipha = (ipha_t *)mp->b_rptr;
17498 		first_mp = mp;
17499 	}
17500 
17501 	/*
17502 	 * Clear hardware checksumming flag as it is currently only
17503 	 * used by TCP and UDP.
17504 	 */
17505 	DB_CKSUMFLAGS(mp) = 0;
17506 
17507 	/* Now we have a complete datagram, destined for this machine. */
17508 	u1 = IPH_HDR_LENGTH(ipha);
17509 	switch (ipha->ipha_protocol) {
17510 	case IPPROTO_ICMP: {
17511 		ire_t		*ire_zone;
17512 		ilm_t		*ilm;
17513 		mblk_t		*mp1;
17514 		zoneid_t	last_zoneid;
17515 		ilm_walker_t	ilw;
17516 
17517 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17518 			ASSERT(ire->ire_type == IRE_BROADCAST);
17519 
17520 			/*
17521 			 * In the multicast case, applications may have joined
17522 			 * the group from different zones, so we need to deliver
17523 			 * the packet to each of them. Loop through the
17524 			 * multicast memberships structures (ilm) on the receive
17525 			 * ill and send a copy of the packet up each matching
17526 			 * one. However, we don't do this for multicasts sent on
17527 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17528 			 * they must stay in the sender's zone.
17529 			 *
17530 			 * ilm_add_v6() ensures that ilms in the same zone are
17531 			 * contiguous in the ill_ilm list. We use this property
17532 			 * to avoid sending duplicates needed when two
17533 			 * applications in the same zone join the same group on
17534 			 * different logical interfaces: we ignore the ilm if
17535 			 * its zoneid is the same as the last matching one.
17536 			 * In addition, the sending of the packet for
17537 			 * ire_zoneid is delayed until all of the other ilms
17538 			 * have been exhausted.
17539 			 */
17540 			last_zoneid = -1;
17541 			ilm = ilm_walker_start(&ilw, recv_ill);
17542 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17543 				if (ipha->ipha_dst != ilm->ilm_addr ||
17544 				    ilm->ilm_zoneid == last_zoneid ||
17545 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17546 				    ilm->ilm_zoneid == ALL_ZONES ||
17547 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17548 					continue;
17549 				mp1 = ip_copymsg(first_mp);
17550 				if (mp1 == NULL)
17551 					continue;
17552 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17553 				    0, sum, mctl_present, B_TRUE,
17554 				    recv_ill, ilm->ilm_zoneid);
17555 				last_zoneid = ilm->ilm_zoneid;
17556 			}
17557 			ilm_walker_finish(&ilw);
17558 		} else if (ire->ire_type == IRE_BROADCAST) {
17559 			/*
17560 			 * In the broadcast case, there may be many zones
17561 			 * which need a copy of the packet delivered to them.
17562 			 * There is one IRE_BROADCAST per broadcast address
17563 			 * and per zone; we walk those using a helper function.
17564 			 * In addition, the sending of the packet for ire is
17565 			 * delayed until all of the other ires have been
17566 			 * processed.
17567 			 */
17568 			IRB_REFHOLD(ire->ire_bucket);
17569 			ire_zone = NULL;
17570 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17571 			    ire)) != NULL) {
17572 				mp1 = ip_copymsg(first_mp);
17573 				if (mp1 == NULL)
17574 					continue;
17575 
17576 				UPDATE_IB_PKT_COUNT(ire_zone);
17577 				ire_zone->ire_last_used_time = lbolt;
17578 				icmp_inbound(q, mp1, B_TRUE, ill,
17579 				    0, sum, mctl_present, B_TRUE,
17580 				    recv_ill, ire_zone->ire_zoneid);
17581 			}
17582 			IRB_REFRELE(ire->ire_bucket);
17583 		}
17584 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17585 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17586 		    ire->ire_zoneid);
17587 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17588 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17589 		return;
17590 	}
17591 	case IPPROTO_IGMP:
17592 		/*
17593 		 * If we are not willing to accept IGMP packets in clear,
17594 		 * then check with global policy.
17595 		 */
17596 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17597 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17598 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17599 			if (first_mp == NULL)
17600 				return;
17601 		}
17602 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17603 			freemsg(first_mp);
17604 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17605 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17606 			return;
17607 		}
17608 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17609 			/* Bad packet - discarded by igmp_input */
17610 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17611 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17612 			if (mctl_present)
17613 				freeb(first_mp);
17614 			return;
17615 		}
17616 		/*
17617 		 * igmp_input() may have returned the pulled up message.
17618 		 * So first_mp and ipha need to be reinitialized.
17619 		 */
17620 		ipha = (ipha_t *)mp->b_rptr;
17621 		if (mctl_present)
17622 			first_mp->b_cont = mp;
17623 		else
17624 			first_mp = mp;
17625 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17626 		    connf_head != NULL) {
17627 			/* No user-level listener for IGMP packets */
17628 			goto drop_pkt;
17629 		}
17630 		/* deliver to local raw users */
17631 		break;
17632 	case IPPROTO_PIM:
17633 		/*
17634 		 * If we are not willing to accept PIM packets in clear,
17635 		 * then check with global policy.
17636 		 */
17637 		if (ipst->ips_pim_accept_clear_messages == 0) {
17638 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17639 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17640 			if (first_mp == NULL)
17641 				return;
17642 		}
17643 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17644 			freemsg(first_mp);
17645 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17646 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17647 			return;
17648 		}
17649 		if (pim_input(q, mp, ill) != 0) {
17650 			/* Bad packet - discarded by pim_input */
17651 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17652 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17653 			if (mctl_present)
17654 				freeb(first_mp);
17655 			return;
17656 		}
17657 
17658 		/*
17659 		 * pim_input() may have pulled up the message so ipha needs to
17660 		 * be reinitialized.
17661 		 */
17662 		ipha = (ipha_t *)mp->b_rptr;
17663 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17664 		    connf_head != NULL) {
17665 			/* No user-level listener for PIM packets */
17666 			goto drop_pkt;
17667 		}
17668 		/* deliver to local raw users */
17669 		break;
17670 	case IPPROTO_ENCAP:
17671 		/*
17672 		 * Handle self-encapsulated packets (IP-in-IP where
17673 		 * the inner addresses == the outer addresses).
17674 		 */
17675 		hdr_length = IPH_HDR_LENGTH(ipha);
17676 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17677 		    mp->b_wptr) {
17678 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17679 			    sizeof (ipha_t) - mp->b_rptr)) {
17680 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17681 				freemsg(first_mp);
17682 				return;
17683 			}
17684 			ipha = (ipha_t *)mp->b_rptr;
17685 		}
17686 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17687 		/*
17688 		 * Check the sanity of the inner IP header.
17689 		 */
17690 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17691 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17692 			freemsg(first_mp);
17693 			return;
17694 		}
17695 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17696 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17697 			freemsg(first_mp);
17698 			return;
17699 		}
17700 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17701 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17702 			ipsec_in_t *ii;
17703 
17704 			/*
17705 			 * Self-encapsulated tunnel packet. Remove
17706 			 * the outer IP header and fanout again.
17707 			 * We also need to make sure that the inner
17708 			 * header is pulled up until options.
17709 			 */
17710 			mp->b_rptr = (uchar_t *)inner_ipha;
17711 			ipha = inner_ipha;
17712 			hdr_length = IPH_HDR_LENGTH(ipha);
17713 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17714 				if (!pullupmsg(mp, (uchar_t *)ipha +
17715 				    + hdr_length - mp->b_rptr)) {
17716 					freemsg(first_mp);
17717 					return;
17718 				}
17719 				ipha = (ipha_t *)mp->b_rptr;
17720 			}
17721 			if (hdr_length > sizeof (ipha_t)) {
17722 				/* We got options on the inner packet. */
17723 				ipaddr_t dst = ipha->ipha_dst;
17724 
17725 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17726 				    -1) {
17727 					/* Bad options! */
17728 					return;
17729 				}
17730 				if (dst != ipha->ipha_dst) {
17731 					/*
17732 					 * Someone put a source-route in
17733 					 * the inside header of a self-
17734 					 * encapsulated packet.  Drop it
17735 					 * with extreme prejudice and let
17736 					 * the sender know.
17737 					 */
17738 					icmp_unreachable(q, first_mp,
17739 					    ICMP_SOURCE_ROUTE_FAILED,
17740 					    recv_ill->ill_zoneid, ipst);
17741 					return;
17742 				}
17743 			}
17744 			if (!mctl_present) {
17745 				ASSERT(first_mp == mp);
17746 				/*
17747 				 * This means that somebody is sending
17748 				 * Self-encapsualted packets without AH/ESP.
17749 				 * If AH/ESP was present, we would have already
17750 				 * allocated the first_mp.
17751 				 *
17752 				 * Send this packet to find a tunnel endpoint.
17753 				 * if I can't find one, an ICMP
17754 				 * PROTOCOL_UNREACHABLE will get sent.
17755 				 */
17756 				goto fanout;
17757 			}
17758 			/*
17759 			 * We generally store the ill_index if we need to
17760 			 * do IPsec processing as we lose the ill queue when
17761 			 * we come back. But in this case, we never should
17762 			 * have to store the ill_index here as it should have
17763 			 * been stored previously when we processed the
17764 			 * AH/ESP header in this routine or for non-ipsec
17765 			 * cases, we still have the queue. But for some bad
17766 			 * packets from the wire, we can get to IPsec after
17767 			 * this and we better store the index for that case.
17768 			 */
17769 			ill = (ill_t *)q->q_ptr;
17770 			ii = (ipsec_in_t *)first_mp->b_rptr;
17771 			ii->ipsec_in_ill_index =
17772 			    ill->ill_phyint->phyint_ifindex;
17773 			ii->ipsec_in_rill_index =
17774 			    recv_ill->ill_phyint->phyint_ifindex;
17775 			if (ii->ipsec_in_decaps) {
17776 				/*
17777 				 * This packet is self-encapsulated multiple
17778 				 * times. We don't want to recurse infinitely.
17779 				 * To keep it simple, drop the packet.
17780 				 */
17781 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17782 				freemsg(first_mp);
17783 				return;
17784 			}
17785 			ii->ipsec_in_decaps = B_TRUE;
17786 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17787 			    ire);
17788 			return;
17789 		}
17790 		break;
17791 	case IPPROTO_AH:
17792 	case IPPROTO_ESP: {
17793 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17794 
17795 		/*
17796 		 * Fast path for AH/ESP. If this is the first time
17797 		 * we are sending a datagram to AH/ESP, allocate
17798 		 * a IPSEC_IN message and prepend it. Otherwise,
17799 		 * just fanout.
17800 		 */
17801 
17802 		int ipsec_rc;
17803 		ipsec_in_t *ii;
17804 		netstack_t *ns = ipst->ips_netstack;
17805 
17806 		IP_STAT(ipst, ipsec_proto_ahesp);
17807 		if (!mctl_present) {
17808 			ASSERT(first_mp == mp);
17809 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17810 			if (first_mp == NULL) {
17811 				ip1dbg(("ip_proto_input: IPSEC_IN "
17812 				    "allocation failure.\n"));
17813 				freemsg(hada_mp); /* okay ifnull */
17814 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17815 				freemsg(mp);
17816 				return;
17817 			}
17818 			/*
17819 			 * Store the ill_index so that when we come back
17820 			 * from IPsec we ride on the same queue.
17821 			 */
17822 			ill = (ill_t *)q->q_ptr;
17823 			ii = (ipsec_in_t *)first_mp->b_rptr;
17824 			ii->ipsec_in_ill_index =
17825 			    ill->ill_phyint->phyint_ifindex;
17826 			ii->ipsec_in_rill_index =
17827 			    recv_ill->ill_phyint->phyint_ifindex;
17828 			first_mp->b_cont = mp;
17829 			/*
17830 			 * Cache hardware acceleration info.
17831 			 */
17832 			if (hada_mp != NULL) {
17833 				IPSECHW_DEBUG(IPSECHW_PKT,
17834 				    ("ip_rput_local: caching data attr.\n"));
17835 				ii->ipsec_in_accelerated = B_TRUE;
17836 				ii->ipsec_in_da = hada_mp;
17837 				hada_mp = NULL;
17838 			}
17839 		} else {
17840 			ii = (ipsec_in_t *)first_mp->b_rptr;
17841 		}
17842 
17843 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17844 
17845 		if (!ipsec_loaded(ipss)) {
17846 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17847 			    ire->ire_zoneid, ipst);
17848 			return;
17849 		}
17850 
17851 		ns = ipst->ips_netstack;
17852 		/* select inbound SA and have IPsec process the pkt */
17853 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17854 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17855 			boolean_t esp_in_udp_sa;
17856 			if (esph == NULL)
17857 				return;
17858 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17859 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17860 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17861 			    IPSA_F_NATT) != 0);
17862 			/*
17863 			 * The following is a fancy, but quick, way of saying:
17864 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17865 			 *    OR
17866 			 * ESP SA and ESP-in-UDP packet --> drop
17867 			 */
17868 			if (esp_in_udp_sa != esp_in_udp_packet) {
17869 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17870 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17871 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17872 				    &ns->netstack_ipsec->ipsec_dropper);
17873 				return;
17874 			}
17875 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17876 			    first_mp, esph);
17877 		} else {
17878 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17879 			if (ah == NULL)
17880 				return;
17881 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17882 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17883 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17884 			    first_mp, ah);
17885 		}
17886 
17887 		switch (ipsec_rc) {
17888 		case IPSEC_STATUS_SUCCESS:
17889 			break;
17890 		case IPSEC_STATUS_FAILED:
17891 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17892 			/* FALLTHRU */
17893 		case IPSEC_STATUS_PENDING:
17894 			return;
17895 		}
17896 		/* we're done with IPsec processing, send it up */
17897 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17898 		return;
17899 	}
17900 	default:
17901 		break;
17902 	}
17903 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17904 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17905 		    ire->ire_zoneid));
17906 		goto drop_pkt;
17907 	}
17908 	/*
17909 	 * Handle protocols with which IP is less intimate.  There
17910 	 * can be more than one stream bound to a particular
17911 	 * protocol.  When this is the case, each one gets a copy
17912 	 * of any incoming packets.
17913 	 */
17914 fanout:
17915 	ip_fanout_proto(q, first_mp, ill, ipha,
17916 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17917 	    B_TRUE, recv_ill, ire->ire_zoneid);
17918 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17919 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17920 	return;
17921 
17922 drop_pkt:
17923 	freemsg(first_mp);
17924 	if (hada_mp != NULL)
17925 		freeb(hada_mp);
17926 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17927 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17928 #undef	rptr
17929 #undef  iphs
17930 
17931 }
17932 
17933 /*
17934  * Update any source route, record route or timestamp options.
17935  * Check that we are at end of strict source route.
17936  * The options have already been checked for sanity in ip_rput_options().
17937  */
17938 static boolean_t
17939 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17940     ip_stack_t *ipst)
17941 {
17942 	ipoptp_t	opts;
17943 	uchar_t		*opt;
17944 	uint8_t		optval;
17945 	uint8_t		optlen;
17946 	ipaddr_t	dst;
17947 	uint32_t	ts;
17948 	ire_t		*dst_ire;
17949 	timestruc_t	now;
17950 	zoneid_t	zoneid;
17951 	ill_t		*ill;
17952 
17953 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17954 
17955 	ip2dbg(("ip_rput_local_options\n"));
17956 
17957 	for (optval = ipoptp_first(&opts, ipha);
17958 	    optval != IPOPT_EOL;
17959 	    optval = ipoptp_next(&opts)) {
17960 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17961 		opt = opts.ipoptp_cur;
17962 		optlen = opts.ipoptp_len;
17963 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17964 		    optval, optlen));
17965 		switch (optval) {
17966 			uint32_t off;
17967 		case IPOPT_SSRR:
17968 		case IPOPT_LSRR:
17969 			off = opt[IPOPT_OFFSET];
17970 			off--;
17971 			if (optlen < IP_ADDR_LEN ||
17972 			    off > optlen - IP_ADDR_LEN) {
17973 				/* End of source route */
17974 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17975 				break;
17976 			}
17977 			/*
17978 			 * This will only happen if two consecutive entries
17979 			 * in the source route contains our address or if
17980 			 * it is a packet with a loose source route which
17981 			 * reaches us before consuming the whole source route
17982 			 */
17983 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17984 			if (optval == IPOPT_SSRR) {
17985 				goto bad_src_route;
17986 			}
17987 			/*
17988 			 * Hack: instead of dropping the packet truncate the
17989 			 * source route to what has been used by filling the
17990 			 * rest with IPOPT_NOP.
17991 			 */
17992 			opt[IPOPT_OLEN] = (uint8_t)off;
17993 			while (off < optlen) {
17994 				opt[off++] = IPOPT_NOP;
17995 			}
17996 			break;
17997 		case IPOPT_RR:
17998 			off = opt[IPOPT_OFFSET];
17999 			off--;
18000 			if (optlen < IP_ADDR_LEN ||
18001 			    off > optlen - IP_ADDR_LEN) {
18002 				/* No more room - ignore */
18003 				ip1dbg((
18004 				    "ip_rput_local_options: end of RR\n"));
18005 				break;
18006 			}
18007 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18008 			    IP_ADDR_LEN);
18009 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18010 			break;
18011 		case IPOPT_TS:
18012 			/* Insert timestamp if there is romm */
18013 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18014 			case IPOPT_TS_TSONLY:
18015 				off = IPOPT_TS_TIMELEN;
18016 				break;
18017 			case IPOPT_TS_PRESPEC:
18018 			case IPOPT_TS_PRESPEC_RFC791:
18019 				/* Verify that the address matched */
18020 				off = opt[IPOPT_OFFSET] - 1;
18021 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18022 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18023 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18024 				    ipst);
18025 				if (dst_ire == NULL) {
18026 					/* Not for us */
18027 					break;
18028 				}
18029 				ire_refrele(dst_ire);
18030 				/* FALLTHRU */
18031 			case IPOPT_TS_TSANDADDR:
18032 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18033 				break;
18034 			default:
18035 				/*
18036 				 * ip_*put_options should have already
18037 				 * dropped this packet.
18038 				 */
18039 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18040 				    "unknown IT - bug in ip_rput_options?\n");
18041 				return (B_TRUE);	/* Keep "lint" happy */
18042 			}
18043 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18044 				/* Increase overflow counter */
18045 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18046 				opt[IPOPT_POS_OV_FLG] =
18047 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18048 				    (off << 4));
18049 				break;
18050 			}
18051 			off = opt[IPOPT_OFFSET] - 1;
18052 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18053 			case IPOPT_TS_PRESPEC:
18054 			case IPOPT_TS_PRESPEC_RFC791:
18055 			case IPOPT_TS_TSANDADDR:
18056 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18057 				    IP_ADDR_LEN);
18058 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18059 				/* FALLTHRU */
18060 			case IPOPT_TS_TSONLY:
18061 				off = opt[IPOPT_OFFSET] - 1;
18062 				/* Compute # of milliseconds since midnight */
18063 				gethrestime(&now);
18064 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18065 				    now.tv_nsec / (NANOSEC / MILLISEC);
18066 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18067 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18068 				break;
18069 			}
18070 			break;
18071 		}
18072 	}
18073 	return (B_TRUE);
18074 
18075 bad_src_route:
18076 	q = WR(q);
18077 	if (q->q_next != NULL)
18078 		ill = q->q_ptr;
18079 	else
18080 		ill = NULL;
18081 
18082 	/* make sure we clear any indication of a hardware checksum */
18083 	DB_CKSUMFLAGS(mp) = 0;
18084 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18085 	if (zoneid == ALL_ZONES)
18086 		freemsg(mp);
18087 	else
18088 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18089 	return (B_FALSE);
18090 
18091 }
18092 
18093 /*
18094  * Process IP options in an inbound packet.  If an option affects the
18095  * effective destination address, return the next hop address via dstp.
18096  * Returns -1 if something fails in which case an ICMP error has been sent
18097  * and mp freed.
18098  */
18099 static int
18100 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18101     ip_stack_t *ipst)
18102 {
18103 	ipoptp_t	opts;
18104 	uchar_t		*opt;
18105 	uint8_t		optval;
18106 	uint8_t		optlen;
18107 	ipaddr_t	dst;
18108 	intptr_t	code = 0;
18109 	ire_t		*ire = NULL;
18110 	zoneid_t	zoneid;
18111 	ill_t		*ill;
18112 
18113 	ip2dbg(("ip_rput_options\n"));
18114 	dst = ipha->ipha_dst;
18115 	for (optval = ipoptp_first(&opts, ipha);
18116 	    optval != IPOPT_EOL;
18117 	    optval = ipoptp_next(&opts)) {
18118 		opt = opts.ipoptp_cur;
18119 		optlen = opts.ipoptp_len;
18120 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18121 		    optval, optlen));
18122 		/*
18123 		 * Note: we need to verify the checksum before we
18124 		 * modify anything thus this routine only extracts the next
18125 		 * hop dst from any source route.
18126 		 */
18127 		switch (optval) {
18128 			uint32_t off;
18129 		case IPOPT_SSRR:
18130 		case IPOPT_LSRR:
18131 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18132 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18133 			if (ire == NULL) {
18134 				if (optval == IPOPT_SSRR) {
18135 					ip1dbg(("ip_rput_options: not next"
18136 					    " strict source route 0x%x\n",
18137 					    ntohl(dst)));
18138 					code = (char *)&ipha->ipha_dst -
18139 					    (char *)ipha;
18140 					goto param_prob; /* RouterReq's */
18141 				}
18142 				ip2dbg(("ip_rput_options: "
18143 				    "not next source route 0x%x\n",
18144 				    ntohl(dst)));
18145 				break;
18146 			}
18147 			ire_refrele(ire);
18148 
18149 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18150 				ip1dbg((
18151 				    "ip_rput_options: bad option offset\n"));
18152 				code = (char *)&opt[IPOPT_OLEN] -
18153 				    (char *)ipha;
18154 				goto param_prob;
18155 			}
18156 			off = opt[IPOPT_OFFSET];
18157 			off--;
18158 		redo_srr:
18159 			if (optlen < IP_ADDR_LEN ||
18160 			    off > optlen - IP_ADDR_LEN) {
18161 				/* End of source route */
18162 				ip1dbg(("ip_rput_options: end of SR\n"));
18163 				break;
18164 			}
18165 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18166 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18167 			    ntohl(dst)));
18168 
18169 			/*
18170 			 * Check if our address is present more than
18171 			 * once as consecutive hops in source route.
18172 			 * XXX verify per-interface ip_forwarding
18173 			 * for source route?
18174 			 */
18175 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18176 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18177 
18178 			if (ire != NULL) {
18179 				ire_refrele(ire);
18180 				off += IP_ADDR_LEN;
18181 				goto redo_srr;
18182 			}
18183 
18184 			if (dst == htonl(INADDR_LOOPBACK)) {
18185 				ip1dbg(("ip_rput_options: loopback addr in "
18186 				    "source route!\n"));
18187 				goto bad_src_route;
18188 			}
18189 			/*
18190 			 * For strict: verify that dst is directly
18191 			 * reachable.
18192 			 */
18193 			if (optval == IPOPT_SSRR) {
18194 				ire = ire_ftable_lookup(dst, 0, 0,
18195 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18196 				    msg_getlabel(mp),
18197 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18198 				if (ire == NULL) {
18199 					ip1dbg(("ip_rput_options: SSRR not "
18200 					    "directly reachable: 0x%x\n",
18201 					    ntohl(dst)));
18202 					goto bad_src_route;
18203 				}
18204 				ire_refrele(ire);
18205 			}
18206 			/*
18207 			 * Defer update of the offset and the record route
18208 			 * until the packet is forwarded.
18209 			 */
18210 			break;
18211 		case IPOPT_RR:
18212 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18213 				ip1dbg((
18214 				    "ip_rput_options: bad option offset\n"));
18215 				code = (char *)&opt[IPOPT_OLEN] -
18216 				    (char *)ipha;
18217 				goto param_prob;
18218 			}
18219 			break;
18220 		case IPOPT_TS:
18221 			/*
18222 			 * Verify that length >= 5 and that there is either
18223 			 * room for another timestamp or that the overflow
18224 			 * counter is not maxed out.
18225 			 */
18226 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18227 			if (optlen < IPOPT_MINLEN_IT) {
18228 				goto param_prob;
18229 			}
18230 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18231 				ip1dbg((
18232 				    "ip_rput_options: bad option offset\n"));
18233 				code = (char *)&opt[IPOPT_OFFSET] -
18234 				    (char *)ipha;
18235 				goto param_prob;
18236 			}
18237 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18238 			case IPOPT_TS_TSONLY:
18239 				off = IPOPT_TS_TIMELEN;
18240 				break;
18241 			case IPOPT_TS_TSANDADDR:
18242 			case IPOPT_TS_PRESPEC:
18243 			case IPOPT_TS_PRESPEC_RFC791:
18244 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18245 				break;
18246 			default:
18247 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18248 				    (char *)ipha;
18249 				goto param_prob;
18250 			}
18251 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18252 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18253 				/*
18254 				 * No room and the overflow counter is 15
18255 				 * already.
18256 				 */
18257 				goto param_prob;
18258 			}
18259 			break;
18260 		}
18261 	}
18262 
18263 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18264 		*dstp = dst;
18265 		return (0);
18266 	}
18267 
18268 	ip1dbg(("ip_rput_options: error processing IP options."));
18269 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18270 
18271 param_prob:
18272 	q = WR(q);
18273 	if (q->q_next != NULL)
18274 		ill = q->q_ptr;
18275 	else
18276 		ill = NULL;
18277 
18278 	/* make sure we clear any indication of a hardware checksum */
18279 	DB_CKSUMFLAGS(mp) = 0;
18280 	/* Don't know whether this is for non-global or global/forwarding */
18281 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18282 	if (zoneid == ALL_ZONES)
18283 		freemsg(mp);
18284 	else
18285 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18286 	return (-1);
18287 
18288 bad_src_route:
18289 	q = WR(q);
18290 	if (q->q_next != NULL)
18291 		ill = q->q_ptr;
18292 	else
18293 		ill = NULL;
18294 
18295 	/* make sure we clear any indication of a hardware checksum */
18296 	DB_CKSUMFLAGS(mp) = 0;
18297 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18298 	if (zoneid == ALL_ZONES)
18299 		freemsg(mp);
18300 	else
18301 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18302 	return (-1);
18303 }
18304 
18305 /*
18306  * IP & ICMP info in >=14 msg's ...
18307  *  - ip fixed part (mib2_ip_t)
18308  *  - icmp fixed part (mib2_icmp_t)
18309  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18310  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18311  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18312  *  - ipRouteAttributeTable (ip 102)	labeled routes
18313  *  - ip multicast membership (ip_member_t)
18314  *  - ip multicast source filtering (ip_grpsrc_t)
18315  *  - igmp fixed part (struct igmpstat)
18316  *  - multicast routing stats (struct mrtstat)
18317  *  - multicast routing vifs (array of struct vifctl)
18318  *  - multicast routing routes (array of struct mfcctl)
18319  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18320  *					One per ill plus one generic
18321  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18322  *					One per ill plus one generic
18323  *  - ipv6RouteEntry			all IPv6 IREs
18324  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18325  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18326  *  - ipv6AddrEntry			all IPv6 ipifs
18327  *  - ipv6 multicast membership (ipv6_member_t)
18328  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18329  *
18330  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18331  *
18332  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18333  * already filled in by the caller.
18334  * Return value of 0 indicates that no messages were sent and caller
18335  * should free mpctl.
18336  */
18337 int
18338 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18339 {
18340 	ip_stack_t *ipst;
18341 	sctp_stack_t *sctps;
18342 
18343 	if (q->q_next != NULL) {
18344 		ipst = ILLQ_TO_IPST(q);
18345 	} else {
18346 		ipst = CONNQ_TO_IPST(q);
18347 	}
18348 	ASSERT(ipst != NULL);
18349 	sctps = ipst->ips_netstack->netstack_sctp;
18350 
18351 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18352 		return (0);
18353 	}
18354 
18355 	/*
18356 	 * For the purposes of the (broken) packet shell use
18357 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18358 	 * to make TCP and UDP appear first in the list of mib items.
18359 	 * TBD: We could expand this and use it in netstat so that
18360 	 * the kernel doesn't have to produce large tables (connections,
18361 	 * routes, etc) when netstat only wants the statistics or a particular
18362 	 * table.
18363 	 */
18364 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18365 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18366 			return (1);
18367 		}
18368 	}
18369 
18370 	if (level != MIB2_TCP) {
18371 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18372 			return (1);
18373 		}
18374 	}
18375 
18376 	if (level != MIB2_UDP) {
18377 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18378 			return (1);
18379 		}
18380 	}
18381 
18382 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18383 	    ipst)) == NULL) {
18384 		return (1);
18385 	}
18386 
18387 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18388 		return (1);
18389 	}
18390 
18391 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18392 		return (1);
18393 	}
18394 
18395 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18396 		return (1);
18397 	}
18398 
18399 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18400 		return (1);
18401 	}
18402 
18403 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18404 		return (1);
18405 	}
18406 
18407 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18408 		return (1);
18409 	}
18410 
18411 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18412 		return (1);
18413 	}
18414 
18415 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18416 		return (1);
18417 	}
18418 
18419 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18420 		return (1);
18421 	}
18422 
18423 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18424 		return (1);
18425 	}
18426 
18427 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18428 		return (1);
18429 	}
18430 
18431 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18432 		return (1);
18433 	}
18434 
18435 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18436 		return (1);
18437 	}
18438 
18439 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18440 	if (mpctl == NULL)
18441 		return (1);
18442 
18443 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18444 	if (mpctl == NULL)
18445 		return (1);
18446 
18447 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18448 		return (1);
18449 	}
18450 	freemsg(mpctl);
18451 	return (1);
18452 }
18453 
18454 /* Get global (legacy) IPv4 statistics */
18455 static mblk_t *
18456 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18457     ip_stack_t *ipst)
18458 {
18459 	mib2_ip_t		old_ip_mib;
18460 	struct opthdr		*optp;
18461 	mblk_t			*mp2ctl;
18462 
18463 	/*
18464 	 * make a copy of the original message
18465 	 */
18466 	mp2ctl = copymsg(mpctl);
18467 
18468 	/* fixed length IP structure... */
18469 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18470 	optp->level = MIB2_IP;
18471 	optp->name = 0;
18472 	SET_MIB(old_ip_mib.ipForwarding,
18473 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18474 	SET_MIB(old_ip_mib.ipDefaultTTL,
18475 	    (uint32_t)ipst->ips_ip_def_ttl);
18476 	SET_MIB(old_ip_mib.ipReasmTimeout,
18477 	    ipst->ips_ip_g_frag_timeout);
18478 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18479 	    sizeof (mib2_ipAddrEntry_t));
18480 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18481 	    sizeof (mib2_ipRouteEntry_t));
18482 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18483 	    sizeof (mib2_ipNetToMediaEntry_t));
18484 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18485 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18486 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18487 	    sizeof (mib2_ipAttributeEntry_t));
18488 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18489 
18490 	/*
18491 	 * Grab the statistics from the new IP MIB
18492 	 */
18493 	SET_MIB(old_ip_mib.ipInReceives,
18494 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18495 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18496 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18497 	SET_MIB(old_ip_mib.ipForwDatagrams,
18498 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18499 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18500 	    ipmib->ipIfStatsInUnknownProtos);
18501 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18502 	SET_MIB(old_ip_mib.ipInDelivers,
18503 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18504 	SET_MIB(old_ip_mib.ipOutRequests,
18505 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18506 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18507 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18508 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18509 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18510 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18511 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18512 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18513 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18514 
18515 	/* ipRoutingDiscards is not being used */
18516 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18517 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18518 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18519 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18520 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18521 	    ipmib->ipIfStatsReasmDuplicates);
18522 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18523 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18524 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18525 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18526 	SET_MIB(old_ip_mib.rawipInOverflows,
18527 	    ipmib->rawipIfStatsInOverflows);
18528 
18529 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18530 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18531 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18532 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18533 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18534 	    ipmib->ipIfStatsOutSwitchIPVersion);
18535 
18536 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18537 	    (int)sizeof (old_ip_mib))) {
18538 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18539 		    (uint_t)sizeof (old_ip_mib)));
18540 	}
18541 
18542 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18543 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18544 	    (int)optp->level, (int)optp->name, (int)optp->len));
18545 	qreply(q, mpctl);
18546 	return (mp2ctl);
18547 }
18548 
18549 /* Per interface IPv4 statistics */
18550 static mblk_t *
18551 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18552 {
18553 	struct opthdr		*optp;
18554 	mblk_t			*mp2ctl;
18555 	ill_t			*ill;
18556 	ill_walk_context_t	ctx;
18557 	mblk_t			*mp_tail = NULL;
18558 	mib2_ipIfStatsEntry_t	global_ip_mib;
18559 
18560 	/*
18561 	 * Make a copy of the original message
18562 	 */
18563 	mp2ctl = copymsg(mpctl);
18564 
18565 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18566 	optp->level = MIB2_IP;
18567 	optp->name = MIB2_IP_TRAFFIC_STATS;
18568 	/* Include "unknown interface" ip_mib */
18569 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18570 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18571 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18572 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18573 	    (ipst->ips_ip_g_forward ? 1 : 2));
18574 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18575 	    (uint32_t)ipst->ips_ip_def_ttl);
18576 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18577 	    sizeof (mib2_ipIfStatsEntry_t));
18578 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18579 	    sizeof (mib2_ipAddrEntry_t));
18580 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18581 	    sizeof (mib2_ipRouteEntry_t));
18582 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18583 	    sizeof (mib2_ipNetToMediaEntry_t));
18584 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18585 	    sizeof (ip_member_t));
18586 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18587 	    sizeof (ip_grpsrc_t));
18588 
18589 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18590 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18591 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18592 		    "failed to allocate %u bytes\n",
18593 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18594 	}
18595 
18596 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18597 
18598 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18599 	ill = ILL_START_WALK_V4(&ctx, ipst);
18600 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18601 		ill->ill_ip_mib->ipIfStatsIfIndex =
18602 		    ill->ill_phyint->phyint_ifindex;
18603 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18604 		    (ipst->ips_ip_g_forward ? 1 : 2));
18605 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18606 		    (uint32_t)ipst->ips_ip_def_ttl);
18607 
18608 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18609 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18610 		    (char *)ill->ill_ip_mib,
18611 		    (int)sizeof (*ill->ill_ip_mib))) {
18612 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18613 			    "failed to allocate %u bytes\n",
18614 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18615 		}
18616 	}
18617 	rw_exit(&ipst->ips_ill_g_lock);
18618 
18619 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18620 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18621 	    "level %d, name %d, len %d\n",
18622 	    (int)optp->level, (int)optp->name, (int)optp->len));
18623 	qreply(q, mpctl);
18624 
18625 	if (mp2ctl == NULL)
18626 		return (NULL);
18627 
18628 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18629 }
18630 
18631 /* Global IPv4 ICMP statistics */
18632 static mblk_t *
18633 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18634 {
18635 	struct opthdr		*optp;
18636 	mblk_t			*mp2ctl;
18637 
18638 	/*
18639 	 * Make a copy of the original message
18640 	 */
18641 	mp2ctl = copymsg(mpctl);
18642 
18643 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18644 	optp->level = MIB2_ICMP;
18645 	optp->name = 0;
18646 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18647 	    (int)sizeof (ipst->ips_icmp_mib))) {
18648 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18649 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18650 	}
18651 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18652 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18653 	    (int)optp->level, (int)optp->name, (int)optp->len));
18654 	qreply(q, mpctl);
18655 	return (mp2ctl);
18656 }
18657 
18658 /* Global IPv4 IGMP statistics */
18659 static mblk_t *
18660 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18661 {
18662 	struct opthdr		*optp;
18663 	mblk_t			*mp2ctl;
18664 
18665 	/*
18666 	 * make a copy of the original message
18667 	 */
18668 	mp2ctl = copymsg(mpctl);
18669 
18670 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18671 	optp->level = EXPER_IGMP;
18672 	optp->name = 0;
18673 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18674 	    (int)sizeof (ipst->ips_igmpstat))) {
18675 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18676 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18677 	}
18678 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18679 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18680 	    (int)optp->level, (int)optp->name, (int)optp->len));
18681 	qreply(q, mpctl);
18682 	return (mp2ctl);
18683 }
18684 
18685 /* Global IPv4 Multicast Routing statistics */
18686 static mblk_t *
18687 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18688 {
18689 	struct opthdr		*optp;
18690 	mblk_t			*mp2ctl;
18691 
18692 	/*
18693 	 * make a copy of the original message
18694 	 */
18695 	mp2ctl = copymsg(mpctl);
18696 
18697 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18698 	optp->level = EXPER_DVMRP;
18699 	optp->name = 0;
18700 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18701 		ip0dbg(("ip_mroute_stats: failed\n"));
18702 	}
18703 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18704 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18705 	    (int)optp->level, (int)optp->name, (int)optp->len));
18706 	qreply(q, mpctl);
18707 	return (mp2ctl);
18708 }
18709 
18710 /* IPv4 address information */
18711 static mblk_t *
18712 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18713 {
18714 	struct opthdr		*optp;
18715 	mblk_t			*mp2ctl;
18716 	mblk_t			*mp_tail = NULL;
18717 	ill_t			*ill;
18718 	ipif_t			*ipif;
18719 	uint_t			bitval;
18720 	mib2_ipAddrEntry_t	mae;
18721 	zoneid_t		zoneid;
18722 	ill_walk_context_t ctx;
18723 
18724 	/*
18725 	 * make a copy of the original message
18726 	 */
18727 	mp2ctl = copymsg(mpctl);
18728 
18729 	/* ipAddrEntryTable */
18730 
18731 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18732 	optp->level = MIB2_IP;
18733 	optp->name = MIB2_IP_ADDR;
18734 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18735 
18736 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18737 	ill = ILL_START_WALK_V4(&ctx, ipst);
18738 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18739 		for (ipif = ill->ill_ipif; ipif != NULL;
18740 		    ipif = ipif->ipif_next) {
18741 			if (ipif->ipif_zoneid != zoneid &&
18742 			    ipif->ipif_zoneid != ALL_ZONES)
18743 				continue;
18744 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18745 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18746 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18747 
18748 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18749 			    OCTET_LENGTH);
18750 			mae.ipAdEntIfIndex.o_length =
18751 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18752 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18753 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18754 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18755 			mae.ipAdEntInfo.ae_subnet_len =
18756 			    ip_mask_to_plen(ipif->ipif_net_mask);
18757 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18758 			for (bitval = 1;
18759 			    bitval &&
18760 			    !(bitval & ipif->ipif_brd_addr);
18761 			    bitval <<= 1)
18762 				noop;
18763 			mae.ipAdEntBcastAddr = bitval;
18764 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18765 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18766 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18767 			mae.ipAdEntInfo.ae_broadcast_addr =
18768 			    ipif->ipif_brd_addr;
18769 			mae.ipAdEntInfo.ae_pp_dst_addr =
18770 			    ipif->ipif_pp_dst_addr;
18771 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18772 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18773 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18774 
18775 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18776 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18777 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18778 				    "allocate %u bytes\n",
18779 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18780 			}
18781 		}
18782 	}
18783 	rw_exit(&ipst->ips_ill_g_lock);
18784 
18785 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18786 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18787 	    (int)optp->level, (int)optp->name, (int)optp->len));
18788 	qreply(q, mpctl);
18789 	return (mp2ctl);
18790 }
18791 
18792 /* IPv6 address information */
18793 static mblk_t *
18794 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18795 {
18796 	struct opthdr		*optp;
18797 	mblk_t			*mp2ctl;
18798 	mblk_t			*mp_tail = NULL;
18799 	ill_t			*ill;
18800 	ipif_t			*ipif;
18801 	mib2_ipv6AddrEntry_t	mae6;
18802 	zoneid_t		zoneid;
18803 	ill_walk_context_t	ctx;
18804 
18805 	/*
18806 	 * make a copy of the original message
18807 	 */
18808 	mp2ctl = copymsg(mpctl);
18809 
18810 	/* ipv6AddrEntryTable */
18811 
18812 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18813 	optp->level = MIB2_IP6;
18814 	optp->name = MIB2_IP6_ADDR;
18815 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18816 
18817 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18818 	ill = ILL_START_WALK_V6(&ctx, ipst);
18819 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18820 		for (ipif = ill->ill_ipif; ipif != NULL;
18821 		    ipif = ipif->ipif_next) {
18822 			if (ipif->ipif_zoneid != zoneid &&
18823 			    ipif->ipif_zoneid != ALL_ZONES)
18824 				continue;
18825 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18826 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18827 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18828 
18829 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18830 			    OCTET_LENGTH);
18831 			mae6.ipv6AddrIfIndex.o_length =
18832 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18833 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18834 			mae6.ipv6AddrPfxLength =
18835 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18836 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18837 			mae6.ipv6AddrInfo.ae_subnet_len =
18838 			    mae6.ipv6AddrPfxLength;
18839 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18840 
18841 			/* Type: stateless(1), stateful(2), unknown(3) */
18842 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18843 				mae6.ipv6AddrType = 1;
18844 			else
18845 				mae6.ipv6AddrType = 2;
18846 			/* Anycast: true(1), false(2) */
18847 			if (ipif->ipif_flags & IPIF_ANYCAST)
18848 				mae6.ipv6AddrAnycastFlag = 1;
18849 			else
18850 				mae6.ipv6AddrAnycastFlag = 2;
18851 
18852 			/*
18853 			 * Address status: preferred(1), deprecated(2),
18854 			 * invalid(3), inaccessible(4), unknown(5)
18855 			 */
18856 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18857 				mae6.ipv6AddrStatus = 3;
18858 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18859 				mae6.ipv6AddrStatus = 2;
18860 			else
18861 				mae6.ipv6AddrStatus = 1;
18862 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18863 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18864 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18865 			    ipif->ipif_v6pp_dst_addr;
18866 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18867 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18868 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18869 			mae6.ipv6AddrIdentifier = ill->ill_token;
18870 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18871 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18872 			mae6.ipv6AddrRetransmitTime =
18873 			    ill->ill_reachable_retrans_time;
18874 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18875 			    (char *)&mae6,
18876 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18877 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18878 				    "allocate %u bytes\n",
18879 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18880 			}
18881 		}
18882 	}
18883 	rw_exit(&ipst->ips_ill_g_lock);
18884 
18885 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18886 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18887 	    (int)optp->level, (int)optp->name, (int)optp->len));
18888 	qreply(q, mpctl);
18889 	return (mp2ctl);
18890 }
18891 
18892 /* IPv4 multicast group membership. */
18893 static mblk_t *
18894 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18895 {
18896 	struct opthdr		*optp;
18897 	mblk_t			*mp2ctl;
18898 	ill_t			*ill;
18899 	ipif_t			*ipif;
18900 	ilm_t			*ilm;
18901 	ip_member_t		ipm;
18902 	mblk_t			*mp_tail = NULL;
18903 	ill_walk_context_t	ctx;
18904 	zoneid_t		zoneid;
18905 	ilm_walker_t		ilw;
18906 
18907 	/*
18908 	 * make a copy of the original message
18909 	 */
18910 	mp2ctl = copymsg(mpctl);
18911 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18912 
18913 	/* ipGroupMember table */
18914 	optp = (struct opthdr *)&mpctl->b_rptr[
18915 	    sizeof (struct T_optmgmt_ack)];
18916 	optp->level = MIB2_IP;
18917 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18918 
18919 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18920 	ill = ILL_START_WALK_V4(&ctx, ipst);
18921 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18922 		if (IS_UNDER_IPMP(ill))
18923 			continue;
18924 
18925 		ilm = ilm_walker_start(&ilw, ill);
18926 		for (ipif = ill->ill_ipif; ipif != NULL;
18927 		    ipif = ipif->ipif_next) {
18928 			if (ipif->ipif_zoneid != zoneid &&
18929 			    ipif->ipif_zoneid != ALL_ZONES)
18930 				continue;	/* not this zone */
18931 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18932 			    OCTET_LENGTH);
18933 			ipm.ipGroupMemberIfIndex.o_length =
18934 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18935 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18936 				ASSERT(ilm->ilm_ipif != NULL);
18937 				ASSERT(ilm->ilm_ill == NULL);
18938 				if (ilm->ilm_ipif != ipif)
18939 					continue;
18940 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18941 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18942 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18943 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18944 				    (char *)&ipm, (int)sizeof (ipm))) {
18945 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18946 					    "failed to allocate %u bytes\n",
18947 					    (uint_t)sizeof (ipm)));
18948 				}
18949 			}
18950 		}
18951 		ilm_walker_finish(&ilw);
18952 	}
18953 	rw_exit(&ipst->ips_ill_g_lock);
18954 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18955 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18956 	    (int)optp->level, (int)optp->name, (int)optp->len));
18957 	qreply(q, mpctl);
18958 	return (mp2ctl);
18959 }
18960 
18961 /* IPv6 multicast group membership. */
18962 static mblk_t *
18963 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18964 {
18965 	struct opthdr		*optp;
18966 	mblk_t			*mp2ctl;
18967 	ill_t			*ill;
18968 	ilm_t			*ilm;
18969 	ipv6_member_t		ipm6;
18970 	mblk_t			*mp_tail = NULL;
18971 	ill_walk_context_t	ctx;
18972 	zoneid_t		zoneid;
18973 	ilm_walker_t		ilw;
18974 
18975 	/*
18976 	 * make a copy of the original message
18977 	 */
18978 	mp2ctl = copymsg(mpctl);
18979 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18980 
18981 	/* ip6GroupMember table */
18982 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18983 	optp->level = MIB2_IP6;
18984 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18985 
18986 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18987 	ill = ILL_START_WALK_V6(&ctx, ipst);
18988 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18989 		if (IS_UNDER_IPMP(ill))
18990 			continue;
18991 
18992 		ilm = ilm_walker_start(&ilw, ill);
18993 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18994 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18995 			ASSERT(ilm->ilm_ipif == NULL);
18996 			ASSERT(ilm->ilm_ill != NULL);
18997 			if (ilm->ilm_zoneid != zoneid)
18998 				continue;	/* not this zone */
18999 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19000 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19001 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19002 			if (!snmp_append_data2(mpctl->b_cont,
19003 			    &mp_tail,
19004 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19005 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19006 				    "failed to allocate %u bytes\n",
19007 				    (uint_t)sizeof (ipm6)));
19008 			}
19009 		}
19010 		ilm_walker_finish(&ilw);
19011 	}
19012 	rw_exit(&ipst->ips_ill_g_lock);
19013 
19014 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19015 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19016 	    (int)optp->level, (int)optp->name, (int)optp->len));
19017 	qreply(q, mpctl);
19018 	return (mp2ctl);
19019 }
19020 
19021 /* IP multicast filtered sources */
19022 static mblk_t *
19023 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19024 {
19025 	struct opthdr		*optp;
19026 	mblk_t			*mp2ctl;
19027 	ill_t			*ill;
19028 	ipif_t			*ipif;
19029 	ilm_t			*ilm;
19030 	ip_grpsrc_t		ips;
19031 	mblk_t			*mp_tail = NULL;
19032 	ill_walk_context_t	ctx;
19033 	zoneid_t		zoneid;
19034 	int			i;
19035 	slist_t			*sl;
19036 	ilm_walker_t		ilw;
19037 
19038 	/*
19039 	 * make a copy of the original message
19040 	 */
19041 	mp2ctl = copymsg(mpctl);
19042 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19043 
19044 	/* ipGroupSource table */
19045 	optp = (struct opthdr *)&mpctl->b_rptr[
19046 	    sizeof (struct T_optmgmt_ack)];
19047 	optp->level = MIB2_IP;
19048 	optp->name = EXPER_IP_GROUP_SOURCES;
19049 
19050 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19051 	ill = ILL_START_WALK_V4(&ctx, ipst);
19052 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19053 		if (IS_UNDER_IPMP(ill))
19054 			continue;
19055 
19056 		ilm = ilm_walker_start(&ilw, ill);
19057 		for (ipif = ill->ill_ipif; ipif != NULL;
19058 		    ipif = ipif->ipif_next) {
19059 			if (ipif->ipif_zoneid != zoneid)
19060 				continue;	/* not this zone */
19061 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19062 			    OCTET_LENGTH);
19063 			ips.ipGroupSourceIfIndex.o_length =
19064 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19065 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19066 				ASSERT(ilm->ilm_ipif != NULL);
19067 				ASSERT(ilm->ilm_ill == NULL);
19068 				sl = ilm->ilm_filter;
19069 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19070 					continue;
19071 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19072 				for (i = 0; i < sl->sl_numsrc; i++) {
19073 					if (!IN6_IS_ADDR_V4MAPPED(
19074 					    &sl->sl_addr[i]))
19075 						continue;
19076 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19077 					    ips.ipGroupSourceAddress);
19078 					if (snmp_append_data2(mpctl->b_cont,
19079 					    &mp_tail, (char *)&ips,
19080 					    (int)sizeof (ips)) == 0) {
19081 						ip1dbg(("ip_snmp_get_mib2_"
19082 						    "ip_group_src: failed to "
19083 						    "allocate %u bytes\n",
19084 						    (uint_t)sizeof (ips)));
19085 					}
19086 				}
19087 			}
19088 		}
19089 		ilm_walker_finish(&ilw);
19090 	}
19091 	rw_exit(&ipst->ips_ill_g_lock);
19092 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19093 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19094 	    (int)optp->level, (int)optp->name, (int)optp->len));
19095 	qreply(q, mpctl);
19096 	return (mp2ctl);
19097 }
19098 
19099 /* IPv6 multicast filtered sources. */
19100 static mblk_t *
19101 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19102 {
19103 	struct opthdr		*optp;
19104 	mblk_t			*mp2ctl;
19105 	ill_t			*ill;
19106 	ilm_t			*ilm;
19107 	ipv6_grpsrc_t		ips6;
19108 	mblk_t			*mp_tail = NULL;
19109 	ill_walk_context_t	ctx;
19110 	zoneid_t		zoneid;
19111 	int			i;
19112 	slist_t			*sl;
19113 	ilm_walker_t		ilw;
19114 
19115 	/*
19116 	 * make a copy of the original message
19117 	 */
19118 	mp2ctl = copymsg(mpctl);
19119 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19120 
19121 	/* ip6GroupMember table */
19122 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19123 	optp->level = MIB2_IP6;
19124 	optp->name = EXPER_IP6_GROUP_SOURCES;
19125 
19126 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19127 	ill = ILL_START_WALK_V6(&ctx, ipst);
19128 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19129 		if (IS_UNDER_IPMP(ill))
19130 			continue;
19131 
19132 		ilm = ilm_walker_start(&ilw, ill);
19133 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19134 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19135 			ASSERT(ilm->ilm_ipif == NULL);
19136 			ASSERT(ilm->ilm_ill != NULL);
19137 			sl = ilm->ilm_filter;
19138 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19139 				continue;
19140 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19141 			for (i = 0; i < sl->sl_numsrc; i++) {
19142 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19143 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19144 				    (char *)&ips6, (int)sizeof (ips6))) {
19145 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19146 					    "group_src: failed to allocate "
19147 					    "%u bytes\n",
19148 					    (uint_t)sizeof (ips6)));
19149 				}
19150 			}
19151 		}
19152 		ilm_walker_finish(&ilw);
19153 	}
19154 	rw_exit(&ipst->ips_ill_g_lock);
19155 
19156 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19157 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19158 	    (int)optp->level, (int)optp->name, (int)optp->len));
19159 	qreply(q, mpctl);
19160 	return (mp2ctl);
19161 }
19162 
19163 /* Multicast routing virtual interface table. */
19164 static mblk_t *
19165 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19166 {
19167 	struct opthdr		*optp;
19168 	mblk_t			*mp2ctl;
19169 
19170 	/*
19171 	 * make a copy of the original message
19172 	 */
19173 	mp2ctl = copymsg(mpctl);
19174 
19175 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19176 	optp->level = EXPER_DVMRP;
19177 	optp->name = EXPER_DVMRP_VIF;
19178 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19179 		ip0dbg(("ip_mroute_vif: failed\n"));
19180 	}
19181 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19182 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19183 	    (int)optp->level, (int)optp->name, (int)optp->len));
19184 	qreply(q, mpctl);
19185 	return (mp2ctl);
19186 }
19187 
19188 /* Multicast routing table. */
19189 static mblk_t *
19190 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19191 {
19192 	struct opthdr		*optp;
19193 	mblk_t			*mp2ctl;
19194 
19195 	/*
19196 	 * make a copy of the original message
19197 	 */
19198 	mp2ctl = copymsg(mpctl);
19199 
19200 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19201 	optp->level = EXPER_DVMRP;
19202 	optp->name = EXPER_DVMRP_MRT;
19203 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19204 		ip0dbg(("ip_mroute_mrt: failed\n"));
19205 	}
19206 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19207 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19208 	    (int)optp->level, (int)optp->name, (int)optp->len));
19209 	qreply(q, mpctl);
19210 	return (mp2ctl);
19211 }
19212 
19213 /*
19214  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19215  * in one IRE walk.
19216  */
19217 static mblk_t *
19218 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19219     ip_stack_t *ipst)
19220 {
19221 	struct opthdr	*optp;
19222 	mblk_t		*mp2ctl;	/* Returned */
19223 	mblk_t		*mp3ctl;	/* nettomedia */
19224 	mblk_t		*mp4ctl;	/* routeattrs */
19225 	iproutedata_t	ird;
19226 	zoneid_t	zoneid;
19227 
19228 	/*
19229 	 * make copies of the original message
19230 	 *	- mp2ctl is returned unchanged to the caller for his use
19231 	 *	- mpctl is sent upstream as ipRouteEntryTable
19232 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19233 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19234 	 */
19235 	mp2ctl = copymsg(mpctl);
19236 	mp3ctl = copymsg(mpctl);
19237 	mp4ctl = copymsg(mpctl);
19238 	if (mp3ctl == NULL || mp4ctl == NULL) {
19239 		freemsg(mp4ctl);
19240 		freemsg(mp3ctl);
19241 		freemsg(mp2ctl);
19242 		freemsg(mpctl);
19243 		return (NULL);
19244 	}
19245 
19246 	bzero(&ird, sizeof (ird));
19247 
19248 	ird.ird_route.lp_head = mpctl->b_cont;
19249 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19250 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19251 	/*
19252 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19253 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19254 	 * intended a temporary solution until a proper MIB API is provided
19255 	 * that provides complete filtering/caller-opt-in.
19256 	 */
19257 	if (level == EXPER_IP_AND_TESTHIDDEN)
19258 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19259 
19260 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19261 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19262 
19263 	/* ipRouteEntryTable in mpctl */
19264 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19265 	optp->level = MIB2_IP;
19266 	optp->name = MIB2_IP_ROUTE;
19267 	optp->len = msgdsize(ird.ird_route.lp_head);
19268 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19269 	    (int)optp->level, (int)optp->name, (int)optp->len));
19270 	qreply(q, mpctl);
19271 
19272 	/* ipNetToMediaEntryTable in mp3ctl */
19273 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19274 	optp->level = MIB2_IP;
19275 	optp->name = MIB2_IP_MEDIA;
19276 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19277 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19278 	    (int)optp->level, (int)optp->name, (int)optp->len));
19279 	qreply(q, mp3ctl);
19280 
19281 	/* ipRouteAttributeTable in mp4ctl */
19282 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19283 	optp->level = MIB2_IP;
19284 	optp->name = EXPER_IP_RTATTR;
19285 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19286 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19287 	    (int)optp->level, (int)optp->name, (int)optp->len));
19288 	if (optp->len == 0)
19289 		freemsg(mp4ctl);
19290 	else
19291 		qreply(q, mp4ctl);
19292 
19293 	return (mp2ctl);
19294 }
19295 
19296 /*
19297  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19298  * ipv6NetToMediaEntryTable in an NDP walk.
19299  */
19300 static mblk_t *
19301 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19302     ip_stack_t *ipst)
19303 {
19304 	struct opthdr	*optp;
19305 	mblk_t		*mp2ctl;	/* Returned */
19306 	mblk_t		*mp3ctl;	/* nettomedia */
19307 	mblk_t		*mp4ctl;	/* routeattrs */
19308 	iproutedata_t	ird;
19309 	zoneid_t	zoneid;
19310 
19311 	/*
19312 	 * make copies of the original message
19313 	 *	- mp2ctl is returned unchanged to the caller for his use
19314 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19315 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19316 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19317 	 */
19318 	mp2ctl = copymsg(mpctl);
19319 	mp3ctl = copymsg(mpctl);
19320 	mp4ctl = copymsg(mpctl);
19321 	if (mp3ctl == NULL || mp4ctl == NULL) {
19322 		freemsg(mp4ctl);
19323 		freemsg(mp3ctl);
19324 		freemsg(mp2ctl);
19325 		freemsg(mpctl);
19326 		return (NULL);
19327 	}
19328 
19329 	bzero(&ird, sizeof (ird));
19330 
19331 	ird.ird_route.lp_head = mpctl->b_cont;
19332 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19333 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19334 	/*
19335 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19336 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19337 	 * intended a temporary solution until a proper MIB API is provided
19338 	 * that provides complete filtering/caller-opt-in.
19339 	 */
19340 	if (level == EXPER_IP_AND_TESTHIDDEN)
19341 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19342 
19343 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19344 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19345 
19346 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19347 	optp->level = MIB2_IP6;
19348 	optp->name = MIB2_IP6_ROUTE;
19349 	optp->len = msgdsize(ird.ird_route.lp_head);
19350 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19351 	    (int)optp->level, (int)optp->name, (int)optp->len));
19352 	qreply(q, mpctl);
19353 
19354 	/* ipv6NetToMediaEntryTable in mp3ctl */
19355 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19356 
19357 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19358 	optp->level = MIB2_IP6;
19359 	optp->name = MIB2_IP6_MEDIA;
19360 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19361 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19362 	    (int)optp->level, (int)optp->name, (int)optp->len));
19363 	qreply(q, mp3ctl);
19364 
19365 	/* ipv6RouteAttributeTable in mp4ctl */
19366 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19367 	optp->level = MIB2_IP6;
19368 	optp->name = EXPER_IP_RTATTR;
19369 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19370 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19371 	    (int)optp->level, (int)optp->name, (int)optp->len));
19372 	if (optp->len == 0)
19373 		freemsg(mp4ctl);
19374 	else
19375 		qreply(q, mp4ctl);
19376 
19377 	return (mp2ctl);
19378 }
19379 
19380 /*
19381  * IPv6 mib: One per ill
19382  */
19383 static mblk_t *
19384 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19385 {
19386 	struct opthdr		*optp;
19387 	mblk_t			*mp2ctl;
19388 	ill_t			*ill;
19389 	ill_walk_context_t	ctx;
19390 	mblk_t			*mp_tail = NULL;
19391 
19392 	/*
19393 	 * Make a copy of the original message
19394 	 */
19395 	mp2ctl = copymsg(mpctl);
19396 
19397 	/* fixed length IPv6 structure ... */
19398 
19399 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19400 	optp->level = MIB2_IP6;
19401 	optp->name = 0;
19402 	/* Include "unknown interface" ip6_mib */
19403 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19404 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19405 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19406 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19407 	    ipst->ips_ipv6_forward ? 1 : 2);
19408 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19409 	    ipst->ips_ipv6_def_hops);
19410 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19411 	    sizeof (mib2_ipIfStatsEntry_t));
19412 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19413 	    sizeof (mib2_ipv6AddrEntry_t));
19414 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19415 	    sizeof (mib2_ipv6RouteEntry_t));
19416 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19417 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19418 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19419 	    sizeof (ipv6_member_t));
19420 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19421 	    sizeof (ipv6_grpsrc_t));
19422 
19423 	/*
19424 	 * Synchronize 64- and 32-bit counters
19425 	 */
19426 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19427 	    ipIfStatsHCInReceives);
19428 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19429 	    ipIfStatsHCInDelivers);
19430 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19431 	    ipIfStatsHCOutRequests);
19432 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19433 	    ipIfStatsHCOutForwDatagrams);
19434 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19435 	    ipIfStatsHCOutMcastPkts);
19436 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19437 	    ipIfStatsHCInMcastPkts);
19438 
19439 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19440 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19441 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19442 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19443 	}
19444 
19445 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19446 	ill = ILL_START_WALK_V6(&ctx, ipst);
19447 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19448 		ill->ill_ip_mib->ipIfStatsIfIndex =
19449 		    ill->ill_phyint->phyint_ifindex;
19450 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19451 		    ipst->ips_ipv6_forward ? 1 : 2);
19452 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19453 		    ill->ill_max_hops);
19454 
19455 		/*
19456 		 * Synchronize 64- and 32-bit counters
19457 		 */
19458 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19459 		    ipIfStatsHCInReceives);
19460 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19461 		    ipIfStatsHCInDelivers);
19462 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19463 		    ipIfStatsHCOutRequests);
19464 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19465 		    ipIfStatsHCOutForwDatagrams);
19466 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19467 		    ipIfStatsHCOutMcastPkts);
19468 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19469 		    ipIfStatsHCInMcastPkts);
19470 
19471 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19472 		    (char *)ill->ill_ip_mib,
19473 		    (int)sizeof (*ill->ill_ip_mib))) {
19474 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19475 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19476 		}
19477 	}
19478 	rw_exit(&ipst->ips_ill_g_lock);
19479 
19480 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19481 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19482 	    (int)optp->level, (int)optp->name, (int)optp->len));
19483 	qreply(q, mpctl);
19484 	return (mp2ctl);
19485 }
19486 
19487 /*
19488  * ICMPv6 mib: One per ill
19489  */
19490 static mblk_t *
19491 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19492 {
19493 	struct opthdr		*optp;
19494 	mblk_t			*mp2ctl;
19495 	ill_t			*ill;
19496 	ill_walk_context_t	ctx;
19497 	mblk_t			*mp_tail = NULL;
19498 	/*
19499 	 * Make a copy of the original message
19500 	 */
19501 	mp2ctl = copymsg(mpctl);
19502 
19503 	/* fixed length ICMPv6 structure ... */
19504 
19505 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19506 	optp->level = MIB2_ICMP6;
19507 	optp->name = 0;
19508 	/* Include "unknown interface" icmp6_mib */
19509 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19510 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19511 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19512 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19513 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19514 	    (char *)&ipst->ips_icmp6_mib,
19515 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19516 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19517 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19518 	}
19519 
19520 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19521 	ill = ILL_START_WALK_V6(&ctx, ipst);
19522 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19523 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19524 		    ill->ill_phyint->phyint_ifindex;
19525 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19526 		    (char *)ill->ill_icmp6_mib,
19527 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19528 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19529 			    "%u bytes\n",
19530 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19531 		}
19532 	}
19533 	rw_exit(&ipst->ips_ill_g_lock);
19534 
19535 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19536 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19537 	    (int)optp->level, (int)optp->name, (int)optp->len));
19538 	qreply(q, mpctl);
19539 	return (mp2ctl);
19540 }
19541 
19542 /*
19543  * ire_walk routine to create both ipRouteEntryTable and
19544  * ipRouteAttributeTable in one IRE walk
19545  */
19546 static void
19547 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19548 {
19549 	ill_t				*ill;
19550 	ipif_t				*ipif;
19551 	mib2_ipRouteEntry_t		*re;
19552 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19553 	ipaddr_t			gw_addr;
19554 	tsol_ire_gw_secattr_t		*attrp;
19555 	tsol_gc_t			*gc = NULL;
19556 	tsol_gcgrp_t			*gcgrp = NULL;
19557 	uint_t				sacnt = 0;
19558 	int				i;
19559 
19560 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19561 
19562 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19563 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19564 		return;
19565 	}
19566 
19567 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19568 		return;
19569 
19570 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19571 		mutex_enter(&attrp->igsa_lock);
19572 		if ((gc = attrp->igsa_gc) != NULL) {
19573 			gcgrp = gc->gc_grp;
19574 			ASSERT(gcgrp != NULL);
19575 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19576 			sacnt = 1;
19577 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19578 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19579 			gc = gcgrp->gcgrp_head;
19580 			sacnt = gcgrp->gcgrp_count;
19581 		}
19582 		mutex_exit(&attrp->igsa_lock);
19583 
19584 		/* do nothing if there's no gc to report */
19585 		if (gc == NULL) {
19586 			ASSERT(sacnt == 0);
19587 			if (gcgrp != NULL) {
19588 				/* we might as well drop the lock now */
19589 				rw_exit(&gcgrp->gcgrp_rwlock);
19590 				gcgrp = NULL;
19591 			}
19592 			attrp = NULL;
19593 		}
19594 
19595 		ASSERT(gc == NULL || (gcgrp != NULL &&
19596 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19597 	}
19598 	ASSERT(sacnt == 0 || gc != NULL);
19599 
19600 	if (sacnt != 0 &&
19601 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19602 		kmem_free(re, sizeof (*re));
19603 		rw_exit(&gcgrp->gcgrp_rwlock);
19604 		return;
19605 	}
19606 
19607 	/*
19608 	 * Return all IRE types for route table... let caller pick and choose
19609 	 */
19610 	re->ipRouteDest = ire->ire_addr;
19611 	ipif = ire->ire_ipif;
19612 	re->ipRouteIfIndex.o_length = 0;
19613 	if (ire->ire_type == IRE_CACHE) {
19614 		ill = (ill_t *)ire->ire_stq->q_ptr;
19615 		re->ipRouteIfIndex.o_length =
19616 		    ill->ill_name_length == 0 ? 0 :
19617 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19618 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19619 		    re->ipRouteIfIndex.o_length);
19620 	} else if (ipif != NULL) {
19621 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19622 		re->ipRouteIfIndex.o_length =
19623 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19624 	}
19625 	re->ipRouteMetric1 = -1;
19626 	re->ipRouteMetric2 = -1;
19627 	re->ipRouteMetric3 = -1;
19628 	re->ipRouteMetric4 = -1;
19629 
19630 	gw_addr = ire->ire_gateway_addr;
19631 
19632 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19633 		re->ipRouteNextHop = ire->ire_src_addr;
19634 	else
19635 		re->ipRouteNextHop = gw_addr;
19636 	/* indirect(4), direct(3), or invalid(2) */
19637 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19638 		re->ipRouteType = 2;
19639 	else
19640 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19641 	re->ipRouteProto = -1;
19642 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19643 	re->ipRouteMask = ire->ire_mask;
19644 	re->ipRouteMetric5 = -1;
19645 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19646 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19647 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19648 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19649 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19650 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19651 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19652 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19653 
19654 	if (ire->ire_flags & RTF_DYNAMIC) {
19655 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19656 	} else {
19657 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19658 	}
19659 
19660 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19661 	    (char *)re, (int)sizeof (*re))) {
19662 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19663 		    (uint_t)sizeof (*re)));
19664 	}
19665 
19666 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19667 		iaeptr->iae_routeidx = ird->ird_idx;
19668 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19669 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19670 	}
19671 
19672 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19673 	    (char *)iae, sacnt * sizeof (*iae))) {
19674 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19675 		    (unsigned)(sacnt * sizeof (*iae))));
19676 	}
19677 
19678 	/* bump route index for next pass */
19679 	ird->ird_idx++;
19680 
19681 	kmem_free(re, sizeof (*re));
19682 	if (sacnt != 0)
19683 		kmem_free(iae, sacnt * sizeof (*iae));
19684 
19685 	if (gcgrp != NULL)
19686 		rw_exit(&gcgrp->gcgrp_rwlock);
19687 }
19688 
19689 /*
19690  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19691  */
19692 static void
19693 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19694 {
19695 	ill_t				*ill;
19696 	ipif_t				*ipif;
19697 	mib2_ipv6RouteEntry_t		*re;
19698 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19699 	in6_addr_t			gw_addr_v6;
19700 	tsol_ire_gw_secattr_t		*attrp;
19701 	tsol_gc_t			*gc = NULL;
19702 	tsol_gcgrp_t			*gcgrp = NULL;
19703 	uint_t				sacnt = 0;
19704 	int				i;
19705 
19706 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19707 
19708 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19709 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19710 		return;
19711 	}
19712 
19713 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19714 		return;
19715 
19716 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19717 		mutex_enter(&attrp->igsa_lock);
19718 		if ((gc = attrp->igsa_gc) != NULL) {
19719 			gcgrp = gc->gc_grp;
19720 			ASSERT(gcgrp != NULL);
19721 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19722 			sacnt = 1;
19723 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19724 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19725 			gc = gcgrp->gcgrp_head;
19726 			sacnt = gcgrp->gcgrp_count;
19727 		}
19728 		mutex_exit(&attrp->igsa_lock);
19729 
19730 		/* do nothing if there's no gc to report */
19731 		if (gc == NULL) {
19732 			ASSERT(sacnt == 0);
19733 			if (gcgrp != NULL) {
19734 				/* we might as well drop the lock now */
19735 				rw_exit(&gcgrp->gcgrp_rwlock);
19736 				gcgrp = NULL;
19737 			}
19738 			attrp = NULL;
19739 		}
19740 
19741 		ASSERT(gc == NULL || (gcgrp != NULL &&
19742 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19743 	}
19744 	ASSERT(sacnt == 0 || gc != NULL);
19745 
19746 	if (sacnt != 0 &&
19747 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19748 		kmem_free(re, sizeof (*re));
19749 		rw_exit(&gcgrp->gcgrp_rwlock);
19750 		return;
19751 	}
19752 
19753 	/*
19754 	 * Return all IRE types for route table... let caller pick and choose
19755 	 */
19756 	re->ipv6RouteDest = ire->ire_addr_v6;
19757 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19758 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19759 	re->ipv6RouteIfIndex.o_length = 0;
19760 	ipif = ire->ire_ipif;
19761 	if (ire->ire_type == IRE_CACHE) {
19762 		ill = (ill_t *)ire->ire_stq->q_ptr;
19763 		re->ipv6RouteIfIndex.o_length =
19764 		    ill->ill_name_length == 0 ? 0 :
19765 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19766 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19767 		    re->ipv6RouteIfIndex.o_length);
19768 	} else if (ipif != NULL) {
19769 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19770 		re->ipv6RouteIfIndex.o_length =
19771 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19772 	}
19773 
19774 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19775 
19776 	mutex_enter(&ire->ire_lock);
19777 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19778 	mutex_exit(&ire->ire_lock);
19779 
19780 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19781 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19782 	else
19783 		re->ipv6RouteNextHop = gw_addr_v6;
19784 
19785 	/* remote(4), local(3), or discard(2) */
19786 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19787 		re->ipv6RouteType = 2;
19788 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19789 		re->ipv6RouteType = 3;
19790 	else
19791 		re->ipv6RouteType = 4;
19792 
19793 	re->ipv6RouteProtocol	= -1;
19794 	re->ipv6RoutePolicy	= 0;
19795 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19796 	re->ipv6RouteNextHopRDI	= 0;
19797 	re->ipv6RouteWeight	= 0;
19798 	re->ipv6RouteMetric	= 0;
19799 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19800 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19801 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19802 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19803 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19804 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19805 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19806 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19807 
19808 	if (ire->ire_flags & RTF_DYNAMIC) {
19809 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19810 	} else {
19811 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19812 	}
19813 
19814 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19815 	    (char *)re, (int)sizeof (*re))) {
19816 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19817 		    (uint_t)sizeof (*re)));
19818 	}
19819 
19820 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19821 		iaeptr->iae_routeidx = ird->ird_idx;
19822 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19823 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19824 	}
19825 
19826 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19827 	    (char *)iae, sacnt * sizeof (*iae))) {
19828 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19829 		    (unsigned)(sacnt * sizeof (*iae))));
19830 	}
19831 
19832 	/* bump route index for next pass */
19833 	ird->ird_idx++;
19834 
19835 	kmem_free(re, sizeof (*re));
19836 	if (sacnt != 0)
19837 		kmem_free(iae, sacnt * sizeof (*iae));
19838 
19839 	if (gcgrp != NULL)
19840 		rw_exit(&gcgrp->gcgrp_rwlock);
19841 }
19842 
19843 /*
19844  * ndp_walk routine to create ipv6NetToMediaEntryTable
19845  */
19846 static int
19847 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19848 {
19849 	ill_t				*ill;
19850 	mib2_ipv6NetToMediaEntry_t	ntme;
19851 	dl_unitdata_req_t		*dl;
19852 
19853 	ill = nce->nce_ill;
19854 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19855 		return (0);
19856 
19857 	/*
19858 	 * Neighbor cache entry attached to IRE with on-link
19859 	 * destination.
19860 	 */
19861 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19862 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19863 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19864 	    (nce->nce_res_mp != NULL)) {
19865 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19866 		ntme.ipv6NetToMediaPhysAddress.o_length =
19867 		    dl->dl_dest_addr_length;
19868 	} else {
19869 		ntme.ipv6NetToMediaPhysAddress.o_length =
19870 		    ill->ill_phys_addr_length;
19871 	}
19872 	if (nce->nce_res_mp != NULL) {
19873 		bcopy((char *)nce->nce_res_mp->b_rptr +
19874 		    NCE_LL_ADDR_OFFSET(ill),
19875 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19876 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19877 	} else {
19878 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19879 		    ill->ill_phys_addr_length);
19880 	}
19881 	/*
19882 	 * Note: Returns ND_* states. Should be:
19883 	 * reachable(1), stale(2), delay(3), probe(4),
19884 	 * invalid(5), unknown(6)
19885 	 */
19886 	ntme.ipv6NetToMediaState = nce->nce_state;
19887 	ntme.ipv6NetToMediaLastUpdated = 0;
19888 
19889 	/* other(1), dynamic(2), static(3), local(4) */
19890 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19891 		ntme.ipv6NetToMediaType = 4;
19892 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19893 		ntme.ipv6NetToMediaType = 1;
19894 	} else {
19895 		ntme.ipv6NetToMediaType = 2;
19896 	}
19897 
19898 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19899 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19900 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19901 		    (uint_t)sizeof (ntme)));
19902 	}
19903 	return (0);
19904 }
19905 
19906 /*
19907  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19908  */
19909 /* ARGSUSED */
19910 int
19911 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19912 {
19913 	switch (level) {
19914 	case MIB2_IP:
19915 	case MIB2_ICMP:
19916 		switch (name) {
19917 		default:
19918 			break;
19919 		}
19920 		return (1);
19921 	default:
19922 		return (1);
19923 	}
19924 }
19925 
19926 /*
19927  * When there exists both a 64- and 32-bit counter of a particular type
19928  * (i.e., InReceives), only the 64-bit counters are added.
19929  */
19930 void
19931 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19932 {
19933 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19934 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19935 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19936 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19937 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19938 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19939 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19940 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19941 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19942 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19943 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19944 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19945 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19946 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19947 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19948 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19949 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19950 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19951 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19952 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19953 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19954 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19955 	    o2->ipIfStatsInWrongIPVersion);
19956 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19957 	    o2->ipIfStatsInWrongIPVersion);
19958 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19959 	    o2->ipIfStatsOutSwitchIPVersion);
19960 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19961 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19962 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19963 	    o2->ipIfStatsHCInForwDatagrams);
19964 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19965 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19966 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19967 	    o2->ipIfStatsHCOutForwDatagrams);
19968 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19969 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19970 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19971 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19972 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19973 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19974 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19975 	    o2->ipIfStatsHCOutMcastOctets);
19976 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19977 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19978 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19979 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19980 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19981 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19982 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19983 }
19984 
19985 void
19986 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19987 {
19988 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19989 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19990 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19991 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19992 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19993 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19994 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19995 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19996 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19997 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19998 	    o2->ipv6IfIcmpInRouterSolicits);
19999 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20000 	    o2->ipv6IfIcmpInRouterAdvertisements);
20001 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20002 	    o2->ipv6IfIcmpInNeighborSolicits);
20003 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20004 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20005 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20006 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20007 	    o2->ipv6IfIcmpInGroupMembQueries);
20008 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20009 	    o2->ipv6IfIcmpInGroupMembResponses);
20010 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20011 	    o2->ipv6IfIcmpInGroupMembReductions);
20012 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20013 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20014 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20015 	    o2->ipv6IfIcmpOutDestUnreachs);
20016 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20017 	    o2->ipv6IfIcmpOutAdminProhibs);
20018 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20019 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20020 	    o2->ipv6IfIcmpOutParmProblems);
20021 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20022 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20023 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20024 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20025 	    o2->ipv6IfIcmpOutRouterSolicits);
20026 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20027 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20028 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20029 	    o2->ipv6IfIcmpOutNeighborSolicits);
20030 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20031 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20032 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20033 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20034 	    o2->ipv6IfIcmpOutGroupMembQueries);
20035 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20036 	    o2->ipv6IfIcmpOutGroupMembResponses);
20037 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20038 	    o2->ipv6IfIcmpOutGroupMembReductions);
20039 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20040 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20041 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20042 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20043 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20044 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20045 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20046 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20047 	    o2->ipv6IfIcmpInGroupMembTotal);
20048 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20049 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20050 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20051 	    o2->ipv6IfIcmpInGroupMembBadReports);
20052 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20053 	    o2->ipv6IfIcmpInGroupMembOurReports);
20054 }
20055 
20056 /*
20057  * Called before the options are updated to check if this packet will
20058  * be source routed from here.
20059  * This routine assumes that the options are well formed i.e. that they
20060  * have already been checked.
20061  */
20062 static boolean_t
20063 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20064 {
20065 	ipoptp_t	opts;
20066 	uchar_t		*opt;
20067 	uint8_t		optval;
20068 	uint8_t		optlen;
20069 	ipaddr_t	dst;
20070 	ire_t		*ire;
20071 
20072 	if (IS_SIMPLE_IPH(ipha)) {
20073 		ip2dbg(("not source routed\n"));
20074 		return (B_FALSE);
20075 	}
20076 	dst = ipha->ipha_dst;
20077 	for (optval = ipoptp_first(&opts, ipha);
20078 	    optval != IPOPT_EOL;
20079 	    optval = ipoptp_next(&opts)) {
20080 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20081 		opt = opts.ipoptp_cur;
20082 		optlen = opts.ipoptp_len;
20083 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20084 		    optval, optlen));
20085 		switch (optval) {
20086 			uint32_t off;
20087 		case IPOPT_SSRR:
20088 		case IPOPT_LSRR:
20089 			/*
20090 			 * If dst is one of our addresses and there are some
20091 			 * entries left in the source route return (true).
20092 			 */
20093 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20094 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20095 			if (ire == NULL) {
20096 				ip2dbg(("ip_source_routed: not next"
20097 				    " source route 0x%x\n",
20098 				    ntohl(dst)));
20099 				return (B_FALSE);
20100 			}
20101 			ire_refrele(ire);
20102 			off = opt[IPOPT_OFFSET];
20103 			off--;
20104 			if (optlen < IP_ADDR_LEN ||
20105 			    off > optlen - IP_ADDR_LEN) {
20106 				/* End of source route */
20107 				ip1dbg(("ip_source_routed: end of SR\n"));
20108 				return (B_FALSE);
20109 			}
20110 			return (B_TRUE);
20111 		}
20112 	}
20113 	ip2dbg(("not source routed\n"));
20114 	return (B_FALSE);
20115 }
20116 
20117 /*
20118  * Check if the packet contains any source route.
20119  */
20120 static boolean_t
20121 ip_source_route_included(ipha_t *ipha)
20122 {
20123 	ipoptp_t	opts;
20124 	uint8_t		optval;
20125 
20126 	if (IS_SIMPLE_IPH(ipha))
20127 		return (B_FALSE);
20128 	for (optval = ipoptp_first(&opts, ipha);
20129 	    optval != IPOPT_EOL;
20130 	    optval = ipoptp_next(&opts)) {
20131 		switch (optval) {
20132 		case IPOPT_SSRR:
20133 		case IPOPT_LSRR:
20134 			return (B_TRUE);
20135 		}
20136 	}
20137 	return (B_FALSE);
20138 }
20139 
20140 /*
20141  * Called when the IRE expiration timer fires.
20142  */
20143 void
20144 ip_trash_timer_expire(void *args)
20145 {
20146 	int			flush_flag = 0;
20147 	ire_expire_arg_t	iea;
20148 	ip_stack_t		*ipst = (ip_stack_t *)args;
20149 
20150 	iea.iea_ipst = ipst;	/* No netstack_hold */
20151 
20152 	/*
20153 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20154 	 * This lock makes sure that a new invocation of this function
20155 	 * that occurs due to an almost immediate timer firing will not
20156 	 * progress beyond this point until the current invocation is done
20157 	 */
20158 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20159 	ipst->ips_ip_ire_expire_id = 0;
20160 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20161 
20162 	/* Periodic timer */
20163 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20164 	    ipst->ips_ip_ire_arp_interval) {
20165 		/*
20166 		 * Remove all IRE_CACHE entries since they might
20167 		 * contain arp information.
20168 		 */
20169 		flush_flag |= FLUSH_ARP_TIME;
20170 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20171 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20172 	}
20173 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20174 	    ipst->ips_ip_ire_redir_interval) {
20175 		/* Remove all redirects */
20176 		flush_flag |= FLUSH_REDIRECT_TIME;
20177 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20178 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20179 	}
20180 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20181 	    ipst->ips_ip_ire_pathmtu_interval) {
20182 		/* Increase path mtu */
20183 		flush_flag |= FLUSH_MTU_TIME;
20184 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20185 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20186 	}
20187 
20188 	/*
20189 	 * Optimize for the case when there are no redirects in the
20190 	 * ftable, that is, no need to walk the ftable in that case.
20191 	 */
20192 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20193 		iea.iea_flush_flag = flush_flag;
20194 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20195 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20196 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20197 		    NULL, ALL_ZONES, ipst);
20198 	}
20199 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20200 	    ipst->ips_ip_redirect_cnt > 0) {
20201 		iea.iea_flush_flag = flush_flag;
20202 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20203 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20204 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20205 	}
20206 	if (flush_flag & FLUSH_MTU_TIME) {
20207 		/*
20208 		 * Walk all IPv6 IRE's and update them
20209 		 * Note that ARP and redirect timers are not
20210 		 * needed since NUD handles stale entries.
20211 		 */
20212 		flush_flag = FLUSH_MTU_TIME;
20213 		iea.iea_flush_flag = flush_flag;
20214 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20215 		    ALL_ZONES, ipst);
20216 	}
20217 
20218 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20219 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20220 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20221 
20222 	/*
20223 	 * Hold the lock to serialize timeout calls and prevent
20224 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20225 	 * for the timer to fire and a new invocation of this function
20226 	 * to start before the return value of timeout has been stored
20227 	 * in ip_ire_expire_id by the current invocation.
20228 	 */
20229 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20230 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20231 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20232 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20233 }
20234 
20235 /*
20236  * Called by the memory allocator subsystem directly, when the system
20237  * is running low on memory.
20238  */
20239 /* ARGSUSED */
20240 void
20241 ip_trash_ire_reclaim(void *args)
20242 {
20243 	netstack_handle_t nh;
20244 	netstack_t *ns;
20245 
20246 	netstack_next_init(&nh);
20247 	while ((ns = netstack_next(&nh)) != NULL) {
20248 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20249 		netstack_rele(ns);
20250 	}
20251 	netstack_next_fini(&nh);
20252 }
20253 
20254 static void
20255 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20256 {
20257 	ire_cache_count_t icc;
20258 	ire_cache_reclaim_t icr;
20259 	ncc_cache_count_t ncc;
20260 	nce_cache_reclaim_t ncr;
20261 	uint_t delete_cnt;
20262 	/*
20263 	 * Memory reclaim call back.
20264 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20265 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20266 	 * entries, determine what fraction to free for
20267 	 * each category of IRE_CACHE entries giving absolute priority
20268 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20269 	 * entry will be freed unless all offlink entries are freed).
20270 	 */
20271 	icc.icc_total = 0;
20272 	icc.icc_unused = 0;
20273 	icc.icc_offlink = 0;
20274 	icc.icc_pmtu = 0;
20275 	icc.icc_onlink = 0;
20276 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20277 
20278 	/*
20279 	 * Free NCEs for IPv6 like the onlink ires.
20280 	 */
20281 	ncc.ncc_total = 0;
20282 	ncc.ncc_host = 0;
20283 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20284 
20285 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20286 	    icc.icc_pmtu + icc.icc_onlink);
20287 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20288 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20289 	if (delete_cnt == 0)
20290 		return;
20291 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20292 	/* Always delete all unused offlink entries */
20293 	icr.icr_ipst = ipst;
20294 	icr.icr_unused = 1;
20295 	if (delete_cnt <= icc.icc_unused) {
20296 		/*
20297 		 * Only need to free unused entries.  In other words,
20298 		 * there are enough unused entries to free to meet our
20299 		 * target number of freed ire cache entries.
20300 		 */
20301 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20302 		ncr.ncr_host = 0;
20303 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20304 		/*
20305 		 * Only need to free unused entries, plus a fraction of offlink
20306 		 * entries.  It follows from the first if statement that
20307 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20308 		 */
20309 		delete_cnt -= icc.icc_unused;
20310 		/* Round up # deleted by truncating fraction */
20311 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20312 		icr.icr_pmtu = icr.icr_onlink = 0;
20313 		ncr.ncr_host = 0;
20314 	} else if (delete_cnt <=
20315 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20316 		/*
20317 		 * Free all unused and offlink entries, plus a fraction of
20318 		 * pmtu entries.  It follows from the previous if statement
20319 		 * that icc_pmtu is non-zero, and that
20320 		 * delete_cnt != icc_unused + icc_offlink.
20321 		 */
20322 		icr.icr_offlink = 1;
20323 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20324 		/* Round up # deleted by truncating fraction */
20325 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20326 		icr.icr_onlink = 0;
20327 		ncr.ncr_host = 0;
20328 	} else {
20329 		/*
20330 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20331 		 * of onlink entries.  If we're here, then we know that
20332 		 * icc_onlink is non-zero, and that
20333 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20334 		 */
20335 		icr.icr_offlink = icr.icr_pmtu = 1;
20336 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20337 		    icc.icc_pmtu;
20338 		/* Round up # deleted by truncating fraction */
20339 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20340 		/* Using the same delete fraction as for onlink IREs */
20341 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20342 	}
20343 #ifdef DEBUG
20344 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20345 	    "fractions %d/%d/%d/%d\n",
20346 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20347 	    icc.icc_unused, icc.icc_offlink,
20348 	    icc.icc_pmtu, icc.icc_onlink,
20349 	    icr.icr_unused, icr.icr_offlink,
20350 	    icr.icr_pmtu, icr.icr_onlink));
20351 #endif
20352 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20353 	if (ncr.ncr_host != 0)
20354 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20355 		    (uchar_t *)&ncr, ipst);
20356 #ifdef DEBUG
20357 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20358 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20359 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20360 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20361 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20362 	    icc.icc_pmtu, icc.icc_onlink));
20363 #endif
20364 }
20365 
20366 /*
20367  * ip_unbind is called when a copy of an unbind request is received from the
20368  * upper level protocol.  We remove this conn from any fanout hash list it is
20369  * on, and zero out the bind information.  No reply is expected up above.
20370  */
20371 void
20372 ip_unbind(conn_t *connp)
20373 {
20374 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20375 
20376 	if (is_system_labeled() && connp->conn_anon_port) {
20377 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20378 		    connp->conn_mlp_type, connp->conn_ulp,
20379 		    ntohs(connp->conn_lport), B_FALSE);
20380 		connp->conn_anon_port = 0;
20381 	}
20382 	connp->conn_mlp_type = mlptSingle;
20383 
20384 	ipcl_hash_remove(connp);
20385 
20386 }
20387 
20388 /*
20389  * Write side put procedure.  Outbound data, IOCTLs, responses from
20390  * resolvers, etc, come down through here.
20391  *
20392  * arg2 is always a queue_t *.
20393  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20394  * the zoneid.
20395  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20396  */
20397 void
20398 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20399 {
20400 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20401 }
20402 
20403 void
20404 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20405     ip_opt_info_t *infop)
20406 {
20407 	conn_t		*connp = NULL;
20408 	queue_t		*q = (queue_t *)arg2;
20409 	ipha_t		*ipha;
20410 #define	rptr	((uchar_t *)ipha)
20411 	ire_t		*ire = NULL;
20412 	ire_t		*sctp_ire = NULL;
20413 	uint32_t	v_hlen_tos_len;
20414 	ipaddr_t	dst;
20415 	mblk_t		*first_mp = NULL;
20416 	boolean_t	mctl_present;
20417 	ipsec_out_t	*io;
20418 	int		match_flags;
20419 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20420 	ipif_t		*dst_ipif;
20421 	boolean_t	multirt_need_resolve = B_FALSE;
20422 	mblk_t		*copy_mp = NULL;
20423 	int		err;
20424 	zoneid_t	zoneid;
20425 	boolean_t	need_decref = B_FALSE;
20426 	boolean_t	ignore_dontroute = B_FALSE;
20427 	boolean_t	ignore_nexthop = B_FALSE;
20428 	boolean_t	ip_nexthop = B_FALSE;
20429 	ipaddr_t	nexthop_addr;
20430 	ip_stack_t	*ipst;
20431 
20432 #ifdef	_BIG_ENDIAN
20433 #define	V_HLEN	(v_hlen_tos_len >> 24)
20434 #else
20435 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20436 #endif
20437 
20438 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20439 	    "ip_wput_start: q %p", q);
20440 
20441 	/*
20442 	 * ip_wput fast path
20443 	 */
20444 
20445 	/* is packet from ARP ? */
20446 	if (q->q_next != NULL) {
20447 		zoneid = (zoneid_t)(uintptr_t)arg;
20448 		goto qnext;
20449 	}
20450 
20451 	connp = (conn_t *)arg;
20452 	ASSERT(connp != NULL);
20453 	zoneid = connp->conn_zoneid;
20454 	ipst = connp->conn_netstack->netstack_ip;
20455 	ASSERT(ipst != NULL);
20456 
20457 	/* is queue flow controlled? */
20458 	if ((q->q_first != NULL || connp->conn_draining) &&
20459 	    (caller == IP_WPUT)) {
20460 		ASSERT(!need_decref);
20461 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20462 		(void) putq(q, mp);
20463 		return;
20464 	}
20465 
20466 	/* Multidata transmit? */
20467 	if (DB_TYPE(mp) == M_MULTIDATA) {
20468 		/*
20469 		 * We should never get here, since all Multidata messages
20470 		 * originating from tcp should have been directed over to
20471 		 * tcp_multisend() in the first place.
20472 		 */
20473 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20474 		freemsg(mp);
20475 		return;
20476 	} else if (DB_TYPE(mp) != M_DATA)
20477 		goto notdata;
20478 
20479 	if (mp->b_flag & MSGHASREF) {
20480 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20481 		mp->b_flag &= ~MSGHASREF;
20482 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20483 		need_decref = B_TRUE;
20484 	}
20485 	ipha = (ipha_t *)mp->b_rptr;
20486 
20487 	/* is IP header non-aligned or mblk smaller than basic IP header */
20488 #ifndef SAFETY_BEFORE_SPEED
20489 	if (!OK_32PTR(rptr) ||
20490 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20491 		goto hdrtoosmall;
20492 #endif
20493 
20494 	ASSERT(OK_32PTR(ipha));
20495 
20496 	/*
20497 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20498 	 * wrong version, we'll catch it again in ip_output_v6.
20499 	 *
20500 	 * Note that this is *only* locally-generated output here, and never
20501 	 * forwarded data, and that we need to deal only with transports that
20502 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20503 	 * label.)
20504 	 */
20505 	if (is_system_labeled() &&
20506 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20507 	    !connp->conn_ulp_labeled) {
20508 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20509 		    connp->conn_mac_exempt, ipst);
20510 		ipha = (ipha_t *)mp->b_rptr;
20511 		if (err != 0) {
20512 			first_mp = mp;
20513 			if (err == EINVAL)
20514 				goto icmp_parameter_problem;
20515 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20516 			goto discard_pkt;
20517 		}
20518 	}
20519 
20520 	ASSERT(infop != NULL);
20521 
20522 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20523 		/*
20524 		 * IP_PKTINFO ancillary option is present.
20525 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20526 		 * allows using address of any zone as the source address.
20527 		 */
20528 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20529 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20530 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20531 		if (ire == NULL)
20532 			goto drop_pkt;
20533 		ire_refrele(ire);
20534 		ire = NULL;
20535 	}
20536 
20537 	/*
20538 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20539 	 */
20540 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20541 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20542 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20543 
20544 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20545 			goto drop_pkt;
20546 		/*
20547 		 * check that there is an ipif belonging
20548 		 * to our zone. IPCL_ZONEID is not used because
20549 		 * IP_ALLZONES option is valid only when the ill is
20550 		 * accessible from all zones i.e has a valid ipif in
20551 		 * all zones.
20552 		 */
20553 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20554 			goto drop_pkt;
20555 		}
20556 	}
20557 
20558 	/*
20559 	 * If there is a policy, try to attach an ipsec_out in
20560 	 * the front. At the end, first_mp either points to a
20561 	 * M_DATA message or IPSEC_OUT message linked to a
20562 	 * M_DATA message. We have to do it now as we might
20563 	 * lose the "conn" if we go through ip_newroute.
20564 	 */
20565 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20566 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20567 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20568 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20569 			if (need_decref)
20570 				CONN_DEC_REF(connp);
20571 			return;
20572 		} else {
20573 			ASSERT(mp->b_datap->db_type == M_CTL);
20574 			first_mp = mp;
20575 			mp = mp->b_cont;
20576 			mctl_present = B_TRUE;
20577 		}
20578 	} else {
20579 		first_mp = mp;
20580 		mctl_present = B_FALSE;
20581 	}
20582 
20583 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20584 
20585 	/* is wrong version or IP options present */
20586 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20587 		goto version_hdrlen_check;
20588 	dst = ipha->ipha_dst;
20589 
20590 	/* If IP_BOUND_IF has been set, use that ill. */
20591 	if (connp->conn_outgoing_ill != NULL) {
20592 		xmit_ill = conn_get_held_ill(connp,
20593 		    &connp->conn_outgoing_ill, &err);
20594 		if (err == ILL_LOOKUP_FAILED)
20595 			goto drop_pkt;
20596 
20597 		goto send_from_ill;
20598 	}
20599 
20600 	/* is packet multicast? */
20601 	if (CLASSD(dst))
20602 		goto multicast;
20603 
20604 	/*
20605 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20606 	 * takes precedence over conn_dontroute and conn_nexthop_set
20607 	 */
20608 	if (xmit_ill != NULL)
20609 		goto send_from_ill;
20610 
20611 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20612 		/*
20613 		 * If the destination is a broadcast, local, or loopback
20614 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20615 		 * standard path.
20616 		 */
20617 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20618 		if ((ire == NULL) || (ire->ire_type &
20619 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20620 			if (ire != NULL) {
20621 				ire_refrele(ire);
20622 				/* No more access to ire */
20623 				ire = NULL;
20624 			}
20625 			/*
20626 			 * bypass routing checks and go directly to interface.
20627 			 */
20628 			if (connp->conn_dontroute)
20629 				goto dontroute;
20630 
20631 			ASSERT(connp->conn_nexthop_set);
20632 			ip_nexthop = B_TRUE;
20633 			nexthop_addr = connp->conn_nexthop_v4;
20634 			goto send_from_ill;
20635 		}
20636 
20637 		/* Must be a broadcast, a loopback or a local ire */
20638 		ire_refrele(ire);
20639 		/* No more access to ire */
20640 		ire = NULL;
20641 	}
20642 
20643 	/*
20644 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20645 	 * this for the tcp global queue and listen end point
20646 	 * as it does not really have a real destination to
20647 	 * talk to.  This is also true for SCTP.
20648 	 */
20649 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20650 	    !connp->conn_fully_bound) {
20651 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20652 		if (ire == NULL)
20653 			goto noirefound;
20654 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20655 		    "ip_wput_end: q %p (%S)", q, "end");
20656 
20657 		/*
20658 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20659 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20660 		 */
20661 		if (ire->ire_flags & RTF_MULTIRT) {
20662 
20663 			/*
20664 			 * Force the TTL of multirouted packets if required.
20665 			 * The TTL of such packets is bounded by the
20666 			 * ip_multirt_ttl ndd variable.
20667 			 */
20668 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20669 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20670 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20671 				    "(was %d), dst 0x%08x\n",
20672 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20673 				    ntohl(ire->ire_addr)));
20674 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20675 			}
20676 			/*
20677 			 * We look at this point if there are pending
20678 			 * unresolved routes. ire_multirt_resolvable()
20679 			 * checks in O(n) that all IRE_OFFSUBNET ire
20680 			 * entries for the packet's destination and
20681 			 * flagged RTF_MULTIRT are currently resolved.
20682 			 * If some remain unresolved, we make a copy
20683 			 * of the current message. It will be used
20684 			 * to initiate additional route resolutions.
20685 			 */
20686 			multirt_need_resolve =
20687 			    ire_multirt_need_resolve(ire->ire_addr,
20688 			    msg_getlabel(first_mp), ipst);
20689 			ip2dbg(("ip_wput[TCP]: ire %p, "
20690 			    "multirt_need_resolve %d, first_mp %p\n",
20691 			    (void *)ire, multirt_need_resolve,
20692 			    (void *)first_mp));
20693 			if (multirt_need_resolve) {
20694 				copy_mp = copymsg(first_mp);
20695 				if (copy_mp != NULL) {
20696 					MULTIRT_DEBUG_TAG(copy_mp);
20697 				}
20698 			}
20699 		}
20700 
20701 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20702 
20703 		/*
20704 		 * Try to resolve another multiroute if
20705 		 * ire_multirt_need_resolve() deemed it necessary.
20706 		 */
20707 		if (copy_mp != NULL)
20708 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20709 		if (need_decref)
20710 			CONN_DEC_REF(connp);
20711 		return;
20712 	}
20713 
20714 	/*
20715 	 * Access to conn_ire_cache. (protected by conn_lock)
20716 	 *
20717 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20718 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20719 	 * send a packet or two with the IRE_CACHE that is going away.
20720 	 * Access to the ire requires an ire refhold on the ire prior to
20721 	 * its use since an interface unplumb thread may delete the cached
20722 	 * ire and release the refhold at any time.
20723 	 *
20724 	 * Caching an ire in the conn_ire_cache
20725 	 *
20726 	 * o Caching an ire pointer in the conn requires a strict check for
20727 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20728 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20729 	 * in the conn is done after making sure under the bucket lock that the
20730 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20731 	 * caching an ire after the unplumb thread has cleaned up the conn.
20732 	 * If the conn does not send a packet subsequently the unplumb thread
20733 	 * will be hanging waiting for the ire count to drop to zero.
20734 	 *
20735 	 * o We also need to atomically test for a null conn_ire_cache and
20736 	 * set the conn_ire_cache under the the protection of the conn_lock
20737 	 * to avoid races among concurrent threads trying to simultaneously
20738 	 * cache an ire in the conn_ire_cache.
20739 	 */
20740 	mutex_enter(&connp->conn_lock);
20741 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20742 
20743 	if (ire != NULL && ire->ire_addr == dst &&
20744 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20745 
20746 		IRE_REFHOLD(ire);
20747 		mutex_exit(&connp->conn_lock);
20748 
20749 	} else {
20750 		boolean_t cached = B_FALSE;
20751 		connp->conn_ire_cache = NULL;
20752 		mutex_exit(&connp->conn_lock);
20753 		/* Release the old ire */
20754 		if (ire != NULL && sctp_ire == NULL)
20755 			IRE_REFRELE_NOTR(ire);
20756 
20757 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20758 		if (ire == NULL)
20759 			goto noirefound;
20760 		IRE_REFHOLD_NOTR(ire);
20761 
20762 		mutex_enter(&connp->conn_lock);
20763 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20764 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20765 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20766 				if (connp->conn_ulp == IPPROTO_TCP)
20767 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20768 				connp->conn_ire_cache = ire;
20769 				cached = B_TRUE;
20770 			}
20771 			rw_exit(&ire->ire_bucket->irb_lock);
20772 		}
20773 		mutex_exit(&connp->conn_lock);
20774 
20775 		/*
20776 		 * We can continue to use the ire but since it was
20777 		 * not cached, we should drop the extra reference.
20778 		 */
20779 		if (!cached)
20780 			IRE_REFRELE_NOTR(ire);
20781 	}
20782 
20783 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20784 	    "ip_wput_end: q %p (%S)", q, "end");
20785 
20786 	/*
20787 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20788 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20789 	 */
20790 	if (ire->ire_flags & RTF_MULTIRT) {
20791 		/*
20792 		 * Force the TTL of multirouted packets if required.
20793 		 * The TTL of such packets is bounded by the
20794 		 * ip_multirt_ttl ndd variable.
20795 		 */
20796 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20797 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20798 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20799 			    "(was %d), dst 0x%08x\n",
20800 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20801 			    ntohl(ire->ire_addr)));
20802 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20803 		}
20804 
20805 		/*
20806 		 * At this point, we check to see if there are any pending
20807 		 * unresolved routes. ire_multirt_resolvable()
20808 		 * checks in O(n) that all IRE_OFFSUBNET ire
20809 		 * entries for the packet's destination and
20810 		 * flagged RTF_MULTIRT are currently resolved.
20811 		 * If some remain unresolved, we make a copy
20812 		 * of the current message. It will be used
20813 		 * to initiate additional route resolutions.
20814 		 */
20815 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20816 		    msg_getlabel(first_mp), ipst);
20817 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20818 		    "multirt_need_resolve %d, first_mp %p\n",
20819 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20820 		if (multirt_need_resolve) {
20821 			copy_mp = copymsg(first_mp);
20822 			if (copy_mp != NULL) {
20823 				MULTIRT_DEBUG_TAG(copy_mp);
20824 			}
20825 		}
20826 	}
20827 
20828 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20829 
20830 	/*
20831 	 * Try to resolve another multiroute if
20832 	 * ire_multirt_resolvable() deemed it necessary
20833 	 */
20834 	if (copy_mp != NULL)
20835 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20836 	if (need_decref)
20837 		CONN_DEC_REF(connp);
20838 	return;
20839 
20840 qnext:
20841 	/*
20842 	 * Upper Level Protocols pass down complete IP datagrams
20843 	 * as M_DATA messages.	Everything else is a sideshow.
20844 	 *
20845 	 * 1) We could be re-entering ip_wput because of ip_neworute
20846 	 *    in which case we could have a IPSEC_OUT message. We
20847 	 *    need to pass through ip_wput like other datagrams and
20848 	 *    hence cannot branch to ip_wput_nondata.
20849 	 *
20850 	 * 2) ARP, AH, ESP, and other clients who are on the module
20851 	 *    instance of IP stream, give us something to deal with.
20852 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20853 	 *
20854 	 * 3) ICMP replies also could come here.
20855 	 */
20856 	ipst = ILLQ_TO_IPST(q);
20857 
20858 	if (DB_TYPE(mp) != M_DATA) {
20859 notdata:
20860 		if (DB_TYPE(mp) == M_CTL) {
20861 			/*
20862 			 * M_CTL messages are used by ARP, AH and ESP to
20863 			 * communicate with IP. We deal with IPSEC_IN and
20864 			 * IPSEC_OUT here. ip_wput_nondata handles other
20865 			 * cases.
20866 			 */
20867 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20868 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20869 				first_mp = mp->b_cont;
20870 				first_mp->b_flag &= ~MSGHASREF;
20871 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20872 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20873 				CONN_DEC_REF(connp);
20874 				connp = NULL;
20875 			}
20876 			if (ii->ipsec_info_type == IPSEC_IN) {
20877 				/*
20878 				 * Either this message goes back to
20879 				 * IPsec for further processing or to
20880 				 * ULP after policy checks.
20881 				 */
20882 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20883 				return;
20884 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20885 				io = (ipsec_out_t *)ii;
20886 				if (io->ipsec_out_proc_begin) {
20887 					/*
20888 					 * IPsec processing has already started.
20889 					 * Complete it.
20890 					 * IPQoS notes: We don't care what is
20891 					 * in ipsec_out_ill_index since this
20892 					 * won't be processed for IPQoS policies
20893 					 * in ipsec_out_process.
20894 					 */
20895 					ipsec_out_process(q, mp, NULL,
20896 					    io->ipsec_out_ill_index);
20897 					return;
20898 				} else {
20899 					connp = (q->q_next != NULL) ?
20900 					    NULL : Q_TO_CONN(q);
20901 					first_mp = mp;
20902 					mp = mp->b_cont;
20903 					mctl_present = B_TRUE;
20904 				}
20905 				zoneid = io->ipsec_out_zoneid;
20906 				ASSERT(zoneid != ALL_ZONES);
20907 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20908 				/*
20909 				 * It's an IPsec control message requesting
20910 				 * an SADB update to be sent to the IPsec
20911 				 * hardware acceleration capable ills.
20912 				 */
20913 				ipsec_ctl_t *ipsec_ctl =
20914 				    (ipsec_ctl_t *)mp->b_rptr;
20915 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20916 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20917 				mblk_t *cmp = mp->b_cont;
20918 
20919 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20920 				ASSERT(cmp != NULL);
20921 
20922 				freeb(mp);
20923 				ill_ipsec_capab_send_all(satype, cmp, sa,
20924 				    ipst->ips_netstack);
20925 				return;
20926 			} else {
20927 				/*
20928 				 * This must be ARP or special TSOL signaling.
20929 				 */
20930 				ip_wput_nondata(NULL, q, mp, NULL);
20931 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20932 				    "ip_wput_end: q %p (%S)", q, "nondata");
20933 				return;
20934 			}
20935 		} else {
20936 			/*
20937 			 * This must be non-(ARP/AH/ESP) messages.
20938 			 */
20939 			ASSERT(!need_decref);
20940 			ip_wput_nondata(NULL, q, mp, NULL);
20941 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20942 			    "ip_wput_end: q %p (%S)", q, "nondata");
20943 			return;
20944 		}
20945 	} else {
20946 		first_mp = mp;
20947 		mctl_present = B_FALSE;
20948 	}
20949 
20950 	ASSERT(first_mp != NULL);
20951 
20952 	if (mctl_present) {
20953 		io = (ipsec_out_t *)first_mp->b_rptr;
20954 		if (io->ipsec_out_ip_nexthop) {
20955 			/*
20956 			 * We may have lost the conn context if we are
20957 			 * coming here from ip_newroute(). Copy the
20958 			 * nexthop information.
20959 			 */
20960 			ip_nexthop = B_TRUE;
20961 			nexthop_addr = io->ipsec_out_nexthop_addr;
20962 
20963 			ipha = (ipha_t *)mp->b_rptr;
20964 			dst = ipha->ipha_dst;
20965 			goto send_from_ill;
20966 		}
20967 	}
20968 
20969 	ASSERT(xmit_ill == NULL);
20970 
20971 	/* We have a complete IP datagram heading outbound. */
20972 	ipha = (ipha_t *)mp->b_rptr;
20973 
20974 #ifndef SPEED_BEFORE_SAFETY
20975 	/*
20976 	 * Make sure we have a full-word aligned message and that at least
20977 	 * a simple IP header is accessible in the first message.  If not,
20978 	 * try a pullup.  For labeled systems we need to always take this
20979 	 * path as M_CTLs are "notdata" but have trailing data to process.
20980 	 */
20981 	if (!OK_32PTR(rptr) ||
20982 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20983 hdrtoosmall:
20984 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20985 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20986 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20987 			if (first_mp == NULL)
20988 				first_mp = mp;
20989 			goto discard_pkt;
20990 		}
20991 
20992 		/* This function assumes that mp points to an IPv4 packet. */
20993 		if (is_system_labeled() && q->q_next == NULL &&
20994 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20995 		    !connp->conn_ulp_labeled) {
20996 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20997 			    connp->conn_mac_exempt, ipst);
20998 			ipha = (ipha_t *)mp->b_rptr;
20999 			if (first_mp != NULL)
21000 				first_mp->b_cont = mp;
21001 			if (err != 0) {
21002 				if (first_mp == NULL)
21003 					first_mp = mp;
21004 				if (err == EINVAL)
21005 					goto icmp_parameter_problem;
21006 				ip2dbg(("ip_wput: label check failed (%d)\n",
21007 				    err));
21008 				goto discard_pkt;
21009 			}
21010 		}
21011 
21012 		ipha = (ipha_t *)mp->b_rptr;
21013 		if (first_mp == NULL) {
21014 			ASSERT(xmit_ill == NULL);
21015 			/*
21016 			 * If we got here because of "goto hdrtoosmall"
21017 			 * We need to attach a IPSEC_OUT.
21018 			 */
21019 			if (connp->conn_out_enforce_policy) {
21020 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21021 				    NULL, ipha->ipha_protocol,
21022 				    ipst->ips_netstack)) == NULL)) {
21023 					BUMP_MIB(&ipst->ips_ip_mib,
21024 					    ipIfStatsOutDiscards);
21025 					if (need_decref)
21026 						CONN_DEC_REF(connp);
21027 					return;
21028 				} else {
21029 					ASSERT(mp->b_datap->db_type == M_CTL);
21030 					first_mp = mp;
21031 					mp = mp->b_cont;
21032 					mctl_present = B_TRUE;
21033 				}
21034 			} else {
21035 				first_mp = mp;
21036 				mctl_present = B_FALSE;
21037 			}
21038 		}
21039 	}
21040 #endif
21041 
21042 	/* Most of the code below is written for speed, not readability */
21043 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21044 
21045 	/*
21046 	 * If ip_newroute() fails, we're going to need a full
21047 	 * header for the icmp wraparound.
21048 	 */
21049 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21050 		uint_t	v_hlen;
21051 version_hdrlen_check:
21052 		ASSERT(first_mp != NULL);
21053 		v_hlen = V_HLEN;
21054 		/*
21055 		 * siphon off IPv6 packets coming down from transport
21056 		 * layer modules here.
21057 		 * Note: high-order bit carries NUD reachability confirmation
21058 		 */
21059 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21060 			/*
21061 			 * FIXME: assume that callers of ip_output* call
21062 			 * the right version?
21063 			 */
21064 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21065 			ASSERT(xmit_ill == NULL);
21066 			if (need_decref)
21067 				mp->b_flag |= MSGHASREF;
21068 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21069 			return;
21070 		}
21071 
21072 		if ((v_hlen >> 4) != IP_VERSION) {
21073 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21074 			    "ip_wput_end: q %p (%S)", q, "badvers");
21075 			goto discard_pkt;
21076 		}
21077 		/*
21078 		 * Is the header length at least 20 bytes?
21079 		 *
21080 		 * Are there enough bytes accessible in the header?  If
21081 		 * not, try a pullup.
21082 		 */
21083 		v_hlen &= 0xF;
21084 		v_hlen <<= 2;
21085 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21086 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21087 			    "ip_wput_end: q %p (%S)", q, "badlen");
21088 			goto discard_pkt;
21089 		}
21090 		if (v_hlen > (mp->b_wptr - rptr)) {
21091 			if (!pullupmsg(mp, v_hlen)) {
21092 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21093 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21094 				goto discard_pkt;
21095 			}
21096 			ipha = (ipha_t *)mp->b_rptr;
21097 		}
21098 		/*
21099 		 * Move first entry from any source route into ipha_dst and
21100 		 * verify the options
21101 		 */
21102 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21103 		    zoneid, ipst)) {
21104 			ASSERT(xmit_ill == NULL);
21105 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21106 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21107 			    "ip_wput_end: q %p (%S)", q, "badopts");
21108 			if (need_decref)
21109 				CONN_DEC_REF(connp);
21110 			return;
21111 		}
21112 	}
21113 	dst = ipha->ipha_dst;
21114 
21115 	/*
21116 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21117 	 * we have to run the packet through ip_newroute which will take
21118 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21119 	 * a resolver, or assigning a default gateway, etc.
21120 	 */
21121 	if (CLASSD(dst)) {
21122 		ipif_t	*ipif;
21123 		uint32_t setsrc = 0;
21124 
21125 multicast:
21126 		ASSERT(first_mp != NULL);
21127 		ip2dbg(("ip_wput: CLASSD\n"));
21128 		if (connp == NULL) {
21129 			/*
21130 			 * Use the first good ipif on the ill.
21131 			 * XXX Should this ever happen? (Appears
21132 			 * to show up with just ppp and no ethernet due
21133 			 * to in.rdisc.)
21134 			 * However, ire_send should be able to
21135 			 * call ip_wput_ire directly.
21136 			 *
21137 			 * XXX Also, this can happen for ICMP and other packets
21138 			 * with multicast source addresses.  Perhaps we should
21139 			 * fix things so that we drop the packet in question,
21140 			 * but for now, just run with it.
21141 			 */
21142 			ill_t *ill = (ill_t *)q->q_ptr;
21143 
21144 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21145 			if (ipif == NULL) {
21146 				if (need_decref)
21147 					CONN_DEC_REF(connp);
21148 				freemsg(first_mp);
21149 				return;
21150 			}
21151 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21152 			    ntohl(dst), ill->ill_name));
21153 		} else {
21154 			/*
21155 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21156 			 * and IP_MULTICAST_IF.  The block comment above this
21157 			 * function explains the locking mechanism used here.
21158 			 */
21159 			if (xmit_ill == NULL) {
21160 				xmit_ill = conn_get_held_ill(connp,
21161 				    &connp->conn_outgoing_ill, &err);
21162 				if (err == ILL_LOOKUP_FAILED) {
21163 					ip1dbg(("ip_wput: No ill for "
21164 					    "IP_BOUND_IF\n"));
21165 					BUMP_MIB(&ipst->ips_ip_mib,
21166 					    ipIfStatsOutNoRoutes);
21167 					goto drop_pkt;
21168 				}
21169 			}
21170 
21171 			if (xmit_ill == NULL) {
21172 				ipif = conn_get_held_ipif(connp,
21173 				    &connp->conn_multicast_ipif, &err);
21174 				if (err == IPIF_LOOKUP_FAILED) {
21175 					ip1dbg(("ip_wput: No ipif for "
21176 					    "multicast\n"));
21177 					BUMP_MIB(&ipst->ips_ip_mib,
21178 					    ipIfStatsOutNoRoutes);
21179 					goto drop_pkt;
21180 				}
21181 			}
21182 			if (xmit_ill != NULL) {
21183 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21184 				if (ipif == NULL) {
21185 					ip1dbg(("ip_wput: No ipif for "
21186 					    "xmit_ill\n"));
21187 					BUMP_MIB(&ipst->ips_ip_mib,
21188 					    ipIfStatsOutNoRoutes);
21189 					goto drop_pkt;
21190 				}
21191 			} else if (ipif == NULL || ipif->ipif_isv6) {
21192 				/*
21193 				 * We must do this ipif determination here
21194 				 * else we could pass through ip_newroute
21195 				 * and come back here without the conn context.
21196 				 *
21197 				 * Note: we do late binding i.e. we bind to
21198 				 * the interface when the first packet is sent.
21199 				 * For performance reasons we do not rebind on
21200 				 * each packet but keep the binding until the
21201 				 * next IP_MULTICAST_IF option.
21202 				 *
21203 				 * conn_multicast_{ipif,ill} are shared between
21204 				 * IPv4 and IPv6 and AF_INET6 sockets can
21205 				 * send both IPv4 and IPv6 packets. Hence
21206 				 * we have to check that "isv6" matches above.
21207 				 */
21208 				if (ipif != NULL)
21209 					ipif_refrele(ipif);
21210 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21211 				if (ipif == NULL) {
21212 					ip1dbg(("ip_wput: No ipif for "
21213 					    "multicast\n"));
21214 					BUMP_MIB(&ipst->ips_ip_mib,
21215 					    ipIfStatsOutNoRoutes);
21216 					goto drop_pkt;
21217 				}
21218 				err = conn_set_held_ipif(connp,
21219 				    &connp->conn_multicast_ipif, ipif);
21220 				if (err == IPIF_LOOKUP_FAILED) {
21221 					ipif_refrele(ipif);
21222 					ip1dbg(("ip_wput: No ipif for "
21223 					    "multicast\n"));
21224 					BUMP_MIB(&ipst->ips_ip_mib,
21225 					    ipIfStatsOutNoRoutes);
21226 					goto drop_pkt;
21227 				}
21228 			}
21229 		}
21230 		ASSERT(!ipif->ipif_isv6);
21231 		/*
21232 		 * As we may lose the conn by the time we reach ip_wput_ire,
21233 		 * we copy conn_multicast_loop and conn_dontroute on to an
21234 		 * ipsec_out. In case if this datagram goes out secure,
21235 		 * we need the ill_index also. Copy that also into the
21236 		 * ipsec_out.
21237 		 */
21238 		if (mctl_present) {
21239 			io = (ipsec_out_t *)first_mp->b_rptr;
21240 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21241 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21242 		} else {
21243 			ASSERT(mp == first_mp);
21244 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21245 			    BPRI_HI)) == NULL) {
21246 				ipif_refrele(ipif);
21247 				first_mp = mp;
21248 				goto discard_pkt;
21249 			}
21250 			first_mp->b_datap->db_type = M_CTL;
21251 			first_mp->b_wptr += sizeof (ipsec_info_t);
21252 			/* ipsec_out_secure is B_FALSE now */
21253 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21254 			io = (ipsec_out_t *)first_mp->b_rptr;
21255 			io->ipsec_out_type = IPSEC_OUT;
21256 			io->ipsec_out_len = sizeof (ipsec_out_t);
21257 			io->ipsec_out_use_global_policy = B_TRUE;
21258 			io->ipsec_out_ns = ipst->ips_netstack;
21259 			first_mp->b_cont = mp;
21260 			mctl_present = B_TRUE;
21261 		}
21262 
21263 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21264 		io->ipsec_out_ill_index =
21265 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21266 
21267 		if (connp != NULL) {
21268 			io->ipsec_out_multicast_loop =
21269 			    connp->conn_multicast_loop;
21270 			io->ipsec_out_dontroute = connp->conn_dontroute;
21271 			io->ipsec_out_zoneid = connp->conn_zoneid;
21272 		}
21273 		/*
21274 		 * If the application uses IP_MULTICAST_IF with
21275 		 * different logical addresses of the same ILL, we
21276 		 * need to make sure that the soruce address of
21277 		 * the packet matches the logical IP address used
21278 		 * in the option. We do it by initializing ipha_src
21279 		 * here. This should keep IPsec also happy as
21280 		 * when we return from IPsec processing, we don't
21281 		 * have to worry about getting the right address on
21282 		 * the packet. Thus it is sufficient to look for
21283 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21284 		 * MATCH_IRE_IPIF.
21285 		 *
21286 		 * NOTE : We need to do it for non-secure case also as
21287 		 * this might go out secure if there is a global policy
21288 		 * match in ip_wput_ire.
21289 		 *
21290 		 * As we do not have the ire yet, it is possible that
21291 		 * we set the source address here and then later discover
21292 		 * that the ire implies the source address to be assigned
21293 		 * through the RTF_SETSRC flag.
21294 		 * In that case, the setsrc variable will remind us
21295 		 * that overwritting the source address by the one
21296 		 * of the RTF_SETSRC-flagged ire is allowed.
21297 		 */
21298 		if (ipha->ipha_src == INADDR_ANY &&
21299 		    (connp == NULL || !connp->conn_unspec_src)) {
21300 			ipha->ipha_src = ipif->ipif_src_addr;
21301 			setsrc = RTF_SETSRC;
21302 		}
21303 		/*
21304 		 * Find an IRE which matches the destination and the outgoing
21305 		 * queue (i.e. the outgoing interface.)
21306 		 * For loopback use a unicast IP address for
21307 		 * the ire lookup.
21308 		 */
21309 		if (IS_LOOPBACK(ipif->ipif_ill))
21310 			dst = ipif->ipif_lcl_addr;
21311 
21312 		/*
21313 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21314 		 * We don't need to lookup ire in ctable as the packet
21315 		 * needs to be sent to the destination through the specified
21316 		 * ill irrespective of ires in the cache table.
21317 		 */
21318 		ire = NULL;
21319 		if (xmit_ill == NULL) {
21320 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21321 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21322 		}
21323 
21324 		if (ire == NULL) {
21325 			/*
21326 			 * Multicast loopback and multicast forwarding is
21327 			 * done in ip_wput_ire.
21328 			 *
21329 			 * Mark this packet to make it be delivered to
21330 			 * ip_wput_ire after the new ire has been
21331 			 * created.
21332 			 *
21333 			 * The call to ip_newroute_ipif takes into account
21334 			 * the setsrc reminder. In any case, we take care
21335 			 * of the RTF_MULTIRT flag.
21336 			 */
21337 			mp->b_prev = mp->b_next = NULL;
21338 			if (xmit_ill == NULL ||
21339 			    xmit_ill->ill_ipif_up_count > 0) {
21340 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21341 				    setsrc | RTF_MULTIRT, zoneid, infop);
21342 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21343 				    "ip_wput_end: q %p (%S)", q, "noire");
21344 			} else {
21345 				freemsg(first_mp);
21346 			}
21347 			ipif_refrele(ipif);
21348 			if (xmit_ill != NULL)
21349 				ill_refrele(xmit_ill);
21350 			if (need_decref)
21351 				CONN_DEC_REF(connp);
21352 			return;
21353 		}
21354 
21355 		ipif_refrele(ipif);
21356 		ipif = NULL;
21357 		ASSERT(xmit_ill == NULL);
21358 
21359 		/*
21360 		 * Honor the RTF_SETSRC flag for multicast packets,
21361 		 * if allowed by the setsrc reminder.
21362 		 */
21363 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21364 			ipha->ipha_src = ire->ire_src_addr;
21365 		}
21366 
21367 		/*
21368 		 * Unconditionally force the TTL to 1 for
21369 		 * multirouted multicast packets:
21370 		 * multirouted multicast should not cross
21371 		 * multicast routers.
21372 		 */
21373 		if (ire->ire_flags & RTF_MULTIRT) {
21374 			if (ipha->ipha_ttl > 1) {
21375 				ip2dbg(("ip_wput: forcing multicast "
21376 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21377 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21378 				ipha->ipha_ttl = 1;
21379 			}
21380 		}
21381 	} else {
21382 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21383 		if ((ire != NULL) && (ire->ire_type &
21384 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21385 			ignore_dontroute = B_TRUE;
21386 			ignore_nexthop = B_TRUE;
21387 		}
21388 		if (ire != NULL) {
21389 			ire_refrele(ire);
21390 			ire = NULL;
21391 		}
21392 		/*
21393 		 * Guard against coming in from arp in which case conn is NULL.
21394 		 * Also guard against non M_DATA with dontroute set but
21395 		 * destined to local, loopback or broadcast addresses.
21396 		 */
21397 		if (connp != NULL && connp->conn_dontroute &&
21398 		    !ignore_dontroute) {
21399 dontroute:
21400 			/*
21401 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21402 			 * routing protocols from seeing false direct
21403 			 * connectivity.
21404 			 */
21405 			ipha->ipha_ttl = 1;
21406 			/* If suitable ipif not found, drop packet */
21407 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21408 			if (dst_ipif == NULL) {
21409 noroute:
21410 				ip1dbg(("ip_wput: no route for dst using"
21411 				    " SO_DONTROUTE\n"));
21412 				BUMP_MIB(&ipst->ips_ip_mib,
21413 				    ipIfStatsOutNoRoutes);
21414 				mp->b_prev = mp->b_next = NULL;
21415 				if (first_mp == NULL)
21416 					first_mp = mp;
21417 				goto drop_pkt;
21418 			} else {
21419 				/*
21420 				 * If suitable ipif has been found, set
21421 				 * xmit_ill to the corresponding
21422 				 * ipif_ill because we'll be using the
21423 				 * send_from_ill logic below.
21424 				 */
21425 				ASSERT(xmit_ill == NULL);
21426 				xmit_ill = dst_ipif->ipif_ill;
21427 				mutex_enter(&xmit_ill->ill_lock);
21428 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21429 					mutex_exit(&xmit_ill->ill_lock);
21430 					xmit_ill = NULL;
21431 					ipif_refrele(dst_ipif);
21432 					goto noroute;
21433 				}
21434 				ill_refhold_locked(xmit_ill);
21435 				mutex_exit(&xmit_ill->ill_lock);
21436 				ipif_refrele(dst_ipif);
21437 			}
21438 		}
21439 
21440 send_from_ill:
21441 		if (xmit_ill != NULL) {
21442 			ipif_t *ipif;
21443 
21444 			/*
21445 			 * Mark this packet as originated locally
21446 			 */
21447 			mp->b_prev = mp->b_next = NULL;
21448 
21449 			/*
21450 			 * Could be SO_DONTROUTE case also.
21451 			 * Verify that at least one ipif is up on the ill.
21452 			 */
21453 			if (xmit_ill->ill_ipif_up_count == 0) {
21454 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21455 				    xmit_ill->ill_name));
21456 				goto drop_pkt;
21457 			}
21458 
21459 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21460 			if (ipif == NULL) {
21461 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21462 				    xmit_ill->ill_name));
21463 				goto drop_pkt;
21464 			}
21465 
21466 			match_flags = 0;
21467 			if (IS_UNDER_IPMP(xmit_ill))
21468 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21469 
21470 			/*
21471 			 * Look for a ire that is part of the group,
21472 			 * if found use it else call ip_newroute_ipif.
21473 			 * IPCL_ZONEID is not used for matching because
21474 			 * IP_ALLZONES option is valid only when the
21475 			 * ill is accessible from all zones i.e has a
21476 			 * valid ipif in all zones.
21477 			 */
21478 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21479 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21480 			    msg_getlabel(mp), match_flags, ipst);
21481 			/*
21482 			 * If an ire exists use it or else create
21483 			 * an ire but don't add it to the cache.
21484 			 * Adding an ire may cause issues with
21485 			 * asymmetric routing.
21486 			 * In case of multiroute always act as if
21487 			 * ire does not exist.
21488 			 */
21489 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21490 				if (ire != NULL)
21491 					ire_refrele(ire);
21492 				ip_newroute_ipif(q, first_mp, ipif,
21493 				    dst, connp, 0, zoneid, infop);
21494 				ipif_refrele(ipif);
21495 				ip1dbg(("ip_output: xmit_ill via %s\n",
21496 				    xmit_ill->ill_name));
21497 				ill_refrele(xmit_ill);
21498 				if (need_decref)
21499 					CONN_DEC_REF(connp);
21500 				return;
21501 			}
21502 			ipif_refrele(ipif);
21503 		} else if (ip_nexthop || (connp != NULL &&
21504 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21505 			if (!ip_nexthop) {
21506 				ip_nexthop = B_TRUE;
21507 				nexthop_addr = connp->conn_nexthop_v4;
21508 			}
21509 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21510 			    MATCH_IRE_GW;
21511 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21512 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21513 		} else {
21514 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21515 			    ipst);
21516 		}
21517 		if (!ire) {
21518 			if (ip_nexthop && !ignore_nexthop) {
21519 				if (mctl_present) {
21520 					io = (ipsec_out_t *)first_mp->b_rptr;
21521 					ASSERT(first_mp->b_datap->db_type ==
21522 					    M_CTL);
21523 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21524 				} else {
21525 					ASSERT(mp == first_mp);
21526 					first_mp = allocb(
21527 					    sizeof (ipsec_info_t), BPRI_HI);
21528 					if (first_mp == NULL) {
21529 						first_mp = mp;
21530 						goto discard_pkt;
21531 					}
21532 					first_mp->b_datap->db_type = M_CTL;
21533 					first_mp->b_wptr +=
21534 					    sizeof (ipsec_info_t);
21535 					/* ipsec_out_secure is B_FALSE now */
21536 					bzero(first_mp->b_rptr,
21537 					    sizeof (ipsec_info_t));
21538 					io = (ipsec_out_t *)first_mp->b_rptr;
21539 					io->ipsec_out_type = IPSEC_OUT;
21540 					io->ipsec_out_len =
21541 					    sizeof (ipsec_out_t);
21542 					io->ipsec_out_use_global_policy =
21543 					    B_TRUE;
21544 					io->ipsec_out_ns = ipst->ips_netstack;
21545 					first_mp->b_cont = mp;
21546 					mctl_present = B_TRUE;
21547 				}
21548 				io->ipsec_out_ip_nexthop = ip_nexthop;
21549 				io->ipsec_out_nexthop_addr = nexthop_addr;
21550 			}
21551 noirefound:
21552 			/*
21553 			 * Mark this packet as having originated on
21554 			 * this machine.  This will be noted in
21555 			 * ire_add_then_send, which needs to know
21556 			 * whether to run it back through ip_wput or
21557 			 * ip_rput following successful resolution.
21558 			 */
21559 			mp->b_prev = NULL;
21560 			mp->b_next = NULL;
21561 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21562 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21563 			    "ip_wput_end: q %p (%S)", q, "newroute");
21564 			if (xmit_ill != NULL)
21565 				ill_refrele(xmit_ill);
21566 			if (need_decref)
21567 				CONN_DEC_REF(connp);
21568 			return;
21569 		}
21570 	}
21571 
21572 	/* We now know where we are going with it. */
21573 
21574 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21575 	    "ip_wput_end: q %p (%S)", q, "end");
21576 
21577 	/*
21578 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21579 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21580 	 */
21581 	if (ire->ire_flags & RTF_MULTIRT) {
21582 		/*
21583 		 * Force the TTL of multirouted packets if required.
21584 		 * The TTL of such packets is bounded by the
21585 		 * ip_multirt_ttl ndd variable.
21586 		 */
21587 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21588 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21589 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21590 			    "(was %d), dst 0x%08x\n",
21591 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21592 			    ntohl(ire->ire_addr)));
21593 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21594 		}
21595 		/*
21596 		 * At this point, we check to see if there are any pending
21597 		 * unresolved routes. ire_multirt_resolvable()
21598 		 * checks in O(n) that all IRE_OFFSUBNET ire
21599 		 * entries for the packet's destination and
21600 		 * flagged RTF_MULTIRT are currently resolved.
21601 		 * If some remain unresolved, we make a copy
21602 		 * of the current message. It will be used
21603 		 * to initiate additional route resolutions.
21604 		 */
21605 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21606 		    msg_getlabel(first_mp), ipst);
21607 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21608 		    "multirt_need_resolve %d, first_mp %p\n",
21609 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21610 		if (multirt_need_resolve) {
21611 			copy_mp = copymsg(first_mp);
21612 			if (copy_mp != NULL) {
21613 				MULTIRT_DEBUG_TAG(copy_mp);
21614 			}
21615 		}
21616 	}
21617 
21618 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21619 	/*
21620 	 * Try to resolve another multiroute if
21621 	 * ire_multirt_resolvable() deemed it necessary.
21622 	 * At this point, we need to distinguish
21623 	 * multicasts from other packets. For multicasts,
21624 	 * we call ip_newroute_ipif() and request that both
21625 	 * multirouting and setsrc flags are checked.
21626 	 */
21627 	if (copy_mp != NULL) {
21628 		if (CLASSD(dst)) {
21629 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21630 			if (ipif) {
21631 				ASSERT(infop->ip_opt_ill_index == 0);
21632 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21633 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21634 				ipif_refrele(ipif);
21635 			} else {
21636 				MULTIRT_DEBUG_UNTAG(copy_mp);
21637 				freemsg(copy_mp);
21638 				copy_mp = NULL;
21639 			}
21640 		} else {
21641 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21642 		}
21643 	}
21644 	if (xmit_ill != NULL)
21645 		ill_refrele(xmit_ill);
21646 	if (need_decref)
21647 		CONN_DEC_REF(connp);
21648 	return;
21649 
21650 icmp_parameter_problem:
21651 	/* could not have originated externally */
21652 	ASSERT(mp->b_prev == NULL);
21653 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21654 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21655 		/* it's the IP header length that's in trouble */
21656 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21657 		first_mp = NULL;
21658 	}
21659 
21660 discard_pkt:
21661 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21662 drop_pkt:
21663 	ip1dbg(("ip_wput: dropped packet\n"));
21664 	if (ire != NULL)
21665 		ire_refrele(ire);
21666 	if (need_decref)
21667 		CONN_DEC_REF(connp);
21668 	freemsg(first_mp);
21669 	if (xmit_ill != NULL)
21670 		ill_refrele(xmit_ill);
21671 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21672 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21673 }
21674 
21675 /*
21676  * If this is a conn_t queue, then we pass in the conn. This includes the
21677  * zoneid.
21678  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21679  * in which case we use the global zoneid since those are all part of
21680  * the global zone.
21681  */
21682 void
21683 ip_wput(queue_t *q, mblk_t *mp)
21684 {
21685 	if (CONN_Q(q))
21686 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21687 	else
21688 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21689 }
21690 
21691 /*
21692  *
21693  * The following rules must be observed when accessing any ipif or ill
21694  * that has been cached in the conn. Typically conn_outgoing_ill,
21695  * conn_multicast_ipif and conn_multicast_ill.
21696  *
21697  * Access: The ipif or ill pointed to from the conn can be accessed under
21698  * the protection of the conn_lock or after it has been refheld under the
21699  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21700  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21701  * The reason for this is that a concurrent unplumb could actually be
21702  * cleaning up these cached pointers by walking the conns and might have
21703  * finished cleaning up the conn in question. The macros check that an
21704  * unplumb has not yet started on the ipif or ill.
21705  *
21706  * Caching: An ipif or ill pointer may be cached in the conn only after
21707  * making sure that an unplumb has not started. So the caching is done
21708  * while holding both the conn_lock and the ill_lock and after using the
21709  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21710  * flag before starting the cleanup of conns.
21711  *
21712  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21713  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21714  * or a reference to the ipif or a reference to an ire that references the
21715  * ipif. An ipif only changes its ill when migrating from an underlying ill
21716  * to an IPMP ill in ipif_up().
21717  */
21718 ipif_t *
21719 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21720 {
21721 	ipif_t	*ipif;
21722 	ill_t	*ill;
21723 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21724 
21725 	*err = 0;
21726 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21727 	mutex_enter(&connp->conn_lock);
21728 	ipif = *ipifp;
21729 	if (ipif != NULL) {
21730 		ill = ipif->ipif_ill;
21731 		mutex_enter(&ill->ill_lock);
21732 		if (IPIF_CAN_LOOKUP(ipif)) {
21733 			ipif_refhold_locked(ipif);
21734 			mutex_exit(&ill->ill_lock);
21735 			mutex_exit(&connp->conn_lock);
21736 			rw_exit(&ipst->ips_ill_g_lock);
21737 			return (ipif);
21738 		} else {
21739 			*err = IPIF_LOOKUP_FAILED;
21740 		}
21741 		mutex_exit(&ill->ill_lock);
21742 	}
21743 	mutex_exit(&connp->conn_lock);
21744 	rw_exit(&ipst->ips_ill_g_lock);
21745 	return (NULL);
21746 }
21747 
21748 ill_t *
21749 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21750 {
21751 	ill_t	*ill;
21752 
21753 	*err = 0;
21754 	mutex_enter(&connp->conn_lock);
21755 	ill = *illp;
21756 	if (ill != NULL) {
21757 		mutex_enter(&ill->ill_lock);
21758 		if (ILL_CAN_LOOKUP(ill)) {
21759 			ill_refhold_locked(ill);
21760 			mutex_exit(&ill->ill_lock);
21761 			mutex_exit(&connp->conn_lock);
21762 			return (ill);
21763 		} else {
21764 			*err = ILL_LOOKUP_FAILED;
21765 		}
21766 		mutex_exit(&ill->ill_lock);
21767 	}
21768 	mutex_exit(&connp->conn_lock);
21769 	return (NULL);
21770 }
21771 
21772 static int
21773 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21774 {
21775 	ill_t	*ill;
21776 
21777 	ill = ipif->ipif_ill;
21778 	mutex_enter(&connp->conn_lock);
21779 	mutex_enter(&ill->ill_lock);
21780 	if (IPIF_CAN_LOOKUP(ipif)) {
21781 		*ipifp = ipif;
21782 		mutex_exit(&ill->ill_lock);
21783 		mutex_exit(&connp->conn_lock);
21784 		return (0);
21785 	}
21786 	mutex_exit(&ill->ill_lock);
21787 	mutex_exit(&connp->conn_lock);
21788 	return (IPIF_LOOKUP_FAILED);
21789 }
21790 
21791 /*
21792  * This is called if the outbound datagram needs fragmentation.
21793  *
21794  * NOTE : This function does not ire_refrele the ire argument passed in.
21795  */
21796 static void
21797 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21798     ip_stack_t *ipst, conn_t *connp)
21799 {
21800 	ipha_t		*ipha;
21801 	mblk_t		*mp;
21802 	uint32_t	v_hlen_tos_len;
21803 	uint32_t	max_frag;
21804 	uint32_t	frag_flag;
21805 	boolean_t	dont_use;
21806 
21807 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21808 		mp = ipsec_mp->b_cont;
21809 	} else {
21810 		mp = ipsec_mp;
21811 	}
21812 
21813 	ipha = (ipha_t *)mp->b_rptr;
21814 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21815 
21816 #ifdef	_BIG_ENDIAN
21817 #define	V_HLEN	(v_hlen_tos_len >> 24)
21818 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21819 #else
21820 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21821 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21822 #endif
21823 
21824 #ifndef SPEED_BEFORE_SAFETY
21825 	/*
21826 	 * Check that ipha_length is consistent with
21827 	 * the mblk length
21828 	 */
21829 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21830 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21831 		    LENGTH, msgdsize(mp)));
21832 		freemsg(ipsec_mp);
21833 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21834 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21835 		    "packet length mismatch");
21836 		return;
21837 	}
21838 #endif
21839 	/*
21840 	 * Don't use frag_flag if pre-built packet or source
21841 	 * routed or if multicast (since multicast packets do not solicit
21842 	 * ICMP "packet too big" messages). Get the values of
21843 	 * max_frag and frag_flag atomically by acquiring the
21844 	 * ire_lock.
21845 	 */
21846 	mutex_enter(&ire->ire_lock);
21847 	max_frag = ire->ire_max_frag;
21848 	frag_flag = ire->ire_frag_flag;
21849 	mutex_exit(&ire->ire_lock);
21850 
21851 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21852 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21853 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21854 
21855 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21856 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21857 }
21858 
21859 /*
21860  * Used for deciding the MSS size for the upper layer. Thus
21861  * we need to check the outbound policy values in the conn.
21862  */
21863 int
21864 conn_ipsec_length(conn_t *connp)
21865 {
21866 	ipsec_latch_t *ipl;
21867 
21868 	ipl = connp->conn_latch;
21869 	if (ipl == NULL)
21870 		return (0);
21871 
21872 	if (ipl->ipl_out_policy == NULL)
21873 		return (0);
21874 
21875 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21876 }
21877 
21878 /*
21879  * Returns an estimate of the IPsec headers size. This is used if
21880  * we don't want to call into IPsec to get the exact size.
21881  */
21882 int
21883 ipsec_out_extra_length(mblk_t *ipsec_mp)
21884 {
21885 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21886 	ipsec_action_t *a;
21887 
21888 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21889 	if (!io->ipsec_out_secure)
21890 		return (0);
21891 
21892 	a = io->ipsec_out_act;
21893 
21894 	if (a == NULL) {
21895 		ASSERT(io->ipsec_out_policy != NULL);
21896 		a = io->ipsec_out_policy->ipsp_act;
21897 	}
21898 	ASSERT(a != NULL);
21899 
21900 	return (a->ipa_ovhd);
21901 }
21902 
21903 /*
21904  * Returns an estimate of the IPsec headers size. This is used if
21905  * we don't want to call into IPsec to get the exact size.
21906  */
21907 int
21908 ipsec_in_extra_length(mblk_t *ipsec_mp)
21909 {
21910 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21911 	ipsec_action_t *a;
21912 
21913 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21914 
21915 	a = ii->ipsec_in_action;
21916 	return (a == NULL ? 0 : a->ipa_ovhd);
21917 }
21918 
21919 /*
21920  * If there are any source route options, return the true final
21921  * destination. Otherwise, return the destination.
21922  */
21923 ipaddr_t
21924 ip_get_dst(ipha_t *ipha)
21925 {
21926 	ipoptp_t	opts;
21927 	uchar_t		*opt;
21928 	uint8_t		optval;
21929 	uint8_t		optlen;
21930 	ipaddr_t	dst;
21931 	uint32_t off;
21932 
21933 	dst = ipha->ipha_dst;
21934 
21935 	if (IS_SIMPLE_IPH(ipha))
21936 		return (dst);
21937 
21938 	for (optval = ipoptp_first(&opts, ipha);
21939 	    optval != IPOPT_EOL;
21940 	    optval = ipoptp_next(&opts)) {
21941 		opt = opts.ipoptp_cur;
21942 		optlen = opts.ipoptp_len;
21943 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21944 		switch (optval) {
21945 		case IPOPT_SSRR:
21946 		case IPOPT_LSRR:
21947 			off = opt[IPOPT_OFFSET];
21948 			/*
21949 			 * If one of the conditions is true, it means
21950 			 * end of options and dst already has the right
21951 			 * value.
21952 			 */
21953 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21954 				off = optlen - IP_ADDR_LEN;
21955 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21956 			}
21957 			return (dst);
21958 		default:
21959 			break;
21960 		}
21961 	}
21962 
21963 	return (dst);
21964 }
21965 
21966 mblk_t *
21967 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21968     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21969 {
21970 	ipsec_out_t	*io;
21971 	mblk_t		*first_mp;
21972 	boolean_t policy_present;
21973 	ip_stack_t	*ipst;
21974 	ipsec_stack_t	*ipss;
21975 
21976 	ASSERT(ire != NULL);
21977 	ipst = ire->ire_ipst;
21978 	ipss = ipst->ips_netstack->netstack_ipsec;
21979 
21980 	first_mp = mp;
21981 	if (mp->b_datap->db_type == M_CTL) {
21982 		io = (ipsec_out_t *)first_mp->b_rptr;
21983 		/*
21984 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21985 		 *
21986 		 * 1) There is per-socket policy (including cached global
21987 		 *    policy) or a policy on the IP-in-IP tunnel.
21988 		 * 2) There is no per-socket policy, but it is
21989 		 *    a multicast packet that needs to go out
21990 		 *    on a specific interface. This is the case
21991 		 *    where (ip_wput and ip_wput_multicast) attaches
21992 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21993 		 *
21994 		 * In case (2) we check with global policy to
21995 		 * see if there is a match and set the ill_index
21996 		 * appropriately so that we can lookup the ire
21997 		 * properly in ip_wput_ipsec_out.
21998 		 */
21999 
22000 		/*
22001 		 * ipsec_out_use_global_policy is set to B_FALSE
22002 		 * in ipsec_in_to_out(). Refer to that function for
22003 		 * details.
22004 		 */
22005 		if ((io->ipsec_out_latch == NULL) &&
22006 		    (io->ipsec_out_use_global_policy)) {
22007 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22008 			    ire, connp, unspec_src, zoneid));
22009 		}
22010 		if (!io->ipsec_out_secure) {
22011 			/*
22012 			 * If this is not a secure packet, drop
22013 			 * the IPSEC_OUT mp and treat it as a clear
22014 			 * packet. This happens when we are sending
22015 			 * a ICMP reply back to a clear packet. See
22016 			 * ipsec_in_to_out() for details.
22017 			 */
22018 			mp = first_mp->b_cont;
22019 			freeb(first_mp);
22020 		}
22021 		return (mp);
22022 	}
22023 	/*
22024 	 * See whether we need to attach a global policy here. We
22025 	 * don't depend on the conn (as it could be null) for deciding
22026 	 * what policy this datagram should go through because it
22027 	 * should have happened in ip_wput if there was some
22028 	 * policy. This normally happens for connections which are not
22029 	 * fully bound preventing us from caching policies in
22030 	 * ip_bind. Packets coming from the TCP listener/global queue
22031 	 * - which are non-hard_bound - could also be affected by
22032 	 * applying policy here.
22033 	 *
22034 	 * If this packet is coming from tcp global queue or listener,
22035 	 * we will be applying policy here.  This may not be *right*
22036 	 * if these packets are coming from the detached connection as
22037 	 * it could have gone in clear before. This happens only if a
22038 	 * TCP connection started when there is no policy and somebody
22039 	 * added policy before it became detached. Thus packets of the
22040 	 * detached connection could go out secure and the other end
22041 	 * would drop it because it will be expecting in clear. The
22042 	 * converse is not true i.e if somebody starts a TCP
22043 	 * connection and deletes the policy, all the packets will
22044 	 * still go out with the policy that existed before deleting
22045 	 * because ip_unbind sends up policy information which is used
22046 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22047 	 * TCP to attach a dummy IPSEC_OUT and set
22048 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22049 	 * affect performance for normal cases, we are not doing it.
22050 	 * Thus, set policy before starting any TCP connections.
22051 	 *
22052 	 * NOTE - We might apply policy even for a hard bound connection
22053 	 * - for which we cached policy in ip_bind - if somebody added
22054 	 * global policy after we inherited the policy in ip_bind.
22055 	 * This means that the packets that were going out in clear
22056 	 * previously would start going secure and hence get dropped
22057 	 * on the other side. To fix this, TCP attaches a dummy
22058 	 * ipsec_out and make sure that we don't apply global policy.
22059 	 */
22060 	if (ipha != NULL)
22061 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22062 	else
22063 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22064 	if (!policy_present)
22065 		return (mp);
22066 
22067 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22068 	    zoneid));
22069 }
22070 
22071 /*
22072  * This function does the ire_refrele of the ire passed in as the
22073  * argument. As this function looks up more ires i.e broadcast ires,
22074  * it needs to REFRELE them. Currently, for simplicity we don't
22075  * differentiate the one passed in and looked up here. We always
22076  * REFRELE.
22077  * IPQoS Notes:
22078  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22079  * IPsec packets are done in ipsec_out_process.
22080  */
22081 void
22082 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22083     zoneid_t zoneid)
22084 {
22085 	ipha_t		*ipha;
22086 #define	rptr	((uchar_t *)ipha)
22087 	queue_t		*stq;
22088 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22089 	uint32_t	v_hlen_tos_len;
22090 	uint32_t	ttl_protocol;
22091 	ipaddr_t	src;
22092 	ipaddr_t	dst;
22093 	uint32_t	cksum;
22094 	ipaddr_t	orig_src;
22095 	ire_t		*ire1;
22096 	mblk_t		*next_mp;
22097 	uint_t		hlen;
22098 	uint16_t	*up;
22099 	uint32_t	max_frag = ire->ire_max_frag;
22100 	ill_t		*ill = ire_to_ill(ire);
22101 	int		clusterwide;
22102 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22103 	int		ipsec_len;
22104 	mblk_t		*first_mp;
22105 	ipsec_out_t	*io;
22106 	boolean_t	conn_dontroute;		/* conn value for multicast */
22107 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22108 	boolean_t	multicast_forward;	/* Should we forward ? */
22109 	boolean_t	unspec_src;
22110 	ill_t		*conn_outgoing_ill = NULL;
22111 	ill_t		*ire_ill;
22112 	ill_t		*ire1_ill;
22113 	ill_t		*out_ill;
22114 	uint32_t 	ill_index = 0;
22115 	boolean_t	multirt_send = B_FALSE;
22116 	int		err;
22117 	ipxmit_state_t	pktxmit_state;
22118 	ip_stack_t	*ipst = ire->ire_ipst;
22119 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22120 
22121 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22122 	    "ip_wput_ire_start: q %p", q);
22123 
22124 	multicast_forward = B_FALSE;
22125 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22126 
22127 	if (ire->ire_flags & RTF_MULTIRT) {
22128 		/*
22129 		 * Multirouting case. The bucket where ire is stored
22130 		 * probably holds other RTF_MULTIRT flagged ire
22131 		 * to the destination. In this call to ip_wput_ire,
22132 		 * we attempt to send the packet through all
22133 		 * those ires. Thus, we first ensure that ire is the
22134 		 * first RTF_MULTIRT ire in the bucket,
22135 		 * before walking the ire list.
22136 		 */
22137 		ire_t *first_ire;
22138 		irb_t *irb = ire->ire_bucket;
22139 		ASSERT(irb != NULL);
22140 
22141 		/* Make sure we do not omit any multiroute ire. */
22142 		IRB_REFHOLD(irb);
22143 		for (first_ire = irb->irb_ire;
22144 		    first_ire != NULL;
22145 		    first_ire = first_ire->ire_next) {
22146 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22147 			    (first_ire->ire_addr == ire->ire_addr) &&
22148 			    !(first_ire->ire_marks &
22149 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22150 				break;
22151 		}
22152 
22153 		if ((first_ire != NULL) && (first_ire != ire)) {
22154 			IRE_REFHOLD(first_ire);
22155 			ire_refrele(ire);
22156 			ire = first_ire;
22157 			ill = ire_to_ill(ire);
22158 		}
22159 		IRB_REFRELE(irb);
22160 	}
22161 
22162 	/*
22163 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22164 	 * for performance we don't grab the mutexs in the fastpath
22165 	 */
22166 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22167 	    connp->conn_outgoing_ill != NULL) {
22168 		conn_outgoing_ill = conn_get_held_ill(connp,
22169 		    &connp->conn_outgoing_ill, &err);
22170 		if (err == ILL_LOOKUP_FAILED) {
22171 			ire_refrele(ire);
22172 			freemsg(mp);
22173 			return;
22174 		}
22175 	}
22176 
22177 	if (mp->b_datap->db_type != M_CTL) {
22178 		ipha = (ipha_t *)mp->b_rptr;
22179 	} else {
22180 		io = (ipsec_out_t *)mp->b_rptr;
22181 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22182 		ASSERT(zoneid == io->ipsec_out_zoneid);
22183 		ASSERT(zoneid != ALL_ZONES);
22184 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22185 		dst = ipha->ipha_dst;
22186 		/*
22187 		 * For the multicast case, ipsec_out carries conn_dontroute and
22188 		 * conn_multicast_loop as conn may not be available here. We
22189 		 * need this for multicast loopback and forwarding which is done
22190 		 * later in the code.
22191 		 */
22192 		if (CLASSD(dst)) {
22193 			conn_dontroute = io->ipsec_out_dontroute;
22194 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22195 			/*
22196 			 * If conn_dontroute is not set or conn_multicast_loop
22197 			 * is set, we need to do forwarding/loopback. For
22198 			 * datagrams from ip_wput_multicast, conn_dontroute is
22199 			 * set to B_TRUE and conn_multicast_loop is set to
22200 			 * B_FALSE so that we neither do forwarding nor
22201 			 * loopback.
22202 			 */
22203 			if (!conn_dontroute || conn_multicast_loop)
22204 				multicast_forward = B_TRUE;
22205 		}
22206 	}
22207 
22208 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22209 	    ire->ire_zoneid != ALL_ZONES) {
22210 		/*
22211 		 * When a zone sends a packet to another zone, we try to deliver
22212 		 * the packet under the same conditions as if the destination
22213 		 * was a real node on the network. To do so, we look for a
22214 		 * matching route in the forwarding table.
22215 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22216 		 * ip_newroute() does.
22217 		 * Note that IRE_LOCAL are special, since they are used
22218 		 * when the zoneid doesn't match in some cases. This means that
22219 		 * we need to handle ipha_src differently since ire_src_addr
22220 		 * belongs to the receiving zone instead of the sending zone.
22221 		 * When ip_restrict_interzone_loopback is set, then
22222 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22223 		 * for loopback between zones when the logical "Ethernet" would
22224 		 * have looped them back.
22225 		 */
22226 		ire_t *src_ire;
22227 
22228 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22229 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22230 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22231 		if (src_ire != NULL &&
22232 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22233 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22234 		    ire_local_same_lan(ire, src_ire))) {
22235 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22236 				ipha->ipha_src = src_ire->ire_src_addr;
22237 			ire_refrele(src_ire);
22238 		} else {
22239 			ire_refrele(ire);
22240 			if (conn_outgoing_ill != NULL)
22241 				ill_refrele(conn_outgoing_ill);
22242 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22243 			if (src_ire != NULL) {
22244 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22245 					ire_refrele(src_ire);
22246 					freemsg(mp);
22247 					return;
22248 				}
22249 				ire_refrele(src_ire);
22250 			}
22251 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22252 				/* Failed */
22253 				freemsg(mp);
22254 				return;
22255 			}
22256 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22257 			    ipst);
22258 			return;
22259 		}
22260 	}
22261 
22262 	if (mp->b_datap->db_type == M_CTL ||
22263 	    ipss->ipsec_outbound_v4_policy_present) {
22264 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22265 		    unspec_src, zoneid);
22266 		if (mp == NULL) {
22267 			ire_refrele(ire);
22268 			if (conn_outgoing_ill != NULL)
22269 				ill_refrele(conn_outgoing_ill);
22270 			return;
22271 		}
22272 		/*
22273 		 * Trusted Extensions supports all-zones interfaces, so
22274 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22275 		 * the global zone.
22276 		 */
22277 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22278 			io = (ipsec_out_t *)mp->b_rptr;
22279 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22280 			zoneid = io->ipsec_out_zoneid;
22281 		}
22282 	}
22283 
22284 	first_mp = mp;
22285 	ipsec_len = 0;
22286 
22287 	if (first_mp->b_datap->db_type == M_CTL) {
22288 		io = (ipsec_out_t *)first_mp->b_rptr;
22289 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22290 		mp = first_mp->b_cont;
22291 		ipsec_len = ipsec_out_extra_length(first_mp);
22292 		ASSERT(ipsec_len >= 0);
22293 		/* We already picked up the zoneid from the M_CTL above */
22294 		ASSERT(zoneid == io->ipsec_out_zoneid);
22295 		ASSERT(zoneid != ALL_ZONES);
22296 
22297 		/*
22298 		 * Drop M_CTL here if IPsec processing is not needed.
22299 		 * (Non-IPsec use of M_CTL extracted any information it
22300 		 * needed above).
22301 		 */
22302 		if (ipsec_len == 0) {
22303 			freeb(first_mp);
22304 			first_mp = mp;
22305 		}
22306 	}
22307 
22308 	/*
22309 	 * Fast path for ip_wput_ire
22310 	 */
22311 
22312 	ipha = (ipha_t *)mp->b_rptr;
22313 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22314 	dst = ipha->ipha_dst;
22315 
22316 	/*
22317 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22318 	 * if the socket is a SOCK_RAW type. The transport checksum should
22319 	 * be provided in the pre-built packet, so we don't need to compute it.
22320 	 * Also, other application set flags, like DF, should not be altered.
22321 	 * Other transport MUST pass down zero.
22322 	 */
22323 	ip_hdr_included = ipha->ipha_ident;
22324 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22325 
22326 	if (CLASSD(dst)) {
22327 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22328 		    ntohl(dst),
22329 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22330 		    ntohl(ire->ire_addr)));
22331 	}
22332 
22333 /* Macros to extract header fields from data already in registers */
22334 #ifdef	_BIG_ENDIAN
22335 #define	V_HLEN	(v_hlen_tos_len >> 24)
22336 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22337 #define	PROTO	(ttl_protocol & 0xFF)
22338 #else
22339 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22340 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22341 #define	PROTO	(ttl_protocol >> 8)
22342 #endif
22343 
22344 	orig_src = src = ipha->ipha_src;
22345 	/* (The loop back to "another" is explained down below.) */
22346 another:;
22347 	/*
22348 	 * Assign an ident value for this packet.  We assign idents on
22349 	 * a per destination basis out of the IRE.  There could be
22350 	 * other threads targeting the same destination, so we have to
22351 	 * arrange for a atomic increment.  Note that we use a 32-bit
22352 	 * atomic add because it has better performance than its
22353 	 * 16-bit sibling.
22354 	 *
22355 	 * If running in cluster mode and if the source address
22356 	 * belongs to a replicated service then vector through
22357 	 * cl_inet_ipident vector to allocate ip identifier
22358 	 * NOTE: This is a contract private interface with the
22359 	 * clustering group.
22360 	 */
22361 	clusterwide = 0;
22362 	if (cl_inet_ipident) {
22363 		ASSERT(cl_inet_isclusterwide);
22364 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22365 
22366 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22367 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22368 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22369 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22370 			    (uint8_t *)(uintptr_t)dst, NULL);
22371 			clusterwide = 1;
22372 		}
22373 	}
22374 	if (!clusterwide) {
22375 		ipha->ipha_ident =
22376 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22377 	}
22378 
22379 #ifndef _BIG_ENDIAN
22380 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22381 #endif
22382 
22383 	/*
22384 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22385 	 * This is needed to obey conn_unspec_src when packets go through
22386 	 * ip_newroute + arp.
22387 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22388 	 */
22389 	if (src == INADDR_ANY && !unspec_src) {
22390 		/*
22391 		 * Assign the appropriate source address from the IRE if none
22392 		 * was specified.
22393 		 */
22394 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22395 
22396 		src = ire->ire_src_addr;
22397 		if (connp == NULL) {
22398 			ip1dbg(("ip_wput_ire: no connp and no src "
22399 			    "address for dst 0x%x, using src 0x%x\n",
22400 			    ntohl(dst),
22401 			    ntohl(src)));
22402 		}
22403 		ipha->ipha_src = src;
22404 	}
22405 	stq = ire->ire_stq;
22406 
22407 	/*
22408 	 * We only allow ire chains for broadcasts since there will
22409 	 * be multiple IRE_CACHE entries for the same multicast
22410 	 * address (one per ipif).
22411 	 */
22412 	next_mp = NULL;
22413 
22414 	/* broadcast packet */
22415 	if (ire->ire_type == IRE_BROADCAST)
22416 		goto broadcast;
22417 
22418 	/* loopback ? */
22419 	if (stq == NULL)
22420 		goto nullstq;
22421 
22422 	/* The ill_index for outbound ILL */
22423 	ill_index = Q_TO_INDEX(stq);
22424 
22425 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22426 	ttl_protocol = ((uint16_t *)ipha)[4];
22427 
22428 	/* pseudo checksum (do it in parts for IP header checksum) */
22429 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22430 
22431 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22432 		queue_t *dev_q = stq->q_next;
22433 
22434 		/*
22435 		 * For DIRECT_CAPABLE, we do flow control at
22436 		 * the time of sending the packet. See
22437 		 * ILL_SEND_TX().
22438 		 */
22439 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22440 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22441 			goto blocked;
22442 
22443 		if ((PROTO == IPPROTO_UDP) &&
22444 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22445 			hlen = (V_HLEN & 0xF) << 2;
22446 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22447 			if (*up != 0) {
22448 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22449 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22450 				/* Software checksum? */
22451 				if (DB_CKSUMFLAGS(mp) == 0) {
22452 					IP_STAT(ipst, ip_out_sw_cksum);
22453 					IP_STAT_UPDATE(ipst,
22454 					    ip_udp_out_sw_cksum_bytes,
22455 					    LENGTH - hlen);
22456 				}
22457 			}
22458 		}
22459 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22460 		hlen = (V_HLEN & 0xF) << 2;
22461 		if (PROTO == IPPROTO_TCP) {
22462 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22463 			/*
22464 			 * The packet header is processed once and for all, even
22465 			 * in the multirouting case. We disable hardware
22466 			 * checksum if the packet is multirouted, as it will be
22467 			 * replicated via several interfaces, and not all of
22468 			 * them may have this capability.
22469 			 */
22470 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22471 			    LENGTH, max_frag, ipsec_len, cksum);
22472 			/* Software checksum? */
22473 			if (DB_CKSUMFLAGS(mp) == 0) {
22474 				IP_STAT(ipst, ip_out_sw_cksum);
22475 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22476 				    LENGTH - hlen);
22477 			}
22478 		} else {
22479 			sctp_hdr_t	*sctph;
22480 
22481 			ASSERT(PROTO == IPPROTO_SCTP);
22482 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22483 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22484 			/*
22485 			 * Zero out the checksum field to ensure proper
22486 			 * checksum calculation.
22487 			 */
22488 			sctph->sh_chksum = 0;
22489 #ifdef	DEBUG
22490 			if (!skip_sctp_cksum)
22491 #endif
22492 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22493 		}
22494 	}
22495 
22496 	/*
22497 	 * If this is a multicast packet and originated from ip_wput
22498 	 * we need to do loopback and forwarding checks. If it comes
22499 	 * from ip_wput_multicast, we SHOULD not do this.
22500 	 */
22501 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22502 
22503 	/* checksum */
22504 	cksum += ttl_protocol;
22505 
22506 	/* fragment the packet */
22507 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22508 		goto fragmentit;
22509 	/*
22510 	 * Don't use frag_flag if packet is pre-built or source
22511 	 * routed or if multicast (since multicast packets do
22512 	 * not solicit ICMP "packet too big" messages).
22513 	 */
22514 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22515 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22516 	    !ip_source_route_included(ipha)) &&
22517 	    !CLASSD(ipha->ipha_dst))
22518 		ipha->ipha_fragment_offset_and_flags |=
22519 		    htons(ire->ire_frag_flag);
22520 
22521 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22522 		/* calculate IP header checksum */
22523 		cksum += ipha->ipha_ident;
22524 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22525 		cksum += ipha->ipha_fragment_offset_and_flags;
22526 
22527 		/* IP options present */
22528 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22529 		if (hlen)
22530 			goto checksumoptions;
22531 
22532 		/* calculate hdr checksum */
22533 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22534 		cksum = ~(cksum + (cksum >> 16));
22535 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22536 	}
22537 	if (ipsec_len != 0) {
22538 		/*
22539 		 * We will do the rest of the processing after
22540 		 * we come back from IPsec in ip_wput_ipsec_out().
22541 		 */
22542 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22543 
22544 		io = (ipsec_out_t *)first_mp->b_rptr;
22545 		io->ipsec_out_ill_index =
22546 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22547 		ipsec_out_process(q, first_mp, ire, 0);
22548 		ire_refrele(ire);
22549 		if (conn_outgoing_ill != NULL)
22550 			ill_refrele(conn_outgoing_ill);
22551 		return;
22552 	}
22553 
22554 	/*
22555 	 * In most cases, the emission loop below is entered only
22556 	 * once. Only in the case where the ire holds the
22557 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22558 	 * flagged ires in the bucket, and send the packet
22559 	 * through all crossed RTF_MULTIRT routes.
22560 	 */
22561 	if (ire->ire_flags & RTF_MULTIRT) {
22562 		multirt_send = B_TRUE;
22563 	}
22564 	do {
22565 		if (multirt_send) {
22566 			irb_t *irb;
22567 			/*
22568 			 * We are in a multiple send case, need to get
22569 			 * the next ire and make a duplicate of the packet.
22570 			 * ire1 holds here the next ire to process in the
22571 			 * bucket. If multirouting is expected,
22572 			 * any non-RTF_MULTIRT ire that has the
22573 			 * right destination address is ignored.
22574 			 */
22575 			irb = ire->ire_bucket;
22576 			ASSERT(irb != NULL);
22577 
22578 			IRB_REFHOLD(irb);
22579 			for (ire1 = ire->ire_next;
22580 			    ire1 != NULL;
22581 			    ire1 = ire1->ire_next) {
22582 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22583 					continue;
22584 				if (ire1->ire_addr != ire->ire_addr)
22585 					continue;
22586 				if (ire1->ire_marks &
22587 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22588 					continue;
22589 
22590 				/* Got one */
22591 				IRE_REFHOLD(ire1);
22592 				break;
22593 			}
22594 			IRB_REFRELE(irb);
22595 
22596 			if (ire1 != NULL) {
22597 				next_mp = copyb(mp);
22598 				if ((next_mp == NULL) ||
22599 				    ((mp->b_cont != NULL) &&
22600 				    ((next_mp->b_cont =
22601 				    dupmsg(mp->b_cont)) == NULL))) {
22602 					freemsg(next_mp);
22603 					next_mp = NULL;
22604 					ire_refrele(ire1);
22605 					ire1 = NULL;
22606 				}
22607 			}
22608 
22609 			/* Last multiroute ire; don't loop anymore. */
22610 			if (ire1 == NULL) {
22611 				multirt_send = B_FALSE;
22612 			}
22613 		}
22614 
22615 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22616 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22617 		    mblk_t *, mp);
22618 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22619 		    ipst->ips_ipv4firewall_physical_out,
22620 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22621 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22622 
22623 		if (mp == NULL)
22624 			goto release_ire_and_ill;
22625 
22626 		if (ipst->ips_ipobs_enabled) {
22627 			zoneid_t szone;
22628 
22629 			/*
22630 			 * On the outbound path the destination zone will be
22631 			 * unknown as we're sending this packet out on the
22632 			 * wire.
22633 			 */
22634 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22635 			    ALL_ZONES);
22636 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22637 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22638 		}
22639 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22640 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22641 
22642 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22643 
22644 		if ((pktxmit_state == SEND_FAILED) ||
22645 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22646 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22647 			    "- packet dropped\n"));
22648 release_ire_and_ill:
22649 			ire_refrele(ire);
22650 			if (next_mp != NULL) {
22651 				freemsg(next_mp);
22652 				ire_refrele(ire1);
22653 			}
22654 			if (conn_outgoing_ill != NULL)
22655 				ill_refrele(conn_outgoing_ill);
22656 			return;
22657 		}
22658 
22659 		if (CLASSD(dst)) {
22660 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22661 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22662 			    LENGTH);
22663 		}
22664 
22665 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22666 		    "ip_wput_ire_end: q %p (%S)",
22667 		    q, "last copy out");
22668 		IRE_REFRELE(ire);
22669 
22670 		if (multirt_send) {
22671 			ASSERT(ire1);
22672 			/*
22673 			 * Proceed with the next RTF_MULTIRT ire,
22674 			 * Also set up the send-to queue accordingly.
22675 			 */
22676 			ire = ire1;
22677 			ire1 = NULL;
22678 			stq = ire->ire_stq;
22679 			mp = next_mp;
22680 			next_mp = NULL;
22681 			ipha = (ipha_t *)mp->b_rptr;
22682 			ill_index = Q_TO_INDEX(stq);
22683 			ill = (ill_t *)stq->q_ptr;
22684 		}
22685 	} while (multirt_send);
22686 	if (conn_outgoing_ill != NULL)
22687 		ill_refrele(conn_outgoing_ill);
22688 	return;
22689 
22690 	/*
22691 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22692 	 */
22693 broadcast:
22694 	{
22695 		/*
22696 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22697 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22698 		 * can be overridden stack-wide through the ip_broadcast_ttl
22699 		 * ndd tunable, or on a per-connection basis through the
22700 		 * IP_BROADCAST_TTL socket option.
22701 		 *
22702 		 * In the event that we are replying to incoming ICMP packets,
22703 		 * connp could be NULL.
22704 		 */
22705 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22706 		if (connp != NULL) {
22707 			if (connp->conn_dontroute)
22708 				ipha->ipha_ttl = 1;
22709 			else if (connp->conn_broadcast_ttl != 0)
22710 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22711 		}
22712 
22713 		/*
22714 		 * Note that we are not doing a IRB_REFHOLD here.
22715 		 * Actually we don't care if the list changes i.e
22716 		 * if somebody deletes an IRE from the list while
22717 		 * we drop the lock, the next time we come around
22718 		 * ire_next will be NULL and hence we won't send
22719 		 * out multiple copies which is fine.
22720 		 */
22721 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22722 		ire1 = ire->ire_next;
22723 		if (conn_outgoing_ill != NULL) {
22724 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22725 				ASSERT(ire1 == ire->ire_next);
22726 				if (ire1 != NULL && ire1->ire_addr == dst) {
22727 					ire_refrele(ire);
22728 					ire = ire1;
22729 					IRE_REFHOLD(ire);
22730 					ire1 = ire->ire_next;
22731 					continue;
22732 				}
22733 				rw_exit(&ire->ire_bucket->irb_lock);
22734 				/* Did not find a matching ill */
22735 				ip1dbg(("ip_wput_ire: broadcast with no "
22736 				    "matching IP_BOUND_IF ill %s dst %x\n",
22737 				    conn_outgoing_ill->ill_name, dst));
22738 				freemsg(first_mp);
22739 				if (ire != NULL)
22740 					ire_refrele(ire);
22741 				ill_refrele(conn_outgoing_ill);
22742 				return;
22743 			}
22744 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22745 			/*
22746 			 * If the next IRE has the same address and is not one
22747 			 * of the two copies that we need to send, try to see
22748 			 * whether this copy should be sent at all. This
22749 			 * assumes that we insert loopbacks first and then
22750 			 * non-loopbacks. This is acheived by inserting the
22751 			 * loopback always before non-loopback.
22752 			 * This is used to send a single copy of a broadcast
22753 			 * packet out all physical interfaces that have an
22754 			 * matching IRE_BROADCAST while also looping
22755 			 * back one copy (to ip_wput_local) for each
22756 			 * matching physical interface. However, we avoid
22757 			 * sending packets out different logical that match by
22758 			 * having ipif_up/ipif_down supress duplicate
22759 			 * IRE_BROADCASTS.
22760 			 *
22761 			 * This feature is currently used to get broadcasts
22762 			 * sent to multiple interfaces, when the broadcast
22763 			 * address being used applies to multiple interfaces.
22764 			 * For example, a whole net broadcast will be
22765 			 * replicated on every connected subnet of
22766 			 * the target net.
22767 			 *
22768 			 * Each zone has its own set of IRE_BROADCASTs, so that
22769 			 * we're able to distribute inbound packets to multiple
22770 			 * zones who share a broadcast address. We avoid looping
22771 			 * back outbound packets in different zones but on the
22772 			 * same ill, as the application would see duplicates.
22773 			 *
22774 			 * This logic assumes that ire_add_v4() groups the
22775 			 * IRE_BROADCAST entries so that those with the same
22776 			 * ire_addr are kept together.
22777 			 */
22778 			ire_ill = ire->ire_ipif->ipif_ill;
22779 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22780 				while (ire1 != NULL && ire1->ire_addr == dst) {
22781 					ire1_ill = ire1->ire_ipif->ipif_ill;
22782 					if (ire1_ill != ire_ill)
22783 						break;
22784 					ire1 = ire1->ire_next;
22785 				}
22786 			}
22787 		}
22788 		ASSERT(multirt_send == B_FALSE);
22789 		if (ire1 != NULL && ire1->ire_addr == dst) {
22790 			if ((ire->ire_flags & RTF_MULTIRT) &&
22791 			    (ire1->ire_flags & RTF_MULTIRT)) {
22792 				/*
22793 				 * We are in the multirouting case.
22794 				 * The message must be sent at least
22795 				 * on both ires. These ires have been
22796 				 * inserted AFTER the standard ones
22797 				 * in ip_rt_add(). There are thus no
22798 				 * other ire entries for the destination
22799 				 * address in the rest of the bucket
22800 				 * that do not have the RTF_MULTIRT
22801 				 * flag. We don't process a copy
22802 				 * of the message here. This will be
22803 				 * done in the final sending loop.
22804 				 */
22805 				multirt_send = B_TRUE;
22806 			} else {
22807 				next_mp = ip_copymsg(first_mp);
22808 				if (next_mp != NULL)
22809 					IRE_REFHOLD(ire1);
22810 			}
22811 		}
22812 		rw_exit(&ire->ire_bucket->irb_lock);
22813 	}
22814 
22815 	if (stq) {
22816 		/*
22817 		 * A non-NULL send-to queue means this packet is going
22818 		 * out of this machine.
22819 		 */
22820 		out_ill = (ill_t *)stq->q_ptr;
22821 
22822 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22823 		ttl_protocol = ((uint16_t *)ipha)[4];
22824 		/*
22825 		 * We accumulate the pseudo header checksum in cksum.
22826 		 * This is pretty hairy code, so watch close.  One
22827 		 * thing to keep in mind is that UDP and TCP have
22828 		 * stored their respective datagram lengths in their
22829 		 * checksum fields.  This lines things up real nice.
22830 		 */
22831 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22832 		    (src >> 16) + (src & 0xFFFF);
22833 		/*
22834 		 * We assume the udp checksum field contains the
22835 		 * length, so to compute the pseudo header checksum,
22836 		 * all we need is the protocol number and src/dst.
22837 		 */
22838 		/* Provide the checksums for UDP and TCP. */
22839 		if ((PROTO == IPPROTO_TCP) &&
22840 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22841 			/* hlen gets the number of uchar_ts in the IP header */
22842 			hlen = (V_HLEN & 0xF) << 2;
22843 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22844 			IP_STAT(ipst, ip_out_sw_cksum);
22845 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22846 			    LENGTH - hlen);
22847 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22848 		} else if (PROTO == IPPROTO_SCTP &&
22849 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22850 			sctp_hdr_t	*sctph;
22851 
22852 			hlen = (V_HLEN & 0xF) << 2;
22853 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22854 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22855 			sctph->sh_chksum = 0;
22856 #ifdef	DEBUG
22857 			if (!skip_sctp_cksum)
22858 #endif
22859 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22860 		} else {
22861 			queue_t	*dev_q = stq->q_next;
22862 
22863 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22864 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22865 blocked:
22866 				ipha->ipha_ident = ip_hdr_included;
22867 				/*
22868 				 * If we don't have a conn to apply
22869 				 * backpressure, free the message.
22870 				 * In the ire_send path, we don't know
22871 				 * the position to requeue the packet. Rather
22872 				 * than reorder packets, we just drop this
22873 				 * packet.
22874 				 */
22875 				if (ipst->ips_ip_output_queue &&
22876 				    connp != NULL &&
22877 				    caller != IRE_SEND) {
22878 					if (caller == IP_WSRV) {
22879 						idl_tx_list_t *idl_txl;
22880 
22881 						idl_txl =
22882 						    &ipst->ips_idl_tx_list[0];
22883 						connp->conn_did_putbq = 1;
22884 						(void) putbq(connp->conn_wq,
22885 						    first_mp);
22886 						conn_drain_insert(connp,
22887 						    idl_txl);
22888 						/*
22889 						 * This is the service thread,
22890 						 * and the queue is already
22891 						 * noenabled. The check for
22892 						 * canput and the putbq is not
22893 						 * atomic. So we need to check
22894 						 * again.
22895 						 */
22896 						if (canput(stq->q_next))
22897 							connp->conn_did_putbq
22898 							    = 0;
22899 						IP_STAT(ipst, ip_conn_flputbq);
22900 					} else {
22901 						/*
22902 						 * We are not the service proc.
22903 						 * ip_wsrv will be scheduled or
22904 						 * is already running.
22905 						 */
22906 
22907 						(void) putq(connp->conn_wq,
22908 						    first_mp);
22909 					}
22910 				} else {
22911 					out_ill = (ill_t *)stq->q_ptr;
22912 					BUMP_MIB(out_ill->ill_ip_mib,
22913 					    ipIfStatsOutDiscards);
22914 					freemsg(first_mp);
22915 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22916 					    "ip_wput_ire_end: q %p (%S)",
22917 					    q, "discard");
22918 				}
22919 				ire_refrele(ire);
22920 				if (next_mp) {
22921 					ire_refrele(ire1);
22922 					freemsg(next_mp);
22923 				}
22924 				if (conn_outgoing_ill != NULL)
22925 					ill_refrele(conn_outgoing_ill);
22926 				return;
22927 			}
22928 			if ((PROTO == IPPROTO_UDP) &&
22929 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22930 				/*
22931 				 * hlen gets the number of uchar_ts in the
22932 				 * IP header
22933 				 */
22934 				hlen = (V_HLEN & 0xF) << 2;
22935 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22936 				max_frag = ire->ire_max_frag;
22937 				if (*up != 0) {
22938 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22939 					    up, PROTO, hlen, LENGTH, max_frag,
22940 					    ipsec_len, cksum);
22941 					/* Software checksum? */
22942 					if (DB_CKSUMFLAGS(mp) == 0) {
22943 						IP_STAT(ipst, ip_out_sw_cksum);
22944 						IP_STAT_UPDATE(ipst,
22945 						    ip_udp_out_sw_cksum_bytes,
22946 						    LENGTH - hlen);
22947 					}
22948 				}
22949 			}
22950 		}
22951 		/*
22952 		 * Need to do this even when fragmenting. The local
22953 		 * loopback can be done without computing checksums
22954 		 * but forwarding out other interface must be done
22955 		 * after the IP checksum (and ULP checksums) have been
22956 		 * computed.
22957 		 *
22958 		 * NOTE : multicast_forward is set only if this packet
22959 		 * originated from ip_wput. For packets originating from
22960 		 * ip_wput_multicast, it is not set.
22961 		 */
22962 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22963 multi_loopback:
22964 			ip2dbg(("ip_wput: multicast, loop %d\n",
22965 			    conn_multicast_loop));
22966 
22967 			/*  Forget header checksum offload */
22968 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22969 
22970 			/*
22971 			 * Local loopback of multicasts?  Check the
22972 			 * ill.
22973 			 *
22974 			 * Note that the loopback function will not come
22975 			 * in through ip_rput - it will only do the
22976 			 * client fanout thus we need to do an mforward
22977 			 * as well.  The is different from the BSD
22978 			 * logic.
22979 			 */
22980 			if (ill != NULL) {
22981 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
22982 				    ALL_ZONES) != NULL) {
22983 					/*
22984 					 * Pass along the virtual output q.
22985 					 * ip_wput_local() will distribute the
22986 					 * packet to all the matching zones,
22987 					 * except the sending zone when
22988 					 * IP_MULTICAST_LOOP is false.
22989 					 */
22990 					ip_multicast_loopback(q, ill, first_mp,
22991 					    conn_multicast_loop ? 0 :
22992 					    IP_FF_NO_MCAST_LOOP, zoneid);
22993 				}
22994 			}
22995 			if (ipha->ipha_ttl == 0) {
22996 				/*
22997 				 * 0 => only to this host i.e. we are
22998 				 * done. We are also done if this was the
22999 				 * loopback interface since it is sufficient
23000 				 * to loopback one copy of a multicast packet.
23001 				 */
23002 				freemsg(first_mp);
23003 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23004 				    "ip_wput_ire_end: q %p (%S)",
23005 				    q, "loopback");
23006 				ire_refrele(ire);
23007 				if (conn_outgoing_ill != NULL)
23008 					ill_refrele(conn_outgoing_ill);
23009 				return;
23010 			}
23011 			/*
23012 			 * ILLF_MULTICAST is checked in ip_newroute
23013 			 * i.e. we don't need to check it here since
23014 			 * all IRE_CACHEs come from ip_newroute.
23015 			 * For multicast traffic, SO_DONTROUTE is interpreted
23016 			 * to mean only send the packet out the interface
23017 			 * (optionally specified with IP_MULTICAST_IF)
23018 			 * and do not forward it out additional interfaces.
23019 			 * RSVP and the rsvp daemon is an example of a
23020 			 * protocol and user level process that
23021 			 * handles it's own routing. Hence, it uses the
23022 			 * SO_DONTROUTE option to accomplish this.
23023 			 */
23024 
23025 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23026 			    ill != NULL) {
23027 				/* Unconditionally redo the checksum */
23028 				ipha->ipha_hdr_checksum = 0;
23029 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23030 
23031 				/*
23032 				 * If this needs to go out secure, we need
23033 				 * to wait till we finish the IPsec
23034 				 * processing.
23035 				 */
23036 				if (ipsec_len == 0 &&
23037 				    ip_mforward(ill, ipha, mp)) {
23038 					freemsg(first_mp);
23039 					ip1dbg(("ip_wput: mforward failed\n"));
23040 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23041 					    "ip_wput_ire_end: q %p (%S)",
23042 					    q, "mforward failed");
23043 					ire_refrele(ire);
23044 					if (conn_outgoing_ill != NULL)
23045 						ill_refrele(conn_outgoing_ill);
23046 					return;
23047 				}
23048 			}
23049 		}
23050 		max_frag = ire->ire_max_frag;
23051 		cksum += ttl_protocol;
23052 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23053 			/* No fragmentation required for this one. */
23054 			/*
23055 			 * Don't use frag_flag if packet is pre-built or source
23056 			 * routed or if multicast (since multicast packets do
23057 			 * not solicit ICMP "packet too big" messages).
23058 			 */
23059 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23060 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23061 			    !ip_source_route_included(ipha)) &&
23062 			    !CLASSD(ipha->ipha_dst))
23063 				ipha->ipha_fragment_offset_and_flags |=
23064 				    htons(ire->ire_frag_flag);
23065 
23066 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23067 				/* Complete the IP header checksum. */
23068 				cksum += ipha->ipha_ident;
23069 				cksum += (v_hlen_tos_len >> 16)+
23070 				    (v_hlen_tos_len & 0xFFFF);
23071 				cksum += ipha->ipha_fragment_offset_and_flags;
23072 				hlen = (V_HLEN & 0xF) -
23073 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23074 				if (hlen) {
23075 checksumoptions:
23076 					/*
23077 					 * Account for the IP Options in the IP
23078 					 * header checksum.
23079 					 */
23080 					up = (uint16_t *)(rptr+
23081 					    IP_SIMPLE_HDR_LENGTH);
23082 					do {
23083 						cksum += up[0];
23084 						cksum += up[1];
23085 						up += 2;
23086 					} while (--hlen);
23087 				}
23088 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23089 				cksum = ~(cksum + (cksum >> 16));
23090 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23091 			}
23092 			if (ipsec_len != 0) {
23093 				ipsec_out_process(q, first_mp, ire, ill_index);
23094 				if (!next_mp) {
23095 					ire_refrele(ire);
23096 					if (conn_outgoing_ill != NULL)
23097 						ill_refrele(conn_outgoing_ill);
23098 					return;
23099 				}
23100 				goto next;
23101 			}
23102 
23103 			/*
23104 			 * multirt_send has already been handled
23105 			 * for broadcast, but not yet for multicast
23106 			 * or IP options.
23107 			 */
23108 			if (next_mp == NULL) {
23109 				if (ire->ire_flags & RTF_MULTIRT) {
23110 					multirt_send = B_TRUE;
23111 				}
23112 			}
23113 
23114 			/*
23115 			 * In most cases, the emission loop below is
23116 			 * entered only once. Only in the case where
23117 			 * the ire holds the RTF_MULTIRT flag, do we loop
23118 			 * to process all RTF_MULTIRT ires in the bucket,
23119 			 * and send the packet through all crossed
23120 			 * RTF_MULTIRT routes.
23121 			 */
23122 			do {
23123 				if (multirt_send) {
23124 					irb_t *irb;
23125 
23126 					irb = ire->ire_bucket;
23127 					ASSERT(irb != NULL);
23128 					/*
23129 					 * We are in a multiple send case,
23130 					 * need to get the next IRE and make
23131 					 * a duplicate of the packet.
23132 					 */
23133 					IRB_REFHOLD(irb);
23134 					for (ire1 = ire->ire_next;
23135 					    ire1 != NULL;
23136 					    ire1 = ire1->ire_next) {
23137 						if (!(ire1->ire_flags &
23138 						    RTF_MULTIRT))
23139 							continue;
23140 
23141 						if (ire1->ire_addr !=
23142 						    ire->ire_addr)
23143 							continue;
23144 
23145 						if (ire1->ire_marks &
23146 						    (IRE_MARK_CONDEMNED |
23147 						    IRE_MARK_TESTHIDDEN))
23148 							continue;
23149 
23150 						/* Got one */
23151 						IRE_REFHOLD(ire1);
23152 						break;
23153 					}
23154 					IRB_REFRELE(irb);
23155 
23156 					if (ire1 != NULL) {
23157 						next_mp = copyb(mp);
23158 						if ((next_mp == NULL) ||
23159 						    ((mp->b_cont != NULL) &&
23160 						    ((next_mp->b_cont =
23161 						    dupmsg(mp->b_cont))
23162 						    == NULL))) {
23163 							freemsg(next_mp);
23164 							next_mp = NULL;
23165 							ire_refrele(ire1);
23166 							ire1 = NULL;
23167 						}
23168 					}
23169 
23170 					/*
23171 					 * Last multiroute ire; don't loop
23172 					 * anymore. The emission is over
23173 					 * and next_mp is NULL.
23174 					 */
23175 					if (ire1 == NULL) {
23176 						multirt_send = B_FALSE;
23177 					}
23178 				}
23179 
23180 				out_ill = ire_to_ill(ire);
23181 				DTRACE_PROBE4(ip4__physical__out__start,
23182 				    ill_t *, NULL,
23183 				    ill_t *, out_ill,
23184 				    ipha_t *, ipha, mblk_t *, mp);
23185 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23186 				    ipst->ips_ipv4firewall_physical_out,
23187 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23188 				DTRACE_PROBE1(ip4__physical__out__end,
23189 				    mblk_t *, mp);
23190 				if (mp == NULL)
23191 					goto release_ire_and_ill_2;
23192 
23193 				ASSERT(ipsec_len == 0);
23194 				mp->b_prev =
23195 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23196 				DTRACE_PROBE2(ip__xmit__2,
23197 				    mblk_t *, mp, ire_t *, ire);
23198 				pktxmit_state = ip_xmit_v4(mp, ire,
23199 				    NULL, B_TRUE, connp);
23200 				if ((pktxmit_state == SEND_FAILED) ||
23201 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23202 release_ire_and_ill_2:
23203 					if (next_mp) {
23204 						freemsg(next_mp);
23205 						ire_refrele(ire1);
23206 					}
23207 					ire_refrele(ire);
23208 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23209 					    "ip_wput_ire_end: q %p (%S)",
23210 					    q, "discard MDATA");
23211 					if (conn_outgoing_ill != NULL)
23212 						ill_refrele(conn_outgoing_ill);
23213 					return;
23214 				}
23215 
23216 				if (CLASSD(dst)) {
23217 					BUMP_MIB(out_ill->ill_ip_mib,
23218 					    ipIfStatsHCOutMcastPkts);
23219 					UPDATE_MIB(out_ill->ill_ip_mib,
23220 					    ipIfStatsHCOutMcastOctets,
23221 					    LENGTH);
23222 				} else if (ire->ire_type == IRE_BROADCAST) {
23223 					BUMP_MIB(out_ill->ill_ip_mib,
23224 					    ipIfStatsHCOutBcastPkts);
23225 				}
23226 
23227 				if (multirt_send) {
23228 					/*
23229 					 * We are in a multiple send case,
23230 					 * need to re-enter the sending loop
23231 					 * using the next ire.
23232 					 */
23233 					ire_refrele(ire);
23234 					ire = ire1;
23235 					stq = ire->ire_stq;
23236 					mp = next_mp;
23237 					next_mp = NULL;
23238 					ipha = (ipha_t *)mp->b_rptr;
23239 					ill_index = Q_TO_INDEX(stq);
23240 				}
23241 			} while (multirt_send);
23242 
23243 			if (!next_mp) {
23244 				/*
23245 				 * Last copy going out (the ultra-common
23246 				 * case).  Note that we intentionally replicate
23247 				 * the putnext rather than calling it before
23248 				 * the next_mp check in hopes of a little
23249 				 * tail-call action out of the compiler.
23250 				 */
23251 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23252 				    "ip_wput_ire_end: q %p (%S)",
23253 				    q, "last copy out(1)");
23254 				ire_refrele(ire);
23255 				if (conn_outgoing_ill != NULL)
23256 					ill_refrele(conn_outgoing_ill);
23257 				return;
23258 			}
23259 			/* More copies going out below. */
23260 		} else {
23261 			int offset;
23262 fragmentit:
23263 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23264 			/*
23265 			 * If this would generate a icmp_frag_needed message,
23266 			 * we need to handle it before we do the IPsec
23267 			 * processing. Otherwise, we need to strip the IPsec
23268 			 * headers before we send up the message to the ULPs
23269 			 * which becomes messy and difficult.
23270 			 */
23271 			if (ipsec_len != 0) {
23272 				if ((max_frag < (unsigned int)(LENGTH +
23273 				    ipsec_len)) && (offset & IPH_DF)) {
23274 					out_ill = (ill_t *)stq->q_ptr;
23275 					BUMP_MIB(out_ill->ill_ip_mib,
23276 					    ipIfStatsOutFragFails);
23277 					BUMP_MIB(out_ill->ill_ip_mib,
23278 					    ipIfStatsOutFragReqds);
23279 					ipha->ipha_hdr_checksum = 0;
23280 					ipha->ipha_hdr_checksum =
23281 					    (uint16_t)ip_csum_hdr(ipha);
23282 					icmp_frag_needed(ire->ire_stq, first_mp,
23283 					    max_frag, zoneid, ipst);
23284 					if (!next_mp) {
23285 						ire_refrele(ire);
23286 						if (conn_outgoing_ill != NULL) {
23287 							ill_refrele(
23288 							    conn_outgoing_ill);
23289 						}
23290 						return;
23291 					}
23292 				} else {
23293 					/*
23294 					 * This won't cause a icmp_frag_needed
23295 					 * message. to be generated. Send it on
23296 					 * the wire. Note that this could still
23297 					 * cause fragmentation and all we
23298 					 * do is the generation of the message
23299 					 * to the ULP if needed before IPsec.
23300 					 */
23301 					if (!next_mp) {
23302 						ipsec_out_process(q, first_mp,
23303 						    ire, ill_index);
23304 						TRACE_2(TR_FAC_IP,
23305 						    TR_IP_WPUT_IRE_END,
23306 						    "ip_wput_ire_end: q %p "
23307 						    "(%S)", q,
23308 						    "last ipsec_out_process");
23309 						ire_refrele(ire);
23310 						if (conn_outgoing_ill != NULL) {
23311 							ill_refrele(
23312 							    conn_outgoing_ill);
23313 						}
23314 						return;
23315 					}
23316 					ipsec_out_process(q, first_mp,
23317 					    ire, ill_index);
23318 				}
23319 			} else {
23320 				/*
23321 				 * Initiate IPPF processing. For
23322 				 * fragmentable packets we finish
23323 				 * all QOS packet processing before
23324 				 * calling:
23325 				 * ip_wput_ire_fragmentit->ip_wput_frag
23326 				 */
23327 
23328 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23329 					ip_process(IPP_LOCAL_OUT, &mp,
23330 					    ill_index);
23331 					if (mp == NULL) {
23332 						out_ill = (ill_t *)stq->q_ptr;
23333 						BUMP_MIB(out_ill->ill_ip_mib,
23334 						    ipIfStatsOutDiscards);
23335 						if (next_mp != NULL) {
23336 							freemsg(next_mp);
23337 							ire_refrele(ire1);
23338 						}
23339 						ire_refrele(ire);
23340 						TRACE_2(TR_FAC_IP,
23341 						    TR_IP_WPUT_IRE_END,
23342 						    "ip_wput_ire: q %p (%S)",
23343 						    q, "discard MDATA");
23344 						if (conn_outgoing_ill != NULL) {
23345 							ill_refrele(
23346 							    conn_outgoing_ill);
23347 						}
23348 						return;
23349 					}
23350 				}
23351 				if (!next_mp) {
23352 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23353 					    "ip_wput_ire_end: q %p (%S)",
23354 					    q, "last fragmentation");
23355 					ip_wput_ire_fragmentit(mp, ire,
23356 					    zoneid, ipst, connp);
23357 					ire_refrele(ire);
23358 					if (conn_outgoing_ill != NULL)
23359 						ill_refrele(conn_outgoing_ill);
23360 					return;
23361 				}
23362 				ip_wput_ire_fragmentit(mp, ire,
23363 				    zoneid, ipst, connp);
23364 			}
23365 		}
23366 	} else {
23367 nullstq:
23368 		/* A NULL stq means the destination address is local. */
23369 		UPDATE_OB_PKT_COUNT(ire);
23370 		ire->ire_last_used_time = lbolt;
23371 		ASSERT(ire->ire_ipif != NULL);
23372 		if (!next_mp) {
23373 			/*
23374 			 * Is there an "in" and "out" for traffic local
23375 			 * to a host (loopback)?  The code in Solaris doesn't
23376 			 * explicitly draw a line in its code for in vs out,
23377 			 * so we've had to draw a line in the sand: ip_wput_ire
23378 			 * is considered to be the "output" side and
23379 			 * ip_wput_local to be the "input" side.
23380 			 */
23381 			out_ill = ire_to_ill(ire);
23382 
23383 			/*
23384 			 * DTrace this as ip:::send.  A blocked packet will
23385 			 * fire the send probe, but not the receive probe.
23386 			 */
23387 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23388 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23389 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23390 
23391 			DTRACE_PROBE4(ip4__loopback__out__start,
23392 			    ill_t *, NULL, ill_t *, out_ill,
23393 			    ipha_t *, ipha, mblk_t *, first_mp);
23394 
23395 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23396 			    ipst->ips_ipv4firewall_loopback_out,
23397 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23398 
23399 			DTRACE_PROBE1(ip4__loopback__out_end,
23400 			    mblk_t *, first_mp);
23401 
23402 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23403 			    "ip_wput_ire_end: q %p (%S)",
23404 			    q, "local address");
23405 
23406 			if (first_mp != NULL)
23407 				ip_wput_local(q, out_ill, ipha,
23408 				    first_mp, ire, 0, ire->ire_zoneid);
23409 			ire_refrele(ire);
23410 			if (conn_outgoing_ill != NULL)
23411 				ill_refrele(conn_outgoing_ill);
23412 			return;
23413 		}
23414 
23415 		out_ill = ire_to_ill(ire);
23416 
23417 		/*
23418 		 * DTrace this as ip:::send.  A blocked packet will fire the
23419 		 * send probe, but not the receive probe.
23420 		 */
23421 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23422 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23423 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23424 
23425 		DTRACE_PROBE4(ip4__loopback__out__start,
23426 		    ill_t *, NULL, ill_t *, out_ill,
23427 		    ipha_t *, ipha, mblk_t *, first_mp);
23428 
23429 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23430 		    ipst->ips_ipv4firewall_loopback_out,
23431 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23432 
23433 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23434 
23435 		if (first_mp != NULL)
23436 			ip_wput_local(q, out_ill, ipha,
23437 			    first_mp, ire, 0, ire->ire_zoneid);
23438 	}
23439 next:
23440 	/*
23441 	 * More copies going out to additional interfaces.
23442 	 * ire1 has already been held. We don't need the
23443 	 * "ire" anymore.
23444 	 */
23445 	ire_refrele(ire);
23446 	ire = ire1;
23447 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23448 	mp = next_mp;
23449 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23450 	ill = ire_to_ill(ire);
23451 	first_mp = mp;
23452 	if (ipsec_len != 0) {
23453 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23454 		mp = mp->b_cont;
23455 	}
23456 	dst = ire->ire_addr;
23457 	ipha = (ipha_t *)mp->b_rptr;
23458 	/*
23459 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23460 	 * Restore ipha_ident "no checksum" flag.
23461 	 */
23462 	src = orig_src;
23463 	ipha->ipha_ident = ip_hdr_included;
23464 	goto another;
23465 
23466 #undef	rptr
23467 #undef	Q_TO_INDEX
23468 }
23469 
23470 /*
23471  * Routine to allocate a message that is used to notify the ULP about MDT.
23472  * The caller may provide a pointer to the link-layer MDT capabilities,
23473  * or NULL if MDT is to be disabled on the stream.
23474  */
23475 mblk_t *
23476 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23477 {
23478 	mblk_t *mp;
23479 	ip_mdt_info_t *mdti;
23480 	ill_mdt_capab_t *idst;
23481 
23482 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23483 		DB_TYPE(mp) = M_CTL;
23484 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23485 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23486 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23487 		idst = &(mdti->mdt_capab);
23488 
23489 		/*
23490 		 * If the caller provides us with the capability, copy
23491 		 * it over into our notification message; otherwise
23492 		 * we zero out the capability portion.
23493 		 */
23494 		if (isrc != NULL)
23495 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23496 		else
23497 			bzero((caddr_t)idst, sizeof (*idst));
23498 	}
23499 	return (mp);
23500 }
23501 
23502 /*
23503  * Routine which determines whether MDT can be enabled on the destination
23504  * IRE and IPC combination, and if so, allocates and returns the MDT
23505  * notification mblk that may be used by ULP.  We also check if we need to
23506  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23507  * MDT usage in the past have been lifted.  This gets called during IP
23508  * and ULP binding.
23509  */
23510 mblk_t *
23511 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23512     ill_mdt_capab_t *mdt_cap)
23513 {
23514 	mblk_t *mp;
23515 	boolean_t rc = B_FALSE;
23516 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23517 
23518 	ASSERT(dst_ire != NULL);
23519 	ASSERT(connp != NULL);
23520 	ASSERT(mdt_cap != NULL);
23521 
23522 	/*
23523 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23524 	 * Multidata, which is handled in tcp_multisend().  This
23525 	 * is the reason why we do all these checks here, to ensure
23526 	 * that we don't enable Multidata for the cases which we
23527 	 * can't handle at the moment.
23528 	 */
23529 	do {
23530 		/* Only do TCP at the moment */
23531 		if (connp->conn_ulp != IPPROTO_TCP)
23532 			break;
23533 
23534 		/*
23535 		 * IPsec outbound policy present?  Note that we get here
23536 		 * after calling ipsec_conn_cache_policy() where the global
23537 		 * policy checking is performed.  conn_latch will be
23538 		 * non-NULL as long as there's a policy defined,
23539 		 * i.e. conn_out_enforce_policy may be NULL in such case
23540 		 * when the connection is non-secure, and hence we check
23541 		 * further if the latch refers to an outbound policy.
23542 		 */
23543 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23544 			break;
23545 
23546 		/* CGTP (multiroute) is enabled? */
23547 		if (dst_ire->ire_flags & RTF_MULTIRT)
23548 			break;
23549 
23550 		/* Outbound IPQoS enabled? */
23551 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23552 			/*
23553 			 * In this case, we disable MDT for this and all
23554 			 * future connections going over the interface.
23555 			 */
23556 			mdt_cap->ill_mdt_on = 0;
23557 			break;
23558 		}
23559 
23560 		/* socket option(s) present? */
23561 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23562 			break;
23563 
23564 		rc = B_TRUE;
23565 	/* CONSTCOND */
23566 	} while (0);
23567 
23568 	/* Remember the result */
23569 	connp->conn_mdt_ok = rc;
23570 
23571 	if (!rc)
23572 		return (NULL);
23573 	else if (!mdt_cap->ill_mdt_on) {
23574 		/*
23575 		 * If MDT has been previously turned off in the past, and we
23576 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23577 		 * then enable it for this interface.
23578 		 */
23579 		mdt_cap->ill_mdt_on = 1;
23580 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23581 		    "interface %s\n", ill_name));
23582 	}
23583 
23584 	/* Allocate the MDT info mblk */
23585 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23586 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23587 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23588 		return (NULL);
23589 	}
23590 	return (mp);
23591 }
23592 
23593 /*
23594  * Routine to allocate a message that is used to notify the ULP about LSO.
23595  * The caller may provide a pointer to the link-layer LSO capabilities,
23596  * or NULL if LSO is to be disabled on the stream.
23597  */
23598 mblk_t *
23599 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23600 {
23601 	mblk_t *mp;
23602 	ip_lso_info_t *lsoi;
23603 	ill_lso_capab_t *idst;
23604 
23605 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23606 		DB_TYPE(mp) = M_CTL;
23607 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23608 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23609 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23610 		idst = &(lsoi->lso_capab);
23611 
23612 		/*
23613 		 * If the caller provides us with the capability, copy
23614 		 * it over into our notification message; otherwise
23615 		 * we zero out the capability portion.
23616 		 */
23617 		if (isrc != NULL)
23618 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23619 		else
23620 			bzero((caddr_t)idst, sizeof (*idst));
23621 	}
23622 	return (mp);
23623 }
23624 
23625 /*
23626  * Routine which determines whether LSO can be enabled on the destination
23627  * IRE and IPC combination, and if so, allocates and returns the LSO
23628  * notification mblk that may be used by ULP.  We also check if we need to
23629  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23630  * LSO usage in the past have been lifted.  This gets called during IP
23631  * and ULP binding.
23632  */
23633 mblk_t *
23634 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23635     ill_lso_capab_t *lso_cap)
23636 {
23637 	mblk_t *mp;
23638 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23639 
23640 	ASSERT(dst_ire != NULL);
23641 	ASSERT(connp != NULL);
23642 	ASSERT(lso_cap != NULL);
23643 
23644 	connp->conn_lso_ok = B_TRUE;
23645 
23646 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23647 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23648 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23649 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23650 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23651 		connp->conn_lso_ok = B_FALSE;
23652 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23653 			/*
23654 			 * Disable LSO for this and all future connections going
23655 			 * over the interface.
23656 			 */
23657 			lso_cap->ill_lso_on = 0;
23658 		}
23659 	}
23660 
23661 	if (!connp->conn_lso_ok)
23662 		return (NULL);
23663 	else if (!lso_cap->ill_lso_on) {
23664 		/*
23665 		 * If LSO has been previously turned off in the past, and we
23666 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23667 		 * then enable it for this interface.
23668 		 */
23669 		lso_cap->ill_lso_on = 1;
23670 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23671 		    ill_name));
23672 	}
23673 
23674 	/* Allocate the LSO info mblk */
23675 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23676 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23677 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23678 
23679 	return (mp);
23680 }
23681 
23682 /*
23683  * Create destination address attribute, and fill it with the physical
23684  * destination address and SAP taken from the template DL_UNITDATA_REQ
23685  * message block.
23686  */
23687 boolean_t
23688 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23689 {
23690 	dl_unitdata_req_t *dlurp;
23691 	pattr_t *pa;
23692 	pattrinfo_t pa_info;
23693 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23694 	uint_t das_len, das_off;
23695 
23696 	ASSERT(dlmp != NULL);
23697 
23698 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23699 	das_len = dlurp->dl_dest_addr_length;
23700 	das_off = dlurp->dl_dest_addr_offset;
23701 
23702 	pa_info.type = PATTR_DSTADDRSAP;
23703 	pa_info.len = sizeof (**das) + das_len - 1;
23704 
23705 	/* create and associate the attribute */
23706 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23707 	if (pa != NULL) {
23708 		ASSERT(*das != NULL);
23709 		(*das)->addr_is_group = 0;
23710 		(*das)->addr_len = (uint8_t)das_len;
23711 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23712 	}
23713 
23714 	return (pa != NULL);
23715 }
23716 
23717 /*
23718  * Create hardware checksum attribute and fill it with the values passed.
23719  */
23720 boolean_t
23721 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23722     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23723 {
23724 	pattr_t *pa;
23725 	pattrinfo_t pa_info;
23726 
23727 	ASSERT(mmd != NULL);
23728 
23729 	pa_info.type = PATTR_HCKSUM;
23730 	pa_info.len = sizeof (pattr_hcksum_t);
23731 
23732 	/* create and associate the attribute */
23733 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23734 	if (pa != NULL) {
23735 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23736 
23737 		hck->hcksum_start_offset = start_offset;
23738 		hck->hcksum_stuff_offset = stuff_offset;
23739 		hck->hcksum_end_offset = end_offset;
23740 		hck->hcksum_flags = flags;
23741 	}
23742 	return (pa != NULL);
23743 }
23744 
23745 /*
23746  * Create zerocopy attribute and fill it with the specified flags
23747  */
23748 boolean_t
23749 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23750 {
23751 	pattr_t *pa;
23752 	pattrinfo_t pa_info;
23753 
23754 	ASSERT(mmd != NULL);
23755 	pa_info.type = PATTR_ZCOPY;
23756 	pa_info.len = sizeof (pattr_zcopy_t);
23757 
23758 	/* create and associate the attribute */
23759 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23760 	if (pa != NULL) {
23761 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23762 
23763 		zcopy->zcopy_flags = flags;
23764 	}
23765 	return (pa != NULL);
23766 }
23767 
23768 /*
23769  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23770  * block chain. We could rewrite to handle arbitrary message block chains but
23771  * that would make the code complicated and slow. Right now there three
23772  * restrictions:
23773  *
23774  *   1. The first message block must contain the complete IP header and
23775  *	at least 1 byte of payload data.
23776  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23777  *	so that we can use a single Multidata message.
23778  *   3. No frag must be distributed over two or more message blocks so
23779  *	that we don't need more than two packet descriptors per frag.
23780  *
23781  * The above restrictions allow us to support userland applications (which
23782  * will send down a single message block) and NFS over UDP (which will
23783  * send down a chain of at most three message blocks).
23784  *
23785  * We also don't use MDT for payloads with less than or equal to
23786  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23787  */
23788 boolean_t
23789 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23790 {
23791 	int	blocks;
23792 	ssize_t	total, missing, size;
23793 
23794 	ASSERT(mp != NULL);
23795 	ASSERT(hdr_len > 0);
23796 
23797 	size = MBLKL(mp) - hdr_len;
23798 	if (size <= 0)
23799 		return (B_FALSE);
23800 
23801 	/* The first mblk contains the header and some payload. */
23802 	blocks = 1;
23803 	total = size;
23804 	size %= len;
23805 	missing = (size == 0) ? 0 : (len - size);
23806 	mp = mp->b_cont;
23807 
23808 	while (mp != NULL) {
23809 		/*
23810 		 * Give up if we encounter a zero length message block.
23811 		 * In practice, this should rarely happen and therefore
23812 		 * not worth the trouble of freeing and re-linking the
23813 		 * mblk from the chain to handle such case.
23814 		 */
23815 		if ((size = MBLKL(mp)) == 0)
23816 			return (B_FALSE);
23817 
23818 		/* Too many payload buffers for a single Multidata message? */
23819 		if (++blocks > MULTIDATA_MAX_PBUFS)
23820 			return (B_FALSE);
23821 
23822 		total += size;
23823 		/* Is a frag distributed over two or more message blocks? */
23824 		if (missing > size)
23825 			return (B_FALSE);
23826 		size -= missing;
23827 
23828 		size %= len;
23829 		missing = (size == 0) ? 0 : (len - size);
23830 
23831 		mp = mp->b_cont;
23832 	}
23833 
23834 	return (total > ip_wput_frag_mdt_min);
23835 }
23836 
23837 /*
23838  * Outbound IPv4 fragmentation routine using MDT.
23839  */
23840 static void
23841 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23842     uint32_t frag_flag, int offset)
23843 {
23844 	ipha_t		*ipha_orig;
23845 	int		i1, ip_data_end;
23846 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23847 	mblk_t		*hdr_mp, *md_mp = NULL;
23848 	unsigned char	*hdr_ptr, *pld_ptr;
23849 	multidata_t	*mmd;
23850 	ip_pdescinfo_t	pdi;
23851 	ill_t		*ill;
23852 	ip_stack_t	*ipst = ire->ire_ipst;
23853 
23854 	ASSERT(DB_TYPE(mp) == M_DATA);
23855 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23856 
23857 	ill = ire_to_ill(ire);
23858 	ASSERT(ill != NULL);
23859 
23860 	ipha_orig = (ipha_t *)mp->b_rptr;
23861 	mp->b_rptr += sizeof (ipha_t);
23862 
23863 	/* Calculate how many packets we will send out */
23864 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23865 	pkts = (i1 + len - 1) / len;
23866 	ASSERT(pkts > 1);
23867 
23868 	/* Allocate a message block which will hold all the IP Headers. */
23869 	wroff = ipst->ips_ip_wroff_extra;
23870 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23871 
23872 	i1 = pkts * hdr_chunk_len;
23873 	/*
23874 	 * Create the header buffer, Multidata and destination address
23875 	 * and SAP attribute that should be associated with it.
23876 	 */
23877 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23878 	    ((hdr_mp->b_wptr += i1),
23879 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23880 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23881 		freemsg(mp);
23882 		if (md_mp == NULL) {
23883 			freemsg(hdr_mp);
23884 		} else {
23885 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23886 			freemsg(md_mp);
23887 		}
23888 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23889 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23890 		return;
23891 	}
23892 	IP_STAT(ipst, ip_frag_mdt_allocd);
23893 
23894 	/*
23895 	 * Add a payload buffer to the Multidata; this operation must not
23896 	 * fail, or otherwise our logic in this routine is broken.  There
23897 	 * is no memory allocation done by the routine, so any returned
23898 	 * failure simply tells us that we've done something wrong.
23899 	 *
23900 	 * A failure tells us that either we're adding the same payload
23901 	 * buffer more than once, or we're trying to add more buffers than
23902 	 * allowed.  None of the above cases should happen, and we panic
23903 	 * because either there's horrible heap corruption, and/or
23904 	 * programming mistake.
23905 	 */
23906 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23907 		goto pbuf_panic;
23908 
23909 	hdr_ptr = hdr_mp->b_rptr;
23910 	pld_ptr = mp->b_rptr;
23911 
23912 	/* Establish the ending byte offset, based on the starting offset. */
23913 	offset <<= 3;
23914 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23915 	    IP_SIMPLE_HDR_LENGTH;
23916 
23917 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23918 
23919 	while (pld_ptr < mp->b_wptr) {
23920 		ipha_t		*ipha;
23921 		uint16_t	offset_and_flags;
23922 		uint16_t	ip_len;
23923 		int		error;
23924 
23925 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23926 		ipha = (ipha_t *)(hdr_ptr + wroff);
23927 		ASSERT(OK_32PTR(ipha));
23928 		*ipha = *ipha_orig;
23929 
23930 		if (ip_data_end - offset > len) {
23931 			offset_and_flags = IPH_MF;
23932 		} else {
23933 			/*
23934 			 * Last frag. Set len to the length of this last piece.
23935 			 */
23936 			len = ip_data_end - offset;
23937 			/* A frag of a frag might have IPH_MF non-zero */
23938 			offset_and_flags =
23939 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23940 			    IPH_MF;
23941 		}
23942 		offset_and_flags |= (uint16_t)(offset >> 3);
23943 		offset_and_flags |= (uint16_t)frag_flag;
23944 		/* Store the offset and flags in the IP header. */
23945 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23946 
23947 		/* Store the length in the IP header. */
23948 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23949 		ipha->ipha_length = htons(ip_len);
23950 
23951 		/*
23952 		 * Set the IP header checksum.  Note that mp is just
23953 		 * the header, so this is easy to pass to ip_csum.
23954 		 */
23955 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23956 
23957 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23958 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23959 		    NULL, int, 0);
23960 
23961 		/*
23962 		 * Record offset and size of header and data of the next packet
23963 		 * in the multidata message.
23964 		 */
23965 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23966 		PDESC_PLD_INIT(&pdi);
23967 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23968 		ASSERT(i1 > 0);
23969 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23970 		if (i1 == len) {
23971 			pld_ptr += len;
23972 		} else {
23973 			i1 = len - i1;
23974 			mp = mp->b_cont;
23975 			ASSERT(mp != NULL);
23976 			ASSERT(MBLKL(mp) >= i1);
23977 			/*
23978 			 * Attach the next payload message block to the
23979 			 * multidata message.
23980 			 */
23981 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23982 				goto pbuf_panic;
23983 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23984 			pld_ptr = mp->b_rptr + i1;
23985 		}
23986 
23987 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23988 		    KM_NOSLEEP)) == NULL) {
23989 			/*
23990 			 * Any failure other than ENOMEM indicates that we
23991 			 * have passed in invalid pdesc info or parameters
23992 			 * to mmd_addpdesc, which must not happen.
23993 			 *
23994 			 * EINVAL is a result of failure on boundary checks
23995 			 * against the pdesc info contents.  It should not
23996 			 * happen, and we panic because either there's
23997 			 * horrible heap corruption, and/or programming
23998 			 * mistake.
23999 			 */
24000 			if (error != ENOMEM) {
24001 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24002 				    "pdesc logic error detected for "
24003 				    "mmd %p pinfo %p (%d)\n",
24004 				    (void *)mmd, (void *)&pdi, error);
24005 				/* NOTREACHED */
24006 			}
24007 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24008 			/* Free unattached payload message blocks as well */
24009 			md_mp->b_cont = mp->b_cont;
24010 			goto free_mmd;
24011 		}
24012 
24013 		/* Advance fragment offset. */
24014 		offset += len;
24015 
24016 		/* Advance to location for next header in the buffer. */
24017 		hdr_ptr += hdr_chunk_len;
24018 
24019 		/* Did we reach the next payload message block? */
24020 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24021 			mp = mp->b_cont;
24022 			/*
24023 			 * Attach the next message block with payload
24024 			 * data to the multidata message.
24025 			 */
24026 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24027 				goto pbuf_panic;
24028 			pld_ptr = mp->b_rptr;
24029 		}
24030 	}
24031 
24032 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24033 	ASSERT(mp->b_wptr == pld_ptr);
24034 
24035 	/* Update IP statistics */
24036 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24037 
24038 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24039 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24040 
24041 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24042 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24043 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24044 
24045 	if (pkt_type == OB_PKT) {
24046 		ire->ire_ob_pkt_count += pkts;
24047 		if (ire->ire_ipif != NULL)
24048 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24049 	} else {
24050 		/* The type is IB_PKT in the forwarding path. */
24051 		ire->ire_ib_pkt_count += pkts;
24052 		ASSERT(!IRE_IS_LOCAL(ire));
24053 		if (ire->ire_type & IRE_BROADCAST) {
24054 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24055 		} else {
24056 			UPDATE_MIB(ill->ill_ip_mib,
24057 			    ipIfStatsHCOutForwDatagrams, pkts);
24058 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24059 		}
24060 	}
24061 	ire->ire_last_used_time = lbolt;
24062 	/* Send it down */
24063 	putnext(ire->ire_stq, md_mp);
24064 	return;
24065 
24066 pbuf_panic:
24067 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24068 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24069 	    pbuf_idx);
24070 	/* NOTREACHED */
24071 }
24072 
24073 /*
24074  * Outbound IP fragmentation routine.
24075  *
24076  * NOTE : This routine does not ire_refrele the ire that is passed in
24077  * as the argument.
24078  */
24079 static void
24080 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24081     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24082 {
24083 	int		i1;
24084 	mblk_t		*ll_hdr_mp;
24085 	int 		ll_hdr_len;
24086 	int		hdr_len;
24087 	mblk_t		*hdr_mp;
24088 	ipha_t		*ipha;
24089 	int		ip_data_end;
24090 	int		len;
24091 	mblk_t		*mp = mp_orig, *mp1;
24092 	int		offset;
24093 	queue_t		*q;
24094 	uint32_t	v_hlen_tos_len;
24095 	mblk_t		*first_mp;
24096 	boolean_t	mctl_present;
24097 	ill_t		*ill;
24098 	ill_t		*out_ill;
24099 	mblk_t		*xmit_mp;
24100 	mblk_t		*carve_mp;
24101 	ire_t		*ire1 = NULL;
24102 	ire_t		*save_ire = NULL;
24103 	mblk_t  	*next_mp = NULL;
24104 	boolean_t	last_frag = B_FALSE;
24105 	boolean_t	multirt_send = B_FALSE;
24106 	ire_t		*first_ire = NULL;
24107 	irb_t		*irb = NULL;
24108 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24109 
24110 	ill = ire_to_ill(ire);
24111 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24112 
24113 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24114 
24115 	if (max_frag == 0) {
24116 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24117 		    " -  dropping packet\n"));
24118 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24119 		freemsg(mp);
24120 		return;
24121 	}
24122 
24123 	/*
24124 	 * IPsec does not allow hw accelerated packets to be fragmented
24125 	 * This check is made in ip_wput_ipsec_out prior to coming here
24126 	 * via ip_wput_ire_fragmentit.
24127 	 *
24128 	 * If at this point we have an ire whose ARP request has not
24129 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24130 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24131 	 * This packet and all fragmentable packets for this ire will
24132 	 * continue to get dropped while ire_nce->nce_state remains in
24133 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24134 	 * ND_REACHABLE, all subsquent large packets for this ire will
24135 	 * get fragemented and sent out by this function.
24136 	 */
24137 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24138 		/* If nce_state is ND_INITIAL, trigger ARP query */
24139 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24140 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24141 		    " -  dropping packet\n"));
24142 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24143 		freemsg(mp);
24144 		return;
24145 	}
24146 
24147 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24148 	    "ip_wput_frag_start:");
24149 
24150 	if (mp->b_datap->db_type == M_CTL) {
24151 		first_mp = mp;
24152 		mp_orig = mp = mp->b_cont;
24153 		mctl_present = B_TRUE;
24154 	} else {
24155 		first_mp = mp;
24156 		mctl_present = B_FALSE;
24157 	}
24158 
24159 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24160 	ipha = (ipha_t *)mp->b_rptr;
24161 
24162 	/*
24163 	 * If the Don't Fragment flag is on, generate an ICMP destination
24164 	 * unreachable, fragmentation needed.
24165 	 */
24166 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24167 	if (offset & IPH_DF) {
24168 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24169 		if (is_system_labeled()) {
24170 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24171 			    ire->ire_max_frag - max_frag, AF_INET);
24172 		}
24173 		/*
24174 		 * Need to compute hdr checksum if called from ip_wput_ire.
24175 		 * Note that ip_rput_forward verifies the checksum before
24176 		 * calling this routine so in that case this is a noop.
24177 		 */
24178 		ipha->ipha_hdr_checksum = 0;
24179 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24180 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24181 		    ipst);
24182 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24183 		    "ip_wput_frag_end:(%S)",
24184 		    "don't fragment");
24185 		return;
24186 	}
24187 	/*
24188 	 * Labeled systems adjust max_frag if they add a label
24189 	 * to send the correct path mtu.  We need the real mtu since we
24190 	 * are fragmenting the packet after label adjustment.
24191 	 */
24192 	if (is_system_labeled())
24193 		max_frag = ire->ire_max_frag;
24194 	if (mctl_present)
24195 		freeb(first_mp);
24196 	/*
24197 	 * Establish the starting offset.  May not be zero if we are fragging
24198 	 * a fragment that is being forwarded.
24199 	 */
24200 	offset = offset & IPH_OFFSET;
24201 
24202 	/* TODO why is this test needed? */
24203 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24204 	if (((max_frag - LENGTH) & ~7) < 8) {
24205 		/* TODO: notify ulp somehow */
24206 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24207 		freemsg(mp);
24208 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24209 		    "ip_wput_frag_end:(%S)",
24210 		    "len < 8");
24211 		return;
24212 	}
24213 
24214 	hdr_len = (V_HLEN & 0xF) << 2;
24215 
24216 	ipha->ipha_hdr_checksum = 0;
24217 
24218 	/*
24219 	 * Establish the number of bytes maximum per frag, after putting
24220 	 * in the header.
24221 	 */
24222 	len = (max_frag - hdr_len) & ~7;
24223 
24224 	/* Check if we can use MDT to send out the frags. */
24225 	ASSERT(!IRE_IS_LOCAL(ire));
24226 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24227 	    ipst->ips_ip_multidata_outbound &&
24228 	    !(ire->ire_flags & RTF_MULTIRT) &&
24229 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24230 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24231 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24232 		ASSERT(ill->ill_mdt_capab != NULL);
24233 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24234 			/*
24235 			 * If MDT has been previously turned off in the past,
24236 			 * and we currently can do MDT (due to IPQoS policy
24237 			 * removal, etc.) then enable it for this interface.
24238 			 */
24239 			ill->ill_mdt_capab->ill_mdt_on = 1;
24240 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24241 			    ill->ill_name));
24242 		}
24243 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24244 		    offset);
24245 		return;
24246 	}
24247 
24248 	/* Get a copy of the header for the trailing frags */
24249 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24250 	    mp);
24251 	if (!hdr_mp) {
24252 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24253 		freemsg(mp);
24254 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24255 		    "ip_wput_frag_end:(%S)",
24256 		    "couldn't copy hdr");
24257 		return;
24258 	}
24259 
24260 	/* Store the starting offset, with the MoreFrags flag. */
24261 	i1 = offset | IPH_MF | frag_flag;
24262 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24263 
24264 	/* Establish the ending byte offset, based on the starting offset. */
24265 	offset <<= 3;
24266 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24267 
24268 	/* Store the length of the first fragment in the IP header. */
24269 	i1 = len + hdr_len;
24270 	ASSERT(i1 <= IP_MAXPACKET);
24271 	ipha->ipha_length = htons((uint16_t)i1);
24272 
24273 	/*
24274 	 * Compute the IP header checksum for the first frag.  We have to
24275 	 * watch out that we stop at the end of the header.
24276 	 */
24277 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24278 
24279 	/*
24280 	 * Now carve off the first frag.  Note that this will include the
24281 	 * original IP header.
24282 	 */
24283 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24284 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24285 		freeb(hdr_mp);
24286 		freemsg(mp_orig);
24287 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24288 		    "ip_wput_frag_end:(%S)",
24289 		    "couldn't carve first");
24290 		return;
24291 	}
24292 
24293 	/*
24294 	 * Multirouting case. Each fragment is replicated
24295 	 * via all non-condemned RTF_MULTIRT routes
24296 	 * currently resolved.
24297 	 * We ensure that first_ire is the first RTF_MULTIRT
24298 	 * ire in the bucket.
24299 	 */
24300 	if (ire->ire_flags & RTF_MULTIRT) {
24301 		irb = ire->ire_bucket;
24302 		ASSERT(irb != NULL);
24303 
24304 		multirt_send = B_TRUE;
24305 
24306 		/* Make sure we do not omit any multiroute ire. */
24307 		IRB_REFHOLD(irb);
24308 		for (first_ire = irb->irb_ire;
24309 		    first_ire != NULL;
24310 		    first_ire = first_ire->ire_next) {
24311 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24312 			    (first_ire->ire_addr == ire->ire_addr) &&
24313 			    !(first_ire->ire_marks &
24314 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24315 				break;
24316 		}
24317 
24318 		if (first_ire != NULL) {
24319 			if (first_ire != ire) {
24320 				IRE_REFHOLD(first_ire);
24321 				/*
24322 				 * Do not release the ire passed in
24323 				 * as the argument.
24324 				 */
24325 				ire = first_ire;
24326 			} else {
24327 				first_ire = NULL;
24328 			}
24329 		}
24330 		IRB_REFRELE(irb);
24331 
24332 		/*
24333 		 * Save the first ire; we will need to restore it
24334 		 * for the trailing frags.
24335 		 * We REFHOLD save_ire, as each iterated ire will be
24336 		 * REFRELEd.
24337 		 */
24338 		save_ire = ire;
24339 		IRE_REFHOLD(save_ire);
24340 	}
24341 
24342 	/*
24343 	 * First fragment emission loop.
24344 	 * In most cases, the emission loop below is entered only
24345 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24346 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24347 	 * bucket, and send the fragment through all crossed
24348 	 * RTF_MULTIRT routes.
24349 	 */
24350 	do {
24351 		if (ire->ire_flags & RTF_MULTIRT) {
24352 			/*
24353 			 * We are in a multiple send case, need to get
24354 			 * the next ire and make a copy of the packet.
24355 			 * ire1 holds here the next ire to process in the
24356 			 * bucket. If multirouting is expected,
24357 			 * any non-RTF_MULTIRT ire that has the
24358 			 * right destination address is ignored.
24359 			 *
24360 			 * We have to take into account the MTU of
24361 			 * each walked ire. max_frag is set by the
24362 			 * the caller and generally refers to
24363 			 * the primary ire entry. Here we ensure that
24364 			 * no route with a lower MTU will be used, as
24365 			 * fragments are carved once for all ires,
24366 			 * then replicated.
24367 			 */
24368 			ASSERT(irb != NULL);
24369 			IRB_REFHOLD(irb);
24370 			for (ire1 = ire->ire_next;
24371 			    ire1 != NULL;
24372 			    ire1 = ire1->ire_next) {
24373 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24374 					continue;
24375 				if (ire1->ire_addr != ire->ire_addr)
24376 					continue;
24377 				if (ire1->ire_marks &
24378 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24379 					continue;
24380 				/*
24381 				 * Ensure we do not exceed the MTU
24382 				 * of the next route.
24383 				 */
24384 				if (ire1->ire_max_frag < max_frag) {
24385 					ip_multirt_bad_mtu(ire1, max_frag);
24386 					continue;
24387 				}
24388 
24389 				/* Got one. */
24390 				IRE_REFHOLD(ire1);
24391 				break;
24392 			}
24393 			IRB_REFRELE(irb);
24394 
24395 			if (ire1 != NULL) {
24396 				next_mp = copyb(mp);
24397 				if ((next_mp == NULL) ||
24398 				    ((mp->b_cont != NULL) &&
24399 				    ((next_mp->b_cont =
24400 				    dupmsg(mp->b_cont)) == NULL))) {
24401 					freemsg(next_mp);
24402 					next_mp = NULL;
24403 					ire_refrele(ire1);
24404 					ire1 = NULL;
24405 				}
24406 			}
24407 
24408 			/* Last multiroute ire; don't loop anymore. */
24409 			if (ire1 == NULL) {
24410 				multirt_send = B_FALSE;
24411 			}
24412 		}
24413 
24414 		ll_hdr_len = 0;
24415 		LOCK_IRE_FP_MP(ire);
24416 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24417 		if (ll_hdr_mp != NULL) {
24418 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24419 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24420 		} else {
24421 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24422 		}
24423 
24424 		/* If there is a transmit header, get a copy for this frag. */
24425 		/*
24426 		 * TODO: should check db_ref before calling ip_carve_mp since
24427 		 * it might give us a dup.
24428 		 */
24429 		if (!ll_hdr_mp) {
24430 			/* No xmit header. */
24431 			xmit_mp = mp;
24432 
24433 		/* We have a link-layer header that can fit in our mblk. */
24434 		} else if (mp->b_datap->db_ref == 1 &&
24435 		    ll_hdr_len != 0 &&
24436 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24437 			/* M_DATA fastpath */
24438 			mp->b_rptr -= ll_hdr_len;
24439 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24440 			xmit_mp = mp;
24441 
24442 		/* Corner case if copyb has failed */
24443 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24444 			UNLOCK_IRE_FP_MP(ire);
24445 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24446 			freeb(hdr_mp);
24447 			freemsg(mp);
24448 			freemsg(mp_orig);
24449 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24450 			    "ip_wput_frag_end:(%S)",
24451 			    "discard");
24452 
24453 			if (multirt_send) {
24454 				ASSERT(ire1);
24455 				ASSERT(next_mp);
24456 
24457 				freemsg(next_mp);
24458 				ire_refrele(ire1);
24459 			}
24460 			if (save_ire != NULL)
24461 				IRE_REFRELE(save_ire);
24462 
24463 			if (first_ire != NULL)
24464 				ire_refrele(first_ire);
24465 			return;
24466 
24467 		/*
24468 		 * Case of res_mp OR the fastpath mp can't fit
24469 		 * in the mblk
24470 		 */
24471 		} else {
24472 			xmit_mp->b_cont = mp;
24473 
24474 			/*
24475 			 * Get priority marking, if any.
24476 			 * We propagate the CoS marking from the
24477 			 * original packet that went to QoS processing
24478 			 * in ip_wput_ire to the newly carved mp.
24479 			 */
24480 			if (DB_TYPE(xmit_mp) == M_DATA)
24481 				xmit_mp->b_band = mp->b_band;
24482 		}
24483 		UNLOCK_IRE_FP_MP(ire);
24484 
24485 		q = ire->ire_stq;
24486 		out_ill = (ill_t *)q->q_ptr;
24487 
24488 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24489 
24490 		DTRACE_PROBE4(ip4__physical__out__start,
24491 		    ill_t *, NULL, ill_t *, out_ill,
24492 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24493 
24494 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24495 		    ipst->ips_ipv4firewall_physical_out,
24496 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24497 
24498 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24499 
24500 		if (xmit_mp != NULL) {
24501 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24502 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24503 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24504 
24505 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24506 
24507 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24508 			UPDATE_MIB(out_ill->ill_ip_mib,
24509 			    ipIfStatsHCOutOctets, i1);
24510 
24511 			if (pkt_type != OB_PKT) {
24512 				/*
24513 				 * Update the packet count and MIB stats
24514 				 * of trailing RTF_MULTIRT ires.
24515 				 */
24516 				UPDATE_OB_PKT_COUNT(ire);
24517 				BUMP_MIB(out_ill->ill_ip_mib,
24518 				    ipIfStatsOutFragReqds);
24519 			}
24520 		}
24521 
24522 		if (multirt_send) {
24523 			/*
24524 			 * We are in a multiple send case; look for
24525 			 * the next ire and re-enter the loop.
24526 			 */
24527 			ASSERT(ire1);
24528 			ASSERT(next_mp);
24529 			/* REFRELE the current ire before looping */
24530 			ire_refrele(ire);
24531 			ire = ire1;
24532 			ire1 = NULL;
24533 			mp = next_mp;
24534 			next_mp = NULL;
24535 		}
24536 	} while (multirt_send);
24537 
24538 	ASSERT(ire1 == NULL);
24539 
24540 	/* Restore the original ire; we need it for the trailing frags */
24541 	if (save_ire != NULL) {
24542 		/* REFRELE the last iterated ire */
24543 		ire_refrele(ire);
24544 		/* save_ire has been REFHOLDed */
24545 		ire = save_ire;
24546 		save_ire = NULL;
24547 		q = ire->ire_stq;
24548 	}
24549 
24550 	if (pkt_type == OB_PKT) {
24551 		UPDATE_OB_PKT_COUNT(ire);
24552 	} else {
24553 		out_ill = (ill_t *)q->q_ptr;
24554 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24555 		UPDATE_IB_PKT_COUNT(ire);
24556 	}
24557 
24558 	/* Advance the offset to the second frag starting point. */
24559 	offset += len;
24560 	/*
24561 	 * Update hdr_len from the copied header - there might be less options
24562 	 * in the later fragments.
24563 	 */
24564 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24565 	/* Loop until done. */
24566 	for (;;) {
24567 		uint16_t	offset_and_flags;
24568 		uint16_t	ip_len;
24569 
24570 		if (ip_data_end - offset > len) {
24571 			/*
24572 			 * Carve off the appropriate amount from the original
24573 			 * datagram.
24574 			 */
24575 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24576 				mp = NULL;
24577 				break;
24578 			}
24579 			/*
24580 			 * More frags after this one.  Get another copy
24581 			 * of the header.
24582 			 */
24583 			if (carve_mp->b_datap->db_ref == 1 &&
24584 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24585 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24586 				/* Inline IP header */
24587 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24588 				    hdr_mp->b_rptr;
24589 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24590 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24591 				mp = carve_mp;
24592 			} else {
24593 				if (!(mp = copyb(hdr_mp))) {
24594 					freemsg(carve_mp);
24595 					break;
24596 				}
24597 				/* Get priority marking, if any. */
24598 				mp->b_band = carve_mp->b_band;
24599 				mp->b_cont = carve_mp;
24600 			}
24601 			ipha = (ipha_t *)mp->b_rptr;
24602 			offset_and_flags = IPH_MF;
24603 		} else {
24604 			/*
24605 			 * Last frag.  Consume the header. Set len to
24606 			 * the length of this last piece.
24607 			 */
24608 			len = ip_data_end - offset;
24609 
24610 			/*
24611 			 * Carve off the appropriate amount from the original
24612 			 * datagram.
24613 			 */
24614 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24615 				mp = NULL;
24616 				break;
24617 			}
24618 			if (carve_mp->b_datap->db_ref == 1 &&
24619 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24620 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24621 				/* Inline IP header */
24622 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24623 				    hdr_mp->b_rptr;
24624 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24625 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24626 				mp = carve_mp;
24627 				freeb(hdr_mp);
24628 				hdr_mp = mp;
24629 			} else {
24630 				mp = hdr_mp;
24631 				/* Get priority marking, if any. */
24632 				mp->b_band = carve_mp->b_band;
24633 				mp->b_cont = carve_mp;
24634 			}
24635 			ipha = (ipha_t *)mp->b_rptr;
24636 			/* A frag of a frag might have IPH_MF non-zero */
24637 			offset_and_flags =
24638 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24639 			    IPH_MF;
24640 		}
24641 		offset_and_flags |= (uint16_t)(offset >> 3);
24642 		offset_and_flags |= (uint16_t)frag_flag;
24643 		/* Store the offset and flags in the IP header. */
24644 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24645 
24646 		/* Store the length in the IP header. */
24647 		ip_len = (uint16_t)(len + hdr_len);
24648 		ipha->ipha_length = htons(ip_len);
24649 
24650 		/*
24651 		 * Set the IP header checksum.	Note that mp is just
24652 		 * the header, so this is easy to pass to ip_csum.
24653 		 */
24654 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24655 
24656 		/* Attach a transmit header, if any, and ship it. */
24657 		if (pkt_type == OB_PKT) {
24658 			UPDATE_OB_PKT_COUNT(ire);
24659 		} else {
24660 			out_ill = (ill_t *)q->q_ptr;
24661 			BUMP_MIB(out_ill->ill_ip_mib,
24662 			    ipIfStatsHCOutForwDatagrams);
24663 			UPDATE_IB_PKT_COUNT(ire);
24664 		}
24665 
24666 		if (ire->ire_flags & RTF_MULTIRT) {
24667 			irb = ire->ire_bucket;
24668 			ASSERT(irb != NULL);
24669 
24670 			multirt_send = B_TRUE;
24671 
24672 			/*
24673 			 * Save the original ire; we will need to restore it
24674 			 * for the tailing frags.
24675 			 */
24676 			save_ire = ire;
24677 			IRE_REFHOLD(save_ire);
24678 		}
24679 		/*
24680 		 * Emission loop for this fragment, similar
24681 		 * to what is done for the first fragment.
24682 		 */
24683 		do {
24684 			if (multirt_send) {
24685 				/*
24686 				 * We are in a multiple send case, need to get
24687 				 * the next ire and make a copy of the packet.
24688 				 */
24689 				ASSERT(irb != NULL);
24690 				IRB_REFHOLD(irb);
24691 				for (ire1 = ire->ire_next;
24692 				    ire1 != NULL;
24693 				    ire1 = ire1->ire_next) {
24694 					if (!(ire1->ire_flags & RTF_MULTIRT))
24695 						continue;
24696 					if (ire1->ire_addr != ire->ire_addr)
24697 						continue;
24698 					if (ire1->ire_marks &
24699 					    (IRE_MARK_CONDEMNED |
24700 					    IRE_MARK_TESTHIDDEN))
24701 						continue;
24702 					/*
24703 					 * Ensure we do not exceed the MTU
24704 					 * of the next route.
24705 					 */
24706 					if (ire1->ire_max_frag < max_frag) {
24707 						ip_multirt_bad_mtu(ire1,
24708 						    max_frag);
24709 						continue;
24710 					}
24711 
24712 					/* Got one. */
24713 					IRE_REFHOLD(ire1);
24714 					break;
24715 				}
24716 				IRB_REFRELE(irb);
24717 
24718 				if (ire1 != NULL) {
24719 					next_mp = copyb(mp);
24720 					if ((next_mp == NULL) ||
24721 					    ((mp->b_cont != NULL) &&
24722 					    ((next_mp->b_cont =
24723 					    dupmsg(mp->b_cont)) == NULL))) {
24724 						freemsg(next_mp);
24725 						next_mp = NULL;
24726 						ire_refrele(ire1);
24727 						ire1 = NULL;
24728 					}
24729 				}
24730 
24731 				/* Last multiroute ire; don't loop anymore. */
24732 				if (ire1 == NULL) {
24733 					multirt_send = B_FALSE;
24734 				}
24735 			}
24736 
24737 			/* Update transmit header */
24738 			ll_hdr_len = 0;
24739 			LOCK_IRE_FP_MP(ire);
24740 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24741 			if (ll_hdr_mp != NULL) {
24742 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24743 				ll_hdr_len = MBLKL(ll_hdr_mp);
24744 			} else {
24745 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24746 			}
24747 
24748 			if (!ll_hdr_mp) {
24749 				xmit_mp = mp;
24750 
24751 			/*
24752 			 * We have link-layer header that can fit in
24753 			 * our mblk.
24754 			 */
24755 			} else if (mp->b_datap->db_ref == 1 &&
24756 			    ll_hdr_len != 0 &&
24757 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24758 				/* M_DATA fastpath */
24759 				mp->b_rptr -= ll_hdr_len;
24760 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24761 				    ll_hdr_len);
24762 				xmit_mp = mp;
24763 
24764 			/*
24765 			 * Case of res_mp OR the fastpath mp can't fit
24766 			 * in the mblk
24767 			 */
24768 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24769 				xmit_mp->b_cont = mp;
24770 				/* Get priority marking, if any. */
24771 				if (DB_TYPE(xmit_mp) == M_DATA)
24772 					xmit_mp->b_band = mp->b_band;
24773 
24774 			/* Corner case if copyb failed */
24775 			} else {
24776 				/*
24777 				 * Exit both the replication and
24778 				 * fragmentation loops.
24779 				 */
24780 				UNLOCK_IRE_FP_MP(ire);
24781 				goto drop_pkt;
24782 			}
24783 			UNLOCK_IRE_FP_MP(ire);
24784 
24785 			mp1 = mp;
24786 			out_ill = (ill_t *)q->q_ptr;
24787 
24788 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24789 
24790 			DTRACE_PROBE4(ip4__physical__out__start,
24791 			    ill_t *, NULL, ill_t *, out_ill,
24792 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24793 
24794 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24795 			    ipst->ips_ipv4firewall_physical_out,
24796 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24797 
24798 			DTRACE_PROBE1(ip4__physical__out__end,
24799 			    mblk_t *, xmit_mp);
24800 
24801 			if (mp != mp1 && hdr_mp == mp1)
24802 				hdr_mp = mp;
24803 			if (mp != mp1 && mp_orig == mp1)
24804 				mp_orig = mp;
24805 
24806 			if (xmit_mp != NULL) {
24807 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24808 				    NULL, void_ip_t *, ipha,
24809 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24810 				    ipha, ip6_t *, NULL, int, 0);
24811 
24812 				ILL_SEND_TX(out_ill, ire, connp,
24813 				    xmit_mp, 0, connp);
24814 
24815 				BUMP_MIB(out_ill->ill_ip_mib,
24816 				    ipIfStatsHCOutTransmits);
24817 				UPDATE_MIB(out_ill->ill_ip_mib,
24818 				    ipIfStatsHCOutOctets, ip_len);
24819 
24820 				if (pkt_type != OB_PKT) {
24821 					/*
24822 					 * Update the packet count of trailing
24823 					 * RTF_MULTIRT ires.
24824 					 */
24825 					UPDATE_OB_PKT_COUNT(ire);
24826 				}
24827 			}
24828 
24829 			/* All done if we just consumed the hdr_mp. */
24830 			if (mp == hdr_mp) {
24831 				last_frag = B_TRUE;
24832 				BUMP_MIB(out_ill->ill_ip_mib,
24833 				    ipIfStatsOutFragOKs);
24834 			}
24835 
24836 			if (multirt_send) {
24837 				/*
24838 				 * We are in a multiple send case; look for
24839 				 * the next ire and re-enter the loop.
24840 				 */
24841 				ASSERT(ire1);
24842 				ASSERT(next_mp);
24843 				/* REFRELE the current ire before looping */
24844 				ire_refrele(ire);
24845 				ire = ire1;
24846 				ire1 = NULL;
24847 				q = ire->ire_stq;
24848 				mp = next_mp;
24849 				next_mp = NULL;
24850 			}
24851 		} while (multirt_send);
24852 		/*
24853 		 * Restore the original ire; we need it for the
24854 		 * trailing frags
24855 		 */
24856 		if (save_ire != NULL) {
24857 			ASSERT(ire1 == NULL);
24858 			/* REFRELE the last iterated ire */
24859 			ire_refrele(ire);
24860 			/* save_ire has been REFHOLDed */
24861 			ire = save_ire;
24862 			q = ire->ire_stq;
24863 			save_ire = NULL;
24864 		}
24865 
24866 		if (last_frag) {
24867 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24868 			    "ip_wput_frag_end:(%S)",
24869 			    "consumed hdr_mp");
24870 
24871 			if (first_ire != NULL)
24872 				ire_refrele(first_ire);
24873 			return;
24874 		}
24875 		/* Otherwise, advance and loop. */
24876 		offset += len;
24877 	}
24878 
24879 drop_pkt:
24880 	/* Clean up following allocation failure. */
24881 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24882 	freemsg(mp);
24883 	if (mp != hdr_mp)
24884 		freeb(hdr_mp);
24885 	if (mp != mp_orig)
24886 		freemsg(mp_orig);
24887 
24888 	if (save_ire != NULL)
24889 		IRE_REFRELE(save_ire);
24890 	if (first_ire != NULL)
24891 		ire_refrele(first_ire);
24892 
24893 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24894 	    "ip_wput_frag_end:(%S)",
24895 	    "end--alloc failure");
24896 }
24897 
24898 /*
24899  * Copy the header plus those options which have the copy bit set
24900  * src is the template to make sure we preserve the cred for TX purposes.
24901  */
24902 static mblk_t *
24903 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24904     mblk_t *src)
24905 {
24906 	mblk_t	*mp;
24907 	uchar_t	*up;
24908 
24909 	/*
24910 	 * Quick check if we need to look for options without the copy bit
24911 	 * set
24912 	 */
24913 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24914 	if (!mp)
24915 		return (mp);
24916 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24917 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24918 		bcopy(rptr, mp->b_rptr, hdr_len);
24919 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24920 		return (mp);
24921 	}
24922 	up  = mp->b_rptr;
24923 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24924 	up += IP_SIMPLE_HDR_LENGTH;
24925 	rptr += IP_SIMPLE_HDR_LENGTH;
24926 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24927 	while (hdr_len > 0) {
24928 		uint32_t optval;
24929 		uint32_t optlen;
24930 
24931 		optval = *rptr;
24932 		if (optval == IPOPT_EOL)
24933 			break;
24934 		if (optval == IPOPT_NOP)
24935 			optlen = 1;
24936 		else
24937 			optlen = rptr[1];
24938 		if (optval & IPOPT_COPY) {
24939 			bcopy(rptr, up, optlen);
24940 			up += optlen;
24941 		}
24942 		rptr += optlen;
24943 		hdr_len -= optlen;
24944 	}
24945 	/*
24946 	 * Make sure that we drop an even number of words by filling
24947 	 * with EOL to the next word boundary.
24948 	 */
24949 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24950 	    hdr_len & 0x3; hdr_len++)
24951 		*up++ = IPOPT_EOL;
24952 	mp->b_wptr = up;
24953 	/* Update header length */
24954 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24955 	return (mp);
24956 }
24957 
24958 /*
24959  * Delivery to local recipients including fanout to multiple recipients.
24960  * Does not do checksumming of UDP/TCP.
24961  * Note: q should be the read side queue for either the ill or conn.
24962  * Note: rq should be the read side q for the lower (ill) stream.
24963  * We don't send packets to IPPF processing, thus the last argument
24964  * to all the fanout calls are B_FALSE.
24965  */
24966 void
24967 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24968     int fanout_flags, zoneid_t zoneid)
24969 {
24970 	uint32_t	protocol;
24971 	mblk_t		*first_mp;
24972 	boolean_t	mctl_present;
24973 	int		ire_type;
24974 #define	rptr	((uchar_t *)ipha)
24975 	ip_stack_t	*ipst = ill->ill_ipst;
24976 
24977 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24978 	    "ip_wput_local_start: q %p", q);
24979 
24980 	if (ire != NULL) {
24981 		ire_type = ire->ire_type;
24982 	} else {
24983 		/*
24984 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24985 		 * packet is not multicast, we can't tell the ire type.
24986 		 */
24987 		ASSERT(CLASSD(ipha->ipha_dst));
24988 		ire_type = IRE_BROADCAST;
24989 	}
24990 
24991 	first_mp = mp;
24992 	if (first_mp->b_datap->db_type == M_CTL) {
24993 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24994 		if (!io->ipsec_out_secure) {
24995 			/*
24996 			 * This ipsec_out_t was allocated in ip_wput
24997 			 * for multicast packets to store the ill_index.
24998 			 * As this is being delivered locally, we don't
24999 			 * need this anymore.
25000 			 */
25001 			mp = first_mp->b_cont;
25002 			freeb(first_mp);
25003 			first_mp = mp;
25004 			mctl_present = B_FALSE;
25005 		} else {
25006 			/*
25007 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25008 			 * security properties for the looped-back packet.
25009 			 */
25010 			mctl_present = B_TRUE;
25011 			mp = first_mp->b_cont;
25012 			ASSERT(mp != NULL);
25013 			ipsec_out_to_in(first_mp);
25014 		}
25015 	} else {
25016 		mctl_present = B_FALSE;
25017 	}
25018 
25019 	DTRACE_PROBE4(ip4__loopback__in__start,
25020 	    ill_t *, ill, ill_t *, NULL,
25021 	    ipha_t *, ipha, mblk_t *, first_mp);
25022 
25023 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25024 	    ipst->ips_ipv4firewall_loopback_in,
25025 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25026 
25027 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25028 
25029 	if (first_mp == NULL)
25030 		return;
25031 
25032 	if (ipst->ips_ipobs_enabled) {
25033 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25034 		zoneid_t stackzoneid = netstackid_to_zoneid(
25035 		    ipst->ips_netstack->netstack_stackid);
25036 
25037 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25038 		/*
25039 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25040 		 * address.  Restrict the lookup below to the destination zone.
25041 		 */
25042 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25043 			lookup_zoneid = zoneid;
25044 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25045 		    lookup_zoneid);
25046 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25047 		    IPV4_VERSION, 0, ipst);
25048 	}
25049 
25050 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25051 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25052 	    int, 1);
25053 
25054 	ipst->ips_loopback_packets++;
25055 
25056 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25057 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25058 	if (!IS_SIMPLE_IPH(ipha)) {
25059 		ip_wput_local_options(ipha, ipst);
25060 	}
25061 
25062 	protocol = ipha->ipha_protocol;
25063 	switch (protocol) {
25064 	case IPPROTO_ICMP: {
25065 		ire_t		*ire_zone;
25066 		ilm_t		*ilm;
25067 		mblk_t		*mp1;
25068 		zoneid_t	last_zoneid;
25069 		ilm_walker_t	ilw;
25070 
25071 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25072 			ASSERT(ire_type == IRE_BROADCAST);
25073 			/*
25074 			 * In the multicast case, applications may have joined
25075 			 * the group from different zones, so we need to deliver
25076 			 * the packet to each of them. Loop through the
25077 			 * multicast memberships structures (ilm) on the receive
25078 			 * ill and send a copy of the packet up each matching
25079 			 * one. However, we don't do this for multicasts sent on
25080 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25081 			 * they must stay in the sender's zone.
25082 			 *
25083 			 * ilm_add_v6() ensures that ilms in the same zone are
25084 			 * contiguous in the ill_ilm list. We use this property
25085 			 * to avoid sending duplicates needed when two
25086 			 * applications in the same zone join the same group on
25087 			 * different logical interfaces: we ignore the ilm if
25088 			 * it's zoneid is the same as the last matching one.
25089 			 * In addition, the sending of the packet for
25090 			 * ire_zoneid is delayed until all of the other ilms
25091 			 * have been exhausted.
25092 			 */
25093 			last_zoneid = -1;
25094 			ilm = ilm_walker_start(&ilw, ill);
25095 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25096 				if (ipha->ipha_dst != ilm->ilm_addr ||
25097 				    ilm->ilm_zoneid == last_zoneid ||
25098 				    ilm->ilm_zoneid == zoneid ||
25099 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25100 					continue;
25101 				mp1 = ip_copymsg(first_mp);
25102 				if (mp1 == NULL)
25103 					continue;
25104 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25105 				    0, 0, mctl_present, B_FALSE, ill,
25106 				    ilm->ilm_zoneid);
25107 				last_zoneid = ilm->ilm_zoneid;
25108 			}
25109 			ilm_walker_finish(&ilw);
25110 			/*
25111 			 * Loopback case: the sending endpoint has
25112 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25113 			 * dispatch the multicast packet to the sending zone.
25114 			 */
25115 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25116 				freemsg(first_mp);
25117 				return;
25118 			}
25119 		} else if (ire_type == IRE_BROADCAST) {
25120 			/*
25121 			 * In the broadcast case, there may be many zones
25122 			 * which need a copy of the packet delivered to them.
25123 			 * There is one IRE_BROADCAST per broadcast address
25124 			 * and per zone; we walk those using a helper function.
25125 			 * In addition, the sending of the packet for zoneid is
25126 			 * delayed until all of the other ires have been
25127 			 * processed.
25128 			 */
25129 			IRB_REFHOLD(ire->ire_bucket);
25130 			ire_zone = NULL;
25131 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25132 			    ire)) != NULL) {
25133 				mp1 = ip_copymsg(first_mp);
25134 				if (mp1 == NULL)
25135 					continue;
25136 
25137 				UPDATE_IB_PKT_COUNT(ire_zone);
25138 				ire_zone->ire_last_used_time = lbolt;
25139 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25140 				    mctl_present, B_FALSE, ill,
25141 				    ire_zone->ire_zoneid);
25142 			}
25143 			IRB_REFRELE(ire->ire_bucket);
25144 		}
25145 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25146 		    0, mctl_present, B_FALSE, ill, zoneid);
25147 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25148 		    "ip_wput_local_end: q %p (%S)",
25149 		    q, "icmp");
25150 		return;
25151 	}
25152 	case IPPROTO_IGMP:
25153 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25154 			/* Bad packet - discarded by igmp_input */
25155 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25156 			    "ip_wput_local_end: q %p (%S)",
25157 			    q, "igmp_input--bad packet");
25158 			if (mctl_present)
25159 				freeb(first_mp);
25160 			return;
25161 		}
25162 		/*
25163 		 * igmp_input() may have returned the pulled up message.
25164 		 * So first_mp and ipha need to be reinitialized.
25165 		 */
25166 		ipha = (ipha_t *)mp->b_rptr;
25167 		if (mctl_present)
25168 			first_mp->b_cont = mp;
25169 		else
25170 			first_mp = mp;
25171 		/* deliver to local raw users */
25172 		break;
25173 	case IPPROTO_ENCAP:
25174 		/*
25175 		 * This case is covered by either ip_fanout_proto, or by
25176 		 * the above security processing for self-tunneled packets.
25177 		 */
25178 		break;
25179 	case IPPROTO_UDP: {
25180 		uint16_t	*up;
25181 		uint32_t	ports;
25182 
25183 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25184 		    UDP_PORTS_OFFSET);
25185 		/* Force a 'valid' checksum. */
25186 		up[3] = 0;
25187 
25188 		ports = *(uint32_t *)up;
25189 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25190 		    (ire_type == IRE_BROADCAST),
25191 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25192 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25193 		    ill, zoneid);
25194 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25195 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25196 		return;
25197 	}
25198 	case IPPROTO_TCP: {
25199 
25200 		/*
25201 		 * For TCP, discard broadcast packets.
25202 		 */
25203 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25204 			freemsg(first_mp);
25205 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25206 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25207 			return;
25208 		}
25209 
25210 		if (mp->b_datap->db_type == M_DATA) {
25211 			/*
25212 			 * M_DATA mblk, so init mblk (chain) for no struio().
25213 			 */
25214 			mblk_t	*mp1 = mp;
25215 
25216 			do {
25217 				mp1->b_datap->db_struioflag = 0;
25218 			} while ((mp1 = mp1->b_cont) != NULL);
25219 		}
25220 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25221 		    <= mp->b_wptr);
25222 		ip_fanout_tcp(q, first_mp, ill, ipha,
25223 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25224 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25225 		    mctl_present, B_FALSE, zoneid);
25226 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25227 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25228 		return;
25229 	}
25230 	case IPPROTO_SCTP:
25231 	{
25232 		uint32_t	ports;
25233 
25234 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25235 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25236 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25237 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25238 		return;
25239 	}
25240 
25241 	default:
25242 		break;
25243 	}
25244 	/*
25245 	 * Find a client for some other protocol.  We give
25246 	 * copies to multiple clients, if more than one is
25247 	 * bound.
25248 	 */
25249 	ip_fanout_proto(q, first_mp, ill, ipha,
25250 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25251 	    mctl_present, B_FALSE, ill, zoneid);
25252 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25253 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25254 #undef	rptr
25255 }
25256 
25257 /*
25258  * Update any source route, record route, or timestamp options.
25259  * Check that we are at end of strict source route.
25260  * The options have been sanity checked by ip_wput_options().
25261  */
25262 static void
25263 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25264 {
25265 	ipoptp_t	opts;
25266 	uchar_t		*opt;
25267 	uint8_t		optval;
25268 	uint8_t		optlen;
25269 	ipaddr_t	dst;
25270 	uint32_t	ts;
25271 	ire_t		*ire;
25272 	timestruc_t	now;
25273 
25274 	ip2dbg(("ip_wput_local_options\n"));
25275 	for (optval = ipoptp_first(&opts, ipha);
25276 	    optval != IPOPT_EOL;
25277 	    optval = ipoptp_next(&opts)) {
25278 		opt = opts.ipoptp_cur;
25279 		optlen = opts.ipoptp_len;
25280 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25281 		switch (optval) {
25282 			uint32_t off;
25283 		case IPOPT_SSRR:
25284 		case IPOPT_LSRR:
25285 			off = opt[IPOPT_OFFSET];
25286 			off--;
25287 			if (optlen < IP_ADDR_LEN ||
25288 			    off > optlen - IP_ADDR_LEN) {
25289 				/* End of source route */
25290 				break;
25291 			}
25292 			/*
25293 			 * This will only happen if two consecutive entries
25294 			 * in the source route contains our address or if
25295 			 * it is a packet with a loose source route which
25296 			 * reaches us before consuming the whole source route
25297 			 */
25298 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25299 			if (optval == IPOPT_SSRR) {
25300 				return;
25301 			}
25302 			/*
25303 			 * Hack: instead of dropping the packet truncate the
25304 			 * source route to what has been used by filling the
25305 			 * rest with IPOPT_NOP.
25306 			 */
25307 			opt[IPOPT_OLEN] = (uint8_t)off;
25308 			while (off < optlen) {
25309 				opt[off++] = IPOPT_NOP;
25310 			}
25311 			break;
25312 		case IPOPT_RR:
25313 			off = opt[IPOPT_OFFSET];
25314 			off--;
25315 			if (optlen < IP_ADDR_LEN ||
25316 			    off > optlen - IP_ADDR_LEN) {
25317 				/* No more room - ignore */
25318 				ip1dbg((
25319 				    "ip_wput_forward_options: end of RR\n"));
25320 				break;
25321 			}
25322 			dst = htonl(INADDR_LOOPBACK);
25323 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25324 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25325 			break;
25326 		case IPOPT_TS:
25327 			/* Insert timestamp if there is romm */
25328 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25329 			case IPOPT_TS_TSONLY:
25330 				off = IPOPT_TS_TIMELEN;
25331 				break;
25332 			case IPOPT_TS_PRESPEC:
25333 			case IPOPT_TS_PRESPEC_RFC791:
25334 				/* Verify that the address matched */
25335 				off = opt[IPOPT_OFFSET] - 1;
25336 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25337 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25338 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25339 				    ipst);
25340 				if (ire == NULL) {
25341 					/* Not for us */
25342 					break;
25343 				}
25344 				ire_refrele(ire);
25345 				/* FALLTHRU */
25346 			case IPOPT_TS_TSANDADDR:
25347 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25348 				break;
25349 			default:
25350 				/*
25351 				 * ip_*put_options should have already
25352 				 * dropped this packet.
25353 				 */
25354 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25355 				    "unknown IT - bug in ip_wput_options?\n");
25356 				return;	/* Keep "lint" happy */
25357 			}
25358 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25359 				/* Increase overflow counter */
25360 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25361 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25362 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25363 				    (off << 4);
25364 				break;
25365 			}
25366 			off = opt[IPOPT_OFFSET] - 1;
25367 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25368 			case IPOPT_TS_PRESPEC:
25369 			case IPOPT_TS_PRESPEC_RFC791:
25370 			case IPOPT_TS_TSANDADDR:
25371 				dst = htonl(INADDR_LOOPBACK);
25372 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25373 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25374 				/* FALLTHRU */
25375 			case IPOPT_TS_TSONLY:
25376 				off = opt[IPOPT_OFFSET] - 1;
25377 				/* Compute # of milliseconds since midnight */
25378 				gethrestime(&now);
25379 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25380 				    now.tv_nsec / (NANOSEC / MILLISEC);
25381 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25382 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25383 				break;
25384 			}
25385 			break;
25386 		}
25387 	}
25388 }
25389 
25390 /*
25391  * Send out a multicast packet on interface ipif.
25392  * The sender does not have an conn.
25393  * Caller verifies that this isn't a PHYI_LOOPBACK.
25394  */
25395 void
25396 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25397 {
25398 	ipha_t	*ipha;
25399 	ire_t	*ire;
25400 	ipaddr_t	dst;
25401 	mblk_t		*first_mp;
25402 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25403 
25404 	/* igmp_sendpkt always allocates a ipsec_out_t */
25405 	ASSERT(mp->b_datap->db_type == M_CTL);
25406 	ASSERT(!ipif->ipif_isv6);
25407 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25408 
25409 	first_mp = mp;
25410 	mp = first_mp->b_cont;
25411 	ASSERT(mp->b_datap->db_type == M_DATA);
25412 	ipha = (ipha_t *)mp->b_rptr;
25413 
25414 	/*
25415 	 * Find an IRE which matches the destination and the outgoing
25416 	 * queue (i.e. the outgoing interface.)
25417 	 */
25418 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25419 		dst = ipif->ipif_pp_dst_addr;
25420 	else
25421 		dst = ipha->ipha_dst;
25422 	/*
25423 	 * The source address has already been initialized by the
25424 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25425 	 * be sufficient rather than MATCH_IRE_IPIF.
25426 	 *
25427 	 * This function is used for sending IGMP packets.  For IPMP,
25428 	 * we sidestep IGMP snooping issues by sending all multicast
25429 	 * traffic on a single interface in the IPMP group.
25430 	 */
25431 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25432 	    MATCH_IRE_ILL, ipst);
25433 	if (!ire) {
25434 		/*
25435 		 * Mark this packet to make it be delivered to
25436 		 * ip_wput_ire after the new ire has been
25437 		 * created.
25438 		 */
25439 		mp->b_prev = NULL;
25440 		mp->b_next = NULL;
25441 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25442 		    zoneid, &zero_info);
25443 		return;
25444 	}
25445 
25446 	/*
25447 	 * Honor the RTF_SETSRC flag; this is the only case
25448 	 * where we force this addr whatever the current src addr is,
25449 	 * because this address is set by igmp_sendpkt(), and
25450 	 * cannot be specified by any user.
25451 	 */
25452 	if (ire->ire_flags & RTF_SETSRC) {
25453 		ipha->ipha_src = ire->ire_src_addr;
25454 	}
25455 
25456 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25457 }
25458 
25459 /*
25460  * NOTE : This function does not ire_refrele the ire argument passed in.
25461  *
25462  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25463  * failure. The nce_fp_mp can vanish any time in the case of
25464  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25465  * the ire_lock to access the nce_fp_mp in this case.
25466  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25467  * prepending a fastpath message IPQoS processing must precede it, we also set
25468  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25469  * (IPQoS might have set the b_band for CoS marking).
25470  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25471  * must follow it so that IPQoS can mark the dl_priority field for CoS
25472  * marking, if needed.
25473  */
25474 static mblk_t *
25475 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25476     uint32_t ill_index, ipha_t **iphap)
25477 {
25478 	uint_t	hlen;
25479 	ipha_t *ipha;
25480 	mblk_t *mp1;
25481 	boolean_t qos_done = B_FALSE;
25482 	uchar_t	*ll_hdr;
25483 	ip_stack_t	*ipst = ire->ire_ipst;
25484 
25485 #define	rptr	((uchar_t *)ipha)
25486 
25487 	ipha = (ipha_t *)mp->b_rptr;
25488 	hlen = 0;
25489 	LOCK_IRE_FP_MP(ire);
25490 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25491 		ASSERT(DB_TYPE(mp1) == M_DATA);
25492 		/* Initiate IPPF processing */
25493 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25494 			UNLOCK_IRE_FP_MP(ire);
25495 			ip_process(proc, &mp, ill_index);
25496 			if (mp == NULL)
25497 				return (NULL);
25498 
25499 			ipha = (ipha_t *)mp->b_rptr;
25500 			LOCK_IRE_FP_MP(ire);
25501 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25502 				qos_done = B_TRUE;
25503 				goto no_fp_mp;
25504 			}
25505 			ASSERT(DB_TYPE(mp1) == M_DATA);
25506 		}
25507 		hlen = MBLKL(mp1);
25508 		/*
25509 		 * Check if we have enough room to prepend fastpath
25510 		 * header
25511 		 */
25512 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25513 			ll_hdr = rptr - hlen;
25514 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25515 			/*
25516 			 * Set the b_rptr to the start of the link layer
25517 			 * header
25518 			 */
25519 			mp->b_rptr = ll_hdr;
25520 			mp1 = mp;
25521 		} else {
25522 			mp1 = copyb(mp1);
25523 			if (mp1 == NULL)
25524 				goto unlock_err;
25525 			mp1->b_band = mp->b_band;
25526 			mp1->b_cont = mp;
25527 			/*
25528 			 * XXX disable ICK_VALID and compute checksum
25529 			 * here; can happen if nce_fp_mp changes and
25530 			 * it can't be copied now due to insufficient
25531 			 * space. (unlikely, fp mp can change, but it
25532 			 * does not increase in length)
25533 			 */
25534 		}
25535 		UNLOCK_IRE_FP_MP(ire);
25536 	} else {
25537 no_fp_mp:
25538 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25539 		if (mp1 == NULL) {
25540 unlock_err:
25541 			UNLOCK_IRE_FP_MP(ire);
25542 			freemsg(mp);
25543 			return (NULL);
25544 		}
25545 		UNLOCK_IRE_FP_MP(ire);
25546 		mp1->b_cont = mp;
25547 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25548 			ip_process(proc, &mp1, ill_index);
25549 			if (mp1 == NULL)
25550 				return (NULL);
25551 
25552 			if (mp1->b_cont == NULL)
25553 				ipha = NULL;
25554 			else
25555 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25556 		}
25557 	}
25558 
25559 	*iphap = ipha;
25560 	return (mp1);
25561 #undef rptr
25562 }
25563 
25564 /*
25565  * Finish the outbound IPsec processing for an IPv6 packet. This function
25566  * is called from ipsec_out_process() if the IPsec packet was processed
25567  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25568  * asynchronously.
25569  */
25570 void
25571 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25572     ire_t *ire_arg)
25573 {
25574 	in6_addr_t *v6dstp;
25575 	ire_t *ire;
25576 	mblk_t *mp;
25577 	ip6_t *ip6h1;
25578 	uint_t	ill_index;
25579 	ipsec_out_t *io;
25580 	boolean_t hwaccel;
25581 	uint32_t flags = IP6_NO_IPPOLICY;
25582 	int match_flags;
25583 	zoneid_t zoneid;
25584 	boolean_t ill_need_rele = B_FALSE;
25585 	boolean_t ire_need_rele = B_FALSE;
25586 	ip_stack_t	*ipst;
25587 
25588 	mp = ipsec_mp->b_cont;
25589 	ip6h1 = (ip6_t *)mp->b_rptr;
25590 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25591 	ASSERT(io->ipsec_out_ns != NULL);
25592 	ipst = io->ipsec_out_ns->netstack_ip;
25593 	ill_index = io->ipsec_out_ill_index;
25594 	if (io->ipsec_out_reachable) {
25595 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25596 	}
25597 	hwaccel = io->ipsec_out_accelerated;
25598 	zoneid = io->ipsec_out_zoneid;
25599 	ASSERT(zoneid != ALL_ZONES);
25600 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25601 	/* Multicast addresses should have non-zero ill_index. */
25602 	v6dstp = &ip6h->ip6_dst;
25603 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25604 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25605 
25606 	if (ill == NULL && ill_index != 0) {
25607 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25608 		/* Failure case frees things for us. */
25609 		if (ill == NULL)
25610 			return;
25611 
25612 		ill_need_rele = B_TRUE;
25613 	}
25614 	ASSERT(mp != NULL);
25615 
25616 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25617 		boolean_t unspec_src;
25618 		ipif_t	*ipif;
25619 
25620 		/*
25621 		 * Use the ill_index to get the right ill.
25622 		 */
25623 		unspec_src = io->ipsec_out_unspec_src;
25624 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25625 		if (ipif == NULL) {
25626 			if (ill_need_rele)
25627 				ill_refrele(ill);
25628 			freemsg(ipsec_mp);
25629 			return;
25630 		}
25631 
25632 		if (ire_arg != NULL) {
25633 			ire = ire_arg;
25634 		} else {
25635 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25636 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25637 			ire_need_rele = B_TRUE;
25638 		}
25639 		if (ire != NULL) {
25640 			ipif_refrele(ipif);
25641 			/*
25642 			 * XXX Do the multicast forwarding now, as the IPsec
25643 			 * processing has been done.
25644 			 */
25645 			goto send;
25646 		}
25647 
25648 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25649 		mp->b_prev = NULL;
25650 		mp->b_next = NULL;
25651 
25652 		/*
25653 		 * If the IPsec packet was processed asynchronously,
25654 		 * drop it now.
25655 		 */
25656 		if (q == NULL) {
25657 			if (ill_need_rele)
25658 				ill_refrele(ill);
25659 			freemsg(ipsec_mp);
25660 			return;
25661 		}
25662 
25663 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25664 		    unspec_src, zoneid);
25665 		ipif_refrele(ipif);
25666 	} else {
25667 		if (ire_arg != NULL) {
25668 			ire = ire_arg;
25669 		} else {
25670 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25671 			ire_need_rele = B_TRUE;
25672 		}
25673 		if (ire != NULL)
25674 			goto send;
25675 		/*
25676 		 * ire disappeared underneath.
25677 		 *
25678 		 * What we need to do here is the ip_newroute
25679 		 * logic to get the ire without doing the IPsec
25680 		 * processing. Follow the same old path. But this
25681 		 * time, ip_wput or ire_add_then_send will call us
25682 		 * directly as all the IPsec operations are done.
25683 		 */
25684 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25685 		mp->b_prev = NULL;
25686 		mp->b_next = NULL;
25687 
25688 		/*
25689 		 * If the IPsec packet was processed asynchronously,
25690 		 * drop it now.
25691 		 */
25692 		if (q == NULL) {
25693 			if (ill_need_rele)
25694 				ill_refrele(ill);
25695 			freemsg(ipsec_mp);
25696 			return;
25697 		}
25698 
25699 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25700 		    zoneid, ipst);
25701 	}
25702 	if (ill != NULL && ill_need_rele)
25703 		ill_refrele(ill);
25704 	return;
25705 send:
25706 	if (ill != NULL && ill_need_rele)
25707 		ill_refrele(ill);
25708 
25709 	/* Local delivery */
25710 	if (ire->ire_stq == NULL) {
25711 		ill_t	*out_ill;
25712 		ASSERT(q != NULL);
25713 
25714 		/* PFHooks: LOOPBACK_OUT */
25715 		out_ill = ire_to_ill(ire);
25716 
25717 		/*
25718 		 * DTrace this as ip:::send.  A blocked packet will fire the
25719 		 * send probe, but not the receive probe.
25720 		 */
25721 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25722 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25723 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25724 
25725 		DTRACE_PROBE4(ip6__loopback__out__start,
25726 		    ill_t *, NULL, ill_t *, out_ill,
25727 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25728 
25729 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25730 		    ipst->ips_ipv6firewall_loopback_out,
25731 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25732 
25733 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25734 
25735 		if (ipsec_mp != NULL) {
25736 			ip_wput_local_v6(RD(q), out_ill,
25737 			    ip6h, ipsec_mp, ire, 0, zoneid);
25738 		}
25739 		if (ire_need_rele)
25740 			ire_refrele(ire);
25741 		return;
25742 	}
25743 	/*
25744 	 * Everything is done. Send it out on the wire.
25745 	 * We force the insertion of a fragment header using the
25746 	 * IPH_FRAG_HDR flag in two cases:
25747 	 * - after reception of an ICMPv6 "packet too big" message
25748 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25749 	 * - for multirouted IPv6 packets, so that the receiver can
25750 	 *   discard duplicates according to their fragment identifier
25751 	 */
25752 	/* XXX fix flow control problems. */
25753 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25754 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25755 		if (hwaccel) {
25756 			/*
25757 			 * hardware acceleration does not handle these
25758 			 * "slow path" cases.
25759 			 */
25760 			/* IPsec KSTATS: should bump bean counter here. */
25761 			if (ire_need_rele)
25762 				ire_refrele(ire);
25763 			freemsg(ipsec_mp);
25764 			return;
25765 		}
25766 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25767 		    (mp->b_cont ? msgdsize(mp) :
25768 		    mp->b_wptr - (uchar_t *)ip6h)) {
25769 			/* IPsec KSTATS: should bump bean counter here. */
25770 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25771 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25772 			    msgdsize(mp)));
25773 			if (ire_need_rele)
25774 				ire_refrele(ire);
25775 			freemsg(ipsec_mp);
25776 			return;
25777 		}
25778 		ASSERT(mp->b_prev == NULL);
25779 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25780 		    ntohs(ip6h->ip6_plen) +
25781 		    IPV6_HDR_LEN, ire->ire_max_frag));
25782 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25783 		    ire->ire_max_frag);
25784 	} else {
25785 		UPDATE_OB_PKT_COUNT(ire);
25786 		ire->ire_last_used_time = lbolt;
25787 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25788 	}
25789 	if (ire_need_rele)
25790 		ire_refrele(ire);
25791 	freeb(ipsec_mp);
25792 }
25793 
25794 void
25795 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25796 {
25797 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25798 	da_ipsec_t *hada;	/* data attributes */
25799 	ill_t *ill = (ill_t *)q->q_ptr;
25800 
25801 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25802 
25803 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25804 		/* IPsec KSTATS: Bump lose counter here! */
25805 		freemsg(mp);
25806 		return;
25807 	}
25808 
25809 	/*
25810 	 * It's an IPsec packet that must be
25811 	 * accelerated by the Provider, and the
25812 	 * outbound ill is IPsec acceleration capable.
25813 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25814 	 * to the ill.
25815 	 * IPsec KSTATS: should bump packet counter here.
25816 	 */
25817 
25818 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25819 	if (hada_mp == NULL) {
25820 		/* IPsec KSTATS: should bump packet counter here. */
25821 		freemsg(mp);
25822 		return;
25823 	}
25824 
25825 	hada_mp->b_datap->db_type = M_CTL;
25826 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25827 	hada_mp->b_cont = mp;
25828 
25829 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25830 	bzero(hada, sizeof (da_ipsec_t));
25831 	hada->da_type = IPHADA_M_CTL;
25832 
25833 	putnext(q, hada_mp);
25834 }
25835 
25836 /*
25837  * Finish the outbound IPsec processing. This function is called from
25838  * ipsec_out_process() if the IPsec packet was processed
25839  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25840  * asynchronously.
25841  */
25842 void
25843 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25844     ire_t *ire_arg)
25845 {
25846 	uint32_t v_hlen_tos_len;
25847 	ipaddr_t	dst;
25848 	ipif_t	*ipif = NULL;
25849 	ire_t *ire;
25850 	ire_t *ire1 = NULL;
25851 	mblk_t *next_mp = NULL;
25852 	uint32_t max_frag;
25853 	boolean_t multirt_send = B_FALSE;
25854 	mblk_t *mp;
25855 	ipha_t *ipha1;
25856 	uint_t	ill_index;
25857 	ipsec_out_t *io;
25858 	int match_flags;
25859 	irb_t *irb = NULL;
25860 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25861 	zoneid_t zoneid;
25862 	ipxmit_state_t	pktxmit_state;
25863 	ip_stack_t	*ipst;
25864 
25865 #ifdef	_BIG_ENDIAN
25866 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25867 #else
25868 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25869 #endif
25870 
25871 	mp = ipsec_mp->b_cont;
25872 	ipha1 = (ipha_t *)mp->b_rptr;
25873 	ASSERT(mp != NULL);
25874 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25875 	dst = ipha->ipha_dst;
25876 
25877 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25878 	ill_index = io->ipsec_out_ill_index;
25879 	zoneid = io->ipsec_out_zoneid;
25880 	ASSERT(zoneid != ALL_ZONES);
25881 	ipst = io->ipsec_out_ns->netstack_ip;
25882 	ASSERT(io->ipsec_out_ns != NULL);
25883 
25884 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25885 	if (ill == NULL && ill_index != 0) {
25886 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25887 		/* Failure case frees things for us. */
25888 		if (ill == NULL)
25889 			return;
25890 
25891 		ill_need_rele = B_TRUE;
25892 	}
25893 
25894 	if (CLASSD(dst)) {
25895 		boolean_t conn_dontroute;
25896 		/*
25897 		 * Use the ill_index to get the right ipif.
25898 		 */
25899 		conn_dontroute = io->ipsec_out_dontroute;
25900 		if (ill_index == 0)
25901 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25902 		else
25903 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25904 		if (ipif == NULL) {
25905 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25906 			    " multicast\n"));
25907 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25908 			freemsg(ipsec_mp);
25909 			goto done;
25910 		}
25911 		/*
25912 		 * ipha_src has already been intialized with the
25913 		 * value of the ipif in ip_wput. All we need now is
25914 		 * an ire to send this downstream.
25915 		 */
25916 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25917 		    msg_getlabel(mp), match_flags, ipst);
25918 		if (ire != NULL) {
25919 			ill_t *ill1;
25920 			/*
25921 			 * Do the multicast forwarding now, as the IPsec
25922 			 * processing has been done.
25923 			 */
25924 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25925 			    (ill1 = ire_to_ill(ire))) {
25926 				if (ip_mforward(ill1, ipha, mp)) {
25927 					freemsg(ipsec_mp);
25928 					ip1dbg(("ip_wput_ipsec_out: mforward "
25929 					    "failed\n"));
25930 					ire_refrele(ire);
25931 					goto done;
25932 				}
25933 			}
25934 			goto send;
25935 		}
25936 
25937 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25938 		mp->b_prev = NULL;
25939 		mp->b_next = NULL;
25940 
25941 		/*
25942 		 * If the IPsec packet was processed asynchronously,
25943 		 * drop it now.
25944 		 */
25945 		if (q == NULL) {
25946 			freemsg(ipsec_mp);
25947 			goto done;
25948 		}
25949 
25950 		/*
25951 		 * We may be using a wrong ipif to create the ire.
25952 		 * But it is okay as the source address is assigned
25953 		 * for the packet already. Next outbound packet would
25954 		 * create the IRE with the right IPIF in ip_wput.
25955 		 *
25956 		 * Also handle RTF_MULTIRT routes.
25957 		 */
25958 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25959 		    zoneid, &zero_info);
25960 	} else {
25961 		if (ire_arg != NULL) {
25962 			ire = ire_arg;
25963 			ire_need_rele = B_FALSE;
25964 		} else {
25965 			ire = ire_cache_lookup(dst, zoneid,
25966 			    msg_getlabel(mp), ipst);
25967 		}
25968 		if (ire != NULL) {
25969 			goto send;
25970 		}
25971 
25972 		/*
25973 		 * ire disappeared underneath.
25974 		 *
25975 		 * What we need to do here is the ip_newroute
25976 		 * logic to get the ire without doing the IPsec
25977 		 * processing. Follow the same old path. But this
25978 		 * time, ip_wput or ire_add_then_put will call us
25979 		 * directly as all the IPsec operations are done.
25980 		 */
25981 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25982 		mp->b_prev = NULL;
25983 		mp->b_next = NULL;
25984 
25985 		/*
25986 		 * If the IPsec packet was processed asynchronously,
25987 		 * drop it now.
25988 		 */
25989 		if (q == NULL) {
25990 			freemsg(ipsec_mp);
25991 			goto done;
25992 		}
25993 
25994 		/*
25995 		 * Since we're going through ip_newroute() again, we
25996 		 * need to make sure we don't:
25997 		 *
25998 		 *	1.) Trigger the ASSERT() with the ipha_ident
25999 		 *	    overloading.
26000 		 *	2.) Redo transport-layer checksumming, since we've
26001 		 *	    already done all that to get this far.
26002 		 *
26003 		 * The easiest way not do either of the above is to set
26004 		 * the ipha_ident field to IP_HDR_INCLUDED.
26005 		 */
26006 		ipha->ipha_ident = IP_HDR_INCLUDED;
26007 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26008 		    zoneid, ipst);
26009 	}
26010 	goto done;
26011 send:
26012 	if (ire->ire_stq == NULL) {
26013 		ill_t	*out_ill;
26014 		/*
26015 		 * Loopbacks go through ip_wput_local except for one case.
26016 		 * We come here if we generate a icmp_frag_needed message
26017 		 * after IPsec processing is over. When this function calls
26018 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26019 		 * icmp_frag_needed. The message generated comes back here
26020 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26021 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26022 		 * source address as it is usually set in ip_wput_ire. As
26023 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26024 		 * and we end up here. We can't enter ip_wput_ire once the
26025 		 * IPsec processing is over and hence we need to do it here.
26026 		 */
26027 		ASSERT(q != NULL);
26028 		UPDATE_OB_PKT_COUNT(ire);
26029 		ire->ire_last_used_time = lbolt;
26030 		if (ipha->ipha_src == 0)
26031 			ipha->ipha_src = ire->ire_src_addr;
26032 
26033 		/* PFHooks: LOOPBACK_OUT */
26034 		out_ill = ire_to_ill(ire);
26035 
26036 		/*
26037 		 * DTrace this as ip:::send.  A blocked packet will fire the
26038 		 * send probe, but not the receive probe.
26039 		 */
26040 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26041 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26042 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26043 
26044 		DTRACE_PROBE4(ip4__loopback__out__start,
26045 		    ill_t *, NULL, ill_t *, out_ill,
26046 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26047 
26048 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26049 		    ipst->ips_ipv4firewall_loopback_out,
26050 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26051 
26052 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26053 
26054 		if (ipsec_mp != NULL)
26055 			ip_wput_local(RD(q), out_ill,
26056 			    ipha, ipsec_mp, ire, 0, zoneid);
26057 		if (ire_need_rele)
26058 			ire_refrele(ire);
26059 		goto done;
26060 	}
26061 
26062 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26063 		/*
26064 		 * We are through with IPsec processing.
26065 		 * Fragment this and send it on the wire.
26066 		 */
26067 		if (io->ipsec_out_accelerated) {
26068 			/*
26069 			 * The packet has been accelerated but must
26070 			 * be fragmented. This should not happen
26071 			 * since AH and ESP must not accelerate
26072 			 * packets that need fragmentation, however
26073 			 * the configuration could have changed
26074 			 * since the AH or ESP processing.
26075 			 * Drop packet.
26076 			 * IPsec KSTATS: bump bean counter here.
26077 			 */
26078 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26079 			    "fragmented accelerated packet!\n"));
26080 			freemsg(ipsec_mp);
26081 		} else {
26082 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26083 			    zoneid, ipst, NULL);
26084 		}
26085 		if (ire_need_rele)
26086 			ire_refrele(ire);
26087 		goto done;
26088 	}
26089 
26090 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26091 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26092 	    (void *)ire->ire_ipif, (void *)ipif));
26093 
26094 	/*
26095 	 * Multiroute the secured packet.
26096 	 */
26097 	if (ire->ire_flags & RTF_MULTIRT) {
26098 		ire_t *first_ire;
26099 		irb = ire->ire_bucket;
26100 		ASSERT(irb != NULL);
26101 		/*
26102 		 * This ire has been looked up as the one that
26103 		 * goes through the given ipif;
26104 		 * make sure we do not omit any other multiroute ire
26105 		 * that may be present in the bucket before this one.
26106 		 */
26107 		IRB_REFHOLD(irb);
26108 		for (first_ire = irb->irb_ire;
26109 		    first_ire != NULL;
26110 		    first_ire = first_ire->ire_next) {
26111 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26112 			    (first_ire->ire_addr == ire->ire_addr) &&
26113 			    !(first_ire->ire_marks &
26114 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26115 				break;
26116 		}
26117 
26118 		if ((first_ire != NULL) && (first_ire != ire)) {
26119 			/*
26120 			 * Don't change the ire if the packet must
26121 			 * be fragmented if sent via this new one.
26122 			 */
26123 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26124 				IRE_REFHOLD(first_ire);
26125 				if (ire_need_rele)
26126 					ire_refrele(ire);
26127 				else
26128 					ire_need_rele = B_TRUE;
26129 				ire = first_ire;
26130 			}
26131 		}
26132 		IRB_REFRELE(irb);
26133 
26134 		multirt_send = B_TRUE;
26135 		max_frag = ire->ire_max_frag;
26136 	}
26137 
26138 	/*
26139 	 * In most cases, the emission loop below is entered only once.
26140 	 * Only in the case where the ire holds the RTF_MULTIRT
26141 	 * flag, we loop to process all RTF_MULTIRT ires in the
26142 	 * bucket, and send the packet through all crossed
26143 	 * RTF_MULTIRT routes.
26144 	 */
26145 	do {
26146 		if (multirt_send) {
26147 			/*
26148 			 * ire1 holds here the next ire to process in the
26149 			 * bucket. If multirouting is expected,
26150 			 * any non-RTF_MULTIRT ire that has the
26151 			 * right destination address is ignored.
26152 			 */
26153 			ASSERT(irb != NULL);
26154 			IRB_REFHOLD(irb);
26155 			for (ire1 = ire->ire_next;
26156 			    ire1 != NULL;
26157 			    ire1 = ire1->ire_next) {
26158 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26159 					continue;
26160 				if (ire1->ire_addr != ire->ire_addr)
26161 					continue;
26162 				if (ire1->ire_marks &
26163 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26164 					continue;
26165 				/* No loopback here */
26166 				if (ire1->ire_stq == NULL)
26167 					continue;
26168 				/*
26169 				 * Ensure we do not exceed the MTU
26170 				 * of the next route.
26171 				 */
26172 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26173 					ip_multirt_bad_mtu(ire1, max_frag);
26174 					continue;
26175 				}
26176 
26177 				IRE_REFHOLD(ire1);
26178 				break;
26179 			}
26180 			IRB_REFRELE(irb);
26181 			if (ire1 != NULL) {
26182 				/*
26183 				 * We are in a multiple send case, need to
26184 				 * make a copy of the packet.
26185 				 */
26186 				next_mp = copymsg(ipsec_mp);
26187 				if (next_mp == NULL) {
26188 					ire_refrele(ire1);
26189 					ire1 = NULL;
26190 				}
26191 			}
26192 		}
26193 		/*
26194 		 * Everything is done. Send it out on the wire
26195 		 *
26196 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26197 		 * either send it on the wire or, in the case of
26198 		 * HW acceleration, call ipsec_hw_putnext.
26199 		 */
26200 		if (ire->ire_nce &&
26201 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26202 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26203 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26204 			/*
26205 			 * If ire's link-layer is unresolved (this
26206 			 * would only happen if the incomplete ire
26207 			 * was added to cachetable via forwarding path)
26208 			 * don't bother going to ip_xmit_v4. Just drop the
26209 			 * packet.
26210 			 * There is a slight risk here, in that, if we
26211 			 * have the forwarding path create an incomplete
26212 			 * IRE, then until the IRE is completed, any
26213 			 * transmitted IPsec packets will be dropped
26214 			 * instead of being queued waiting for resolution.
26215 			 *
26216 			 * But the likelihood of a forwarding packet and a wput
26217 			 * packet sending to the same dst at the same time
26218 			 * and there not yet be an ARP entry for it is small.
26219 			 * Furthermore, if this actually happens, it might
26220 			 * be likely that wput would generate multiple
26221 			 * packets (and forwarding would also have a train
26222 			 * of packets) for that destination. If this is
26223 			 * the case, some of them would have been dropped
26224 			 * anyway, since ARP only queues a few packets while
26225 			 * waiting for resolution
26226 			 *
26227 			 * NOTE: We should really call ip_xmit_v4,
26228 			 * and let it queue the packet and send the
26229 			 * ARP query and have ARP come back thus:
26230 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26231 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26232 			 * hw accel work. But it's too complex to get
26233 			 * the IPsec hw  acceleration approach to fit
26234 			 * well with ip_xmit_v4 doing ARP without
26235 			 * doing IPsec simplification. For now, we just
26236 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26237 			 * that we can continue with the send on the next
26238 			 * attempt.
26239 			 *
26240 			 * XXX THis should be revisited, when
26241 			 * the IPsec/IP interaction is cleaned up
26242 			 */
26243 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26244 			    " - dropping packet\n"));
26245 			freemsg(ipsec_mp);
26246 			/*
26247 			 * Call ip_xmit_v4() to trigger ARP query
26248 			 * in case the nce_state is ND_INITIAL
26249 			 */
26250 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26251 			goto drop_pkt;
26252 		}
26253 
26254 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26255 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26256 		    mblk_t *, ipsec_mp);
26257 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26258 		    ipst->ips_ipv4firewall_physical_out, NULL,
26259 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26260 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26261 		if (ipsec_mp == NULL)
26262 			goto drop_pkt;
26263 
26264 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26265 		pktxmit_state = ip_xmit_v4(mp, ire,
26266 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26267 
26268 		if ((pktxmit_state ==  SEND_FAILED) ||
26269 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26270 
26271 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26272 drop_pkt:
26273 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26274 			    ipIfStatsOutDiscards);
26275 			if (ire_need_rele)
26276 				ire_refrele(ire);
26277 			if (ire1 != NULL) {
26278 				ire_refrele(ire1);
26279 				freemsg(next_mp);
26280 			}
26281 			goto done;
26282 		}
26283 
26284 		freeb(ipsec_mp);
26285 		if (ire_need_rele)
26286 			ire_refrele(ire);
26287 
26288 		if (ire1 != NULL) {
26289 			ire = ire1;
26290 			ire_need_rele = B_TRUE;
26291 			ASSERT(next_mp);
26292 			ipsec_mp = next_mp;
26293 			mp = ipsec_mp->b_cont;
26294 			ire1 = NULL;
26295 			next_mp = NULL;
26296 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26297 		} else {
26298 			multirt_send = B_FALSE;
26299 		}
26300 	} while (multirt_send);
26301 done:
26302 	if (ill != NULL && ill_need_rele)
26303 		ill_refrele(ill);
26304 	if (ipif != NULL)
26305 		ipif_refrele(ipif);
26306 }
26307 
26308 /*
26309  * Get the ill corresponding to the specified ire, and compare its
26310  * capabilities with the protocol and algorithms specified by the
26311  * the SA obtained from ipsec_out. If they match, annotate the
26312  * ipsec_out structure to indicate that the packet needs acceleration.
26313  *
26314  *
26315  * A packet is eligible for outbound hardware acceleration if the
26316  * following conditions are satisfied:
26317  *
26318  * 1. the packet will not be fragmented
26319  * 2. the provider supports the algorithm
26320  * 3. there is no pending control message being exchanged
26321  * 4. snoop is not attached
26322  * 5. the destination address is not a broadcast or multicast address.
26323  *
26324  * Rationale:
26325  *	- Hardware drivers do not support fragmentation with
26326  *	  the current interface.
26327  *	- snoop, multicast, and broadcast may result in exposure of
26328  *	  a cleartext datagram.
26329  * We check all five of these conditions here.
26330  *
26331  * XXX would like to nuke "ire_t *" parameter here; problem is that
26332  * IRE is only way to figure out if a v4 address is a broadcast and
26333  * thus ineligible for acceleration...
26334  */
26335 static void
26336 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26337 {
26338 	ipsec_out_t *io;
26339 	mblk_t *data_mp;
26340 	uint_t plen, overhead;
26341 	ip_stack_t	*ipst;
26342 
26343 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26344 		return;
26345 
26346 	if (ill == NULL)
26347 		return;
26348 	ipst = ill->ill_ipst;
26349 	/*
26350 	 * Destination address is a broadcast or multicast.  Punt.
26351 	 */
26352 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26353 	    IRE_LOCAL)))
26354 		return;
26355 
26356 	data_mp = ipsec_mp->b_cont;
26357 
26358 	if (ill->ill_isv6) {
26359 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26360 
26361 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26362 			return;
26363 
26364 		plen = ip6h->ip6_plen;
26365 	} else {
26366 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26367 
26368 		if (CLASSD(ipha->ipha_dst))
26369 			return;
26370 
26371 		plen = ipha->ipha_length;
26372 	}
26373 	/*
26374 	 * Is there a pending DLPI control message being exchanged
26375 	 * between IP/IPsec and the DLS Provider? If there is, it
26376 	 * could be a SADB update, and the state of the DLS Provider
26377 	 * SADB might not be in sync with the SADB maintained by
26378 	 * IPsec. To avoid dropping packets or using the wrong keying
26379 	 * material, we do not accelerate this packet.
26380 	 */
26381 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26382 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26383 		    "ill_dlpi_pending! don't accelerate packet\n"));
26384 		return;
26385 	}
26386 
26387 	/*
26388 	 * Is the Provider in promiscous mode? If it does, we don't
26389 	 * accelerate the packet since it will bounce back up to the
26390 	 * listeners in the clear.
26391 	 */
26392 	if (ill->ill_promisc_on_phys) {
26393 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26394 		    "ill in promiscous mode, don't accelerate packet\n"));
26395 		return;
26396 	}
26397 
26398 	/*
26399 	 * Will the packet require fragmentation?
26400 	 */
26401 
26402 	/*
26403 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26404 	 * as is used elsewhere.
26405 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26406 	 *	+ 2-byte trailer
26407 	 */
26408 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26409 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26410 
26411 	if ((plen + overhead) > ill->ill_max_mtu)
26412 		return;
26413 
26414 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26415 
26416 	/*
26417 	 * Can the ill accelerate this IPsec protocol and algorithm
26418 	 * specified by the SA?
26419 	 */
26420 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26421 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26422 		return;
26423 	}
26424 
26425 	/*
26426 	 * Tell AH or ESP that the outbound ill is capable of
26427 	 * accelerating this packet.
26428 	 */
26429 	io->ipsec_out_is_capab_ill = B_TRUE;
26430 }
26431 
26432 /*
26433  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26434  *
26435  * If this function returns B_TRUE, the requested SA's have been filled
26436  * into the ipsec_out_*_sa pointers.
26437  *
26438  * If the function returns B_FALSE, the packet has been "consumed", most
26439  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26440  *
26441  * The SA references created by the protocol-specific "select"
26442  * function will be released when the ipsec_mp is freed, thanks to the
26443  * ipsec_out_free destructor -- see spd.c.
26444  */
26445 static boolean_t
26446 ipsec_out_select_sa(mblk_t *ipsec_mp)
26447 {
26448 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26449 	ipsec_out_t *io;
26450 	ipsec_policy_t *pp;
26451 	ipsec_action_t *ap;
26452 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26453 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26454 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26455 
26456 	if (!io->ipsec_out_secure) {
26457 		/*
26458 		 * We came here by mistake.
26459 		 * Don't bother with ipsec processing
26460 		 * We should "discourage" this path in the future.
26461 		 */
26462 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26463 		return (B_FALSE);
26464 	}
26465 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26466 	ASSERT((io->ipsec_out_policy != NULL) ||
26467 	    (io->ipsec_out_act != NULL));
26468 
26469 	ASSERT(io->ipsec_out_failed == B_FALSE);
26470 
26471 	/*
26472 	 * IPsec processing has started.
26473 	 */
26474 	io->ipsec_out_proc_begin = B_TRUE;
26475 	ap = io->ipsec_out_act;
26476 	if (ap == NULL) {
26477 		pp = io->ipsec_out_policy;
26478 		ASSERT(pp != NULL);
26479 		ap = pp->ipsp_act;
26480 		ASSERT(ap != NULL);
26481 	}
26482 
26483 	/*
26484 	 * We have an action.  now, let's select SA's.
26485 	 * (In the future, we can cache this in the conn_t..)
26486 	 */
26487 	if (ap->ipa_want_esp) {
26488 		if (io->ipsec_out_esp_sa == NULL) {
26489 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26490 			    IPPROTO_ESP);
26491 		}
26492 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26493 	}
26494 
26495 	if (ap->ipa_want_ah) {
26496 		if (io->ipsec_out_ah_sa == NULL) {
26497 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26498 			    IPPROTO_AH);
26499 		}
26500 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26501 		/*
26502 		 * The ESP and AH processing order needs to be preserved
26503 		 * when both protocols are required (ESP should be applied
26504 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26505 		 * when both ESP and AH are required, and an AH ACQUIRE
26506 		 * is needed.
26507 		 */
26508 		if (ap->ipa_want_esp && need_ah_acquire)
26509 			need_esp_acquire = B_TRUE;
26510 	}
26511 
26512 	/*
26513 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26514 	 * Release SAs that got referenced, but will not be used until we
26515 	 * acquire _all_ of the SAs we need.
26516 	 */
26517 	if (need_ah_acquire || need_esp_acquire) {
26518 		if (io->ipsec_out_ah_sa != NULL) {
26519 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26520 			io->ipsec_out_ah_sa = NULL;
26521 		}
26522 		if (io->ipsec_out_esp_sa != NULL) {
26523 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26524 			io->ipsec_out_esp_sa = NULL;
26525 		}
26526 
26527 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26528 		return (B_FALSE);
26529 	}
26530 
26531 	return (B_TRUE);
26532 }
26533 
26534 /*
26535  * Process an IPSEC_OUT message and see what you can
26536  * do with it.
26537  * IPQoS Notes:
26538  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26539  * IPsec.
26540  * XXX would like to nuke ire_t.
26541  * XXX ill_index better be "real"
26542  */
26543 void
26544 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26545 {
26546 	ipsec_out_t *io;
26547 	ipsec_policy_t *pp;
26548 	ipsec_action_t *ap;
26549 	ipha_t *ipha;
26550 	ip6_t *ip6h;
26551 	mblk_t *mp;
26552 	ill_t *ill;
26553 	zoneid_t zoneid;
26554 	ipsec_status_t ipsec_rc;
26555 	boolean_t ill_need_rele = B_FALSE;
26556 	ip_stack_t	*ipst;
26557 	ipsec_stack_t	*ipss;
26558 
26559 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26560 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26561 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26562 	ipst = io->ipsec_out_ns->netstack_ip;
26563 	mp = ipsec_mp->b_cont;
26564 
26565 	/*
26566 	 * Initiate IPPF processing. We do it here to account for packets
26567 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26568 	 * We can check for ipsec_out_proc_begin even for such packets, as
26569 	 * they will always be false (asserted below).
26570 	 */
26571 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26572 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26573 		    io->ipsec_out_ill_index : ill_index);
26574 		if (mp == NULL) {
26575 			ip2dbg(("ipsec_out_process: packet dropped "\
26576 			    "during IPPF processing\n"));
26577 			freeb(ipsec_mp);
26578 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26579 			return;
26580 		}
26581 	}
26582 
26583 	if (!io->ipsec_out_secure) {
26584 		/*
26585 		 * We came here by mistake.
26586 		 * Don't bother with ipsec processing
26587 		 * Should "discourage" this path in the future.
26588 		 */
26589 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26590 		goto done;
26591 	}
26592 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26593 	ASSERT((io->ipsec_out_policy != NULL) ||
26594 	    (io->ipsec_out_act != NULL));
26595 	ASSERT(io->ipsec_out_failed == B_FALSE);
26596 
26597 	ipss = ipst->ips_netstack->netstack_ipsec;
26598 	if (!ipsec_loaded(ipss)) {
26599 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26600 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26601 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26602 		} else {
26603 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26604 		}
26605 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26606 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26607 		    &ipss->ipsec_dropper);
26608 		return;
26609 	}
26610 
26611 	/*
26612 	 * IPsec processing has started.
26613 	 */
26614 	io->ipsec_out_proc_begin = B_TRUE;
26615 	ap = io->ipsec_out_act;
26616 	if (ap == NULL) {
26617 		pp = io->ipsec_out_policy;
26618 		ASSERT(pp != NULL);
26619 		ap = pp->ipsp_act;
26620 		ASSERT(ap != NULL);
26621 	}
26622 
26623 	/*
26624 	 * Save the outbound ill index. When the packet comes back
26625 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26626 	 * before sending it the accelerated packet.
26627 	 */
26628 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26629 		ill = ire_to_ill(ire);
26630 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26631 	}
26632 
26633 	/*
26634 	 * The order of processing is first insert a IP header if needed.
26635 	 * Then insert the ESP header and then the AH header.
26636 	 */
26637 	if ((io->ipsec_out_se_done == B_FALSE) &&
26638 	    (ap->ipa_want_se)) {
26639 		/*
26640 		 * First get the outer IP header before sending
26641 		 * it to ESP.
26642 		 */
26643 		ipha_t *oipha, *iipha;
26644 		mblk_t *outer_mp, *inner_mp;
26645 
26646 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26647 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26648 			    "ipsec_out_process: "
26649 			    "Self-Encapsulation failed: Out of memory\n");
26650 			freemsg(ipsec_mp);
26651 			if (ill != NULL) {
26652 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26653 			} else {
26654 				BUMP_MIB(&ipst->ips_ip_mib,
26655 				    ipIfStatsOutDiscards);
26656 			}
26657 			return;
26658 		}
26659 		inner_mp = ipsec_mp->b_cont;
26660 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26661 		oipha = (ipha_t *)outer_mp->b_rptr;
26662 		iipha = (ipha_t *)inner_mp->b_rptr;
26663 		*oipha = *iipha;
26664 		outer_mp->b_wptr += sizeof (ipha_t);
26665 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26666 		    sizeof (ipha_t));
26667 		oipha->ipha_protocol = IPPROTO_ENCAP;
26668 		oipha->ipha_version_and_hdr_length =
26669 		    IP_SIMPLE_HDR_VERSION;
26670 		oipha->ipha_hdr_checksum = 0;
26671 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26672 		outer_mp->b_cont = inner_mp;
26673 		ipsec_mp->b_cont = outer_mp;
26674 
26675 		io->ipsec_out_se_done = B_TRUE;
26676 		io->ipsec_out_tunnel = B_TRUE;
26677 	}
26678 
26679 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26680 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26681 	    !ipsec_out_select_sa(ipsec_mp))
26682 		return;
26683 
26684 	/*
26685 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26686 	 * to do the heavy lifting.
26687 	 */
26688 	zoneid = io->ipsec_out_zoneid;
26689 	ASSERT(zoneid != ALL_ZONES);
26690 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26691 		ASSERT(io->ipsec_out_esp_sa != NULL);
26692 		io->ipsec_out_esp_done = B_TRUE;
26693 		/*
26694 		 * Note that since hw accel can only apply one transform,
26695 		 * not two, we skip hw accel for ESP if we also have AH
26696 		 * This is an design limitation of the interface
26697 		 * which should be revisited.
26698 		 */
26699 		ASSERT(ire != NULL);
26700 		if (io->ipsec_out_ah_sa == NULL) {
26701 			ill = (ill_t *)ire->ire_stq->q_ptr;
26702 			ipsec_out_is_accelerated(ipsec_mp,
26703 			    io->ipsec_out_esp_sa, ill, ire);
26704 		}
26705 
26706 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26707 		switch (ipsec_rc) {
26708 		case IPSEC_STATUS_SUCCESS:
26709 			break;
26710 		case IPSEC_STATUS_FAILED:
26711 			if (ill != NULL) {
26712 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26713 			} else {
26714 				BUMP_MIB(&ipst->ips_ip_mib,
26715 				    ipIfStatsOutDiscards);
26716 			}
26717 			/* FALLTHRU */
26718 		case IPSEC_STATUS_PENDING:
26719 			return;
26720 		}
26721 	}
26722 
26723 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26724 		ASSERT(io->ipsec_out_ah_sa != NULL);
26725 		io->ipsec_out_ah_done = B_TRUE;
26726 		if (ire == NULL) {
26727 			int idx = io->ipsec_out_capab_ill_index;
26728 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26729 			    NULL, NULL, NULL, NULL, ipst);
26730 			ill_need_rele = B_TRUE;
26731 		} else {
26732 			ill = (ill_t *)ire->ire_stq->q_ptr;
26733 		}
26734 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26735 		    ire);
26736 
26737 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26738 		switch (ipsec_rc) {
26739 		case IPSEC_STATUS_SUCCESS:
26740 			break;
26741 		case IPSEC_STATUS_FAILED:
26742 			if (ill != NULL) {
26743 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26744 			} else {
26745 				BUMP_MIB(&ipst->ips_ip_mib,
26746 				    ipIfStatsOutDiscards);
26747 			}
26748 			/* FALLTHRU */
26749 		case IPSEC_STATUS_PENDING:
26750 			if (ill != NULL && ill_need_rele)
26751 				ill_refrele(ill);
26752 			return;
26753 		}
26754 	}
26755 	/*
26756 	 * We are done with IPsec processing. Send it over the wire.
26757 	 */
26758 done:
26759 	mp = ipsec_mp->b_cont;
26760 	ipha = (ipha_t *)mp->b_rptr;
26761 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26762 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26763 		    ire);
26764 	} else {
26765 		ip6h = (ip6_t *)ipha;
26766 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26767 		    ire);
26768 	}
26769 	if (ill != NULL && ill_need_rele)
26770 		ill_refrele(ill);
26771 }
26772 
26773 /* ARGSUSED */
26774 void
26775 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26776 {
26777 	opt_restart_t	*or;
26778 	int	err;
26779 	conn_t	*connp;
26780 	cred_t	*cr;
26781 
26782 	ASSERT(CONN_Q(q));
26783 	connp = Q_TO_CONN(q);
26784 
26785 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26786 	or = (opt_restart_t *)first_mp->b_rptr;
26787 	/*
26788 	 * We checked for a db_credp the first time svr4_optcom_req
26789 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26790 	 */
26791 	cr = msg_getcred(first_mp, NULL);
26792 	ASSERT(cr != NULL);
26793 
26794 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26795 		err = svr4_optcom_req(q, first_mp, cr,
26796 		    &ip_opt_obj, B_FALSE);
26797 	} else {
26798 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26799 		err = tpi_optcom_req(q, first_mp, cr,
26800 		    &ip_opt_obj, B_FALSE);
26801 	}
26802 	if (err != EINPROGRESS) {
26803 		/* operation is done */
26804 		CONN_OPER_PENDING_DONE(connp);
26805 	}
26806 }
26807 
26808 /*
26809  * ioctls that go through a down/up sequence may need to wait for the down
26810  * to complete. This involves waiting for the ire and ipif refcnts to go down
26811  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26812  */
26813 /* ARGSUSED */
26814 void
26815 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26816 {
26817 	struct iocblk *iocp;
26818 	mblk_t *mp1;
26819 	ip_ioctl_cmd_t *ipip;
26820 	int err;
26821 	sin_t	*sin;
26822 	struct lifreq *lifr;
26823 	struct ifreq *ifr;
26824 
26825 	iocp = (struct iocblk *)mp->b_rptr;
26826 	ASSERT(ipsq != NULL);
26827 	/* Existence of mp1 verified in ip_wput_nondata */
26828 	mp1 = mp->b_cont->b_cont;
26829 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26830 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26831 		/*
26832 		 * Special case where ipx_current_ipif is not set:
26833 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26834 		 * We are here as were not able to complete the operation in
26835 		 * ipif_set_values because we could not become exclusive on
26836 		 * the new ipsq.
26837 		 */
26838 		ill_t *ill = q->q_ptr;
26839 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26840 	}
26841 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26842 
26843 	if (ipip->ipi_cmd_type == IF_CMD) {
26844 		/* This a old style SIOC[GS]IF* command */
26845 		ifr = (struct ifreq *)mp1->b_rptr;
26846 		sin = (sin_t *)&ifr->ifr_addr;
26847 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26848 		/* This a new style SIOC[GS]LIF* command */
26849 		lifr = (struct lifreq *)mp1->b_rptr;
26850 		sin = (sin_t *)&lifr->lifr_addr;
26851 	} else {
26852 		sin = NULL;
26853 	}
26854 
26855 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26856 	    q, mp, ipip, mp1->b_rptr);
26857 
26858 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26859 }
26860 
26861 /*
26862  * ioctl processing
26863  *
26864  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26865  * the ioctl command in the ioctl tables, determines the copyin data size
26866  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26867  *
26868  * ioctl processing then continues when the M_IOCDATA makes its way down to
26869  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26870  * associated 'conn' is refheld till the end of the ioctl and the general
26871  * ioctl processing function ip_process_ioctl() is called to extract the
26872  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26873  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26874  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26875  * is used to extract the ioctl's arguments.
26876  *
26877  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26878  * so goes thru the serialization primitive ipsq_try_enter. Then the
26879  * appropriate function to handle the ioctl is called based on the entry in
26880  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26881  * which also refreleases the 'conn' that was refheld at the start of the
26882  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26883  *
26884  * Many exclusive ioctls go thru an internal down up sequence as part of
26885  * the operation. For example an attempt to change the IP address of an
26886  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26887  * does all the cleanup such as deleting all ires that use this address.
26888  * Then we need to wait till all references to the interface go away.
26889  */
26890 void
26891 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26892 {
26893 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26894 	ip_ioctl_cmd_t *ipip = arg;
26895 	ip_extract_func_t *extract_funcp;
26896 	cmd_info_t ci;
26897 	int err;
26898 	boolean_t entered_ipsq = B_FALSE;
26899 
26900 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26901 
26902 	if (ipip == NULL)
26903 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26904 
26905 	/*
26906 	 * SIOCLIFADDIF needs to go thru a special path since the
26907 	 * ill may not exist yet. This happens in the case of lo0
26908 	 * which is created using this ioctl.
26909 	 */
26910 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26911 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26912 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26913 		return;
26914 	}
26915 
26916 	ci.ci_ipif = NULL;
26917 	if (ipip->ipi_cmd_type == MISC_CMD) {
26918 		/*
26919 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26920 		 */
26921 		if (ipip->ipi_cmd == IF_UNITSEL) {
26922 			/* ioctl comes down the ill */
26923 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26924 			ipif_refhold(ci.ci_ipif);
26925 		}
26926 		err = 0;
26927 		ci.ci_sin = NULL;
26928 		ci.ci_sin6 = NULL;
26929 		ci.ci_lifr = NULL;
26930 	} else {
26931 		switch (ipip->ipi_cmd_type) {
26932 		case IF_CMD:
26933 		case LIF_CMD:
26934 			extract_funcp = ip_extract_lifreq;
26935 			break;
26936 
26937 		case ARP_CMD:
26938 		case XARP_CMD:
26939 			extract_funcp = ip_extract_arpreq;
26940 			break;
26941 
26942 		case TUN_CMD:
26943 			extract_funcp = ip_extract_tunreq;
26944 			break;
26945 
26946 		case MSFILT_CMD:
26947 			extract_funcp = ip_extract_msfilter;
26948 			break;
26949 
26950 		default:
26951 			ASSERT(0);
26952 		}
26953 
26954 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26955 		if (err != 0) {
26956 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26957 			return;
26958 		}
26959 
26960 		/*
26961 		 * All of the extraction functions return a refheld ipif.
26962 		 */
26963 		ASSERT(ci.ci_ipif != NULL);
26964 	}
26965 
26966 	if (!(ipip->ipi_flags & IPI_WR)) {
26967 		/*
26968 		 * A return value of EINPROGRESS means the ioctl is
26969 		 * either queued and waiting for some reason or has
26970 		 * already completed.
26971 		 */
26972 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26973 		    ci.ci_lifr);
26974 		if (ci.ci_ipif != NULL)
26975 			ipif_refrele(ci.ci_ipif);
26976 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26977 		return;
26978 	}
26979 
26980 	ASSERT(ci.ci_ipif != NULL);
26981 
26982 	/*
26983 	 * If ipsq is non-NULL, we are already being called exclusively.
26984 	 */
26985 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26986 	if (ipsq == NULL) {
26987 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
26988 		    NEW_OP, B_TRUE);
26989 		if (ipsq == NULL) {
26990 			ipif_refrele(ci.ci_ipif);
26991 			return;
26992 		}
26993 		entered_ipsq = B_TRUE;
26994 	}
26995 
26996 	/*
26997 	 * Release the ipif so that ipif_down and friends that wait for
26998 	 * references to go away are not misled about the current ipif_refcnt
26999 	 * values. We are writer so we can access the ipif even after releasing
27000 	 * the ipif.
27001 	 */
27002 	ipif_refrele(ci.ci_ipif);
27003 
27004 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27005 
27006 	/*
27007 	 * For most set ioctls that come here, this serves as a single point
27008 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27009 	 * be any new references to the ipif. This helps functions that go
27010 	 * through this path and end up trying to wait for the refcnts
27011 	 * associated with the ipif to go down to zero.  The exception is
27012 	 * SIOCSLIFREMOVEIF, which sets IPIF_CONDEMNED internally after
27013 	 * identifying the right ipif to operate on.
27014 	 */
27015 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27016 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF)
27017 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27018 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27019 
27020 	/*
27021 	 * A return value of EINPROGRESS means the ioctl is
27022 	 * either queued and waiting for some reason or has
27023 	 * already completed.
27024 	 */
27025 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27026 
27027 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27028 
27029 	if (entered_ipsq)
27030 		ipsq_exit(ipsq);
27031 }
27032 
27033 /*
27034  * Complete the ioctl. Typically ioctls use the mi package and need to
27035  * do mi_copyout/mi_copy_done.
27036  */
27037 void
27038 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27039 {
27040 	conn_t	*connp = NULL;
27041 
27042 	if (err == EINPROGRESS)
27043 		return;
27044 
27045 	if (CONN_Q(q)) {
27046 		connp = Q_TO_CONN(q);
27047 		ASSERT(connp->conn_ref >= 2);
27048 	}
27049 
27050 	switch (mode) {
27051 	case COPYOUT:
27052 		if (err == 0)
27053 			mi_copyout(q, mp);
27054 		else
27055 			mi_copy_done(q, mp, err);
27056 		break;
27057 
27058 	case NO_COPYOUT:
27059 		mi_copy_done(q, mp, err);
27060 		break;
27061 
27062 	default:
27063 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27064 		break;
27065 	}
27066 
27067 	/*
27068 	 * The refhold placed at the start of the ioctl is released here.
27069 	 */
27070 	if (connp != NULL)
27071 		CONN_OPER_PENDING_DONE(connp);
27072 
27073 	if (ipsq != NULL)
27074 		ipsq_current_finish(ipsq);
27075 }
27076 
27077 /* Called from ip_wput for all non data messages */
27078 /* ARGSUSED */
27079 void
27080 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27081 {
27082 	mblk_t		*mp1;
27083 	ire_t		*ire, *fake_ire;
27084 	ill_t		*ill;
27085 	struct iocblk	*iocp;
27086 	ip_ioctl_cmd_t	*ipip;
27087 	cred_t		*cr;
27088 	conn_t		*connp;
27089 	int		err;
27090 	nce_t		*nce;
27091 	ipif_t		*ipif;
27092 	ip_stack_t	*ipst;
27093 	char		*proto_str;
27094 
27095 	if (CONN_Q(q)) {
27096 		connp = Q_TO_CONN(q);
27097 		ipst = connp->conn_netstack->netstack_ip;
27098 	} else {
27099 		connp = NULL;
27100 		ipst = ILLQ_TO_IPST(q);
27101 	}
27102 
27103 	switch (DB_TYPE(mp)) {
27104 	case M_IOCTL:
27105 		/*
27106 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27107 		 * will arrange to copy in associated control structures.
27108 		 */
27109 		ip_sioctl_copyin_setup(q, mp);
27110 		return;
27111 	case M_IOCDATA:
27112 		/*
27113 		 * Ensure that this is associated with one of our trans-
27114 		 * parent ioctls.  If it's not ours, discard it if we're
27115 		 * running as a driver, or pass it on if we're a module.
27116 		 */
27117 		iocp = (struct iocblk *)mp->b_rptr;
27118 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27119 		if (ipip == NULL) {
27120 			if (q->q_next == NULL) {
27121 				goto nak;
27122 			} else {
27123 				putnext(q, mp);
27124 			}
27125 			return;
27126 		}
27127 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27128 			/*
27129 			 * the ioctl is one we recognise, but is not
27130 			 * consumed by IP as a module, pass M_IOCDATA
27131 			 * for processing downstream, but only for
27132 			 * common Streams ioctls.
27133 			 */
27134 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27135 				putnext(q, mp);
27136 				return;
27137 			} else {
27138 				goto nak;
27139 			}
27140 		}
27141 
27142 		/* IOCTL continuation following copyin or copyout. */
27143 		if (mi_copy_state(q, mp, NULL) == -1) {
27144 			/*
27145 			 * The copy operation failed.  mi_copy_state already
27146 			 * cleaned up, so we're out of here.
27147 			 */
27148 			return;
27149 		}
27150 		/*
27151 		 * If we just completed a copy in, we become writer and
27152 		 * continue processing in ip_sioctl_copyin_done.  If it
27153 		 * was a copy out, we call mi_copyout again.  If there is
27154 		 * nothing more to copy out, it will complete the IOCTL.
27155 		 */
27156 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27157 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27158 				mi_copy_done(q, mp, EPROTO);
27159 				return;
27160 			}
27161 			/*
27162 			 * Check for cases that need more copying.  A return
27163 			 * value of 0 means a second copyin has been started,
27164 			 * so we return; a return value of 1 means no more
27165 			 * copying is needed, so we continue.
27166 			 */
27167 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27168 			    MI_COPY_COUNT(mp) == 1) {
27169 				if (ip_copyin_msfilter(q, mp) == 0)
27170 					return;
27171 			}
27172 			/*
27173 			 * Refhold the conn, till the ioctl completes. This is
27174 			 * needed in case the ioctl ends up in the pending mp
27175 			 * list. Every mp in the ill_pending_mp list and
27176 			 * the ipx_pending_mp must have a refhold on the conn
27177 			 * to resume processing. The refhold is released when
27178 			 * the ioctl completes. (normally or abnormally)
27179 			 * In all cases ip_ioctl_finish is called to finish
27180 			 * the ioctl.
27181 			 */
27182 			if (connp != NULL) {
27183 				/* This is not a reentry */
27184 				ASSERT(ipsq == NULL);
27185 				CONN_INC_REF(connp);
27186 			} else {
27187 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27188 					mi_copy_done(q, mp, EINVAL);
27189 					return;
27190 				}
27191 			}
27192 
27193 			ip_process_ioctl(ipsq, q, mp, ipip);
27194 
27195 		} else {
27196 			mi_copyout(q, mp);
27197 		}
27198 		return;
27199 nak:
27200 		iocp->ioc_error = EINVAL;
27201 		mp->b_datap->db_type = M_IOCNAK;
27202 		iocp->ioc_count = 0;
27203 		qreply(q, mp);
27204 		return;
27205 
27206 	case M_IOCNAK:
27207 		/*
27208 		 * The only way we could get here is if a resolver didn't like
27209 		 * an IOCTL we sent it.	 This shouldn't happen.
27210 		 */
27211 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27212 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27213 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27214 		freemsg(mp);
27215 		return;
27216 	case M_IOCACK:
27217 		/* /dev/ip shouldn't see this */
27218 		if (CONN_Q(q))
27219 			goto nak;
27220 
27221 		/*
27222 		 * Finish socket ioctls passed through to ARP.  We use the
27223 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27224 		 * we need to become writer before calling ip_sioctl_iocack().
27225 		 * Note that qwriter_ip() will release the refhold, and that a
27226 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27227 		 * ill stream.
27228 		 */
27229 		iocp = (struct iocblk *)mp->b_rptr;
27230 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27231 			ip_sioctl_iocack(NULL, q, mp, NULL);
27232 			return;
27233 		}
27234 
27235 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27236 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27237 		ill = q->q_ptr;
27238 		ill_refhold(ill);
27239 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27240 		return;
27241 	case M_FLUSH:
27242 		if (*mp->b_rptr & FLUSHW)
27243 			flushq(q, FLUSHALL);
27244 		if (q->q_next) {
27245 			putnext(q, mp);
27246 			return;
27247 		}
27248 		if (*mp->b_rptr & FLUSHR) {
27249 			*mp->b_rptr &= ~FLUSHW;
27250 			qreply(q, mp);
27251 			return;
27252 		}
27253 		freemsg(mp);
27254 		return;
27255 	case IRE_DB_REQ_TYPE:
27256 		if (connp == NULL) {
27257 			proto_str = "IRE_DB_REQ_TYPE";
27258 			goto protonak;
27259 		}
27260 		/* An Upper Level Protocol wants a copy of an IRE. */
27261 		ip_ire_req(q, mp);
27262 		return;
27263 	case M_CTL:
27264 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27265 			break;
27266 
27267 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27268 		    TUN_HELLO) {
27269 			ASSERT(connp != NULL);
27270 			connp->conn_flags |= IPCL_IPTUN;
27271 			freeb(mp);
27272 			return;
27273 		}
27274 
27275 		/* M_CTL messages are used by ARP to tell us things. */
27276 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27277 			break;
27278 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27279 		case AR_ENTRY_SQUERY:
27280 			ip_wput_ctl(q, mp);
27281 			return;
27282 		case AR_CLIENT_NOTIFY:
27283 			ip_arp_news(q, mp);
27284 			return;
27285 		case AR_DLPIOP_DONE:
27286 			ASSERT(q->q_next != NULL);
27287 			ill = (ill_t *)q->q_ptr;
27288 			/* qwriter_ip releases the refhold */
27289 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27290 			ill_refhold(ill);
27291 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27292 			return;
27293 		case AR_ARP_CLOSING:
27294 			/*
27295 			 * ARP (above us) is closing. If no ARP bringup is
27296 			 * currently pending, ack the message so that ARP
27297 			 * can complete its close. Also mark ill_arp_closing
27298 			 * so that new ARP bringups will fail. If any
27299 			 * ARP bringup is currently in progress, we will
27300 			 * ack this when the current ARP bringup completes.
27301 			 */
27302 			ASSERT(q->q_next != NULL);
27303 			ill = (ill_t *)q->q_ptr;
27304 			mutex_enter(&ill->ill_lock);
27305 			ill->ill_arp_closing = 1;
27306 			if (!ill->ill_arp_bringup_pending) {
27307 				mutex_exit(&ill->ill_lock);
27308 				qreply(q, mp);
27309 			} else {
27310 				mutex_exit(&ill->ill_lock);
27311 				freemsg(mp);
27312 			}
27313 			return;
27314 		case AR_ARP_EXTEND:
27315 			/*
27316 			 * The ARP module above us is capable of duplicate
27317 			 * address detection.  Old ATM drivers will not send
27318 			 * this message.
27319 			 */
27320 			ASSERT(q->q_next != NULL);
27321 			ill = (ill_t *)q->q_ptr;
27322 			ill->ill_arp_extend = B_TRUE;
27323 			freemsg(mp);
27324 			return;
27325 		default:
27326 			break;
27327 		}
27328 		break;
27329 	case M_PROTO:
27330 	case M_PCPROTO:
27331 		/*
27332 		 * The only PROTO messages we expect are copies of option
27333 		 * negotiation acknowledgements, AH and ESP bind requests
27334 		 * are also expected.
27335 		 */
27336 		switch (((union T_primitives *)mp->b_rptr)->type) {
27337 		case O_T_BIND_REQ:
27338 		case T_BIND_REQ: {
27339 			/* Request can get queued in bind */
27340 			if (connp == NULL) {
27341 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27342 				goto protonak;
27343 			}
27344 			/*
27345 			 * The transports except SCTP call ip_bind_{v4,v6}()
27346 			 * directly instead of a a putnext. SCTP doesn't
27347 			 * generate any T_BIND_REQ since it has its own
27348 			 * fanout data structures. However, ESP and AH
27349 			 * come in for regular binds; all other cases are
27350 			 * bind retries.
27351 			 */
27352 			ASSERT(!IPCL_IS_SCTP(connp));
27353 
27354 			/* Don't increment refcnt if this is a re-entry */
27355 			if (ipsq == NULL)
27356 				CONN_INC_REF(connp);
27357 
27358 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27359 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27360 			ASSERT(mp != NULL);
27361 
27362 			ASSERT(!IPCL_IS_TCP(connp));
27363 			ASSERT(!IPCL_IS_UDP(connp));
27364 			ASSERT(!IPCL_IS_RAWIP(connp));
27365 
27366 			/* The case of AH and ESP */
27367 			qreply(q, mp);
27368 			CONN_OPER_PENDING_DONE(connp);
27369 			return;
27370 		}
27371 		case T_SVR4_OPTMGMT_REQ:
27372 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27373 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27374 
27375 			if (connp == NULL) {
27376 				proto_str = "T_SVR4_OPTMGMT_REQ";
27377 				goto protonak;
27378 			}
27379 
27380 			/*
27381 			 * All Solaris components should pass a db_credp
27382 			 * for this TPI message, hence we ASSERT.
27383 			 * But in case there is some other M_PROTO that looks
27384 			 * like a TPI message sent by some other kernel
27385 			 * component, we check and return an error.
27386 			 */
27387 			cr = msg_getcred(mp, NULL);
27388 			ASSERT(cr != NULL);
27389 			if (cr == NULL) {
27390 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27391 				if (mp != NULL)
27392 					qreply(q, mp);
27393 				return;
27394 			}
27395 
27396 			if (!snmpcom_req(q, mp, ip_snmp_set,
27397 			    ip_snmp_get, cr)) {
27398 				/*
27399 				 * Call svr4_optcom_req so that it can
27400 				 * generate the ack. We don't come here
27401 				 * if this operation is being restarted.
27402 				 * ip_restart_optmgmt will drop the conn ref.
27403 				 * In the case of ipsec option after the ipsec
27404 				 * load is complete conn_restart_ipsec_waiter
27405 				 * drops the conn ref.
27406 				 */
27407 				ASSERT(ipsq == NULL);
27408 				CONN_INC_REF(connp);
27409 				if (ip_check_for_ipsec_opt(q, mp))
27410 					return;
27411 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27412 				    B_FALSE);
27413 				if (err != EINPROGRESS) {
27414 					/* Operation is done */
27415 					CONN_OPER_PENDING_DONE(connp);
27416 				}
27417 			}
27418 			return;
27419 		case T_OPTMGMT_REQ:
27420 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27421 			/*
27422 			 * Note: No snmpcom_req support through new
27423 			 * T_OPTMGMT_REQ.
27424 			 * Call tpi_optcom_req so that it can
27425 			 * generate the ack.
27426 			 */
27427 			if (connp == NULL) {
27428 				proto_str = "T_OPTMGMT_REQ";
27429 				goto protonak;
27430 			}
27431 
27432 			/*
27433 			 * All Solaris components should pass a db_credp
27434 			 * for this TPI message, hence we ASSERT.
27435 			 * But in case there is some other M_PROTO that looks
27436 			 * like a TPI message sent by some other kernel
27437 			 * component, we check and return an error.
27438 			 */
27439 			cr = msg_getcred(mp, NULL);
27440 			ASSERT(cr != NULL);
27441 			if (cr == NULL) {
27442 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27443 				if (mp != NULL)
27444 					qreply(q, mp);
27445 				return;
27446 			}
27447 			ASSERT(ipsq == NULL);
27448 			/*
27449 			 * We don't come here for restart. ip_restart_optmgmt
27450 			 * will drop the conn ref. In the case of ipsec option
27451 			 * after the ipsec load is complete
27452 			 * conn_restart_ipsec_waiter drops the conn ref.
27453 			 */
27454 			CONN_INC_REF(connp);
27455 			if (ip_check_for_ipsec_opt(q, mp))
27456 				return;
27457 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27458 			if (err != EINPROGRESS) {
27459 				/* Operation is done */
27460 				CONN_OPER_PENDING_DONE(connp);
27461 			}
27462 			return;
27463 		case T_UNBIND_REQ:
27464 			if (connp == NULL) {
27465 				proto_str = "T_UNBIND_REQ";
27466 				goto protonak;
27467 			}
27468 			ip_unbind(Q_TO_CONN(q));
27469 			mp = mi_tpi_ok_ack_alloc(mp);
27470 			qreply(q, mp);
27471 			return;
27472 		default:
27473 			/*
27474 			 * Have to drop any DLPI messages coming down from
27475 			 * arp (such as an info_req which would cause ip
27476 			 * to receive an extra info_ack if it was passed
27477 			 * through.
27478 			 */
27479 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27480 			    (int)*(uint_t *)mp->b_rptr));
27481 			freemsg(mp);
27482 			return;
27483 		}
27484 		/* NOTREACHED */
27485 	case IRE_DB_TYPE: {
27486 		nce_t		*nce;
27487 		ill_t		*ill;
27488 		in6_addr_t	gw_addr_v6;
27489 
27490 		/*
27491 		 * This is a response back from a resolver.  It
27492 		 * consists of a message chain containing:
27493 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27494 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27495 		 * The LL_HDR_MBLK is the DLPI header to use to get
27496 		 * the attached packet, and subsequent ones for the
27497 		 * same destination, transmitted.
27498 		 */
27499 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27500 			break;
27501 		/*
27502 		 * First, check to make sure the resolution succeeded.
27503 		 * If it failed, the second mblk will be empty.
27504 		 * If it is, free the chain, dropping the packet.
27505 		 * (We must ire_delete the ire; that frees the ire mblk)
27506 		 * We're doing this now to support PVCs for ATM; it's
27507 		 * a partial xresolv implementation. When we fully implement
27508 		 * xresolv interfaces, instead of freeing everything here
27509 		 * we'll initiate neighbor discovery.
27510 		 *
27511 		 * For v4 (ARP and other external resolvers) the resolver
27512 		 * frees the message, so no check is needed. This check
27513 		 * is required, though, for a full xresolve implementation.
27514 		 * Including this code here now both shows how external
27515 		 * resolvers can NACK a resolution request using an
27516 		 * existing design that has no specific provisions for NACKs,
27517 		 * and also takes into account that the current non-ARP
27518 		 * external resolver has been coded to use this method of
27519 		 * NACKing for all IPv6 (xresolv) cases,
27520 		 * whether our xresolv implementation is complete or not.
27521 		 *
27522 		 */
27523 		ire = (ire_t *)mp->b_rptr;
27524 		ill = ire_to_ill(ire);
27525 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27526 		if (mp1->b_rptr == mp1->b_wptr) {
27527 			if (ire->ire_ipversion == IPV6_VERSION) {
27528 				/*
27529 				 * XRESOLV interface.
27530 				 */
27531 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27532 				mutex_enter(&ire->ire_lock);
27533 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27534 				mutex_exit(&ire->ire_lock);
27535 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27536 					nce = ndp_lookup_v6(ill, B_FALSE,
27537 					    &ire->ire_addr_v6, B_FALSE);
27538 				} else {
27539 					nce = ndp_lookup_v6(ill, B_FALSE,
27540 					    &gw_addr_v6, B_FALSE);
27541 				}
27542 				if (nce != NULL) {
27543 					nce_resolv_failed(nce);
27544 					ndp_delete(nce);
27545 					NCE_REFRELE(nce);
27546 				}
27547 			}
27548 			mp->b_cont = NULL;
27549 			freemsg(mp1);		/* frees the pkt as well */
27550 			ASSERT(ire->ire_nce == NULL);
27551 			ire_delete((ire_t *)mp->b_rptr);
27552 			return;
27553 		}
27554 
27555 		/*
27556 		 * Split them into IRE_MBLK and pkt and feed it into
27557 		 * ire_add_then_send. Then in ire_add_then_send
27558 		 * the IRE will be added, and then the packet will be
27559 		 * run back through ip_wput. This time it will make
27560 		 * it to the wire.
27561 		 */
27562 		mp->b_cont = NULL;
27563 		mp = mp1->b_cont;		/* now, mp points to pkt */
27564 		mp1->b_cont = NULL;
27565 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27566 		if (ire->ire_ipversion == IPV6_VERSION) {
27567 			/*
27568 			 * XRESOLV interface. Find the nce and put a copy
27569 			 * of the dl_unitdata_req in nce_res_mp
27570 			 */
27571 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27572 			mutex_enter(&ire->ire_lock);
27573 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27574 			mutex_exit(&ire->ire_lock);
27575 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27576 				nce = ndp_lookup_v6(ill, B_FALSE,
27577 				    &ire->ire_addr_v6, B_FALSE);
27578 			} else {
27579 				nce = ndp_lookup_v6(ill, B_FALSE,
27580 				    &gw_addr_v6, B_FALSE);
27581 			}
27582 			if (nce != NULL) {
27583 				/*
27584 				 * We have to protect nce_res_mp here
27585 				 * from being accessed by other threads
27586 				 * while we change the mblk pointer.
27587 				 * Other functions will also lock the nce when
27588 				 * accessing nce_res_mp.
27589 				 *
27590 				 * The reason we change the mblk pointer
27591 				 * here rather than copying the resolved address
27592 				 * into the template is that, unlike with
27593 				 * ethernet, we have no guarantee that the
27594 				 * resolved address length will be
27595 				 * smaller than or equal to the lla length
27596 				 * with which the template was allocated,
27597 				 * (for ethernet, they're equal)
27598 				 * so we have to use the actual resolved
27599 				 * address mblk - which holds the real
27600 				 * dl_unitdata_req with the resolved address.
27601 				 *
27602 				 * Doing this is the same behavior as was
27603 				 * previously used in the v4 ARP case.
27604 				 */
27605 				mutex_enter(&nce->nce_lock);
27606 				if (nce->nce_res_mp != NULL)
27607 					freemsg(nce->nce_res_mp);
27608 				nce->nce_res_mp = mp1;
27609 				mutex_exit(&nce->nce_lock);
27610 				/*
27611 				 * We do a fastpath probe here because
27612 				 * we have resolved the address without
27613 				 * using Neighbor Discovery.
27614 				 * In the non-XRESOLV v6 case, the fastpath
27615 				 * probe is done right after neighbor
27616 				 * discovery completes.
27617 				 */
27618 				if (nce->nce_res_mp != NULL) {
27619 					int res;
27620 					nce_fastpath_list_add(nce);
27621 					res = ill_fastpath_probe(ill,
27622 					    nce->nce_res_mp);
27623 					if (res != 0 && res != EAGAIN)
27624 						nce_fastpath_list_delete(nce);
27625 				}
27626 
27627 				ire_add_then_send(q, ire, mp);
27628 				/*
27629 				 * Now we have to clean out any packets
27630 				 * that may have been queued on the nce
27631 				 * while it was waiting for address resolution
27632 				 * to complete.
27633 				 */
27634 				mutex_enter(&nce->nce_lock);
27635 				mp1 = nce->nce_qd_mp;
27636 				nce->nce_qd_mp = NULL;
27637 				mutex_exit(&nce->nce_lock);
27638 				while (mp1 != NULL) {
27639 					mblk_t *nxt_mp;
27640 					queue_t *fwdq = NULL;
27641 					ill_t   *inbound_ill;
27642 					uint_t ifindex;
27643 
27644 					nxt_mp = mp1->b_next;
27645 					mp1->b_next = NULL;
27646 					/*
27647 					 * Retrieve ifindex stored in
27648 					 * ip_rput_data_v6()
27649 					 */
27650 					ifindex =
27651 					    (uint_t)(uintptr_t)mp1->b_prev;
27652 					inbound_ill =
27653 					    ill_lookup_on_ifindex(ifindex,
27654 					    B_TRUE, NULL, NULL, NULL,
27655 					    NULL, ipst);
27656 					mp1->b_prev = NULL;
27657 					if (inbound_ill != NULL)
27658 						fwdq = inbound_ill->ill_rq;
27659 
27660 					if (fwdq != NULL) {
27661 						put(fwdq, mp1);
27662 						ill_refrele(inbound_ill);
27663 					} else
27664 						put(WR(ill->ill_rq), mp1);
27665 					mp1 = nxt_mp;
27666 				}
27667 				NCE_REFRELE(nce);
27668 			} else {	/* nce is NULL; clean up */
27669 				ire_delete(ire);
27670 				freemsg(mp);
27671 				freemsg(mp1);
27672 				return;
27673 			}
27674 		} else {
27675 			nce_t *arpce;
27676 			/*
27677 			 * Link layer resolution succeeded. Recompute the
27678 			 * ire_nce.
27679 			 */
27680 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27681 			if ((arpce = ndp_lookup_v4(ill,
27682 			    (ire->ire_gateway_addr != INADDR_ANY ?
27683 			    &ire->ire_gateway_addr : &ire->ire_addr),
27684 			    B_FALSE)) == NULL) {
27685 				freeb(ire->ire_mp);
27686 				freeb(mp1);
27687 				freemsg(mp);
27688 				return;
27689 			}
27690 			mutex_enter(&arpce->nce_lock);
27691 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27692 			if (arpce->nce_state == ND_REACHABLE) {
27693 				/*
27694 				 * Someone resolved this before us;
27695 				 * cleanup the res_mp. Since ire has
27696 				 * not been added yet, the call to ire_add_v4
27697 				 * from ire_add_then_send (when a dup is
27698 				 * detected) will clean up the ire.
27699 				 */
27700 				freeb(mp1);
27701 			} else {
27702 				ASSERT(arpce->nce_res_mp == NULL);
27703 				arpce->nce_res_mp = mp1;
27704 				arpce->nce_state = ND_REACHABLE;
27705 			}
27706 			mutex_exit(&arpce->nce_lock);
27707 			if (ire->ire_marks & IRE_MARK_NOADD) {
27708 				/*
27709 				 * this ire will not be added to the ire
27710 				 * cache table, so we can set the ire_nce
27711 				 * here, as there are no atomicity constraints.
27712 				 */
27713 				ire->ire_nce = arpce;
27714 				/*
27715 				 * We are associating this nce with the ire
27716 				 * so change the nce ref taken in
27717 				 * ndp_lookup_v4() from
27718 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27719 				 */
27720 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27721 			} else {
27722 				NCE_REFRELE(arpce);
27723 			}
27724 			ire_add_then_send(q, ire, mp);
27725 		}
27726 		return;	/* All is well, the packet has been sent. */
27727 	}
27728 	case IRE_ARPRESOLVE_TYPE: {
27729 
27730 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27731 			break;
27732 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27733 		mp->b_cont = NULL;
27734 		/*
27735 		 * First, check to make sure the resolution succeeded.
27736 		 * If it failed, the second mblk will be empty.
27737 		 */
27738 		if (mp1->b_rptr == mp1->b_wptr) {
27739 			/* cleanup  the incomplete ire, free queued packets */
27740 			freemsg(mp); /* fake ire */
27741 			freeb(mp1);  /* dl_unitdata response */
27742 			return;
27743 		}
27744 
27745 		/*
27746 		 * Update any incomplete nce_t found. We search the ctable
27747 		 * and find the nce from the ire->ire_nce because we need
27748 		 * to pass the ire to ip_xmit_v4 later, and can find both
27749 		 * ire and nce in one lookup.
27750 		 */
27751 		fake_ire = (ire_t *)mp->b_rptr;
27752 
27753 		/*
27754 		 * By the time we come back here from ARP the logical outgoing
27755 		 * interface of the incomplete ire we added in ire_forward()
27756 		 * could have disappeared, causing the incomplete ire to also
27757 		 * disappear.  So we need to retreive the proper ipif for the
27758 		 * ire before looking in ctable.  In the case of IPMP, the
27759 		 * ipif may be on the IPMP ill, so look it up based on the
27760 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27761 		 * Then, we can verify that ire_ipif_seqid still exists.
27762 		 */
27763 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27764 		    NULL, NULL, NULL, NULL, ipst);
27765 		if (ill == NULL) {
27766 			ip1dbg(("ill for incomplete ire vanished\n"));
27767 			freemsg(mp); /* fake ire */
27768 			freeb(mp1);  /* dl_unitdata response */
27769 			return;
27770 		}
27771 
27772 		/* Get the outgoing ipif */
27773 		mutex_enter(&ill->ill_lock);
27774 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27775 		if (ipif == NULL) {
27776 			mutex_exit(&ill->ill_lock);
27777 			ill_refrele(ill);
27778 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27779 			freemsg(mp); /* fake_ire */
27780 			freeb(mp1);  /* dl_unitdata response */
27781 			return;
27782 		}
27783 
27784 		ipif_refhold_locked(ipif);
27785 		mutex_exit(&ill->ill_lock);
27786 		ill_refrele(ill);
27787 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27788 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27789 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27790 		ipif_refrele(ipif);
27791 		if (ire == NULL) {
27792 			/*
27793 			 * no ire was found; check if there is an nce
27794 			 * for this lookup; if it has no ire's pointing at it
27795 			 * cleanup.
27796 			 */
27797 			if ((nce = ndp_lookup_v4(q->q_ptr,
27798 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27799 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27800 			    B_FALSE)) != NULL) {
27801 				/*
27802 				 * cleanup:
27803 				 * We check for refcnt 2 (one for the nce
27804 				 * hash list + 1 for the ref taken by
27805 				 * ndp_lookup_v4) to check that there are
27806 				 * no ire's pointing at the nce.
27807 				 */
27808 				if (nce->nce_refcnt == 2)
27809 					ndp_delete(nce);
27810 				NCE_REFRELE(nce);
27811 			}
27812 			freeb(mp1);  /* dl_unitdata response */
27813 			freemsg(mp); /* fake ire */
27814 			return;
27815 		}
27816 
27817 		nce = ire->ire_nce;
27818 		DTRACE_PROBE2(ire__arpresolve__type,
27819 		    ire_t *, ire, nce_t *, nce);
27820 		ASSERT(nce->nce_state != ND_INITIAL);
27821 		mutex_enter(&nce->nce_lock);
27822 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27823 		if (nce->nce_state == ND_REACHABLE) {
27824 			/*
27825 			 * Someone resolved this before us;
27826 			 * our response is not needed any more.
27827 			 */
27828 			mutex_exit(&nce->nce_lock);
27829 			freeb(mp1);  /* dl_unitdata response */
27830 		} else {
27831 			ASSERT(nce->nce_res_mp == NULL);
27832 			nce->nce_res_mp = mp1;
27833 			nce->nce_state = ND_REACHABLE;
27834 			mutex_exit(&nce->nce_lock);
27835 			nce_fastpath(nce);
27836 		}
27837 		/*
27838 		 * The cached nce_t has been updated to be reachable;
27839 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27840 		 */
27841 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27842 		freemsg(mp);
27843 		/*
27844 		 * send out queued packets.
27845 		 */
27846 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27847 
27848 		IRE_REFRELE(ire);
27849 		return;
27850 	}
27851 	default:
27852 		break;
27853 	}
27854 	if (q->q_next) {
27855 		putnext(q, mp);
27856 	} else
27857 		freemsg(mp);
27858 	return;
27859 
27860 protonak:
27861 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27862 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27863 		qreply(q, mp);
27864 }
27865 
27866 /*
27867  * Process IP options in an outbound packet.  Modify the destination if there
27868  * is a source route option.
27869  * Returns non-zero if something fails in which case an ICMP error has been
27870  * sent and mp freed.
27871  */
27872 static int
27873 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27874     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27875 {
27876 	ipoptp_t	opts;
27877 	uchar_t		*opt;
27878 	uint8_t		optval;
27879 	uint8_t		optlen;
27880 	ipaddr_t	dst;
27881 	intptr_t	code = 0;
27882 	mblk_t		*mp;
27883 	ire_t		*ire = NULL;
27884 
27885 	ip2dbg(("ip_wput_options\n"));
27886 	mp = ipsec_mp;
27887 	if (mctl_present) {
27888 		mp = ipsec_mp->b_cont;
27889 	}
27890 
27891 	dst = ipha->ipha_dst;
27892 	for (optval = ipoptp_first(&opts, ipha);
27893 	    optval != IPOPT_EOL;
27894 	    optval = ipoptp_next(&opts)) {
27895 		opt = opts.ipoptp_cur;
27896 		optlen = opts.ipoptp_len;
27897 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27898 		    optval, optlen));
27899 		switch (optval) {
27900 			uint32_t off;
27901 		case IPOPT_SSRR:
27902 		case IPOPT_LSRR:
27903 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27904 				ip1dbg((
27905 				    "ip_wput_options: bad option offset\n"));
27906 				code = (char *)&opt[IPOPT_OLEN] -
27907 				    (char *)ipha;
27908 				goto param_prob;
27909 			}
27910 			off = opt[IPOPT_OFFSET];
27911 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27912 			    ntohl(dst)));
27913 			/*
27914 			 * For strict: verify that dst is directly
27915 			 * reachable.
27916 			 */
27917 			if (optval == IPOPT_SSRR) {
27918 				ire = ire_ftable_lookup(dst, 0, 0,
27919 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27920 				    msg_getlabel(mp),
27921 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27922 				if (ire == NULL) {
27923 					ip1dbg(("ip_wput_options: SSRR not"
27924 					    " directly reachable: 0x%x\n",
27925 					    ntohl(dst)));
27926 					goto bad_src_route;
27927 				}
27928 				ire_refrele(ire);
27929 			}
27930 			break;
27931 		case IPOPT_RR:
27932 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27933 				ip1dbg((
27934 				    "ip_wput_options: bad option offset\n"));
27935 				code = (char *)&opt[IPOPT_OLEN] -
27936 				    (char *)ipha;
27937 				goto param_prob;
27938 			}
27939 			break;
27940 		case IPOPT_TS:
27941 			/*
27942 			 * Verify that length >=5 and that there is either
27943 			 * room for another timestamp or that the overflow
27944 			 * counter is not maxed out.
27945 			 */
27946 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27947 			if (optlen < IPOPT_MINLEN_IT) {
27948 				goto param_prob;
27949 			}
27950 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27951 				ip1dbg((
27952 				    "ip_wput_options: bad option offset\n"));
27953 				code = (char *)&opt[IPOPT_OFFSET] -
27954 				    (char *)ipha;
27955 				goto param_prob;
27956 			}
27957 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27958 			case IPOPT_TS_TSONLY:
27959 				off = IPOPT_TS_TIMELEN;
27960 				break;
27961 			case IPOPT_TS_TSANDADDR:
27962 			case IPOPT_TS_PRESPEC:
27963 			case IPOPT_TS_PRESPEC_RFC791:
27964 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27965 				break;
27966 			default:
27967 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27968 				    (char *)ipha;
27969 				goto param_prob;
27970 			}
27971 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27972 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27973 				/*
27974 				 * No room and the overflow counter is 15
27975 				 * already.
27976 				 */
27977 				goto param_prob;
27978 			}
27979 			break;
27980 		}
27981 	}
27982 
27983 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27984 		return (0);
27985 
27986 	ip1dbg(("ip_wput_options: error processing IP options."));
27987 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27988 
27989 param_prob:
27990 	/*
27991 	 * Since ip_wput() isn't close to finished, we fill
27992 	 * in enough of the header for credible error reporting.
27993 	 */
27994 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27995 		/* Failed */
27996 		freemsg(ipsec_mp);
27997 		return (-1);
27998 	}
27999 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28000 	return (-1);
28001 
28002 bad_src_route:
28003 	/*
28004 	 * Since ip_wput() isn't close to finished, we fill
28005 	 * in enough of the header for credible error reporting.
28006 	 */
28007 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28008 		/* Failed */
28009 		freemsg(ipsec_mp);
28010 		return (-1);
28011 	}
28012 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28013 	return (-1);
28014 }
28015 
28016 /*
28017  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28018  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28019  * thru /etc/system.
28020  */
28021 #define	CONN_MAXDRAINCNT	64
28022 
28023 static void
28024 conn_drain_init(ip_stack_t *ipst)
28025 {
28026 	int i, j;
28027 	idl_tx_list_t *itl_tx;
28028 
28029 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28030 
28031 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28032 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28033 		/*
28034 		 * Default value of the number of drainers is the
28035 		 * number of cpus, subject to maximum of 8 drainers.
28036 		 */
28037 		if (boot_max_ncpus != -1)
28038 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28039 		else
28040 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28041 	}
28042 
28043 	ipst->ips_idl_tx_list =
28044 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28045 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28046 		itl_tx =  &ipst->ips_idl_tx_list[i];
28047 		itl_tx->txl_drain_list =
28048 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28049 		    sizeof (idl_t), KM_SLEEP);
28050 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28051 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28052 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28053 			    MUTEX_DEFAULT, NULL);
28054 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28055 		}
28056 	}
28057 }
28058 
28059 static void
28060 conn_drain_fini(ip_stack_t *ipst)
28061 {
28062 	int i;
28063 	idl_tx_list_t *itl_tx;
28064 
28065 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28066 		itl_tx =  &ipst->ips_idl_tx_list[i];
28067 		kmem_free(itl_tx->txl_drain_list,
28068 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28069 	}
28070 	kmem_free(ipst->ips_idl_tx_list,
28071 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28072 	ipst->ips_idl_tx_list = NULL;
28073 }
28074 
28075 /*
28076  * Note: For an overview of how flowcontrol is handled in IP please see the
28077  * IP Flowcontrol notes at the top of this file.
28078  *
28079  * Flow control has blocked us from proceeding. Insert the given conn in one
28080  * of the conn drain lists. These conn wq's will be qenabled later on when
28081  * STREAMS flow control does a backenable. conn_walk_drain will enable
28082  * the first conn in each of these drain lists. Each of these qenabled conns
28083  * in turn enables the next in the list, after it runs, or when it closes,
28084  * thus sustaining the drain process.
28085  */
28086 void
28087 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28088 {
28089 	idl_t	*idl = tx_list->txl_drain_list;
28090 	uint_t	index;
28091 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28092 
28093 	mutex_enter(&connp->conn_lock);
28094 	if (connp->conn_state_flags & CONN_CLOSING) {
28095 		/*
28096 		 * The conn is closing as a result of which CONN_CLOSING
28097 		 * is set. Return.
28098 		 */
28099 		mutex_exit(&connp->conn_lock);
28100 		return;
28101 	} else if (connp->conn_idl == NULL) {
28102 		/*
28103 		 * Assign the next drain list round robin. We dont' use
28104 		 * a lock, and thus it may not be strictly round robin.
28105 		 * Atomicity of load/stores is enough to make sure that
28106 		 * conn_drain_list_index is always within bounds.
28107 		 */
28108 		index = tx_list->txl_drain_index;
28109 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28110 		connp->conn_idl = &tx_list->txl_drain_list[index];
28111 		index++;
28112 		if (index == ipst->ips_conn_drain_list_cnt)
28113 			index = 0;
28114 		tx_list->txl_drain_index = index;
28115 	}
28116 	mutex_exit(&connp->conn_lock);
28117 
28118 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28119 	if ((connp->conn_drain_prev != NULL) ||
28120 	    (connp->conn_state_flags & CONN_CLOSING)) {
28121 		/*
28122 		 * The conn is already in the drain list, OR
28123 		 * the conn is closing. We need to check again for
28124 		 * the closing case again since close can happen
28125 		 * after we drop the conn_lock, and before we
28126 		 * acquire the CONN_DRAIN_LIST_LOCK.
28127 		 */
28128 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28129 		return;
28130 	} else {
28131 		idl = connp->conn_idl;
28132 	}
28133 
28134 	/*
28135 	 * The conn is not in the drain list. Insert it at the
28136 	 * tail of the drain list. The drain list is circular
28137 	 * and doubly linked. idl_conn points to the 1st element
28138 	 * in the list.
28139 	 */
28140 	if (idl->idl_conn == NULL) {
28141 		idl->idl_conn = connp;
28142 		connp->conn_drain_next = connp;
28143 		connp->conn_drain_prev = connp;
28144 	} else {
28145 		conn_t *head = idl->idl_conn;
28146 
28147 		connp->conn_drain_next = head;
28148 		connp->conn_drain_prev = head->conn_drain_prev;
28149 		head->conn_drain_prev->conn_drain_next = connp;
28150 		head->conn_drain_prev = connp;
28151 	}
28152 	/*
28153 	 * For non streams based sockets assert flow control.
28154 	 */
28155 	if (IPCL_IS_NONSTR(connp)) {
28156 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28157 		(*connp->conn_upcalls->su_txq_full)
28158 		    (connp->conn_upper_handle, B_TRUE);
28159 	} else {
28160 		conn_setqfull(connp);
28161 		noenable(connp->conn_wq);
28162 	}
28163 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28164 }
28165 
28166 /*
28167  * This conn is closing, and we are called from ip_close. OR
28168  * This conn has been serviced by ip_wsrv, and we need to do the tail
28169  * processing.
28170  * If this conn is part of the drain list, we may need to sustain the drain
28171  * process by qenabling the next conn in the drain list. We may also need to
28172  * remove this conn from the list, if it is done.
28173  */
28174 static void
28175 conn_drain_tail(conn_t *connp, boolean_t closing)
28176 {
28177 	idl_t *idl;
28178 
28179 	/*
28180 	 * connp->conn_idl is stable at this point, and no lock is needed
28181 	 * to check it. If we are called from ip_close, close has already
28182 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28183 	 * called us only because conn_idl is non-null. If we are called thru
28184 	 * service, conn_idl could be null, but it cannot change because
28185 	 * service is single-threaded per queue, and there cannot be another
28186 	 * instance of service trying to call conn_drain_insert on this conn
28187 	 * now.
28188 	 */
28189 	ASSERT(!closing || (connp->conn_idl != NULL));
28190 
28191 	/*
28192 	 * If connp->conn_idl is null, the conn has not been inserted into any
28193 	 * drain list even once since creation of the conn. Just return.
28194 	 */
28195 	if (connp->conn_idl == NULL)
28196 		return;
28197 
28198 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28199 
28200 	if (connp->conn_drain_prev == NULL) {
28201 		/* This conn is currently not in the drain list.  */
28202 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28203 		return;
28204 	}
28205 	idl = connp->conn_idl;
28206 	if (idl->idl_conn_draining == connp) {
28207 		/*
28208 		 * This conn is the current drainer. If this is the last conn
28209 		 * in the drain list, we need to do more checks, in the 'if'
28210 		 * below. Otherwwise we need to just qenable the next conn,
28211 		 * to sustain the draining, and is handled in the 'else'
28212 		 * below.
28213 		 */
28214 		if (connp->conn_drain_next == idl->idl_conn) {
28215 			/*
28216 			 * This conn is the last in this list. This round
28217 			 * of draining is complete. If idl_repeat is set,
28218 			 * it means another flow enabling has happened from
28219 			 * the driver/streams and we need to another round
28220 			 * of draining.
28221 			 * If there are more than 2 conns in the drain list,
28222 			 * do a left rotate by 1, so that all conns except the
28223 			 * conn at the head move towards the head by 1, and the
28224 			 * the conn at the head goes to the tail. This attempts
28225 			 * a more even share for all queues that are being
28226 			 * drained.
28227 			 */
28228 			if ((connp->conn_drain_next != connp) &&
28229 			    (idl->idl_conn->conn_drain_next != connp)) {
28230 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28231 			}
28232 			if (idl->idl_repeat) {
28233 				qenable(idl->idl_conn->conn_wq);
28234 				idl->idl_conn_draining = idl->idl_conn;
28235 				idl->idl_repeat = 0;
28236 			} else {
28237 				idl->idl_conn_draining = NULL;
28238 			}
28239 		} else {
28240 			/*
28241 			 * If the next queue that we are now qenable'ing,
28242 			 * is closing, it will remove itself from this list
28243 			 * and qenable the subsequent queue in ip_close().
28244 			 * Serialization is acheived thru idl_lock.
28245 			 */
28246 			qenable(connp->conn_drain_next->conn_wq);
28247 			idl->idl_conn_draining = connp->conn_drain_next;
28248 		}
28249 	}
28250 	if (!connp->conn_did_putbq || closing) {
28251 		/*
28252 		 * Remove ourself from the drain list, if we did not do
28253 		 * a putbq, or if the conn is closing.
28254 		 * Note: It is possible that q->q_first is non-null. It means
28255 		 * that these messages landed after we did a enableok() in
28256 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28257 		 * service them.
28258 		 */
28259 		if (connp->conn_drain_next == connp) {
28260 			/* Singleton in the list */
28261 			ASSERT(connp->conn_drain_prev == connp);
28262 			idl->idl_conn = NULL;
28263 			idl->idl_conn_draining = NULL;
28264 		} else {
28265 			connp->conn_drain_prev->conn_drain_next =
28266 			    connp->conn_drain_next;
28267 			connp->conn_drain_next->conn_drain_prev =
28268 			    connp->conn_drain_prev;
28269 			if (idl->idl_conn == connp)
28270 				idl->idl_conn = connp->conn_drain_next;
28271 			ASSERT(idl->idl_conn_draining != connp);
28272 
28273 		}
28274 		connp->conn_drain_next = NULL;
28275 		connp->conn_drain_prev = NULL;
28276 
28277 		/*
28278 		 * For non streams based sockets open up flow control.
28279 		 */
28280 		if (IPCL_IS_NONSTR(connp)) {
28281 			(*connp->conn_upcalls->su_txq_full)
28282 			    (connp->conn_upper_handle, B_FALSE);
28283 		} else {
28284 			conn_clrqfull(connp);
28285 			enableok(connp->conn_wq);
28286 		}
28287 	}
28288 
28289 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28290 }
28291 
28292 /*
28293  * Write service routine. Shared perimeter entry point.
28294  * ip_wsrv can be called in any of the following ways.
28295  * 1. The device queue's messages has fallen below the low water mark
28296  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28297  *    the drain lists and backenable the first conn in each list.
28298  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28299  *    qenabled non-tcp upper layers. We start dequeing messages and call
28300  *    ip_wput for each message.
28301  */
28302 
28303 void
28304 ip_wsrv(queue_t *q)
28305 {
28306 	conn_t	*connp;
28307 	ill_t	*ill;
28308 	mblk_t	*mp;
28309 
28310 	if (q->q_next) {
28311 		ill = (ill_t *)q->q_ptr;
28312 		if (ill->ill_state_flags == 0) {
28313 			ip_stack_t *ipst = ill->ill_ipst;
28314 
28315 			/*
28316 			 * The device flow control has opened up.
28317 			 * Walk through conn drain lists and qenable the
28318 			 * first conn in each list. This makes sense only
28319 			 * if the stream is fully plumbed and setup.
28320 			 * Hence the if check above.
28321 			 */
28322 			ip1dbg(("ip_wsrv: walking\n"));
28323 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28324 		}
28325 		return;
28326 	}
28327 
28328 	connp = Q_TO_CONN(q);
28329 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28330 
28331 	/*
28332 	 * 1. Set conn_draining flag to signal that service is active.
28333 	 *
28334 	 * 2. ip_output determines whether it has been called from service,
28335 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28336 	 *    has been called from service.
28337 	 *
28338 	 * 3. Message ordering is preserved by the following logic.
28339 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28340 	 *    the message at the tail, if conn_draining is set (i.e. service
28341 	 *    is running) or if q->q_first is non-null.
28342 	 *
28343 	 *    ii. If ip_output is called from service, and if ip_output cannot
28344 	 *    putnext due to flow control, it does a putbq.
28345 	 *
28346 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28347 	 *    (causing an infinite loop).
28348 	 */
28349 	ASSERT(!connp->conn_did_putbq);
28350 
28351 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28352 		connp->conn_draining = 1;
28353 		noenable(q);
28354 		while ((mp = getq(q)) != NULL) {
28355 			ASSERT(CONN_Q(q));
28356 
28357 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28358 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28359 			if (connp->conn_did_putbq) {
28360 				/* ip_wput did a putbq */
28361 				break;
28362 			}
28363 		}
28364 		/*
28365 		 * At this point, a thread coming down from top, calling
28366 		 * ip_wput, may end up queueing the message. We have not yet
28367 		 * enabled the queue, so ip_wsrv won't be called again.
28368 		 * To avoid this race, check q->q_first again (in the loop)
28369 		 * If the other thread queued the message before we call
28370 		 * enableok(), we will catch it in the q->q_first check.
28371 		 * If the other thread queues the message after we call
28372 		 * enableok(), ip_wsrv will be called again by STREAMS.
28373 		 */
28374 		connp->conn_draining = 0;
28375 		enableok(q);
28376 	}
28377 
28378 	/* Enable the next conn for draining */
28379 	conn_drain_tail(connp, B_FALSE);
28380 
28381 	/*
28382 	 * conn_direct_blocked is used to indicate blocked
28383 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28384 	 * This is the only place where it is set without
28385 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28386 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28387 	 */
28388 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28389 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28390 		connp->conn_direct_blocked = B_FALSE;
28391 	}
28392 
28393 	connp->conn_did_putbq = 0;
28394 }
28395 
28396 /*
28397  * Callback to disable flow control in IP.
28398  *
28399  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28400  * is enabled.
28401  *
28402  * When MAC_TX() is not able to send any more packets, dld sets its queue
28403  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28404  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28405  * function and wakes up corresponding mac worker threads, which in turn
28406  * calls this callback function, and disables flow control.
28407  */
28408 void
28409 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28410 {
28411 	ill_t *ill = (ill_t *)arg;
28412 	ip_stack_t *ipst = ill->ill_ipst;
28413 	idl_tx_list_t *idl_txl;
28414 
28415 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28416 	mutex_enter(&idl_txl->txl_lock);
28417 	/* add code to to set a flag to indicate idl_txl is enabled */
28418 	conn_walk_drain(ipst, idl_txl);
28419 	mutex_exit(&idl_txl->txl_lock);
28420 }
28421 
28422 /*
28423  * Walk the list of all conn's calling the function provided with the
28424  * specified argument for each.	 Note that this only walks conn's that
28425  * have been bound.
28426  * Applies to both IPv4 and IPv6.
28427  */
28428 static void
28429 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28430 {
28431 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28432 	    ipst->ips_ipcl_udp_fanout_size,
28433 	    func, arg, zoneid);
28434 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28435 	    ipst->ips_ipcl_conn_fanout_size,
28436 	    func, arg, zoneid);
28437 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28438 	    ipst->ips_ipcl_bind_fanout_size,
28439 	    func, arg, zoneid);
28440 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28441 	    IPPROTO_MAX, func, arg, zoneid);
28442 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28443 	    IPPROTO_MAX, func, arg, zoneid);
28444 }
28445 
28446 /*
28447  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28448  * of conns that need to be drained, check if drain is already in progress.
28449  * If so set the idl_repeat bit, indicating that the last conn in the list
28450  * needs to reinitiate the drain once again, for the list. If drain is not
28451  * in progress for the list, initiate the draining, by qenabling the 1st
28452  * conn in the list. The drain is self-sustaining, each qenabled conn will
28453  * in turn qenable the next conn, when it is done/blocked/closing.
28454  */
28455 static void
28456 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28457 {
28458 	int i;
28459 	idl_t *idl;
28460 
28461 	IP_STAT(ipst, ip_conn_walk_drain);
28462 
28463 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28464 		idl = &tx_list->txl_drain_list[i];
28465 		mutex_enter(&idl->idl_lock);
28466 		if (idl->idl_conn == NULL) {
28467 			mutex_exit(&idl->idl_lock);
28468 			continue;
28469 		}
28470 		/*
28471 		 * If this list is not being drained currently by
28472 		 * an ip_wsrv thread, start the process.
28473 		 */
28474 		if (idl->idl_conn_draining == NULL) {
28475 			ASSERT(idl->idl_repeat == 0);
28476 			qenable(idl->idl_conn->conn_wq);
28477 			idl->idl_conn_draining = idl->idl_conn;
28478 		} else {
28479 			idl->idl_repeat = 1;
28480 		}
28481 		mutex_exit(&idl->idl_lock);
28482 	}
28483 }
28484 
28485 /*
28486  * Walk an conn hash table of `count' buckets, calling func for each entry.
28487  */
28488 static void
28489 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28490     zoneid_t zoneid)
28491 {
28492 	conn_t	*connp;
28493 
28494 	while (count-- > 0) {
28495 		mutex_enter(&connfp->connf_lock);
28496 		for (connp = connfp->connf_head; connp != NULL;
28497 		    connp = connp->conn_next) {
28498 			if (zoneid == GLOBAL_ZONEID ||
28499 			    zoneid == connp->conn_zoneid) {
28500 				CONN_INC_REF(connp);
28501 				mutex_exit(&connfp->connf_lock);
28502 				(*func)(connp, arg);
28503 				mutex_enter(&connfp->connf_lock);
28504 				CONN_DEC_REF(connp);
28505 			}
28506 		}
28507 		mutex_exit(&connfp->connf_lock);
28508 		connfp++;
28509 	}
28510 }
28511 
28512 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28513 static void
28514 conn_report1(conn_t *connp, void *mp)
28515 {
28516 	char	buf1[INET6_ADDRSTRLEN];
28517 	char	buf2[INET6_ADDRSTRLEN];
28518 	uint_t	print_len, buf_len;
28519 
28520 	ASSERT(connp != NULL);
28521 
28522 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28523 	if (buf_len <= 0)
28524 		return;
28525 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28526 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28527 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28528 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28529 	    "%5d %s/%05d %s/%05d\n",
28530 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28531 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28532 	    buf1, connp->conn_lport,
28533 	    buf2, connp->conn_fport);
28534 	if (print_len < buf_len) {
28535 		((mblk_t *)mp)->b_wptr += print_len;
28536 	} else {
28537 		((mblk_t *)mp)->b_wptr += buf_len;
28538 	}
28539 }
28540 
28541 /*
28542  * Named Dispatch routine to produce a formatted report on all conns
28543  * that are listed in one of the fanout tables.
28544  * This report is accessed by using the ndd utility to "get" ND variable
28545  * "ip_conn_status".
28546  */
28547 /* ARGSUSED */
28548 static int
28549 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28550 {
28551 	conn_t *connp = Q_TO_CONN(q);
28552 
28553 	(void) mi_mpprintf(mp,
28554 	    "CONN      " MI_COL_HDRPAD_STR
28555 	    "rfq      " MI_COL_HDRPAD_STR
28556 	    "stq      " MI_COL_HDRPAD_STR
28557 	    " zone local		 remote");
28558 
28559 	/*
28560 	 * Because of the ndd constraint, at most we can have 64K buffer
28561 	 * to put in all conn info.  So to be more efficient, just
28562 	 * allocate a 64K buffer here, assuming we need that large buffer.
28563 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28564 	 */
28565 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28566 		/* The following may work even if we cannot get a large buf. */
28567 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28568 		return (0);
28569 	}
28570 
28571 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28572 	    connp->conn_netstack->netstack_ip);
28573 	return (0);
28574 }
28575 
28576 /*
28577  * Determine if the ill and multicast aspects of that packets
28578  * "matches" the conn.
28579  */
28580 boolean_t
28581 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28582     zoneid_t zoneid)
28583 {
28584 	ill_t *bound_ill;
28585 	boolean_t found;
28586 	ipif_t *ipif;
28587 	ire_t *ire;
28588 	ipaddr_t dst, src;
28589 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28590 
28591 	dst = ipha->ipha_dst;
28592 	src = ipha->ipha_src;
28593 
28594 	/*
28595 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28596 	 * unicast, broadcast and multicast reception to
28597 	 * conn_incoming_ill. conn_wantpacket itself is called
28598 	 * only for BROADCAST and multicast.
28599 	 */
28600 	bound_ill = connp->conn_incoming_ill;
28601 	if (bound_ill != NULL) {
28602 		if (IS_IPMP(bound_ill)) {
28603 			if (bound_ill->ill_grp != ill->ill_grp)
28604 				return (B_FALSE);
28605 		} else {
28606 			if (bound_ill != ill)
28607 				return (B_FALSE);
28608 		}
28609 	}
28610 
28611 	if (!CLASSD(dst)) {
28612 		if (IPCL_ZONE_MATCH(connp, zoneid))
28613 			return (B_TRUE);
28614 		/*
28615 		 * The conn is in a different zone; we need to check that this
28616 		 * broadcast address is configured in the application's zone.
28617 		 */
28618 		ipif = ipif_get_next_ipif(NULL, ill);
28619 		if (ipif == NULL)
28620 			return (B_FALSE);
28621 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28622 		    connp->conn_zoneid, NULL,
28623 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28624 		ipif_refrele(ipif);
28625 		if (ire != NULL) {
28626 			ire_refrele(ire);
28627 			return (B_TRUE);
28628 		} else {
28629 			return (B_FALSE);
28630 		}
28631 	}
28632 
28633 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28634 	    connp->conn_zoneid == zoneid) {
28635 		/*
28636 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28637 		 * disabled, therefore we don't dispatch the multicast packet to
28638 		 * the sending zone.
28639 		 */
28640 		return (B_FALSE);
28641 	}
28642 
28643 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28644 		/*
28645 		 * Multicast packet on the loopback interface: we only match
28646 		 * conns who joined the group in the specified zone.
28647 		 */
28648 		return (B_FALSE);
28649 	}
28650 
28651 	if (connp->conn_multi_router) {
28652 		/* multicast packet and multicast router socket: send up */
28653 		return (B_TRUE);
28654 	}
28655 
28656 	mutex_enter(&connp->conn_lock);
28657 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28658 	mutex_exit(&connp->conn_lock);
28659 	return (found);
28660 }
28661 
28662 static void
28663 conn_setqfull(conn_t *connp)
28664 {
28665 	queue_t *q = connp->conn_wq;
28666 
28667 	if (!(q->q_flag & QFULL)) {
28668 		mutex_enter(QLOCK(q));
28669 		if (!(q->q_flag & QFULL)) {
28670 			/* still need to set QFULL */
28671 			q->q_flag |= QFULL;
28672 			mutex_exit(QLOCK(q));
28673 		} else {
28674 			mutex_exit(QLOCK(q));
28675 		}
28676 	}
28677 }
28678 
28679 static void
28680 conn_clrqfull(conn_t *connp)
28681 {
28682 	queue_t *q = connp->conn_wq;
28683 
28684 	if (q->q_flag & QFULL) {
28685 		mutex_enter(QLOCK(q));
28686 		if (q->q_flag & QFULL) {
28687 			q->q_flag &= ~QFULL;
28688 			mutex_exit(QLOCK(q));
28689 			if (q->q_flag & QWANTW)
28690 				qbackenable(q, 0);
28691 		} else {
28692 			mutex_exit(QLOCK(q));
28693 		}
28694 	}
28695 }
28696 
28697 /*
28698  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28699  */
28700 /* ARGSUSED */
28701 static void
28702 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28703 {
28704 	ill_t *ill = (ill_t *)q->q_ptr;
28705 	mblk_t	*mp1, *mp2;
28706 	ipif_t  *ipif;
28707 	int err = 0;
28708 	conn_t *connp = NULL;
28709 	ipsq_t	*ipsq;
28710 	arc_t	*arc;
28711 
28712 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28713 
28714 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28715 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28716 
28717 	ASSERT(IAM_WRITER_ILL(ill));
28718 	mp2 = mp->b_cont;
28719 	mp->b_cont = NULL;
28720 
28721 	/*
28722 	 * We have now received the arp bringup completion message
28723 	 * from ARP. Mark the arp bringup as done. Also if the arp
28724 	 * stream has already started closing, send up the AR_ARP_CLOSING
28725 	 * ack now since ARP is waiting in close for this ack.
28726 	 */
28727 	mutex_enter(&ill->ill_lock);
28728 	ill->ill_arp_bringup_pending = 0;
28729 	if (ill->ill_arp_closing) {
28730 		mutex_exit(&ill->ill_lock);
28731 		/* Let's reuse the mp for sending the ack */
28732 		arc = (arc_t *)mp->b_rptr;
28733 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28734 		arc->arc_cmd = AR_ARP_CLOSING;
28735 		qreply(q, mp);
28736 	} else {
28737 		mutex_exit(&ill->ill_lock);
28738 		freeb(mp);
28739 	}
28740 
28741 	ipsq = ill->ill_phyint->phyint_ipsq;
28742 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28743 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28744 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28745 	if (mp1 == NULL) {
28746 		/* bringup was aborted by the user */
28747 		freemsg(mp2);
28748 		return;
28749 	}
28750 
28751 	/*
28752 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28753 	 * must have an associated conn_t.  Otherwise, we're bringing this
28754 	 * interface back up as part of handling an asynchronous event (e.g.,
28755 	 * physical address change).
28756 	 */
28757 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28758 		ASSERT(connp != NULL);
28759 		q = CONNP_TO_WQ(connp);
28760 	} else {
28761 		ASSERT(connp == NULL);
28762 		q = ill->ill_rq;
28763 	}
28764 
28765 	/*
28766 	 * If the DL_BIND_REQ fails, it is noted
28767 	 * in arc_name_offset.
28768 	 */
28769 	err = *((int *)mp2->b_rptr);
28770 	if (err == 0) {
28771 		if (ipif->ipif_isv6) {
28772 			if ((err = ipif_up_done_v6(ipif)) != 0)
28773 				ip0dbg(("ip_arp_done: init failed\n"));
28774 		} else {
28775 			if ((err = ipif_up_done(ipif)) != 0)
28776 				ip0dbg(("ip_arp_done: init failed\n"));
28777 		}
28778 	} else {
28779 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28780 	}
28781 
28782 	freemsg(mp2);
28783 
28784 	if ((err == 0) && (ill->ill_up_ipifs)) {
28785 		err = ill_up_ipifs(ill, q, mp1);
28786 		if (err == EINPROGRESS)
28787 			return;
28788 	}
28789 
28790 	/*
28791 	 * If we have a moved ipif to bring up, and everything has succeeded
28792 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28793 	 * down -- the admin can try to bring it up by hand if need be.
28794 	 */
28795 	if (ill->ill_move_ipif != NULL) {
28796 		ipif = ill->ill_move_ipif;
28797 		ill->ill_move_ipif = NULL;
28798 		if (err == 0) {
28799 			err = ipif_up(ipif, q, mp1);
28800 			if (err == EINPROGRESS)
28801 				return;
28802 		}
28803 	}
28804 
28805 	/*
28806 	 * The operation must complete without EINPROGRESS since
28807 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28808 	 * operation will be stuck forever in the ipsq.
28809 	 */
28810 	ASSERT(err != EINPROGRESS);
28811 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28812 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28813 	else
28814 		ipsq_current_finish(ipsq);
28815 }
28816 
28817 /* Allocate the private structure */
28818 static int
28819 ip_priv_alloc(void **bufp)
28820 {
28821 	void	*buf;
28822 
28823 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28824 		return (ENOMEM);
28825 
28826 	*bufp = buf;
28827 	return (0);
28828 }
28829 
28830 /* Function to delete the private structure */
28831 void
28832 ip_priv_free(void *buf)
28833 {
28834 	ASSERT(buf != NULL);
28835 	kmem_free(buf, sizeof (ip_priv_t));
28836 }
28837 
28838 /*
28839  * The entry point for IPPF processing.
28840  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28841  * routine just returns.
28842  *
28843  * When called, ip_process generates an ipp_packet_t structure
28844  * which holds the state information for this packet and invokes the
28845  * the classifier (via ipp_packet_process). The classification, depending on
28846  * configured filters, results in a list of actions for this packet. Invoking
28847  * an action may cause the packet to be dropped, in which case the resulting
28848  * mblk (*mpp) is NULL. proc indicates the callout position for
28849  * this packet and ill_index is the interface this packet on or will leave
28850  * on (inbound and outbound resp.).
28851  */
28852 void
28853 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28854 {
28855 	mblk_t		*mp;
28856 	ip_priv_t	*priv;
28857 	ipp_action_id_t	aid;
28858 	int		rc = 0;
28859 	ipp_packet_t	*pp;
28860 #define	IP_CLASS	"ip"
28861 
28862 	/* If the classifier is not loaded, return  */
28863 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28864 		return;
28865 	}
28866 
28867 	mp = *mpp;
28868 	ASSERT(mp != NULL);
28869 
28870 	/* Allocate the packet structure */
28871 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28872 	if (rc != 0) {
28873 		*mpp = NULL;
28874 		freemsg(mp);
28875 		return;
28876 	}
28877 
28878 	/* Allocate the private structure */
28879 	rc = ip_priv_alloc((void **)&priv);
28880 	if (rc != 0) {
28881 		*mpp = NULL;
28882 		freemsg(mp);
28883 		ipp_packet_free(pp);
28884 		return;
28885 	}
28886 	priv->proc = proc;
28887 	priv->ill_index = ill_index;
28888 	ipp_packet_set_private(pp, priv, ip_priv_free);
28889 	ipp_packet_set_data(pp, mp);
28890 
28891 	/* Invoke the classifier */
28892 	rc = ipp_packet_process(&pp);
28893 	if (pp != NULL) {
28894 		mp = ipp_packet_get_data(pp);
28895 		ipp_packet_free(pp);
28896 		if (rc != 0) {
28897 			freemsg(mp);
28898 			*mpp = NULL;
28899 		}
28900 	} else {
28901 		*mpp = NULL;
28902 	}
28903 #undef	IP_CLASS
28904 }
28905 
28906 /*
28907  * Propagate a multicast group membership operation (add/drop) on
28908  * all the interfaces crossed by the related multirt routes.
28909  * The call is considered successful if the operation succeeds
28910  * on at least one interface.
28911  */
28912 static int
28913 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28914     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28915     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28916     mblk_t *first_mp)
28917 {
28918 	ire_t		*ire_gw;
28919 	irb_t		*irb;
28920 	int		error = 0;
28921 	opt_restart_t	*or;
28922 	ip_stack_t	*ipst = ire->ire_ipst;
28923 
28924 	irb = ire->ire_bucket;
28925 	ASSERT(irb != NULL);
28926 
28927 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28928 
28929 	or = (opt_restart_t *)first_mp->b_rptr;
28930 	IRB_REFHOLD(irb);
28931 	for (; ire != NULL; ire = ire->ire_next) {
28932 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28933 			continue;
28934 		if (ire->ire_addr != group)
28935 			continue;
28936 
28937 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28938 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28939 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28940 		/* No resolver exists for the gateway; skip this ire. */
28941 		if (ire_gw == NULL)
28942 			continue;
28943 
28944 		/*
28945 		 * This function can return EINPROGRESS. If so the operation
28946 		 * will be restarted from ip_restart_optmgmt which will
28947 		 * call ip_opt_set and option processing will restart for
28948 		 * this option. So we may end up calling 'fn' more than once.
28949 		 * This requires that 'fn' is idempotent except for the
28950 		 * return value. The operation is considered a success if
28951 		 * it succeeds at least once on any one interface.
28952 		 */
28953 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28954 		    NULL, fmode, src, first_mp);
28955 		if (error == 0)
28956 			or->or_private = CGTP_MCAST_SUCCESS;
28957 
28958 		if (ip_debug > 0) {
28959 			ulong_t	off;
28960 			char	*ksym;
28961 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28962 			ip2dbg(("ip_multirt_apply_membership: "
28963 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28964 			    "error %d [success %u]\n",
28965 			    ksym ? ksym : "?",
28966 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28967 			    error, or->or_private));
28968 		}
28969 
28970 		ire_refrele(ire_gw);
28971 		if (error == EINPROGRESS) {
28972 			IRB_REFRELE(irb);
28973 			return (error);
28974 		}
28975 	}
28976 	IRB_REFRELE(irb);
28977 	/*
28978 	 * Consider the call as successful if we succeeded on at least
28979 	 * one interface. Otherwise, return the last encountered error.
28980 	 */
28981 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28982 }
28983 
28984 /*
28985  * Issue a warning regarding a route crossing an interface with an
28986  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28987  * amount of time is logged.
28988  */
28989 static void
28990 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28991 {
28992 	hrtime_t	current = gethrtime();
28993 	char		buf[INET_ADDRSTRLEN];
28994 	ip_stack_t	*ipst = ire->ire_ipst;
28995 
28996 	/* Convert interval in ms to hrtime in ns */
28997 	if (ipst->ips_multirt_bad_mtu_last_time +
28998 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28999 	    current) {
29000 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29001 		    "to %s, incorrect MTU %u (expected %u)\n",
29002 		    ip_dot_addr(ire->ire_addr, buf),
29003 		    ire->ire_max_frag, max_frag);
29004 
29005 		ipst->ips_multirt_bad_mtu_last_time = current;
29006 	}
29007 }
29008 
29009 /*
29010  * Get the CGTP (multirouting) filtering status.
29011  * If 0, the CGTP hooks are transparent.
29012  */
29013 /* ARGSUSED */
29014 static int
29015 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29016 {
29017 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29018 
29019 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29020 	return (0);
29021 }
29022 
29023 /*
29024  * Set the CGTP (multirouting) filtering status.
29025  * If the status is changed from active to transparent
29026  * or from transparent to active, forward the new status
29027  * to the filtering module (if loaded).
29028  */
29029 /* ARGSUSED */
29030 static int
29031 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29032     cred_t *ioc_cr)
29033 {
29034 	long		new_value;
29035 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29036 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29037 
29038 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29039 		return (EPERM);
29040 
29041 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29042 	    new_value < 0 || new_value > 1) {
29043 		return (EINVAL);
29044 	}
29045 
29046 	if ((!*ip_cgtp_filter_value) && new_value) {
29047 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29048 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29049 		    " (module not loaded)" : "");
29050 	}
29051 	if (*ip_cgtp_filter_value && (!new_value)) {
29052 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29053 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29054 		    " (module not loaded)" : "");
29055 	}
29056 
29057 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29058 		int	res;
29059 		netstackid_t stackid;
29060 
29061 		stackid = ipst->ips_netstack->netstack_stackid;
29062 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29063 		    new_value);
29064 		if (res)
29065 			return (res);
29066 	}
29067 
29068 	*ip_cgtp_filter_value = (boolean_t)new_value;
29069 
29070 	return (0);
29071 }
29072 
29073 /*
29074  * Return the expected CGTP hooks version number.
29075  */
29076 int
29077 ip_cgtp_filter_supported(void)
29078 {
29079 	return (ip_cgtp_filter_rev);
29080 }
29081 
29082 /*
29083  * CGTP hooks can be registered by invoking this function.
29084  * Checks that the version number matches.
29085  */
29086 int
29087 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29088 {
29089 	netstack_t *ns;
29090 	ip_stack_t *ipst;
29091 
29092 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29093 		return (ENOTSUP);
29094 
29095 	ns = netstack_find_by_stackid(stackid);
29096 	if (ns == NULL)
29097 		return (EINVAL);
29098 	ipst = ns->netstack_ip;
29099 	ASSERT(ipst != NULL);
29100 
29101 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29102 		netstack_rele(ns);
29103 		return (EALREADY);
29104 	}
29105 
29106 	ipst->ips_ip_cgtp_filter_ops = ops;
29107 	netstack_rele(ns);
29108 	return (0);
29109 }
29110 
29111 /*
29112  * CGTP hooks can be unregistered by invoking this function.
29113  * Returns ENXIO if there was no registration.
29114  * Returns EBUSY if the ndd variable has not been turned off.
29115  */
29116 int
29117 ip_cgtp_filter_unregister(netstackid_t stackid)
29118 {
29119 	netstack_t *ns;
29120 	ip_stack_t *ipst;
29121 
29122 	ns = netstack_find_by_stackid(stackid);
29123 	if (ns == NULL)
29124 		return (EINVAL);
29125 	ipst = ns->netstack_ip;
29126 	ASSERT(ipst != NULL);
29127 
29128 	if (ipst->ips_ip_cgtp_filter) {
29129 		netstack_rele(ns);
29130 		return (EBUSY);
29131 	}
29132 
29133 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29134 		netstack_rele(ns);
29135 		return (ENXIO);
29136 	}
29137 	ipst->ips_ip_cgtp_filter_ops = NULL;
29138 	netstack_rele(ns);
29139 	return (0);
29140 }
29141 
29142 /*
29143  * Check whether there is a CGTP filter registration.
29144  * Returns non-zero if there is a registration, otherwise returns zero.
29145  * Note: returns zero if bad stackid.
29146  */
29147 int
29148 ip_cgtp_filter_is_registered(netstackid_t stackid)
29149 {
29150 	netstack_t *ns;
29151 	ip_stack_t *ipst;
29152 	int ret;
29153 
29154 	ns = netstack_find_by_stackid(stackid);
29155 	if (ns == NULL)
29156 		return (0);
29157 	ipst = ns->netstack_ip;
29158 	ASSERT(ipst != NULL);
29159 
29160 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29161 		ret = 1;
29162 	else
29163 		ret = 0;
29164 
29165 	netstack_rele(ns);
29166 	return (ret);
29167 }
29168 
29169 static int
29170 ip_squeue_switch(int val)
29171 {
29172 	int rval = SQ_FILL;
29173 
29174 	switch (val) {
29175 	case IP_SQUEUE_ENTER_NODRAIN:
29176 		rval = SQ_NODRAIN;
29177 		break;
29178 	case IP_SQUEUE_ENTER:
29179 		rval = SQ_PROCESS;
29180 		break;
29181 	default:
29182 		break;
29183 	}
29184 	return (rval);
29185 }
29186 
29187 /* ARGSUSED */
29188 static int
29189 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29190     caddr_t addr, cred_t *cr)
29191 {
29192 	int *v = (int *)addr;
29193 	long new_value;
29194 
29195 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29196 		return (EPERM);
29197 
29198 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29199 		return (EINVAL);
29200 
29201 	ip_squeue_flag = ip_squeue_switch(new_value);
29202 	*v = new_value;
29203 	return (0);
29204 }
29205 
29206 /*
29207  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29208  * ip_debug.
29209  */
29210 /* ARGSUSED */
29211 static int
29212 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29213     caddr_t addr, cred_t *cr)
29214 {
29215 	int *v = (int *)addr;
29216 	long new_value;
29217 
29218 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29219 		return (EPERM);
29220 
29221 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29222 		return (EINVAL);
29223 
29224 	*v = new_value;
29225 	return (0);
29226 }
29227 
29228 static void *
29229 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29230 {
29231 	kstat_t *ksp;
29232 
29233 	ip_stat_t template = {
29234 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29235 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29236 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29237 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29238 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29239 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29240 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29241 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29242 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29243 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29244 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29245 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29246 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29247 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29248 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29249 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29250 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29251 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29252 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29253 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29254 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29255 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29256 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29257 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29258 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29259 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29260 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29261 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29262 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29263 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29264 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29265 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29266 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29267 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29268 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29269 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29270 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29271 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29272 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29273 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29274 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29275 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29276 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29277 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29278 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29279 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29280 	};
29281 
29282 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29283 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29284 	    KSTAT_FLAG_VIRTUAL, stackid);
29285 
29286 	if (ksp == NULL)
29287 		return (NULL);
29288 
29289 	bcopy(&template, ip_statisticsp, sizeof (template));
29290 	ksp->ks_data = (void *)ip_statisticsp;
29291 	ksp->ks_private = (void *)(uintptr_t)stackid;
29292 
29293 	kstat_install(ksp);
29294 	return (ksp);
29295 }
29296 
29297 static void
29298 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29299 {
29300 	if (ksp != NULL) {
29301 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29302 		kstat_delete_netstack(ksp, stackid);
29303 	}
29304 }
29305 
29306 static void *
29307 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29308 {
29309 	kstat_t	*ksp;
29310 
29311 	ip_named_kstat_t template = {
29312 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29313 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29314 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29315 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29316 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29317 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29318 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29319 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29320 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29321 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29322 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29323 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29324 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29325 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29326 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29327 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29328 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29329 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29330 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29331 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29332 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29333 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29334 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29335 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29336 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29337 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29338 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29339 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29340 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29341 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29342 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29343 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29344 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29345 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29346 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29347 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29348 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29349 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29350 	};
29351 
29352 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29353 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29354 	if (ksp == NULL || ksp->ks_data == NULL)
29355 		return (NULL);
29356 
29357 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29358 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29359 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29360 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29361 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29362 
29363 	template.netToMediaEntrySize.value.i32 =
29364 	    sizeof (mib2_ipNetToMediaEntry_t);
29365 
29366 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29367 
29368 	bcopy(&template, ksp->ks_data, sizeof (template));
29369 	ksp->ks_update = ip_kstat_update;
29370 	ksp->ks_private = (void *)(uintptr_t)stackid;
29371 
29372 	kstat_install(ksp);
29373 	return (ksp);
29374 }
29375 
29376 static void
29377 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29378 {
29379 	if (ksp != NULL) {
29380 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29381 		kstat_delete_netstack(ksp, stackid);
29382 	}
29383 }
29384 
29385 static int
29386 ip_kstat_update(kstat_t *kp, int rw)
29387 {
29388 	ip_named_kstat_t *ipkp;
29389 	mib2_ipIfStatsEntry_t ipmib;
29390 	ill_walk_context_t ctx;
29391 	ill_t *ill;
29392 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29393 	netstack_t	*ns;
29394 	ip_stack_t	*ipst;
29395 
29396 	if (kp == NULL || kp->ks_data == NULL)
29397 		return (EIO);
29398 
29399 	if (rw == KSTAT_WRITE)
29400 		return (EACCES);
29401 
29402 	ns = netstack_find_by_stackid(stackid);
29403 	if (ns == NULL)
29404 		return (-1);
29405 	ipst = ns->netstack_ip;
29406 	if (ipst == NULL) {
29407 		netstack_rele(ns);
29408 		return (-1);
29409 	}
29410 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29411 
29412 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29413 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29414 	ill = ILL_START_WALK_V4(&ctx, ipst);
29415 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29416 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29417 	rw_exit(&ipst->ips_ill_g_lock);
29418 
29419 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29420 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29421 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29422 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29423 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29424 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29425 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29426 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29427 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29428 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29429 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29430 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29431 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29432 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29433 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29434 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29435 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29436 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29437 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29438 
29439 	ipkp->routingDiscards.value.ui32 =	0;
29440 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29441 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29442 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29443 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29444 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29445 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29446 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29447 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29448 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29449 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29450 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29451 
29452 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29453 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29454 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29455 
29456 	netstack_rele(ns);
29457 
29458 	return (0);
29459 }
29460 
29461 static void *
29462 icmp_kstat_init(netstackid_t stackid)
29463 {
29464 	kstat_t	*ksp;
29465 
29466 	icmp_named_kstat_t template = {
29467 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29468 		{ "inErrors",		KSTAT_DATA_UINT32 },
29469 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29470 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29471 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29472 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29473 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29474 		{ "inEchos",		KSTAT_DATA_UINT32 },
29475 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29476 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29477 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29478 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29479 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29480 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29481 		{ "outErrors",		KSTAT_DATA_UINT32 },
29482 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29483 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29484 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29485 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29486 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29487 		{ "outEchos",		KSTAT_DATA_UINT32 },
29488 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29489 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29490 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29491 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29492 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29493 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29494 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29495 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29496 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29497 		{ "outDrops",		KSTAT_DATA_UINT32 },
29498 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29499 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29500 	};
29501 
29502 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29503 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29504 	if (ksp == NULL || ksp->ks_data == NULL)
29505 		return (NULL);
29506 
29507 	bcopy(&template, ksp->ks_data, sizeof (template));
29508 
29509 	ksp->ks_update = icmp_kstat_update;
29510 	ksp->ks_private = (void *)(uintptr_t)stackid;
29511 
29512 	kstat_install(ksp);
29513 	return (ksp);
29514 }
29515 
29516 static void
29517 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29518 {
29519 	if (ksp != NULL) {
29520 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29521 		kstat_delete_netstack(ksp, stackid);
29522 	}
29523 }
29524 
29525 static int
29526 icmp_kstat_update(kstat_t *kp, int rw)
29527 {
29528 	icmp_named_kstat_t *icmpkp;
29529 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29530 	netstack_t	*ns;
29531 	ip_stack_t	*ipst;
29532 
29533 	if ((kp == NULL) || (kp->ks_data == NULL))
29534 		return (EIO);
29535 
29536 	if (rw == KSTAT_WRITE)
29537 		return (EACCES);
29538 
29539 	ns = netstack_find_by_stackid(stackid);
29540 	if (ns == NULL)
29541 		return (-1);
29542 	ipst = ns->netstack_ip;
29543 	if (ipst == NULL) {
29544 		netstack_rele(ns);
29545 		return (-1);
29546 	}
29547 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29548 
29549 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29550 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29551 	icmpkp->inDestUnreachs.value.ui32 =
29552 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29553 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29554 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29555 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29556 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29557 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29558 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29559 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29560 	icmpkp->inTimestampReps.value.ui32 =
29561 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29562 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29563 	icmpkp->inAddrMaskReps.value.ui32 =
29564 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29565 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29566 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29567 	icmpkp->outDestUnreachs.value.ui32 =
29568 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29569 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29570 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29571 	icmpkp->outSrcQuenchs.value.ui32 =
29572 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29573 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29574 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29575 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29576 	icmpkp->outTimestamps.value.ui32 =
29577 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29578 	icmpkp->outTimestampReps.value.ui32 =
29579 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29580 	icmpkp->outAddrMasks.value.ui32 =
29581 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29582 	icmpkp->outAddrMaskReps.value.ui32 =
29583 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29584 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29585 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29586 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29587 	icmpkp->outFragNeeded.value.ui32 =
29588 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29589 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29590 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29591 	icmpkp->inBadRedirects.value.ui32 =
29592 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29593 
29594 	netstack_rele(ns);
29595 	return (0);
29596 }
29597 
29598 /*
29599  * This is the fanout function for raw socket opened for SCTP.  Note
29600  * that it is called after SCTP checks that there is no socket which
29601  * wants a packet.  Then before SCTP handles this out of the blue packet,
29602  * this function is called to see if there is any raw socket for SCTP.
29603  * If there is and it is bound to the correct address, the packet will
29604  * be sent to that socket.  Note that only one raw socket can be bound to
29605  * a port.  This is assured in ipcl_sctp_hash_insert();
29606  */
29607 void
29608 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29609     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29610     zoneid_t zoneid)
29611 {
29612 	conn_t		*connp;
29613 	queue_t		*rq;
29614 	mblk_t		*first_mp;
29615 	boolean_t	secure;
29616 	ip6_t		*ip6h;
29617 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29618 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29619 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29620 	boolean_t	sctp_csum_err = B_FALSE;
29621 
29622 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29623 		sctp_csum_err = B_TRUE;
29624 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29625 	}
29626 
29627 	first_mp = mp;
29628 	if (mctl_present) {
29629 		mp = first_mp->b_cont;
29630 		secure = ipsec_in_is_secure(first_mp);
29631 		ASSERT(mp != NULL);
29632 	} else {
29633 		secure = B_FALSE;
29634 	}
29635 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29636 
29637 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29638 	if (connp == NULL) {
29639 		/*
29640 		 * Although raw sctp is not summed, OOB chunks must be.
29641 		 * Drop the packet here if the sctp checksum failed.
29642 		 */
29643 		if (sctp_csum_err) {
29644 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29645 			freemsg(first_mp);
29646 			return;
29647 		}
29648 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29649 		return;
29650 	}
29651 	rq = connp->conn_rq;
29652 	if (!canputnext(rq)) {
29653 		CONN_DEC_REF(connp);
29654 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29655 		freemsg(first_mp);
29656 		return;
29657 	}
29658 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29659 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29660 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29661 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29662 		if (first_mp == NULL) {
29663 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29664 			CONN_DEC_REF(connp);
29665 			return;
29666 		}
29667 	}
29668 	/*
29669 	 * We probably should not send M_CTL message up to
29670 	 * raw socket.
29671 	 */
29672 	if (mctl_present)
29673 		freeb(first_mp);
29674 
29675 	/* Initiate IPPF processing here if needed. */
29676 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29677 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29678 		ip_process(IPP_LOCAL_IN, &mp,
29679 		    recv_ill->ill_phyint->phyint_ifindex);
29680 		if (mp == NULL) {
29681 			CONN_DEC_REF(connp);
29682 			return;
29683 		}
29684 	}
29685 
29686 	if (connp->conn_recvif || connp->conn_recvslla ||
29687 	    ((connp->conn_ip_recvpktinfo ||
29688 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29689 	    (flags & IP_FF_IPINFO))) {
29690 		int in_flags = 0;
29691 
29692 		/*
29693 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29694 		 * IPF_RECVIF.
29695 		 */
29696 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29697 			in_flags = IPF_RECVIF;
29698 		}
29699 		if (connp->conn_recvslla) {
29700 			in_flags |= IPF_RECVSLLA;
29701 		}
29702 		if (isv4) {
29703 			mp = ip_add_info(mp, recv_ill, in_flags,
29704 			    IPCL_ZONEID(connp), ipst);
29705 		} else {
29706 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29707 			if (mp == NULL) {
29708 				BUMP_MIB(recv_ill->ill_ip_mib,
29709 				    ipIfStatsInDiscards);
29710 				CONN_DEC_REF(connp);
29711 				return;
29712 			}
29713 		}
29714 	}
29715 
29716 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29717 	/*
29718 	 * We are sending the IPSEC_IN message also up. Refer
29719 	 * to comments above this function.
29720 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29721 	 */
29722 	(connp->conn_recv)(connp, mp, NULL);
29723 	CONN_DEC_REF(connp);
29724 }
29725 
29726 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29727 {									\
29728 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29729 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29730 }
29731 /*
29732  * This function should be called only if all packet processing
29733  * including fragmentation is complete. Callers of this function
29734  * must set mp->b_prev to one of these values:
29735  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29736  * prior to handing over the mp as first argument to this function.
29737  *
29738  * If the ire passed by caller is incomplete, this function
29739  * queues the packet and if necessary, sends ARP request and bails.
29740  * If the ire passed is fully resolved, we simply prepend
29741  * the link-layer header to the packet, do ipsec hw acceleration
29742  * work if necessary, and send the packet out on the wire.
29743  *
29744  * NOTE: IPsec will only call this function with fully resolved
29745  * ires if hw acceleration is involved.
29746  * TODO list :
29747  * 	a Handle M_MULTIDATA so that
29748  *	  tcp_multisend->tcp_multisend_data can
29749  *	  call ip_xmit_v4 directly
29750  *	b Handle post-ARP work for fragments so that
29751  *	  ip_wput_frag can call this function.
29752  */
29753 ipxmit_state_t
29754 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29755     boolean_t flow_ctl_enabled, conn_t *connp)
29756 {
29757 	nce_t		*arpce;
29758 	ipha_t		*ipha;
29759 	queue_t		*q;
29760 	int		ill_index;
29761 	mblk_t		*nxt_mp, *first_mp;
29762 	boolean_t	xmit_drop = B_FALSE;
29763 	ip_proc_t	proc;
29764 	ill_t		*out_ill;
29765 	int		pkt_len;
29766 
29767 	arpce = ire->ire_nce;
29768 	ASSERT(arpce != NULL);
29769 
29770 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29771 
29772 	mutex_enter(&arpce->nce_lock);
29773 	switch (arpce->nce_state) {
29774 	case ND_REACHABLE:
29775 		/* If there are other queued packets, queue this packet */
29776 		if (arpce->nce_qd_mp != NULL) {
29777 			if (mp != NULL)
29778 				nce_queue_mp_common(arpce, mp, B_FALSE);
29779 			mp = arpce->nce_qd_mp;
29780 		}
29781 		arpce->nce_qd_mp = NULL;
29782 		mutex_exit(&arpce->nce_lock);
29783 
29784 		/*
29785 		 * Flush the queue.  In the common case, where the
29786 		 * ARP is already resolved,  it will go through the
29787 		 * while loop only once.
29788 		 */
29789 		while (mp != NULL) {
29790 
29791 			nxt_mp = mp->b_next;
29792 			mp->b_next = NULL;
29793 			ASSERT(mp->b_datap->db_type != M_CTL);
29794 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29795 			/*
29796 			 * This info is needed for IPQOS to do COS marking
29797 			 * in ip_wput_attach_llhdr->ip_process.
29798 			 */
29799 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29800 			mp->b_prev = NULL;
29801 
29802 			/* set up ill index for outbound qos processing */
29803 			out_ill = ire_to_ill(ire);
29804 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29805 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29806 			    ill_index, &ipha);
29807 			if (first_mp == NULL) {
29808 				xmit_drop = B_TRUE;
29809 				BUMP_MIB(out_ill->ill_ip_mib,
29810 				    ipIfStatsOutDiscards);
29811 				goto next_mp;
29812 			}
29813 
29814 			/* non-ipsec hw accel case */
29815 			if (io == NULL || !io->ipsec_out_accelerated) {
29816 				/* send it */
29817 				q = ire->ire_stq;
29818 				if (proc == IPP_FWD_OUT) {
29819 					UPDATE_IB_PKT_COUNT(ire);
29820 				} else {
29821 					UPDATE_OB_PKT_COUNT(ire);
29822 				}
29823 				ire->ire_last_used_time = lbolt;
29824 
29825 				if (flow_ctl_enabled || canputnext(q)) {
29826 					if (proc == IPP_FWD_OUT) {
29827 
29828 					BUMP_MIB(out_ill->ill_ip_mib,
29829 					    ipIfStatsHCOutForwDatagrams);
29830 
29831 					}
29832 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29833 					    pkt_len);
29834 
29835 					DTRACE_IP7(send, mblk_t *, first_mp,
29836 					    conn_t *, NULL, void_ip_t *, ipha,
29837 					    __dtrace_ipsr_ill_t *, out_ill,
29838 					    ipha_t *, ipha, ip6_t *, NULL, int,
29839 					    0);
29840 
29841 					ILL_SEND_TX(out_ill,
29842 					    ire, connp, first_mp, 0, connp);
29843 				} else {
29844 					BUMP_MIB(out_ill->ill_ip_mib,
29845 					    ipIfStatsOutDiscards);
29846 					xmit_drop = B_TRUE;
29847 					freemsg(first_mp);
29848 				}
29849 			} else {
29850 				/*
29851 				 * Safety Pup says: make sure this
29852 				 *  is going to the right interface!
29853 				 */
29854 				ill_t *ill1 =
29855 				    (ill_t *)ire->ire_stq->q_ptr;
29856 				int ifindex =
29857 				    ill1->ill_phyint->phyint_ifindex;
29858 				if (ifindex !=
29859 				    io->ipsec_out_capab_ill_index) {
29860 					xmit_drop = B_TRUE;
29861 					freemsg(mp);
29862 				} else {
29863 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29864 					    pkt_len);
29865 
29866 					DTRACE_IP7(send, mblk_t *, first_mp,
29867 					    conn_t *, NULL, void_ip_t *, ipha,
29868 					    __dtrace_ipsr_ill_t *, ill1,
29869 					    ipha_t *, ipha, ip6_t *, NULL,
29870 					    int, 0);
29871 
29872 					ipsec_hw_putnext(ire->ire_stq, mp);
29873 				}
29874 			}
29875 next_mp:
29876 			mp = nxt_mp;
29877 		} /* while (mp != NULL) */
29878 		if (xmit_drop)
29879 			return (SEND_FAILED);
29880 		else
29881 			return (SEND_PASSED);
29882 
29883 	case ND_INITIAL:
29884 	case ND_INCOMPLETE:
29885 
29886 		/*
29887 		 * While we do send off packets to dests that
29888 		 * use fully-resolved CGTP routes, we do not
29889 		 * handle unresolved CGTP routes.
29890 		 */
29891 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29892 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29893 
29894 		if (mp != NULL) {
29895 			/* queue the packet */
29896 			nce_queue_mp_common(arpce, mp, B_FALSE);
29897 		}
29898 
29899 		if (arpce->nce_state == ND_INCOMPLETE) {
29900 			mutex_exit(&arpce->nce_lock);
29901 			DTRACE_PROBE3(ip__xmit__incomplete,
29902 			    (ire_t *), ire, (mblk_t *), mp,
29903 			    (ipsec_out_t *), io);
29904 			return (LOOKUP_IN_PROGRESS);
29905 		}
29906 
29907 		arpce->nce_state = ND_INCOMPLETE;
29908 		mutex_exit(&arpce->nce_lock);
29909 
29910 		/*
29911 		 * Note that ire_add() (called from ire_forward())
29912 		 * holds a ref on the ire until ARP is completed.
29913 		 */
29914 		ire_arpresolve(ire);
29915 		return (LOOKUP_IN_PROGRESS);
29916 	default:
29917 		ASSERT(0);
29918 		mutex_exit(&arpce->nce_lock);
29919 		return (LLHDR_RESLV_FAILED);
29920 	}
29921 }
29922 
29923 #undef	UPDATE_IP_MIB_OB_COUNTERS
29924 
29925 /*
29926  * Return B_TRUE if the buffers differ in length or content.
29927  * This is used for comparing extension header buffers.
29928  * Note that an extension header would be declared different
29929  * even if all that changed was the next header value in that header i.e.
29930  * what really changed is the next extension header.
29931  */
29932 boolean_t
29933 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29934     uint_t blen)
29935 {
29936 	if (!b_valid)
29937 		blen = 0;
29938 
29939 	if (alen != blen)
29940 		return (B_TRUE);
29941 	if (alen == 0)
29942 		return (B_FALSE);	/* Both zero length */
29943 	return (bcmp(abuf, bbuf, alen));
29944 }
29945 
29946 /*
29947  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29948  * Return B_FALSE if memory allocation fails - don't change any state!
29949  */
29950 boolean_t
29951 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29952     const void *src, uint_t srclen)
29953 {
29954 	void *dst;
29955 
29956 	if (!src_valid)
29957 		srclen = 0;
29958 
29959 	ASSERT(*dstlenp == 0);
29960 	if (src != NULL && srclen != 0) {
29961 		dst = mi_alloc(srclen, BPRI_MED);
29962 		if (dst == NULL)
29963 			return (B_FALSE);
29964 	} else {
29965 		dst = NULL;
29966 	}
29967 	if (*dstp != NULL)
29968 		mi_free(*dstp);
29969 	*dstp = dst;
29970 	*dstlenp = dst == NULL ? 0 : srclen;
29971 	return (B_TRUE);
29972 }
29973 
29974 /*
29975  * Replace what is in *dst, *dstlen with the source.
29976  * Assumes ip_allocbuf has already been called.
29977  */
29978 void
29979 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29980     const void *src, uint_t srclen)
29981 {
29982 	if (!src_valid)
29983 		srclen = 0;
29984 
29985 	ASSERT(*dstlenp == srclen);
29986 	if (src != NULL && srclen != 0)
29987 		bcopy(src, *dstp, srclen);
29988 }
29989 
29990 /*
29991  * Free the storage pointed to by the members of an ip6_pkt_t.
29992  */
29993 void
29994 ip6_pkt_free(ip6_pkt_t *ipp)
29995 {
29996 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29997 
29998 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29999 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30000 		ipp->ipp_hopopts = NULL;
30001 		ipp->ipp_hopoptslen = 0;
30002 	}
30003 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30004 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30005 		ipp->ipp_rtdstopts = NULL;
30006 		ipp->ipp_rtdstoptslen = 0;
30007 	}
30008 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30009 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30010 		ipp->ipp_dstopts = NULL;
30011 		ipp->ipp_dstoptslen = 0;
30012 	}
30013 	if (ipp->ipp_fields & IPPF_RTHDR) {
30014 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30015 		ipp->ipp_rthdr = NULL;
30016 		ipp->ipp_rthdrlen = 0;
30017 	}
30018 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30019 	    IPPF_RTHDR);
30020 }
30021 
30022 zoneid_t
30023 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30024     zoneid_t lookup_zoneid)
30025 {
30026 	ire_t		*ire;
30027 	int		ire_flags = MATCH_IRE_TYPE;
30028 	zoneid_t	zoneid = ALL_ZONES;
30029 
30030 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30031 		return (ALL_ZONES);
30032 
30033 	if (lookup_zoneid != ALL_ZONES)
30034 		ire_flags |= MATCH_IRE_ZONEONLY;
30035 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30036 	    lookup_zoneid, NULL, ire_flags, ipst);
30037 	if (ire != NULL) {
30038 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30039 		ire_refrele(ire);
30040 	}
30041 	return (zoneid);
30042 }
30043 
30044 zoneid_t
30045 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30046     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30047 {
30048 	ire_t		*ire;
30049 	int		ire_flags = MATCH_IRE_TYPE;
30050 	zoneid_t	zoneid = ALL_ZONES;
30051 	ipif_t		*ipif_arg = NULL;
30052 
30053 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30054 		return (ALL_ZONES);
30055 
30056 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30057 		ire_flags |= MATCH_IRE_ILL;
30058 		ipif_arg = ill->ill_ipif;
30059 	}
30060 	if (lookup_zoneid != ALL_ZONES)
30061 		ire_flags |= MATCH_IRE_ZONEONLY;
30062 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30063 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30064 	if (ire != NULL) {
30065 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30066 		ire_refrele(ire);
30067 	}
30068 	return (zoneid);
30069 }
30070 
30071 /*
30072  * IP obserability hook support functions.
30073  */
30074 
30075 static void
30076 ipobs_init(ip_stack_t *ipst)
30077 {
30078 	ipst->ips_ipobs_enabled = B_FALSE;
30079 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30080 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30081 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30082 	ipst->ips_ipobs_cb_nwalkers = 0;
30083 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30084 }
30085 
30086 static void
30087 ipobs_fini(ip_stack_t *ipst)
30088 {
30089 	ipobs_cb_t *cb;
30090 
30091 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30092 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30093 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30094 
30095 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30096 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30097 		kmem_free(cb, sizeof (*cb));
30098 	}
30099 	list_destroy(&ipst->ips_ipobs_cb_list);
30100 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30101 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30102 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30103 }
30104 
30105 void
30106 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30107     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30108 {
30109 	mblk_t *mp2;
30110 	ipobs_cb_t *ipobs_cb;
30111 	ipobs_hook_data_t *ihd;
30112 	uint64_t grifindex = 0;
30113 
30114 	ASSERT(DB_TYPE(mp) == M_DATA);
30115 
30116 	if (IS_UNDER_IPMP(ill))
30117 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30118 
30119 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30120 	ipst->ips_ipobs_cb_nwalkers++;
30121 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30122 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30123 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30124 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30125 		if (mp2 != NULL) {
30126 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30127 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30128 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30129 				freemsg(mp2);
30130 				continue;
30131 			}
30132 			ihd->ihd_mp->b_rptr += hlen;
30133 			ihd->ihd_htype = htype;
30134 			ihd->ihd_ipver = ipver;
30135 			ihd->ihd_zsrc = zsrc;
30136 			ihd->ihd_zdst = zdst;
30137 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30138 			ihd->ihd_grifindex = grifindex;
30139 			ihd->ihd_stack = ipst->ips_netstack;
30140 			mp2->b_wptr += sizeof (*ihd);
30141 			ipobs_cb->ipobs_cbfunc(mp2);
30142 		}
30143 	}
30144 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30145 	ipst->ips_ipobs_cb_nwalkers--;
30146 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30147 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30148 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30149 }
30150 
30151 void
30152 ipobs_register_hook(netstack_t *ns, pfv_t func)
30153 {
30154 	ipobs_cb_t   *cb;
30155 	ip_stack_t *ipst = ns->netstack_ip;
30156 
30157 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30158 
30159 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30160 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30161 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30162 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30163 
30164 	cb->ipobs_cbfunc = func;
30165 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30166 	ipst->ips_ipobs_enabled = B_TRUE;
30167 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30168 }
30169 
30170 void
30171 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30172 {
30173 	ipobs_cb_t	*curcb;
30174 	ip_stack_t	*ipst = ns->netstack_ip;
30175 
30176 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30177 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30178 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30179 
30180 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30181 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30182 		if (func == curcb->ipobs_cbfunc) {
30183 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30184 			kmem_free(curcb, sizeof (*curcb));
30185 			break;
30186 		}
30187 	}
30188 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30189 		ipst->ips_ipobs_enabled = B_FALSE;
30190 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30191 }
30192